From cf7d388a83499d319f85f79bce49a34a77593279 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Mon, 13 Jul 2026 11:05:46 -0400 Subject: [PATCH 1/2] refactor(opencode): simplify HTTP API exercise DSL --- .../test/server/httpapi-exercise/backend.ts | 6 +- .../test/server/httpapi-exercise/dsl.ts | 68 +- .../test/server/httpapi-exercise/index.ts | 690 +++++++----------- .../test/server/httpapi-exercise/report.ts | 5 +- .../test/server/httpapi-exercise/runner.ts | 5 +- .../test/server/httpapi-exercise/runtime.ts | 3 - .../test/server/httpapi-exercise/types.ts | 10 +- 7 files changed, 284 insertions(+), 503 deletions(-) diff --git a/packages/opencode/test/server/httpapi-exercise/backend.ts b/packages/opencode/test/server/httpapi-exercise/backend.ts index a10b0089729e..dd63ea118a9c 100644 --- a/packages/opencode/test/server/httpapi-exercise/backend.ts +++ b/packages/opencode/test/server/httpapi-exercise/backend.ts @@ -11,9 +11,9 @@ type CallOptions = { } } -export function call(scenario: ActiveScenario, ctx: SeededContext, options: CallOptions = {}) { +export function call(scenario: ActiveScenario, ctx: SeededContext) { return Effect.promise(async () => - capture(await app(await runtime(), options).request(toRequest(scenario, ctx)), scenario.capture), + capture(await app(await runtime(), {}).request(toRequest(scenario, ctx)), scenario.capture), ) } @@ -78,7 +78,7 @@ function app(modules: Runtime, options: CallOptions) { } function toRequest(scenario: ActiveScenario, ctx: SeededContext) { - const spec = scenario.request(ctx, ctx.state) + const spec = scenario.request(ctx) return new Request(new URL(spec.path, "http://localhost"), { method: scenario.method, headers: spec.body === undefined ? spec.headers : { "content-type": "application/json", ...spec.headers }, diff --git a/packages/opencode/test/server/httpapi-exercise/dsl.ts b/packages/opencode/test/server/httpapi-exercise/dsl.ts index 60d41576f04b..f4539deee44a 100644 --- a/packages/opencode/test/server/httpapi-exercise/dsl.ts +++ b/packages/opencode/test/server/httpapi-exercise/dsl.ts @@ -5,7 +5,6 @@ import type { AuthPolicy, BuilderState, CallResult, - Comparison, Method, ProjectOptions, RequestSpec, @@ -28,7 +27,6 @@ class ScenarioBuilder { request: (ctx) => ({ path, headers: ctx.headers() }), authProbe: undefined, capture: "full", - mutates: false, reset: true, auth, } @@ -54,11 +52,7 @@ class ScenarioBuilder { return this.clone({ authProbe }) } - mutating() { - return this.clone({ mutates: true }) - } - - preserveDatabase() { + preserveState() { return this.clone({ reset: false }) } @@ -66,41 +60,8 @@ class ScenarioBuilder { return this.clone({ capture: "stream" }) } - protected() { - return this.auth("protected") - } - - public() { - return this.auth("public") - } - - publicBypass() { - return this.auth("public-bypass") - } - - ticketBypass() { - return this.auth("ticket-bypass") - } - - private auth(auth: AuthPolicy) { - return this.clone({ auth }) - } - - /** Assert a non-JSON or shape-only response. */ - ok(status = 200, compare: Comparison = "status") { - return this.done(compare, (_ctx, result) => - Effect.sync(() => { - if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`) - }), - ) - } - - status( - status = 200, - inspect?: (ctx: SeededContext, result: CallResult) => Effect.Effect, - compare: Comparison = "status", - ) { - return this.done(compare, (ctx, result) => + status(status = 200, inspect?: (ctx: SeededContext, result: CallResult) => Effect.Effect) { + return this.done((ctx, result) => Effect.gen(function* () { if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`) if (inspect) yield* inspect(ctx, result) @@ -109,17 +70,13 @@ class ScenarioBuilder { } /** Assert JSON status/content-type plus an optional synchronous body check. */ - json(status = 200, inspect?: (body: unknown, ctx: SeededContext) => void, compare: Comparison = "json") { - return this.jsonEffect(status, inspect ? (body, ctx) => Effect.sync(() => inspect(body, ctx)) : undefined, compare) + json(status = 200, inspect?: (body: unknown, ctx: SeededContext) => void) { + return this.jsonEffect(status, inspect ? (body, ctx) => Effect.sync(() => inspect(body, ctx)) : undefined) } /** Assert JSON status/content-type plus optional Effect assertions, e.g. DB side effects. */ - jsonEffect( - status = 200, - inspect?: (body: unknown, ctx: SeededContext) => Effect.Effect, - compare: Comparison = "json", - ) { - return this.done(compare, (ctx, result) => + jsonEffect(status = 200, inspect?: (body: unknown, ctx: SeededContext) => Effect.Effect) { + return this.done((ctx, result) => Effect.gen(function* () { if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`) if (!looksJson(result)) @@ -145,10 +102,7 @@ class ScenarioBuilder { return builder } - private done( - compare: Comparison, - expect: (ctx: SeededContext, result: CallResult) => Effect.Effect, - ): ActiveScenario { + private done(expect: (ctx: SeededContext, result: CallResult) => Effect.Effect): ActiveScenario { const state = this.state return { kind: "active", @@ -159,12 +113,10 @@ class ScenarioBuilder { seed: state.seed, authProbe: state.authProbe, // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- `.seeded(...)` preserves the paired request/state type inside the builder. - request: (ctx, seeded) => state.request({ ...ctx, state: seeded as S }), + request: (ctx) => state.request(ctx as SeededContext), // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- `.seeded(...)` preserves the paired assertion/state type inside the builder. - expect: (ctx, seeded, result) => expect({ ...ctx, state: seeded as S }, result), - compare, + expect: (ctx, result) => expect(ctx as SeededContext, result), capture: state.capture, - mutates: state.mutates, reset: state.reset, auth: state.auth, } diff --git a/packages/opencode/test/server/httpapi-exercise/index.ts b/packages/opencode/test/server/httpapi-exercise/index.ts index af534b51eae5..6726619372af 100644 --- a/packages/opencode/test/server/httpapi-exercise/index.ts +++ b/packages/opencode/test/server/httpapi-exercise/index.ts @@ -15,7 +15,7 @@ * - `.seeded(...)` creates typed per-scenario state using Effect helpers on `ctx`. * - `.at(...)` builds the request from that typed state. * - `.json(...)` / `.jsonEffect(...)` assert response shape and optional side effects. - * - `.mutating()` tells the runner to reset isolated state after destructive routes. + * - Scenarios reset isolated runtime state by default; `.preserveState()` opts out. */ import { Effect } from "effect" import { OpenApi } from "effect/unstable/httpapi" @@ -69,14 +69,11 @@ const scenarios: Scenario[] = [ .get("/global/event", "global.event") .global() .stream() - .status( - 200, - (_ctx, result) => - Effect.sync(() => { - check(result.contentType.includes("text/event-stream"), "global event should be an SSE stream") - check(result.text.includes("server.connected"), "global event should emit initial connection event") - }), - "status", + .status(200, (_ctx, result) => + Effect.sync(() => { + check(result.contentType.includes("text/event-stream"), "global event should be an SSE stream") + check(result.text.includes("server.connected"), "global event should emit initial connection event") + }), ), http.protected.get("/global/config", "global.config.get").global().json(), http.protected @@ -91,30 +88,20 @@ const scenarios: Scenario[] = [ ), ) .at(() => ({ path: "/global/config", body: { username: "httpapi-global" } })) - .jsonEffect( - 200, - (body) => - Effect.gen(function* () { - object(body) - check(body.username === "httpapi-global", "global config update should return patched config") - const text = yield* Effect.promise(() => - Bun.file(path.join(exerciseConfigDirectory, "opencode.jsonc")).text(), - ) - check(text.includes('"username": "httpapi-global"'), "global config update should write isolated config file") - }), - "status", + .jsonEffect(200, (body) => + Effect.gen(function* () { + object(body) + check(body.username === "httpapi-global", "global config update should return patched config") + const text = yield* Effect.promise(() => Bun.file(path.join(exerciseConfigDirectory, "opencode.jsonc")).text()) + check(text.includes('"username": "httpapi-global"'), "global config update should write isolated config file") + }), ), http.protected .post("/global/dispose", "global.dispose") .global() - .mutating() - .json( - 200, - (body) => { - check(body === true, "global dispose should return true") - }, - "status", - ), + .json(200, (body) => { + check(body === true, "global dispose should return true") + }), http.protected.get("/path", "path.get").json(200, (body, ctx) => { object(body) check(body.directory === ctx.directory, "directory should resolve from x-opencode-directory") @@ -126,94 +113,71 @@ const scenarios: Scenario[] = [ .get("/vcs/diff", "vcs.diff") .at((ctx) => ({ path: "/vcs/diff?mode=git", headers: ctx.headers() })) .json(200, array), - http.protected.get("/vcs/diff/raw", "vcs.diff.raw").status( - 200, - (_ctx, result) => - Effect.sync(() => { - check(typeof result.text === "string", "raw VCS diff should return text") - }), - "status", + http.protected.get("/vcs/diff/raw", "vcs.diff.raw").status(200, (_ctx, result) => + Effect.sync(() => { + check(typeof result.text === "string", "raw VCS diff should return text") + }), ), http.protected .post("/vcs/apply", "vcs.apply") .inProject({ git: false }) .at((ctx) => ({ path: "/vcs/apply", headers: ctx.headers(), body: { patch: "" } })) - .status(400, undefined, "status"), - http.protected.get("/command", "command.list").json(200, array, "status"), - http.protected.get("/agent", "app.agents").json(200, array, "status"), - http.protected.get("/skill", "app.skills").json(200, array, "status"), + .status(400, undefined), + http.protected.get("/command", "command.list").json(200, array), + http.protected.get("/agent", "app.agents").json(200, array), + http.protected.get("/skill", "app.skills").json(200, array), http.protected.get("/lsp", "lsp.status").json(200, array), http.protected.get("/formatter", "formatter.status").json(200, array), - http.protected.get("/config", "config.get").json(200, undefined, "status"), + http.protected.get("/config", "config.get").json(200, undefined), http.protected .patch("/config", "config.update") - .mutating() .at((ctx) => ({ path: "/config", headers: ctx.headers(), body: { username: "httpapi-local" } })) - .json( - 200, - (body) => { - object(body) - check(body.username === "httpapi-local", "local config update should return patched config") - }, - "status", - ), + .json(200, (body) => { + object(body) + check(body.username === "httpapi-local", "local config update should return patched config") + }), http.protected .patch("/config", "config.update.invalid") .at((ctx) => ({ path: "/config", headers: ctx.headers(), body: { username: 1 } })) .status(400), http.protected.get("/config/providers", "config.providers").json(), - http.protected.get("/project", "project.list").json(200, array, "status"), - http.protected.get("/project/current", "project.current").json( - 200, - (body, ctx) => { - object(body) - check(body.worktree === ctx.directory, "current project should resolve from scenario directory") - }, - "status", - ), + http.protected.get("/project", "project.list").json(200, array), + http.protected.get("/project/current", "project.current").json(200, (body, ctx) => { + object(body) + check(body.worktree === ctx.directory, "current project should resolve from scenario directory") + }), http.protected .patch("/project/{projectID}", "project.update") - .mutating() .seeded((ctx) => ctx.project()) .at((ctx) => ({ path: route("/project/{projectID}", { projectID: ctx.state.id }), headers: ctx.headers(), body: { name: "HTTP API Project", commands: { start: "bun --version" } }, })) - .json( - 200, - (body) => { - object(body) - check(body.name === "HTTP API Project", "project update should return patched name") - check( - isRecord(body.commands) && body.commands.start === "bun --version", - "project update should return patched command", - ) - }, - "status", - ), + .json(200, (body) => { + object(body) + check(body.name === "HTTP API Project", "project update should return patched name") + check( + isRecord(body.commands) && body.commands.start === "bun --version", + "project update should return patched command", + ) + }), http.protected .patch("/project/{projectID}", "project.update.missing") - .mutating() .at((ctx) => ({ path: route("/project/{projectID}", { projectID: "project_httpapi_missing" }), headers: ctx.headers(), body: { name: "Missing Project" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/project/git/init", "project.initGit") - .mutating() .inProject({ git: false }) - .json( - 200, - (body, ctx) => { - object(body) - check(body.worktree === ctx.directory, "git init should return current project") - check(body.vcs === "git", "git init should mark the project as git-backed") - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.worktree === ctx.directory, "git init should return current project") + check(body.vcs === "git", "git init should mark the project as git-backed") + }), http.protected .get("/project/{projectID}/directories", "project.directories") .seeded((ctx) => ctx.project()) @@ -221,7 +185,7 @@ const scenarios: Scenario[] = [ path: route("/project/{projectID}/directories", { projectID: ctx.state.id }), headers: ctx.headers(), })) - .json(200, array, "status"), + .json(200, array), http.protected .post("/experimental/project/{projectID}/copy/generate-name", "experimental.projectCopy.generateName") .seeded((ctx) => ctx.project()) @@ -254,13 +218,12 @@ const scenarios: Scenario[] = [ .status(400), http.protected .post("/experimental/project/{projectID}/copy/refresh", "experimental.projectCopy.refresh") - .mutating() .seeded((ctx) => ctx.project()) .at((ctx) => ({ path: route("/experimental/project/{projectID}/copy/refresh", { projectID: ctx.state.id }), headers: ctx.headers(), })) - .status(204, undefined, "status"), + .status(204, undefined), http.protected.get("/provider", "provider.list").json(), http.protected.get("/provider/auth", "provider.auth").json(), http.protected @@ -295,7 +258,7 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { reply: "once" }, })) - .json(404, object, "status"), + .json(404, object), http.protected.get("/question", "question.list").json(200, array), http.protected .post("/question/{requestID}/reply", "question.reply.invalid") @@ -312,14 +275,14 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { answers: [["Yes"]] }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/question/{requestID}/reject", "question.reject") .at((ctx) => ({ path: route("/question/{requestID}/reject", { requestID: "que_httpapi_reject" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/file", "file.list") .seeded((ctx) => ctx.file("hello.txt", "hello\n")) @@ -362,33 +325,25 @@ const scenarios: Scenario[] = [ http.protected .get("/event", "event.stream") .stream() - .status( - 200, - (_ctx, result) => - Effect.sync(() => { - check(result.contentType.includes("text/event-stream"), "event should be an SSE stream") - check(result.text.includes("server.connected"), "event should emit initial connection event") - }), - "status", + .status(200, (_ctx, result) => + Effect.sync(() => { + check(result.contentType.includes("text/event-stream"), "event should be an SSE stream") + check(result.text.includes("server.connected"), "event should emit initial connection event") + }), ), http.protected.get("/mcp", "mcp.status").json(), http.protected .post("/mcp", "mcp.add") - .mutating() .at((ctx) => ({ path: "/mcp", headers: ctx.headers(), body: { name: "httpapi-disabled", config: { type: "local", command: ["bun", "--version"], enabled: false } }, })) - .json( - 200, - (body) => { - object(body) - object(body["httpapi-disabled"]) - check(body["httpapi-disabled"].status === "disabled", "disabled MCP server should be added without spawning") - }, - "status", - ), + .json(200, (body) => { + object(body) + object(body["httpapi-disabled"]) + check(body["httpapi-disabled"].status === "disabled", "disabled MCP server should be added without spawning") + }), http.protected .post("/mcp", "mcp.add.invalid") .at((ctx) => ({ @@ -400,19 +355,18 @@ const scenarios: Scenario[] = [ http.protected .post("/mcp/{name}/auth", "mcp.auth.start") .at((ctx) => ({ path: route("/mcp/{name}/auth", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected .delete("/mcp/{name}/auth", "mcp.auth.remove") - .mutating() .at((ctx) => ({ path: route("/mcp/{name}/auth", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/mcp/{name}/auth/authenticate", "mcp.auth.authenticate") .at((ctx) => ({ path: route("/mcp/{name}/auth/authenticate", { name: "httpapi-missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/mcp/{name}/auth/callback", "mcp.auth.callback") .at((ctx) => ({ @@ -420,33 +374,26 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { code: "code" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/mcp/{name}/connect", "mcp.connect") - .mutating() .at((ctx) => ({ path: route("/mcp/{name}/connect", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/mcp/{name}/disconnect", "mcp.disconnect") - .mutating() .at((ctx) => ({ path: route("/mcp/{name}/disconnect", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected.get("/pty/shells", "pty.shells").json(200, array), http.protected.get("/pty", "pty.list").json(200, array), http.protected .post("/pty", "pty.create") - .mutating() .at((ctx) => ({ path: "/pty", headers: ctx.headers(), body: controlledPtyInput("HTTP API PTY") })) - .json( - 200, - (body, ctx) => { - object(body) - check(body.title === "HTTP API PTY", "PTY create should return requested title") - check(body.command === "/bin/sh", "PTY create should use controlled shell command") - check(body.cwd === ctx.directory, "PTY create should default cwd to scenario directory") - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.title === "HTTP API PTY", "PTY create should return requested title") + check(body.command === "/bin/sh", "PTY create should use controlled shell command") + check(body.cwd === ctx.directory, "PTY create should default cwd to scenario directory") + }), http.protected .post("/pty", "pty.create.invalid") .at((ctx) => ({ path: "/pty", headers: ctx.headers(), body: { command: 1 } })) @@ -457,14 +404,13 @@ const scenarios: Scenario[] = [ path: route("/pty/{ptyID}/connect-token", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers(), })) - .status(403, undefined, "status"), + .status(403, undefined), http.protected .get("/pty/{ptyID}", "pty.get") .at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) .status(404), http.protected .put("/pty/{ptyID}", "pty.update") - .mutating() .at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers(), @@ -473,13 +419,12 @@ const scenarios: Scenario[] = [ .status(400), http.protected .delete("/pty/{ptyID}", "pty.remove") - .mutating() .at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/pty/{ptyID}/connect", "pty.connect") .at((ctx) => ({ path: route("/pty/{ptyID}/connect", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .status(404, undefined, "none"), + .status(404, undefined), http.protected.get("/experimental/console", "experimental.console.get").json(), http.protected.get("/experimental/console/orgs", "experimental.console.listOrgs").json(), http.protected @@ -489,7 +434,7 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { accountID: "httpapi-account", orgID: "httpapi-org" }, })) - .status(400, undefined, "none"), + .status(400, undefined), http.protected.get("/experimental/workspace/adapter", "experimental.workspace.adapter.list").json(200, array), http.protected.get("/experimental/workspace", "experimental.workspace.list").json(200, array), http.protected.get("/experimental/workspace/status", "experimental.workspace.status").json(200, array), @@ -497,12 +442,9 @@ const scenarios: Scenario[] = [ .post("/experimental/workspace", "experimental.workspace.create") .at((ctx) => ({ path: "/experimental/workspace", headers: ctx.headers(), body: {} })) .status(400), - http.protected - .post("/experimental/workspace/sync-list", "experimental.workspace.syncList") - .status(204, undefined, "status"), + http.protected.post("/experimental/workspace/sync-list", "experimental.workspace.syncList").status(204, undefined), http.protected .delete("/experimental/workspace/{id}", "experimental.workspace.remove") - .mutating() .at((ctx) => ({ path: route("/experimental/workspace/{id}", { id: "wrk_httpapi_missing" }), headers: ctx.headers(), @@ -530,22 +472,18 @@ const scenarios: Scenario[] = [ path: `/experimental/tool?${new URLSearchParams({ provider: "opencode", model: "test" })}`, headers: ctx.headers(), })) - .json(200, array, "status"), + .json(200, array), http.protected.get("/experimental/tool/ids", "tool.ids").json(200, array), http.protected.get("/experimental/worktree", "worktree.list").json(200, array), http.protected .post("/experimental/worktree", "worktree.create") - .mutating() .at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { name: "api-dsl" } })) - .jsonEffect( - 200, - (body, ctx) => - Effect.gen(function* () { - object(body) - check(typeof body.directory === "string", "created worktree should include directory") - yield* ctx.worktreeRemove(body.directory) - }), - "status", + .jsonEffect(200, (body, ctx) => + Effect.gen(function* () { + object(body) + check(typeof body.directory === "string", "created worktree should include directory") + yield* ctx.worktreeRemove(body.directory) + }), ), http.protected .post("/experimental/worktree", "worktree.create.invalid") @@ -553,7 +491,6 @@ const scenarios: Scenario[] = [ .status(400), http.protected .delete("/experimental/worktree", "worktree.remove") - .mutating() .seeded((ctx) => ctx.worktree({ name: "api-remove" })) .at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { directory: ctx.state.directory } })) .json(200, (body) => { @@ -561,7 +498,6 @@ const scenarios: Scenario[] = [ }), http.protected .post("/experimental/worktree/reset", "worktree.reset") - .mutating() .seeded((ctx) => ctx.worktree({ name: "api-reset" })) .at((ctx) => ({ path: "/experimental/worktree/reset", @@ -586,7 +522,6 @@ const scenarios: Scenario[] = [ }), http.protected .post("/experimental/session/{sessionID}/background", "experimental.session.background") - .mutating() .seeded((ctx) => ctx.session({ title: "Background route owner" })) .at((ctx) => ({ path: route("/experimental/session/{sessionID}/background", { sessionID: ctx.state.id }), @@ -607,20 +542,16 @@ const scenarios: Scenario[] = [ http.protected .post("/sync/steal", "sync.steal.invalid") .at((ctx) => ({ path: "/sync/steal", headers: ctx.headers(), body: {} })) - .status(400, undefined, "status"), + .status(400, undefined), http.protected .post("/sync/start", "sync.start") - .mutating() - .preserveDatabase() + .preserveState() .json(200, (body) => { check(body === true, "sync start should return true when no workspace sessions exist") }), - http.protected - .post("/instance/dispose", "instance.dispose") - .mutating() - .json(200, (body) => { - check(body === true, "instance dispose should return true") - }), + http.protected.post("/instance/dispose", "instance.dispose").json(200, (body) => { + check(body === true, "instance dispose should return true") + }), http.protected .post("/log", "app.log") .global() @@ -685,7 +616,7 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { key: "test" }, })) - .status(500, undefined, "status"), + .status(500, undefined), http.protected .post("/api/integration/{integrationID}/connect/oauth", "v2.integration.connect.oauth") .at((ctx) => ({ @@ -693,14 +624,14 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { methodID: "missing", inputs: {} }, })) - .status(500, undefined, "status"), + .status(500, undefined), http.protected .get("/api/integration/attempt/{attemptID}", "v2.integration.attempt.status") .at((ctx) => ({ path: route("/api/integration/attempt/{attemptID}", { attemptID: "con_missing" }), headers: ctx.headers(), })) - .status(500, undefined, "status"), + .status(500, undefined), http.protected .post("/api/integration/attempt/{attemptID}/complete", "v2.integration.attempt.complete") .at((ctx) => ({ @@ -708,21 +639,21 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: {}, })) - .status(500, undefined, "status"), + .status(500, undefined), http.protected .delete("/api/integration/attempt/{attemptID}", "v2.integration.attempt.cancel") .at((ctx) => ({ path: route("/api/integration/attempt/{attemptID}", { attemptID: "con_missing" }), headers: ctx.headers(), })) - .status(204, undefined, "status"), + .status(204, undefined), http.protected .delete("/api/credential/{credentialID}", "v2.credential.remove") .at((ctx) => ({ path: route("/api/credential/{credentialID}", { credentialID: "cred_missing" }), headers: ctx.headers(), })) - .status(204, undefined, "status"), + .status(204, undefined), http.protected .patch("/api/credential/{credentialID}", "v2.credential.update") .at((ctx) => ({ @@ -730,34 +661,28 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { label: "Work" }, })) - .status(204, undefined, "status"), + .status(204, undefined), http.protected.get("/api/command", "v2.command.list").json(200, locationData(array)), http.protected.get("/api/skill", "v2.skill.list").json(200, locationData(array)), http.protected .get("/api/event", "v2.event.subscribe") .stream() - .status( - 200, - (_ctx, result) => - Effect.sync(() => { - check(result.contentType.includes("text/event-stream"), "v2 event should be an SSE stream") - check(result.text.includes("server.connected"), "v2 event should emit initial connection event") - check(!result.text.includes('"location"'), "v2 connection event should not be scoped to a location") - }), - "status", + .status(200, (_ctx, result) => + Effect.sync(() => { + check(result.contentType.includes("text/event-stream"), "v2 event should be an SSE stream") + check(result.text.includes("server.connected"), "v2 event should emit initial connection event") + check(!result.text.includes('"location"'), "v2 connection event should not be scoped to a location") + }), ), http.protected .get("/api/fs/read/*", "v2.fs.read") .seeded((ctx) => ctx.file("hello.txt", "hello\n")) .at((ctx) => ({ path: "/api/fs/read/hello.txt", headers: ctx.headers() })) - .status( - 200, - (_ctx, result) => - Effect.sync(() => { - check(result.text === "hello\n", "v2 fs read should return the file body") - check(result.contentType.includes("text/plain"), "v2 fs read should return the file content type") - }), - "status", + .status(200, (_ctx, result) => + Effect.sync(() => { + check(result.text === "hello\n", "v2 fs read should return the file body") + check(result.contentType.includes("text/plain"), "v2 fs read should return the file content type") + }), ), http.protected.get("/api/fs/list", "v2.fs.list").json(200, locationData(array)), http.protected @@ -768,46 +693,43 @@ const scenarios: Scenario[] = [ http.protected.get("/api/pty", "v2.pty.list").json(200, locationData(array)), http.protected .post("/api/pty", "v2.pty.create") - .mutating() .at((ctx) => ({ path: "/api/pty", headers: ctx.headers(), body: controlledPtyInput("HTTP API V2 PTY") })) .json(200, locationData(object)), http.protected .get("/api/pty/{ptyID}", "v2.pty.get") .at((ctx) => ({ path: route("/api/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected .put("/api/pty/{ptyID}", "v2.pty.update") - .mutating() .at((ctx) => ({ path: route("/api/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers(), body: { title: "missing" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .delete("/api/pty/{ptyID}", "v2.pty.remove") - .mutating() .at((ctx) => ({ path: route("/api/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/pty/{ptyID}/connect-token", "v2.pty.connectToken") .at((ctx) => ({ path: route("/api/pty/{ptyID}/connect-token", { ptyID: "pty_httpapi_missing" }), headers: { ...ctx.headers(), "x-opencode-ticket": "1" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/pty/{ptyID}/connect", "v2.pty.connect") .at((ctx) => ({ path: route("/api/pty/{ptyID}/connect", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers(), })) - .status(404, undefined, "none"), + .status(404, undefined), http.protected.get("/api/reference", "v2.reference.list").json(200, object), http.protected .get("/api/provider/{providerID}", "v2.provider.get") .at((ctx) => ({ path: route("/api/provider/{providerID}", { providerID: "missing" }), headers: ctx.headers() })) - .json(404, object, "status"), + .json(404, object), http.protected.get("/api/permission/request", "v2.permission.request.list").json(200, (body) => { object(body) object(body.location) @@ -833,7 +755,6 @@ const scenarios: Scenario[] = [ .json(200, data(array)), http.protected .post("/api/session/{sessionID}/form", "v2.session.form.create") - .mutating() .seeded((ctx) => ctx.session({ title: "Form create owner" })) .at((ctx) => ({ path: route("/api/session/{sessionID}/form", { sessionID: ctx.state.id }), @@ -858,7 +779,7 @@ const scenarios: Scenario[] = [ path: route("/api/session/{sessionID}/form/{formID}", { sessionID: ctx.state.id, formID: "frm_httpapi_missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/form/{formID}/state", "v2.session.form.state") .seeded((ctx) => ctx.session({ title: "Form state owner" })) @@ -869,10 +790,9 @@ const scenarios: Scenario[] = [ }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/form/{formID}/reply", "v2.session.form.reply") - .mutating() .seeded((ctx) => ctx.session({ title: "Form reply owner" })) .at((ctx) => ({ path: route("/api/session/{sessionID}/form/{formID}/reply", { @@ -882,10 +802,9 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { answer: {} }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/form/{formID}/cancel", "v2.session.form.cancel") - .mutating() .seeded((ctx) => ctx.session({ title: "Form cancel owner" })) .at((ctx) => ({ path: route("/api/session/{sessionID}/form/{formID}/cancel", { @@ -894,7 +813,7 @@ const scenarios: Scenario[] = [ }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/permission", "v2.session.permission.create") .seeded((ctx) => ctx.session({ title: "Permission create owner" })) @@ -927,7 +846,7 @@ const scenarios: Scenario[] = [ }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/question", "v2.session.question.list") .seeded((ctx) => ctx.session({ title: "Question list owner" })) @@ -947,7 +866,7 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { reply: "once" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/question/{requestID}/reply", "v2.session.question.reply") .seeded((ctx) => ctx.session({ title: "Question reply owner" })) @@ -959,7 +878,7 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { answers: [] }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/question/{requestID}/reject", "v2.session.question.reject") .seeded((ctx) => ctx.session({ title: "Question reject owner" })) @@ -970,7 +889,7 @@ const scenarios: Scenario[] = [ }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected.get("/api/permission/saved", "v2.permission.saved.list").json(200, (body) => { object(body) array(body.data) @@ -978,19 +897,15 @@ const scenarios: Scenario[] = [ http.protected .delete("/api/permission/saved/{id}", "v2.permission.saved.remove") .at((ctx) => ({ path: route("/api/permission/saved/{id}", { id: "psv_httpapi_missing" }), headers: ctx.headers() })) - .status(204, undefined, "status"), + .status(204, undefined), http.protected .get("/api/session", "v2.session.list") .at((ctx) => ({ path: "/api/session?roots=true", headers: ctx.headers() })) - .json( - 200, - (body) => { - object(body) - array(body.data) - object(body.cursor) - }, - "none", - ), + .json(200, (body) => { + object(body) + array(body.data) + object(body.cursor) + }), http.protected .get("/api/session", "v2.session.list.filters") .at((ctx) => ({ @@ -1005,15 +920,11 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .json( - 200, - (body) => { - object(body) - array(body.data) - object(body.cursor) - }, - "none", - ), + .json(200, (body) => { + object(body) + array(body.data) + object(body.cursor) + }), http.protected .get("/api/session", "v2.session.list.cursor") .at((ctx) => ({ @@ -1027,15 +938,11 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .json( - 200, - (body) => { - object(body) - array(body.data) - object(body.cursor) - }, - "none", - ), + .json(200, (body) => { + object(body) + array(body.data) + object(body.cursor) + }), http.protected .get("/api/session", "v2.session.list.cursor.invalid") .at((ctx) => ({ @@ -1044,8 +951,8 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .status(400, undefined, "none"), - http.protected.get("/api/session/active", "v2.session.active").json(200, data(object), "none"), + .status(400, undefined), + http.protected.get("/api/session/active", "v2.session.active").json(200, data(object)), http.protected .post("/api/session", "v2.session.create") .at((ctx) => ({ @@ -1070,7 +977,7 @@ const scenarios: Scenario[] = [ headers: { ...ctx.headers(), "content-type": "application/json" }, body: { agent: "plan" }, })) - .status(204, undefined, "none"), + .status(204, undefined), http.protected .post("/api/session/{sessionID}/model", "v2.session.switchModel") .seeded((ctx) => ctx.session({ title: "Switch model" })) @@ -1079,14 +986,14 @@ const scenarios: Scenario[] = [ headers: { ...ctx.headers(), "content-type": "application/json" }, body: { model: { providerID: "opencode", id: "big-pickle" } }, })) - .status(204, undefined, "none"), + .status(204, undefined), http.protected .get("/api/session/{sessionID}/context", "v2.session.context") .at((ctx) => ({ path: route("/api/session/{sessionID}/context", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/pending", "v2.session.pending.list") .seeded((ctx) => ctx.session({ title: "Pending list owner" })) @@ -1102,28 +1009,28 @@ const scenarios: Scenario[] = [ headers: { ...ctx.headers(), "content-type": "application/json" }, body: { messageID: "msg_httpapi_missing" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/revert/clear", "v2.session.revert.clear") .at((ctx) => ({ path: route("/api/session/{sessionID}/revert/clear", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/revert/commit", "v2.session.revert.commit") .at((ctx) => ({ path: route("/api/session/{sessionID}/revert/commit", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/message", "v2.session.messages") .at((ctx) => ({ path: route("/api/session/{sessionID}/message", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/message", "v2.session.messages.params") .at((ctx) => ({ @@ -1133,7 +1040,7 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/message", "v2.session.messages.cursor") .at((ctx) => ({ @@ -1144,7 +1051,7 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/message", "v2.session.messages.cursor.invalid") .seeded((ctx) => ctx.session({ title: "Invalid message cursor owner" })) @@ -1155,7 +1062,7 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .status(400, undefined, "none"), + .status(400, undefined), http.protected .get("/api/session/{sessionID}/history", "v2.session.history") .seeded((ctx) => ctx.session({ title: "Session history" })) @@ -1166,22 +1073,18 @@ const scenarios: Scenario[] = [ })}`, headers: ctx.headers(), })) - .json( - 200, - (body) => { - object(body) - array(body.data) - check(typeof body.hasMore === "boolean", "Expected a history exhaustion signal") - }, - "none", - ), + .json(200, (body) => { + object(body) + array(body.data) + check(typeof body.hasMore === "boolean", "Expected a history exhaustion signal") + }), http.protected .get("/api/session/{sessionID}/history", "v2.session.history.missing") .at((ctx) => ({ path: route("/api/session/{sessionID}/history", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .get("/api/session/{sessionID}/history", "v2.session.history.invalid") .seeded((ctx) => ctx.session({ title: "Invalid history sequence" })) @@ -1189,14 +1092,14 @@ const scenarios: Scenario[] = [ path: `${route("/api/session/{sessionID}/history", { sessionID: ctx.state.id })}?after=-1`, headers: ctx.headers(), })) - .json(400, object, "status"), + .json(400, object), http.protected .get("/api/session/{sessionID}/event", "v2.session.events.missing") .at((ctx) => ({ path: `${route("/api/session/{sessionID}/event", { sessionID: "ses_httpapi_missing" })}?after=0`, headers: ctx.headers(), })) - .status(404, undefined, "status"), + .status(404, undefined), http.protected .post("/api/session/{sessionID}/interrupt", "v2.session.interrupt") .seeded((ctx) => ctx.session({ title: "Interrupt session" })) @@ -1204,7 +1107,7 @@ const scenarios: Scenario[] = [ path: route("/api/session/{sessionID}/interrupt", { sessionID: ctx.state.id }), headers: ctx.headers(), })) - .status(204, undefined, "none"), + .status(204, undefined), http.protected .get("/api/session/{sessionID}/message/{messageID}", "v2.session.message.missing") .at((ctx) => ({ @@ -1214,7 +1117,7 @@ const scenarios: Scenario[] = [ }), headers: ctx.headers(), })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/api/session/{sessionID}/prompt", "v2.session.prompt.invalid") .seeded((ctx) => ctx.session({ title: "Invalid prompt owner" })) @@ -1223,21 +1126,21 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: {}, })) - .status(400, undefined, "none"), + .status(400, undefined), http.protected .post("/api/session/{sessionID}/compact", "v2.session.compact") .at((ctx) => ({ path: route("/api/session/{sessionID}/compact", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .status(404, undefined, "status"), + .status(404, undefined), http.protected .post("/api/session/{sessionID}/wait", "v2.session.wait") .at((ctx) => ({ path: route("/api/session/{sessionID}/wait", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), })) - .status(404, undefined, "status"), + .status(404, undefined), http.protected .get("/session", "session.list") .seeded((ctx) => ctx.session({ title: "List me" })) @@ -1255,17 +1158,12 @@ const scenarios: Scenario[] = [ .json(200, object), http.protected .post("/session", "session.create") - .mutating() .at((ctx) => ({ path: "/session", headers: ctx.headers(), body: { title: "Created session" } })) - .json( - 200, - (body, ctx) => { - object(body) - check(body.title === "Created session", "created session should use requested title") - check(body.directory === ctx.directory, "created session should use scenario directory") - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.title === "Created session", "created session should use requested title") + check(body.directory === ctx.directory, "created session should use scenario directory") + }), http.protected .get("/session/{sessionID}", "session.get") .seeded((ctx) => ctx.session({ title: "Get me" })) @@ -1284,24 +1182,18 @@ const scenarios: Scenario[] = [ .status(404), http.protected .patch("/session/{sessionID}", "session.update") - .mutating() .seeded((ctx) => ctx.session({ title: "Before rename" })) .at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: ctx.state.id }), headers: ctx.headers(), body: { title: "After rename" }, })) - .json( - 200, - (body) => { - object(body) - check(body.title === "After rename", "updated session should use new title") - }, - "status", - ), + .json(200, (body) => { + object(body) + check(body.title === "After rename", "updated session should use new title") + }), http.protected .patch("/session/{sessionID}", "session.update.invalid") - .mutating() .at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: "ses_httpapi_missing" }), headers: ctx.headers(), @@ -1310,7 +1202,6 @@ const scenarios: Scenario[] = [ .status(400), http.protected .delete("/session/{sessionID}", "session.delete") - .mutating() .seeded((ctx) => ctx.session({ title: "Delete me" })) .at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: ctx.state.id }), headers: ctx.headers() })) .jsonEffect(200, (body, ctx) => @@ -1378,7 +1269,6 @@ const scenarios: Scenario[] = [ }), http.protected .patch("/session/{sessionID}/message/{messageID}/part/{partID}", "part.update") - .mutating() .seeded((ctx) => Effect.gen(function* () { const session = yield* ctx.session({ title: "Part update session" }) @@ -1395,17 +1285,12 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { ...ctx.state.message.part, text: "after" }, })) - .json( - 200, - (body) => { - object(body) - check(body.type === "text" && body.text === "after", "updated part should be returned") - }, - "status", - ), + .json(200, (body) => { + object(body) + check(body.type === "text" && body.text === "after", "updated part should be returned") + }), http.protected .delete("/session/{sessionID}/message/{messageID}/part/{partID}", "part.delete") - .mutating() .seeded((ctx) => Effect.gen(function* () { const session = yield* ctx.session({ title: "Part delete session" }) @@ -1430,7 +1315,6 @@ const scenarios: Scenario[] = [ ), http.protected .delete("/session/{sessionID}/message/{messageID}", "session.deleteMessage") - .mutating() .seeded((ctx) => Effect.gen(function* () { const session = yield* ctx.session({ title: "Message delete session" }) @@ -1453,24 +1337,18 @@ const scenarios: Scenario[] = [ ), http.protected .post("/session/{sessionID}/fork", "session.fork") - .mutating() .seeded((ctx) => ctx.session({ title: "Fork source" })) .at((ctx) => ({ path: route("/session/{sessionID}/fork", { sessionID: ctx.state.id }), headers: ctx.headers(), body: {}, })) - .json( - 200, - (body) => { - object(body) - check(typeof body.id === "string", "fork should return a session") - }, - "status", - ), + .json(200, (body) => { + object(body) + check(typeof body.id === "string", "fork should return a session") + }), http.protected .post("/session/{sessionID}/abort", "session.abort") - .mutating() .seeded((ctx) => ctx.session({ title: "Abort session" })) .at((ctx) => ({ path: route("/session/{sessionID}/abort", { sessionID: ctx.state.id }), headers: ctx.headers() })) .json(200, (body) => { @@ -1487,7 +1365,7 @@ const scenarios: Scenario[] = [ }), http.protected .post("/session/{sessionID}/init", "session.init") - .preserveDatabase() + .preserveState() .withLlm() .seeded((ctx) => Effect.gen(function* () { @@ -1511,7 +1389,7 @@ const scenarios: Scenario[] = [ ), http.protected .post("/session/{sessionID}/message", "session.prompt") - .preserveDatabase() + .preserveState() .withLlm() .seeded((ctx) => Effect.gen(function* () { @@ -1530,23 +1408,20 @@ const scenarios: Scenario[] = [ parts: [{ type: "text", text: "hello llm" }], }, })) - .jsonEffect( - 200, - (body, ctx) => - Effect.gen(function* () { - object(body) - check(isRecord(body.info) && body.info.role === "assistant", "prompt should return assistant message") - check( - Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.text === "fake assistant"), - "assistant message should use fake LLM text", - ) - yield* ctx.llmWait(1) - }), - "status", + .jsonEffect(200, (body, ctx) => + Effect.gen(function* () { + object(body) + check(isRecord(body.info) && body.info.role === "assistant", "prompt should return assistant message") + check( + Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.text === "fake assistant"), + "assistant message should use fake LLM text", + ) + yield* ctx.llmWait(1) + }), ), http.protected .post("/session/{sessionID}/prompt_async", "session.prompt_async") - .preserveDatabase() + .preserveState() .withLlm() .seeded((ctx) => Effect.gen(function* () { @@ -1572,7 +1447,7 @@ const scenarios: Scenario[] = [ ), http.protected .post("/session/{sessionID}/command", "session.command") - .preserveDatabase() + .preserveState() .withLlm() .seeded((ctx) => Effect.gen(function* () { @@ -1587,41 +1462,33 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { command: "init", arguments: "", model: "test/test-model" }, })) - .jsonEffect( - 200, - (body, ctx) => - Effect.gen(function* () { - object(body) - check(isRecord(body.info) && body.info.role === "assistant", "command should return assistant message") - yield* ctx.llmWait(1) - }), - "status", + .jsonEffect(200, (body, ctx) => + Effect.gen(function* () { + object(body) + check(isRecord(body.info) && body.info.role === "assistant", "command should return assistant message") + yield* ctx.llmWait(1) + }), ), http.protected .post("/session/{sessionID}/shell", "session.shell") - .preserveDatabase() - .mutating() + .preserveState() .seeded((ctx) => ctx.session({ title: "Shell session" })) .at((ctx) => ({ path: route("/session/{sessionID}/shell", { sessionID: ctx.state.id }), headers: ctx.headers(), body: { agent: "build", model: { providerID: "test", modelID: "test-model" }, command: "printf shell-ok" }, })) - .json( - 200, - (body) => { - object(body) - check(isRecord(body.info) && body.info.role === "assistant", "shell should return assistant message") - check( - Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.type === "tool"), - "shell should return a tool part", - ) - }, - "status", - ), + .json(200, (body) => { + object(body) + check(isRecord(body.info) && body.info.role === "assistant", "shell should return assistant message") + check( + Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.type === "tool"), + "shell should return a tool part", + ) + }), http.protected .post("/session/{sessionID}/summarize", "session.summarize") - .preserveDatabase() + .preserveState() .withLlm() .seeded((ctx) => Effect.gen(function* () { @@ -1654,23 +1521,19 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { providerID: "test", modelID: "test-model", auto: false }, })) - .jsonEffect( - 200, - (body, ctx) => - Effect.gen(function* () { - check(body === true, "summarize should return true") - const messages = yield* ctx.messages(ctx.state.id) - check( - messages.some((message) => message.info.role === "assistant" && message.info.summary === true), - "summarize should create a summary assistant message", - ) - yield* ctx.llmWait(1) - }), - "status", + .jsonEffect(200, (body, ctx) => + Effect.gen(function* () { + check(body === true, "summarize should return true") + const messages = yield* ctx.messages(ctx.state.id) + check( + messages.some((message) => message.info.role === "assistant" && message.info.summary === true), + "summarize should create a summary assistant message", + ) + yield* ctx.llmWait(1) + }), ), http.protected .post("/session/{sessionID}/revert", "session.revert") - .mutating() .seeded((ctx) => Effect.gen(function* () { const session = yield* ctx.session({ title: "Revert session" }) @@ -1683,34 +1546,25 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { messageID: ctx.state.message.info.id }, })) - .json( - 200, - (body, ctx) => { - object(body) - check(body.id === ctx.state.session.id, "revert should return the session") - check( - isRecord(body.revert) && body.revert.messageID === ctx.state.message.info.id, - "revert should record reverted message", - ) - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.id === ctx.state.session.id, "revert should return the session") + check( + isRecord(body.revert) && body.revert.messageID === ctx.state.message.info.id, + "revert should record reverted message", + ) + }), http.protected .post("/session/{sessionID}/unrevert", "session.unrevert") - .mutating() .seeded((ctx) => ctx.session({ title: "Unrevert session" })) .at((ctx) => ({ path: route("/session/{sessionID}/unrevert", { sessionID: ctx.state.id }), headers: ctx.headers(), })) - .json( - 200, - (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "unrevert should return the session") - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.id === ctx.state.id, "unrevert should return the session") + }), http.protected .post("/session/{sessionID}/permissions/{permissionID}", "permission.respond") .seeded((ctx) => ctx.session({ title: "Deprecated permission session" })) @@ -1722,51 +1576,41 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { response: "once" }, })) - .json(404, object, "status"), + .json(404, object), http.protected .post("/session/{sessionID}/share", "session.share") - .mutating() .seeded((ctx) => ctx.session({ title: "Share session" })) .at((ctx) => ({ path: route("/session/{sessionID}/share", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json( - 200, - (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "share should return the session") - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.id === ctx.state.id, "share should return the session") + }), http.protected .delete("/session/{sessionID}/share", "session.unshare") - .mutating() .seeded((ctx) => ctx.session({ title: "Unshare session" })) .at((ctx) => ({ path: route("/session/{sessionID}/share", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json( - 200, - (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "unshare should return the session") - }, - "status", - ), + .json(200, (body, ctx) => { + object(body) + check(body.id === ctx.state.id, "unshare should return the session") + }), http.protected .post("/tui/append-prompt", "tui.appendPrompt") .at((ctx) => ({ path: "/tui/append-prompt", headers: ctx.headers(), body: { text: "hello" } })) - .json(200, boolean, "status"), + .json(200, boolean), http.protected .post("/tui/select-session", "tui.selectSession.invalid") .at((ctx) => ({ path: "/tui/select-session", headers: ctx.headers(), body: { sessionID: "invalid" } })) .status(400), - http.protected.post("/tui/open-help", "tui.openHelp").json(200, boolean, "status"), - http.protected.post("/tui/open-sessions", "tui.openSessions").json(200, boolean, "status"), - http.protected.post("/tui/open-themes", "tui.openThemes").json(200, boolean, "status"), - http.protected.post("/tui/open-models", "tui.openModels").json(200, boolean, "status"), - http.protected.post("/tui/submit-prompt", "tui.submitPrompt").json(200, boolean, "status"), - http.protected.post("/tui/clear-prompt", "tui.clearPrompt").json(200, boolean, "status"), + http.protected.post("/tui/open-help", "tui.openHelp").json(200, boolean), + http.protected.post("/tui/open-sessions", "tui.openSessions").json(200, boolean), + http.protected.post("/tui/open-themes", "tui.openThemes").json(200, boolean), + http.protected.post("/tui/open-models", "tui.openModels").json(200, boolean), + http.protected.post("/tui/submit-prompt", "tui.submitPrompt").json(200, boolean), + http.protected.post("/tui/clear-prompt", "tui.clearPrompt").json(200, boolean), http.protected .post("/tui/execute-command", "tui.executeCommand") .at((ctx) => ({ path: "/tui/execute-command", headers: ctx.headers(), body: { command: "agent_cycle" } })) - .json(200, boolean, "status"), + .json(200, boolean), http.protected .post("/tui/show-toast", "tui.showToast") .at((ctx) => ({ @@ -1774,7 +1618,7 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { title: "Exercise", message: "covered", variant: "info", duration: 1000 }, })) - .json(200, boolean, "status"), + .json(200, boolean), http.protected .post("/tui/publish", "tui.publish") .at((ctx) => ({ @@ -1782,30 +1626,25 @@ const scenarios: Scenario[] = [ headers: ctx.headers(), body: { type: "tui.prompt.append", properties: { text: "published" } }, })) - .json(200, boolean, "status"), + .json(200, boolean), http.protected .post("/tui/select-session", "tui.selectSession") .seeded((ctx) => ctx.session({ title: "TUI select" })) .at((ctx) => ({ path: "/tui/select-session", headers: ctx.headers(), body: { sessionID: ctx.state.id } })) - .json(200, boolean, "status"), + .json(200, boolean), http.protected .post("/tui/control/response", "tui.control.response") .at((ctx) => ({ path: "/tui/control/response", headers: ctx.headers(), body: { ok: true } })) - .json(200, boolean, "status"), + .json(200, boolean), http.protected .get("/tui/control/next", "tui.control.next") - .mutating() .seeded((ctx) => ctx.tuiRequest({ path: "/tui/exercise", body: { text: "queued" } })) - .json( - 200, - (body) => { - object(body) - check(body.path === "/tui/exercise", "control next should return queued path") - object(body.body) - check(body.body.text === "queued", "control next should return queued body") - }, - "status", - ), + .json(200, (body) => { + object(body) + check(body.path === "/tui/exercise", "control next should return queued path") + object(body.body) + check(body.body.text === "queued", "control next should return queued body") + }), http.protected .post("/global/upgrade", "global.upgrade") .global() @@ -1823,9 +1662,14 @@ const llmScenarios = new Set([ ]) const main = Effect.gen(function* () { - yield* Effect.addFinalizer(() => Effect.promise(() => disposeApps()).pipe(Effect.andThen(cleanupExercisePaths))) const options = parseOptions(Bun.argv.slice(2)) const modules = yield* Effect.promise(() => runtime()) + yield* Effect.addFinalizer(() => + Effect.promise(async () => { + await disposeApps() + await modules.disposeAllInstances() + }).pipe(Effect.andThen(cleanupExercisePaths)), + ) const effectRoutes = routeKeys(OpenApi.fromApi(modules.PublicApi)) const selected = selectedScenarios(options, scenarios) const missing = effectRoutes.filter((route) => !scenarios.some((scenario) => route === routeKey(scenario))) diff --git a/packages/opencode/test/server/httpapi-exercise/report.ts b/packages/opencode/test/server/httpapi-exercise/report.ts index 7e79e972cb6e..1bc4aef33b22 100644 --- a/packages/opencode/test/server/httpapi-exercise/report.ts +++ b/packages/opencode/test/server/httpapi-exercise/report.ts @@ -1,5 +1,6 @@ import { Duration } from "effect" import { indent, pad } from "./assertions" +import { routeKey } from "./routing" import type { Options, Result, Scenario } from "./types" export const color = { @@ -60,7 +61,3 @@ export function printResults(results: Result[], missing: string[], extra: Scenar `\n${color.dim}summary pass=${results.filter((result) => result.status === "pass").length} fail=${results.filter((result) => result.status === "fail").length} skip=${results.filter((result) => result.status === "skip").length} missing=${missing.length} extra=${extra.length}${color.reset}`, ) } - -function routeKey(scenario: Scenario) { - return `${scenario.method} ${scenario.path}` -} diff --git a/packages/opencode/test/server/httpapi-exercise/runner.ts b/packages/opencode/test/server/httpapi-exercise/runner.ts index 37e24b790bf2..203921e918a8 100644 --- a/packages/opencode/test/server/httpapi-exercise/runner.ts +++ b/packages/opencode/test/server/httpapi-exercise/runner.ts @@ -3,9 +3,6 @@ import { ConfigV1 } from "@opencode-ai/core/v1/config/config" import { SessionV1 } from "@opencode-ai/core/v1/session" import { Cause, Duration, Effect, Layer, Scope } from "effect" import { TestLLMServer } from "../../lib/llm-server" -import type { Config } from "../../../src/config/config" - -import type { MessageV2 } from "../../../src/session/message-v2" import { MessageID, PartID } from "../../../src/session/schema" import { call, callAuthProbe, disposeApps } from "./backend" import { original } from "./environment" @@ -38,7 +35,7 @@ function runActive(options: Options, scenario: ActiveScenario) { const result = yield* call(scenario, ctx) yield* trace(options, scenario, `response ${result.status}`) yield* trace(options, scenario, "expect start") - yield* scenario.expect(ctx, ctx.state, result) + yield* scenario.expect(ctx, result) yield* trace(options, scenario, "expect done") }), ) diff --git a/packages/opencode/test/server/httpapi-exercise/runtime.ts b/packages/opencode/test/server/httpapi-exercise/runtime.ts index b7a3952bde01..40d87f9d8417 100644 --- a/packages/opencode/test/server/httpapi-exercise/runtime.ts +++ b/packages/opencode/test/server/httpapi-exercise/runtime.ts @@ -7,7 +7,6 @@ export type Runtime = { InstanceStore: (typeof import("../../../src/project/instance-store"))["InstanceStore"] Session: (typeof import("../../../src/session/session"))["Session"] Worktree: (typeof import("../../../src/worktree"))["Worktree"] - Project: (typeof import("../../../src/project/project"))["Project"] Tui: typeof import("../../../src/server/shared/tui-control") disposeAllInstances: (typeof import("../../fixture/fixture"))["disposeAllInstances"] tmpdir: (typeof import("../../fixture/fixture"))["tmpdir"] @@ -26,7 +25,6 @@ export function runtime() { const instanceStore = await import("../../../src/project/instance-store") const session = await import("../../../src/session/session") const worktree = await import("../../../src/worktree") - const project = await import("../../../src/project/project") const tui = await import("../../../src/server/shared/tui-control") const fixture = await import("../../fixture/fixture") const db = await import("../../fixture/db") @@ -39,7 +37,6 @@ export function runtime() { InstanceStore: instanceStore.InstanceStore, Session: session.Session, Worktree: worktree.Worktree, - Project: project.Project, Tui: tui, disposeAllInstances: fixture.disposeAllInstances, tmpdir: fixture.tmpdir, diff --git a/packages/opencode/test/server/httpapi-exercise/types.ts b/packages/opencode/test/server/httpapi-exercise/types.ts index 08952165050f..e68024e0df1f 100644 --- a/packages/opencode/test/server/httpapi-exercise/types.ts +++ b/packages/opencode/test/server/httpapi-exercise/types.ts @@ -1,10 +1,8 @@ import type { Duration, Effect } from "effect" import { ConfigV1 } from "@opencode-ai/core/v1/config/config" import { SessionV1 } from "@opencode-ai/core/v1/session" -import type { Config } from "../../../src/config/config" import type { Project } from "../../../src/project/project" import type { Worktree } from "../../../src/worktree" -import type { MessageV2 } from "../../../src/session/message-v2" import type { SessionID } from "../../../src/session/schema" export const OpenApiMethods = ["get", "post", "put", "delete", "patch"] as const @@ -13,7 +11,6 @@ export const Methods = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const export type Method = (typeof Methods)[number] export type OpenApiMethod = (typeof OpenApiMethods)[number] export type Mode = "effect" | "coverage" | "auth" -export type Comparison = "none" | "status" | "json" export type CaptureMode = "full" | "stream" export type AuthPolicy = "protected" | "public" | "public-bypass" | "ticket-bypass" export type ProjectOptions = { git?: boolean; config?: Partial; llm?: boolean } @@ -80,12 +77,10 @@ export type ActiveScenario = { name: string project: ProjectOptions | undefined seed: (ctx: ScenarioContext) => Effect.Effect - request: (ctx: ScenarioContext, state: unknown) => RequestSpec + request: (ctx: SeededContext) => RequestSpec authProbe: RequestSpec | undefined - expect: (ctx: ScenarioContext, state: unknown, result: CallResult) => Effect.Effect - compare: Comparison + expect: (ctx: SeededContext, result: CallResult) => Effect.Effect capture: CaptureMode - mutates: boolean reset: boolean auth: AuthPolicy } @@ -99,7 +94,6 @@ export type BuilderState = { request: (ctx: SeededContext) => RequestSpec authProbe: RequestSpec | undefined capture: CaptureMode - mutates: boolean reset: boolean auth: AuthPolicy } From 680ed534cd85b589d4fd09a548ef489b2ce5ec78 Mon Sep 17 00:00:00 2001 From: Kit Langton Date: Mon, 13 Jul 2026 12:49:33 -0400 Subject: [PATCH 2/2] test(opencode): remove obsolete HTTP API exerciser --- packages/opencode/package.json | 1 - packages/opencode/script/httpapi-exercise.ts | 1 - .../server/httpapi-exercise/assertions.ts | 64 - .../test/server/httpapi-exercise/backend.ts | 144 -- .../test/server/httpapi-exercise/dsl.ts | 162 -- .../server/httpapi-exercise/environment.ts | 40 - .../test/server/httpapi-exercise/index.ts | 1718 ----------------- .../test/server/httpapi-exercise/report.ts | 63 - .../test/server/httpapi-exercise/routing.ts | 96 - .../test/server/httpapi-exercise/runner.ts | 263 --- .../test/server/httpapi-exercise/runtime.ts | 46 - .../test/server/httpapi-exercise/types.ts | 115 -- 12 files changed, 2713 deletions(-) delete mode 100644 packages/opencode/script/httpapi-exercise.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/assertions.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/backend.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/dsl.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/environment.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/index.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/report.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/routing.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/runner.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/runtime.ts delete mode 100644 packages/opencode/test/server/httpapi-exercise/types.ts diff --git a/packages/opencode/package.json b/packages/opencode/package.json index f1695e9d89af..01aadda6fa9a 100644 --- a/packages/opencode/package.json +++ b/packages/opencode/package.json @@ -8,7 +8,6 @@ "scripts": { "typecheck": "tsgo --noEmit", "test": "bun test --timeout 30000 --only-failures", - "test:httpapi": "bun run script/httpapi-exercise.ts --mode coverage --fail-on-missing --fail-on-skip && bun run script/httpapi-exercise.ts --mode auth --fail-on-missing --fail-on-skip && bun run script/httpapi-exercise.ts --mode effect --fail-on-missing --fail-on-skip", "bench:test": "bun run script/bench-test-suite.ts", "profile:test": "bun run script/profile-test-files.ts", "build": "bun run script/build.ts", diff --git a/packages/opencode/script/httpapi-exercise.ts b/packages/opencode/script/httpapi-exercise.ts deleted file mode 100644 index 5395a812f550..000000000000 --- a/packages/opencode/script/httpapi-exercise.ts +++ /dev/null @@ -1 +0,0 @@ -await import("../test/server/httpapi-exercise/index") diff --git a/packages/opencode/test/server/httpapi-exercise/assertions.ts b/packages/opencode/test/server/httpapi-exercise/assertions.ts deleted file mode 100644 index c59acfb36618..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/assertions.ts +++ /dev/null @@ -1,64 +0,0 @@ -import type { CallResult, JsonObject } from "./types" - -export function parse(text: string): unknown { - if (!text) return undefined - try { - return JSON.parse(text) as unknown - } catch { - return text - } -} - -export function looksJson(result: CallResult) { - return result.contentType.includes("application/json") || result.text.startsWith("{") || result.text.startsWith("[") -} - -export function stable(value: unknown): string { - return JSON.stringify(sort(value)) -} - -function sort(value: unknown): unknown { - if (Array.isArray(value)) return value.map(sort) - if (!value || typeof value !== "object") return value - return Object.fromEntries( - Object.entries(value) - .sort(([left], [right]) => left.localeCompare(right)) - .map(([key, item]) => [key, sort(item)]), - ) -} - -export function array(value: unknown): asserts value is unknown[] { - if (!Array.isArray(value)) throw new Error("expected array") -} - -export function object(value: unknown): asserts value is JsonObject { - if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("expected object") -} - -export function boolean(value: unknown): asserts value is boolean { - if (typeof value !== "boolean") throw new Error("expected boolean") -} - -export function isRecord(value: unknown): value is JsonObject { - return !!value && typeof value === "object" && !Array.isArray(value) -} - -export function check(value: boolean, message: string): asserts value { - if (!value) throw new Error(message) -} - -export function message(error: unknown) { - if (error instanceof Error) return error.message - return String(error) -} - -export function pad(value: string, size: number) { - return value.length >= size ? value : value + " ".repeat(size - value.length) -} - -export function indent(value: string) { - return value - .split("\n") - .map((line) => ` ${line}`) - .join("\n") -} diff --git a/packages/opencode/test/server/httpapi-exercise/backend.ts b/packages/opencode/test/server/httpapi-exercise/backend.ts deleted file mode 100644 index dd63ea118a9c..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/backend.ts +++ /dev/null @@ -1,144 +0,0 @@ -import { ConfigProvider, Effect, Layer } from "effect" -import { HttpRouter } from "effect/unstable/http" -import { parse } from "./assertions" -import { runtime, type Runtime } from "./runtime" -import type { ActiveScenario, BackendApp, CallResult, CaptureMode, SeededContext } from "./types" - -type CallOptions = { - auth?: { - password?: string - username?: string - } -} - -export function call(scenario: ActiveScenario, ctx: SeededContext) { - return Effect.promise(async () => - capture(await app(await runtime(), {}).request(toRequest(scenario, ctx)), scenario.capture), - ) -} - -export function callAuthProbe(scenario: ActiveScenario, credentials: "missing" | "valid" = "missing") { - return Effect.promise(async () => { - const controller = new AbortController() - return Promise.race([ - Promise.resolve( - app(await runtime(), { auth: { password: "secret" } }).request( - toAuthProbeRequest(scenario, credentials, controller.signal), - ), - ).then((response) => capture(response, scenario.capture)), - Bun.sleep(1_000).then(() => { - controller.abort("auth probe timed out") - return { - status: 0, - contentType: "", - text: "auth probe timed out", - body: undefined, - timedOut: true, - } - }), - ]) - }) -} - -type CachedApp = BackendApp & { readonly dispose: () => Promise } - -const appCache: Partial> = {} - -export async function disposeApps() { - const apps = Object.values(appCache) - for (const key of Object.keys(appCache)) delete appCache[key] - await Promise.all(apps.flatMap((app) => (app === undefined ? [] : [app.dispose()]))) -} - -function app(modules: Runtime, options: CallOptions) { - const username = options.auth?.username - const password = options.auth?.password - const cacheKey = `${username ?? ""}:${password ?? ""}` - if (appCache[cacheKey]) return appCache[cacheKey] - - const web = HttpRouter.toWebHandler( - modules.HttpApiApp.routes.pipe( - Layer.provide( - ConfigProvider.layer( - ConfigProvider.fromUnknown({ OPENCODE_SERVER_PASSWORD: password, OPENCODE_SERVER_USERNAME: username }), - ), - ), - ), - { disableLogger: true, memoMap: modules.memoMap }, - ) - return (appCache[cacheKey] = { - dispose: web.dispose, - request(input: string | URL | Request, init?: RequestInit) { - return web.handler( - input instanceof Request ? input : new Request(new URL(input, "http://localhost"), init), - modules.HttpApiApp.context, - ) - }, - }) -} - -function toRequest(scenario: ActiveScenario, ctx: SeededContext) { - const spec = scenario.request(ctx) - return new Request(new URL(spec.path, "http://localhost"), { - method: scenario.method, - headers: spec.body === undefined ? spec.headers : { "content-type": "application/json", ...spec.headers }, - body: spec.body === undefined ? undefined : JSON.stringify(spec.body), - }) -} - -function toAuthProbeRequest(scenario: ActiveScenario, credentials: "missing" | "valid", signal: AbortSignal) { - const spec = scenario.authProbe ?? { - path: authProbePath(scenario.path), - body: scenario.method === "GET" ? undefined : {}, - } - const headers = { - ...(spec.body === undefined ? {} : { "content-type": "application/json" }), - ...spec.headers, - ...(credentials === "valid" ? { authorization: basic("opencode", "secret") } : {}), - } - return new Request(new URL(spec.path, "http://localhost"), { - method: scenario.method, - headers, - body: spec.body === undefined ? undefined : JSON.stringify(spec.body), - signal, - }) -} - -function basic(username: string, password: string) { - return `Basic ${Buffer.from(`${username}:${password}`).toString("base64")}` -} - -function authProbePath(path: string) { - return path - .replace(/\{([^}]+)\}/g, (_match, key: string) => `auth_${key}`) - .replace(/:([^/]+)/g, (_match, key: string) => `auth_${key}`) -} - -async function capture(response: Response, mode: CaptureMode): Promise { - const text = mode === "stream" ? await captureStream(response) : await response.text() - return { - status: response.status, - contentType: response.headers.get("content-type") ?? "", - text, - body: parse(text), - timedOut: false, - } -} - -async function captureStream(response: Response) { - if (!response.body) return "" - const reader = response.body.getReader() - const read = reader.read().then( - (result) => ({ result }), - (error: unknown) => ({ error }), - ) - const winner = await Promise.race([read, Bun.sleep(1_000).then(() => ({ timeout: true }))]) - if ("timeout" in winner) { - await reader.cancel("timed out waiting for stream chunk").catch(() => undefined) - throw new Error("timed out waiting for stream chunk") - } - if ("error" in winner) throw winner.error - await reader.cancel().catch(() => undefined) - if (winner.result.done) return "" - return new TextDecoder().decode(winner.result.value) -} diff --git a/packages/opencode/test/server/httpapi-exercise/dsl.ts b/packages/opencode/test/server/httpapi-exercise/dsl.ts deleted file mode 100644 index f4539deee44a..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/dsl.ts +++ /dev/null @@ -1,162 +0,0 @@ -import { Effect } from "effect" -import { looksJson } from "./assertions" -import type { - ActiveScenario, - AuthPolicy, - BuilderState, - CallResult, - Method, - ProjectOptions, - RequestSpec, - ScenarioContext, - SeededContext, - TodoScenario, -} from "./types" - -class ScenarioBuilder { - private readonly state: BuilderState - - constructor(method: Method, path: string, name: string, auth: AuthPolicy) { - this.state = { - method, - path, - name, - project: { git: true }, - // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- The unseeded builder state is intentionally undefined until `.seeded(...)` narrows it. - seed: () => Effect.succeed(undefined as S), - request: (ctx) => ({ path, headers: ctx.headers() }), - authProbe: undefined, - capture: "full", - reset: true, - auth, - } - } - - global() { - return this.clone({ project: undefined, request: () => ({ path: this.state.path }) }) - } - - inProject(project: ProjectOptions = { git: true }) { - return this.clone({ project }) - } - - withLlm() { - return this.clone({ project: { ...(this.state.project ?? { git: true }), llm: true } }) - } - - at(request: BuilderState["request"]) { - return this.clone({ request }) - } - - probe(authProbe: RequestSpec) { - return this.clone({ authProbe }) - } - - preserveState() { - return this.clone({ reset: false }) - } - - stream() { - return this.clone({ capture: "stream" }) - } - - status(status = 200, inspect?: (ctx: SeededContext, result: CallResult) => Effect.Effect) { - return this.done((ctx, result) => - Effect.gen(function* () { - if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`) - if (inspect) yield* inspect(ctx, result) - }), - ) - } - - /** Assert JSON status/content-type plus an optional synchronous body check. */ - json(status = 200, inspect?: (body: unknown, ctx: SeededContext) => void) { - return this.jsonEffect(status, inspect ? (body, ctx) => Effect.sync(() => inspect(body, ctx)) : undefined) - } - - /** Assert JSON status/content-type plus optional Effect assertions, e.g. DB side effects. */ - jsonEffect(status = 200, inspect?: (body: unknown, ctx: SeededContext) => Effect.Effect) { - return this.done((ctx, result) => - Effect.gen(function* () { - if (result.status !== status) throw new Error(`expected ${status}, got ${result.status}: ${result.text}`) - if (!looksJson(result)) - throw new Error(`expected JSON response, got ${result.contentType || "no content-type"}`) - if (inspect) yield* inspect(result.body, ctx) - }), - ) - } - - private clone(next: Partial>) { - const builder = new ScenarioBuilder(this.state.method, this.state.path, this.state.name, this.state.auth) - Object.assign(builder.state, this.state, next) - return builder - } - - /** - * Seed typed state before the HTTP request. The returned value becomes `ctx.state` - * for `.at(...)` and assertions, giving stateful route tests type-safe setup. - */ - seeded(seed: (ctx: ScenarioContext) => Effect.Effect) { - const builder = new ScenarioBuilder(this.state.method, this.state.path, this.state.name, this.state.auth) - Object.assign(builder.state, this.state, { seed }) - return builder - } - - private done(expect: (ctx: SeededContext, result: CallResult) => Effect.Effect): ActiveScenario { - const state = this.state - return { - kind: "active", - method: state.method, - path: state.path, - name: state.name, - project: state.project, - seed: state.seed, - authProbe: state.authProbe, - // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- `.seeded(...)` preserves the paired request/state type inside the builder. - request: (ctx) => state.request(ctx as SeededContext), - // oxlint-disable-next-line typescript-eslint/no-unsafe-type-assertion -- `.seeded(...)` preserves the paired assertion/state type inside the builder. - expect: (ctx, result) => expect(ctx as SeededContext, result), - capture: state.capture, - reset: state.reset, - auth: state.auth, - } - } -} - -const routes = (auth: AuthPolicy) => ({ - get: (path: string, name: string) => new ScenarioBuilder("GET", path, name, auth), - post: (path: string, name: string) => new ScenarioBuilder("POST", path, name, auth), - put: (path: string, name: string) => new ScenarioBuilder("PUT", path, name, auth), - patch: (path: string, name: string) => new ScenarioBuilder("PATCH", path, name, auth), - delete: (path: string, name: string) => new ScenarioBuilder("DELETE", path, name, auth), -}) - -export const http = { - protected: routes("protected"), - public: routes("public"), - publicBypass: routes("public-bypass"), - ticketBypass: routes("ticket-bypass"), -} - -export const pending = (method: Method, path: string, name: string, reason: string): TodoScenario => ({ - kind: "todo", - method, - path, - name, - reason, -}) - -export function route(template: string, params: Record) { - return Object.entries(params).reduce( - (next, [key, value]) => next.replaceAll(`{${key}}`, value).replaceAll(`:${key}`, value), - template, - ) -} - -export function controlledPtyInput(title: string | undefined) { - return { - command: "/bin/sh", - args: ["-c", "sleep 30"], - ...(title ? { title } : {}), - } -} diff --git a/packages/opencode/test/server/httpapi-exercise/environment.ts b/packages/opencode/test/server/httpapi-exercise/environment.ts deleted file mode 100644 index 9d3eaa0e5329..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/environment.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { Flag } from "@opencode-ai/core/flag/flag" -import { Effect } from "effect" -import path from "path" - -const preserveExerciseGlobalRoot = !!process.env.OPENCODE_HTTPAPI_EXERCISE_GLOBAL -export const exerciseGlobalRoot = - process.env.OPENCODE_HTTPAPI_EXERCISE_GLOBAL ?? - path.join(process.env.TMPDIR ?? "/tmp", `opencode-httpapi-global-${process.pid}`) -process.env.XDG_DATA_HOME = path.join(exerciseGlobalRoot, "data") -process.env.XDG_CONFIG_HOME = path.join(exerciseGlobalRoot, "config") -process.env.XDG_STATE_HOME = path.join(exerciseGlobalRoot, "state") -process.env.XDG_CACHE_HOME = path.join(exerciseGlobalRoot, "cache") -process.env.OPENCODE_DISABLE_SHARE = "true" -export const exerciseConfigDirectory = path.join(exerciseGlobalRoot, "config", "opencode") -export const exerciseDataDirectory = path.join(exerciseGlobalRoot, "data", "opencode") - -const preserveExerciseDatabase = !!process.env.OPENCODE_HTTPAPI_EXERCISE_DB -export const exerciseDatabasePath = - process.env.OPENCODE_HTTPAPI_EXERCISE_DB ?? - path.join(process.env.TMPDIR ?? "/tmp", `opencode-httpapi-exercise-${process.pid}.db`) -process.env.OPENCODE_DB = exerciseDatabasePath -Flag.OPENCODE_DB = exerciseDatabasePath - -export const original = { - OPENCODE_SERVER_PASSWORD: Flag.OPENCODE_SERVER_PASSWORD, - OPENCODE_SERVER_USERNAME: Flag.OPENCODE_SERVER_USERNAME, -} - -export const cleanupExercisePaths = Effect.promise(async () => { - const fs = await import("fs/promises") - if (!preserveExerciseDatabase) { - await Promise.all( - [exerciseDatabasePath, `${exerciseDatabasePath}-wal`, `${exerciseDatabasePath}-shm`].map((file) => - fs.rm(file, { force: true }).catch(() => undefined), - ), - ) - } - if (!preserveExerciseGlobalRoot) - await fs.rm(exerciseGlobalRoot, { recursive: true, force: true }).catch(() => undefined) -}) diff --git a/packages/opencode/test/server/httpapi-exercise/index.ts b/packages/opencode/test/server/httpapi-exercise/index.ts deleted file mode 100644 index 6726619372af..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/index.ts +++ /dev/null @@ -1,1718 +0,0 @@ -/** - * End-to-end exerciser for the Effect HttpApi routes. - * - * The goal is not to be a normal unit test file. This is a route-coverage harness: - * every public route should have a small scenario that proves the route decodes - * requests, uses the right instance context, mutates storage when expected, and - * returns the expected response shape. - * - * The script intentionally isolates `OPENCODE_DB` before importing modules that touch - * storage. Scenarios may create/delete sessions and reset the database after each run, - * so this must never point at a developer's real session database. - * - * DSL shape: - * - `http.protected.get/post/...` starts a scenario for one OpenAPI route key. - * - `.seeded(...)` creates typed per-scenario state using Effect helpers on `ctx`. - * - `.at(...)` builds the request from that typed state. - * - `.json(...)` / `.jsonEffect(...)` assert response shape and optional side effects. - * - Scenarios reset isolated runtime state by default; `.preserveState()` opts out. - */ -import { Effect } from "effect" -import { OpenApi } from "effect/unstable/httpapi" -import { TestLLMServer } from "../../lib/llm-server" -import path from "path" -import { array, boolean, check, isRecord, message, object, stable } from "./assertions" -import { controlledPtyInput, http, route } from "./dsl" -import { - cleanupExercisePaths, - exerciseConfigDirectory, - exerciseDataDirectory, - exerciseDatabasePath, - exerciseGlobalRoot, -} from "./environment" -import { color, printHeader, printResults } from "./report" -import { coverageResult, parseOptions, routeKey, routeKeys, selectedScenarios } from "./routing" -import { runScenario } from "./runner" -import { disposeApps } from "./backend" -import { runtime } from "./runtime" -import { type Scenario } from "./types" - -function cursor(input: Record) { - return Buffer.from(JSON.stringify(input)).toString("base64url") -} - -function data(validate: (value: any) => void) { - return (body: any) => { - object(body) - validate(body.data) - } -} - -function locationData(validate: (value: any) => void) { - return (body: any) => { - object(body) - object(body.location) - object(body.location.project) - validate(body.data) - } -} - -const scenarios: Scenario[] = [ - http.protected - .get("/global/health", "global.health") - .global() - .json(200, (body) => { - object(body) - check(body.healthy === true, "server should report healthy") - }), - http.protected - .get("/global/event", "global.event") - .global() - .stream() - .status(200, (_ctx, result) => - Effect.sync(() => { - check(result.contentType.includes("text/event-stream"), "global event should be an SSE stream") - check(result.text.includes("server.connected"), "global event should emit initial connection event") - }), - ), - http.protected.get("/global/config", "global.config.get").global().json(), - http.protected - .patch("/global/config", "global.config.update") - .global() - .seeded(() => - Effect.promise(() => - Bun.write( - path.join(exerciseConfigDirectory, "opencode.jsonc"), - JSON.stringify({ username: "httpapi-global" }, null, 2), - ), - ), - ) - .at(() => ({ path: "/global/config", body: { username: "httpapi-global" } })) - .jsonEffect(200, (body) => - Effect.gen(function* () { - object(body) - check(body.username === "httpapi-global", "global config update should return patched config") - const text = yield* Effect.promise(() => Bun.file(path.join(exerciseConfigDirectory, "opencode.jsonc")).text()) - check(text.includes('"username": "httpapi-global"'), "global config update should write isolated config file") - }), - ), - http.protected - .post("/global/dispose", "global.dispose") - .global() - .json(200, (body) => { - check(body === true, "global dispose should return true") - }), - http.protected.get("/path", "path.get").json(200, (body, ctx) => { - object(body) - check(body.directory === ctx.directory, "directory should resolve from x-opencode-directory") - check(body.worktree === ctx.directory, "worktree should resolve from x-opencode-directory") - }), - http.protected.get("/vcs", "vcs.get").json(), - http.protected.get("/vcs/status", "vcs.status").json(200, array), - http.protected - .get("/vcs/diff", "vcs.diff") - .at((ctx) => ({ path: "/vcs/diff?mode=git", headers: ctx.headers() })) - .json(200, array), - http.protected.get("/vcs/diff/raw", "vcs.diff.raw").status(200, (_ctx, result) => - Effect.sync(() => { - check(typeof result.text === "string", "raw VCS diff should return text") - }), - ), - http.protected - .post("/vcs/apply", "vcs.apply") - .inProject({ git: false }) - .at((ctx) => ({ path: "/vcs/apply", headers: ctx.headers(), body: { patch: "" } })) - .status(400, undefined), - http.protected.get("/command", "command.list").json(200, array), - http.protected.get("/agent", "app.agents").json(200, array), - http.protected.get("/skill", "app.skills").json(200, array), - http.protected.get("/lsp", "lsp.status").json(200, array), - http.protected.get("/formatter", "formatter.status").json(200, array), - http.protected.get("/config", "config.get").json(200, undefined), - http.protected - .patch("/config", "config.update") - .at((ctx) => ({ path: "/config", headers: ctx.headers(), body: { username: "httpapi-local" } })) - .json(200, (body) => { - object(body) - check(body.username === "httpapi-local", "local config update should return patched config") - }), - http.protected - .patch("/config", "config.update.invalid") - .at((ctx) => ({ path: "/config", headers: ctx.headers(), body: { username: 1 } })) - .status(400), - http.protected.get("/config/providers", "config.providers").json(), - http.protected.get("/project", "project.list").json(200, array), - http.protected.get("/project/current", "project.current").json(200, (body, ctx) => { - object(body) - check(body.worktree === ctx.directory, "current project should resolve from scenario directory") - }), - http.protected - .patch("/project/{projectID}", "project.update") - .seeded((ctx) => ctx.project()) - .at((ctx) => ({ - path: route("/project/{projectID}", { projectID: ctx.state.id }), - headers: ctx.headers(), - body: { name: "HTTP API Project", commands: { start: "bun --version" } }, - })) - .json(200, (body) => { - object(body) - check(body.name === "HTTP API Project", "project update should return patched name") - check( - isRecord(body.commands) && body.commands.start === "bun --version", - "project update should return patched command", - ) - }), - http.protected - .patch("/project/{projectID}", "project.update.missing") - .at((ctx) => ({ - path: route("/project/{projectID}", { projectID: "project_httpapi_missing" }), - headers: ctx.headers(), - body: { name: "Missing Project" }, - })) - .json(404, object), - http.protected - .post("/project/git/init", "project.initGit") - .inProject({ git: false }) - .json(200, (body, ctx) => { - object(body) - check(body.worktree === ctx.directory, "git init should return current project") - check(body.vcs === "git", "git init should mark the project as git-backed") - }), - http.protected - .get("/project/{projectID}/directories", "project.directories") - .seeded((ctx) => ctx.project()) - .at((ctx) => ({ - path: route("/project/{projectID}/directories", { projectID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, array), - http.protected - .post("/experimental/project/{projectID}/copy/generate-name", "experimental.projectCopy.generateName") - .seeded((ctx) => ctx.project()) - .at((ctx) => ({ - path: route("/experimental/project/{projectID}/copy/generate-name", { projectID: ctx.state.id }), - headers: ctx.headers(), - body: {}, - })) - .json(200, (body) => { - object(body) - check(typeof body.name === "string" && body.name.length > 0, "generated copy name should be non-empty") - }), - http.protected - .post("/experimental/project/{projectID}/copy", "experimental.projectCopy.create") - .seeded((ctx) => ctx.project()) - .at((ctx) => ({ - path: route("/experimental/project/{projectID}/copy", { projectID: ctx.state.id }), - headers: ctx.headers(), - body: {}, - })) - .status(400), - http.protected - .delete("/experimental/project/{projectID}/copy", "experimental.projectCopy.remove") - .seeded((ctx) => ctx.project()) - .at((ctx) => ({ - path: route("/experimental/project/{projectID}/copy", { projectID: ctx.state.id }), - headers: ctx.headers(), - body: {}, - })) - .status(400), - http.protected - .post("/experimental/project/{projectID}/copy/refresh", "experimental.projectCopy.refresh") - .seeded((ctx) => ctx.project()) - .at((ctx) => ({ - path: route("/experimental/project/{projectID}/copy/refresh", { projectID: ctx.state.id }), - headers: ctx.headers(), - })) - .status(204, undefined), - http.protected.get("/provider", "provider.list").json(), - http.protected.get("/provider/auth", "provider.auth").json(), - http.protected - .post("/provider/{providerID}/oauth/authorize", "provider.oauth.authorize") - .at((ctx) => ({ - path: route("/provider/{providerID}/oauth/authorize", { providerID: "httpapi" }), - headers: ctx.headers(), - body: { method: "bad" }, - })) - .status(400), - http.protected - .post("/provider/{providerID}/oauth/callback", "provider.oauth.callback") - .at((ctx) => ({ - path: route("/provider/{providerID}/oauth/callback", { providerID: "httpapi" }), - headers: ctx.headers(), - body: { method: "bad" }, - })) - .status(400), - http.protected.get("/permission", "permission.list").json(200, array), - http.protected - .post("/permission/{requestID}/reply", "permission.reply.invalid") - .at((ctx) => ({ - path: route("/permission/{requestID}/reply", { requestID: "per_httpapi" }), - headers: ctx.headers(), - body: { reply: "bad" }, - })) - .status(400), - http.protected - .post("/permission/{requestID}/reply", "permission.reply") - .at((ctx) => ({ - path: route("/permission/{requestID}/reply", { requestID: "per_httpapi" }), - headers: ctx.headers(), - body: { reply: "once" }, - })) - .json(404, object), - http.protected.get("/question", "question.list").json(200, array), - http.protected - .post("/question/{requestID}/reply", "question.reply.invalid") - .at((ctx) => ({ - path: route("/question/{requestID}/reply", { requestID: "que_httpapi_reply" }), - headers: ctx.headers(), - body: { answers: "Yes" }, - })) - .status(400), - http.protected - .post("/question/{requestID}/reply", "question.reply") - .at((ctx) => ({ - path: route("/question/{requestID}/reply", { requestID: "que_httpapi_reply" }), - headers: ctx.headers(), - body: { answers: [["Yes"]] }, - })) - .json(404, object), - http.protected - .post("/question/{requestID}/reject", "question.reject") - .at((ctx) => ({ - path: route("/question/{requestID}/reject", { requestID: "que_httpapi_reject" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/file", "file.list") - .seeded((ctx) => ctx.file("hello.txt", "hello\n")) - .at((ctx) => ({ path: `/file?${new URLSearchParams({ path: "." })}`, headers: ctx.headers() })) - .json(200, array), - http.protected - .get("/file/content", "file.read") - .seeded((ctx) => ctx.file("hello.txt", "hello\n")) - .at((ctx) => ({ path: `/file/content?${new URLSearchParams({ path: "hello.txt" })}`, headers: ctx.headers() })) - .json(200, (body) => { - object(body) - check(body.content === "hello", `content should match seeded file: ${JSON.stringify(body)}`) - }), - http.protected - .get("/file/content", "file.read.missing") - .at((ctx) => ({ path: `/file/content?${new URLSearchParams({ path: "missing.txt" })}`, headers: ctx.headers() })) - .json(200, (body) => { - object(body) - check(body.type === "text" && body.content === "", "missing file content should return an empty text result") - }), - http.protected.get("/file/status", "file.status").json(200, array), - http.protected - .get("/find", "find.text") - .seeded((ctx) => ctx.file("hello.txt", "hello\n")) - .at((ctx) => ({ path: `/find?${new URLSearchParams({ pattern: "hello" })}`, headers: ctx.headers() })) - .json(200, array), - http.protected - .get("/find/file", "find.files") - .seeded((ctx) => ctx.file("hello.txt", "hello\n")) - .at((ctx) => ({ - path: `/find/file?${new URLSearchParams({ query: "hello", dirs: "false" })}`, - headers: ctx.headers(), - })) - .json(200, array), - http.protected - .get("/find/symbol", "find.symbols") - .seeded((ctx) => ctx.file("hello.ts", "export const hello = 1\n")) - .at((ctx) => ({ path: `/find/symbol?${new URLSearchParams({ query: "hello" })}`, headers: ctx.headers() })) - .json(200, array), - http.protected - .get("/event", "event.stream") - .stream() - .status(200, (_ctx, result) => - Effect.sync(() => { - check(result.contentType.includes("text/event-stream"), "event should be an SSE stream") - check(result.text.includes("server.connected"), "event should emit initial connection event") - }), - ), - http.protected.get("/mcp", "mcp.status").json(), - http.protected - .post("/mcp", "mcp.add") - .at((ctx) => ({ - path: "/mcp", - headers: ctx.headers(), - body: { name: "httpapi-disabled", config: { type: "local", command: ["bun", "--version"], enabled: false } }, - })) - .json(200, (body) => { - object(body) - object(body["httpapi-disabled"]) - check(body["httpapi-disabled"].status === "disabled", "disabled MCP server should be added without spawning") - }), - http.protected - .post("/mcp", "mcp.add.invalid") - .at((ctx) => ({ - path: "/mcp", - headers: ctx.headers(), - body: { name: "httpapi-invalid", config: { type: "invalid" } }, - })) - .status(400), - http.protected - .post("/mcp/{name}/auth", "mcp.auth.start") - .at((ctx) => ({ path: route("/mcp/{name}/auth", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected - .delete("/mcp/{name}/auth", "mcp.auth.remove") - .at((ctx) => ({ path: route("/mcp/{name}/auth", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected - .post("/mcp/{name}/auth/authenticate", "mcp.auth.authenticate") - .at((ctx) => ({ - path: route("/mcp/{name}/auth/authenticate", { name: "httpapi-missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .post("/mcp/{name}/auth/callback", "mcp.auth.callback") - .at((ctx) => ({ - path: route("/mcp/{name}/auth/callback", { name: "httpapi-missing" }), - headers: ctx.headers(), - body: { code: "code" }, - })) - .json(404, object), - http.protected - .post("/mcp/{name}/connect", "mcp.connect") - .at((ctx) => ({ path: route("/mcp/{name}/connect", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected - .post("/mcp/{name}/disconnect", "mcp.disconnect") - .at((ctx) => ({ path: route("/mcp/{name}/disconnect", { name: "httpapi-missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected.get("/pty/shells", "pty.shells").json(200, array), - http.protected.get("/pty", "pty.list").json(200, array), - http.protected - .post("/pty", "pty.create") - .at((ctx) => ({ path: "/pty", headers: ctx.headers(), body: controlledPtyInput("HTTP API PTY") })) - .json(200, (body, ctx) => { - object(body) - check(body.title === "HTTP API PTY", "PTY create should return requested title") - check(body.command === "/bin/sh", "PTY create should use controlled shell command") - check(body.cwd === ctx.directory, "PTY create should default cwd to scenario directory") - }), - http.protected - .post("/pty", "pty.create.invalid") - .at((ctx) => ({ path: "/pty", headers: ctx.headers(), body: { command: 1 } })) - .status(400), - http.protected - .post("/pty/{ptyID}/connect-token", "pty.connectToken.invalid") - .at((ctx) => ({ - path: route("/pty/{ptyID}/connect-token", { ptyID: "pty_httpapi_missing" }), - headers: ctx.headers(), - })) - .status(403, undefined), - http.protected - .get("/pty/{ptyID}", "pty.get") - .at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .status(404), - http.protected - .put("/pty/{ptyID}", "pty.update") - .at((ctx) => ({ - path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), - headers: ctx.headers(), - body: { size: { rows: 0, cols: 0 } }, - })) - .status(400), - http.protected - .delete("/pty/{ptyID}", "pty.remove") - .at((ctx) => ({ path: route("/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected - .get("/pty/{ptyID}/connect", "pty.connect") - .at((ctx) => ({ path: route("/pty/{ptyID}/connect", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .status(404, undefined), - http.protected.get("/experimental/console", "experimental.console.get").json(), - http.protected.get("/experimental/console/orgs", "experimental.console.listOrgs").json(), - http.protected - .post("/experimental/console/switch", "experimental.console.switchOrg") - .at((ctx) => ({ - path: "/experimental/console/switch", - headers: ctx.headers(), - body: { accountID: "httpapi-account", orgID: "httpapi-org" }, - })) - .status(400, undefined), - http.protected.get("/experimental/workspace/adapter", "experimental.workspace.adapter.list").json(200, array), - http.protected.get("/experimental/workspace", "experimental.workspace.list").json(200, array), - http.protected.get("/experimental/workspace/status", "experimental.workspace.status").json(200, array), - http.protected - .post("/experimental/workspace", "experimental.workspace.create") - .at((ctx) => ({ path: "/experimental/workspace", headers: ctx.headers(), body: {} })) - .status(400), - http.protected.post("/experimental/workspace/sync-list", "experimental.workspace.syncList").status(204, undefined), - http.protected - .delete("/experimental/workspace/{id}", "experimental.workspace.remove") - .at((ctx) => ({ - path: route("/experimental/workspace/{id}", { id: "wrk_httpapi_missing" }), - headers: ctx.headers(), - })) - .status(200), - http.protected - .post("/experimental/workspace/warp", "experimental.workspace.warp") - .at((ctx) => ({ - path: "/experimental/workspace/warp", - headers: ctx.headers(), - body: {}, - })) - .status(400), - http.protected - .post("/experimental/control-plane/move-session", "experimental.controlPlane.moveSession") - .global() - .at(() => ({ - path: "/experimental/control-plane/move-session", - body: {}, - })) - .status(400), - http.protected - .get("/experimental/tool", "tool.list") - .at((ctx) => ({ - path: `/experimental/tool?${new URLSearchParams({ provider: "opencode", model: "test" })}`, - headers: ctx.headers(), - })) - .json(200, array), - http.protected.get("/experimental/tool/ids", "tool.ids").json(200, array), - http.protected.get("/experimental/worktree", "worktree.list").json(200, array), - http.protected - .post("/experimental/worktree", "worktree.create") - .at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { name: "api-dsl" } })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - object(body) - check(typeof body.directory === "string", "created worktree should include directory") - yield* ctx.worktreeRemove(body.directory) - }), - ), - http.protected - .post("/experimental/worktree", "worktree.create.invalid") - .at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { name: 1 } })) - .status(400), - http.protected - .delete("/experimental/worktree", "worktree.remove") - .seeded((ctx) => ctx.worktree({ name: "api-remove" })) - .at((ctx) => ({ path: "/experimental/worktree", headers: ctx.headers(), body: { directory: ctx.state.directory } })) - .json(200, (body) => { - check(body === true, "worktree remove should return true") - }), - http.protected - .post("/experimental/worktree/reset", "worktree.reset") - .seeded((ctx) => ctx.worktree({ name: "api-reset" })) - .at((ctx) => ({ - path: "/experimental/worktree/reset", - headers: ctx.headers(), - body: { directory: ctx.state.directory }, - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - check(body === true, "worktree reset should return true") - yield* ctx.worktreeRemove(ctx.state.directory) - }), - ), - http.protected - .get("/experimental/session", "experimental.session.list") - .at((ctx) => ({ path: "/experimental/session?roots=false&archived=false", headers: ctx.headers() })) - .json(200, array), - http.protected.get("/experimental/capabilities", "experimental.capabilities.get").json(200, (body) => { - check( - typeof body === "object" && body !== null && "backgroundSubagents" in body && body.backgroundSubagents === true, - "capabilities should report background subagents as available", - ) - }), - http.protected - .post("/experimental/session/{sessionID}/background", "experimental.session.background") - .seeded((ctx) => ctx.session({ title: "Background route owner" })) - .at((ctx) => ({ - path: route("/experimental/session/{sessionID}/background", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, (body) => { - check(body === false, "background route should be a no-op without running subagents") - }), - http.protected.get("/experimental/resource", "experimental.resource.list").json(), - http.protected - .post("/sync/history", "sync.history.list") - .at((ctx) => ({ path: "/sync/history", headers: ctx.headers(), body: {} })) - .json(200, array), - http.protected - .post("/sync/replay", "sync.replay") - .at((ctx) => ({ path: "/sync/replay", headers: ctx.headers(), body: { directory: ctx.directory, events: [] } })) - .status(400), - http.protected - .post("/sync/steal", "sync.steal.invalid") - .at((ctx) => ({ path: "/sync/steal", headers: ctx.headers(), body: {} })) - .status(400, undefined), - http.protected - .post("/sync/start", "sync.start") - .preserveState() - .json(200, (body) => { - check(body === true, "sync start should return true when no workspace sessions exist") - }), - http.protected.post("/instance/dispose", "instance.dispose").json(200, (body) => { - check(body === true, "instance dispose should return true") - }), - http.protected - .post("/log", "app.log") - .global() - .at(() => ({ path: "/log", body: { service: "httpapi-exercise", level: "info", message: "route coverage" } })) - .json(200, (body) => { - check(body === true, "log route should return true") - }), - http.protected - .put("/auth/{providerID}", "auth.set") - .global() - .at(() => ({ path: route("/auth/{providerID}", { providerID: "test" }), body: { type: "api", key: "test-key" } })) - .jsonEffect(200, (body) => - Effect.gen(function* () { - check(body === true, "auth set should return true") - const auth = yield* Effect.promise(() => Bun.file(path.join(exerciseDataDirectory, "auth.json")).json()) - object(auth) - check(isRecord(auth.test) && auth.test.key === "test-key", "auth set should write isolated auth file") - }), - ), - http.protected - .delete("/auth/{providerID}", "auth.remove") - .global() - .seeded(() => - Effect.promise(() => - Bun.write( - path.join(exerciseDataDirectory, "auth.json"), - JSON.stringify({ test: { type: "api", key: "remove-me" } }), - ), - ), - ) - .at(() => ({ path: route("/auth/{providerID}", { providerID: "test" }) })) - .jsonEffect(200, (body) => - Effect.gen(function* () { - check(body === true, "auth remove should return true") - const auth = yield* Effect.promise(() => Bun.file(path.join(exerciseDataDirectory, "auth.json")).json()) - object(auth) - check(auth.test === undefined, "auth remove should delete provider from isolated auth file") - }), - ), - http.protected.get("/api/health", "v2.health.get").json(200, (body) => { - object(body) - check(body.healthy === true, "v2 server should report healthy") - }), - http.protected.get("/api/location", "v2.location.get").json(200, object), - http.protected.get("/api/agent", "v2.agent.list").json(200, locationData(array)), - http.protected.get("/api/model", "v2.model.list").json(200, locationData(array)), - // The default model may be undefined in the exercise environment, so only the location envelope is asserted. - http.protected.get("/api/model/default", "v2.model.default").json(200, object), - http.protected.get("/api/provider", "v2.provider.list").json(200, locationData(array)), - http.protected.get("/api/integration", "v2.integration.list").json(200, locationData(array)), - http.protected - .get("/api/integration/{integrationID}", "v2.integration.get") - .at((ctx) => ({ - path: route("/api/integration/{integrationID}", { integrationID: "missing" }), - headers: ctx.headers(), - })) - .json(200, object), - http.protected - .post("/api/integration/{integrationID}/connect/key", "v2.integration.connect.key") - .at((ctx) => ({ - path: route("/api/integration/{integrationID}/connect/key", { integrationID: "missing" }), - headers: ctx.headers(), - body: { key: "test" }, - })) - .status(500, undefined), - http.protected - .post("/api/integration/{integrationID}/connect/oauth", "v2.integration.connect.oauth") - .at((ctx) => ({ - path: route("/api/integration/{integrationID}/connect/oauth", { integrationID: "missing" }), - headers: ctx.headers(), - body: { methodID: "missing", inputs: {} }, - })) - .status(500, undefined), - http.protected - .get("/api/integration/attempt/{attemptID}", "v2.integration.attempt.status") - .at((ctx) => ({ - path: route("/api/integration/attempt/{attemptID}", { attemptID: "con_missing" }), - headers: ctx.headers(), - })) - .status(500, undefined), - http.protected - .post("/api/integration/attempt/{attemptID}/complete", "v2.integration.attempt.complete") - .at((ctx) => ({ - path: route("/api/integration/attempt/{attemptID}/complete", { attemptID: "con_missing" }), - headers: ctx.headers(), - body: {}, - })) - .status(500, undefined), - http.protected - .delete("/api/integration/attempt/{attemptID}", "v2.integration.attempt.cancel") - .at((ctx) => ({ - path: route("/api/integration/attempt/{attemptID}", { attemptID: "con_missing" }), - headers: ctx.headers(), - })) - .status(204, undefined), - http.protected - .delete("/api/credential/{credentialID}", "v2.credential.remove") - .at((ctx) => ({ - path: route("/api/credential/{credentialID}", { credentialID: "cred_missing" }), - headers: ctx.headers(), - })) - .status(204, undefined), - http.protected - .patch("/api/credential/{credentialID}", "v2.credential.update") - .at((ctx) => ({ - path: route("/api/credential/{credentialID}", { credentialID: "cred_missing" }), - headers: ctx.headers(), - body: { label: "Work" }, - })) - .status(204, undefined), - http.protected.get("/api/command", "v2.command.list").json(200, locationData(array)), - http.protected.get("/api/skill", "v2.skill.list").json(200, locationData(array)), - http.protected - .get("/api/event", "v2.event.subscribe") - .stream() - .status(200, (_ctx, result) => - Effect.sync(() => { - check(result.contentType.includes("text/event-stream"), "v2 event should be an SSE stream") - check(result.text.includes("server.connected"), "v2 event should emit initial connection event") - check(!result.text.includes('"location"'), "v2 connection event should not be scoped to a location") - }), - ), - http.protected - .get("/api/fs/read/*", "v2.fs.read") - .seeded((ctx) => ctx.file("hello.txt", "hello\n")) - .at((ctx) => ({ path: "/api/fs/read/hello.txt", headers: ctx.headers() })) - .status(200, (_ctx, result) => - Effect.sync(() => { - check(result.text === "hello\n", "v2 fs read should return the file body") - check(result.contentType.includes("text/plain"), "v2 fs read should return the file content type") - }), - ), - http.protected.get("/api/fs/list", "v2.fs.list").json(200, locationData(array)), - http.protected - .get("/api/fs/find", "v2.fs.find") - .seeded((ctx) => ctx.file("hello.txt", "hello\n")) - .at((ctx) => ({ path: "/api/fs/find?query=hello&type=file", headers: ctx.headers() })) - .json(200, locationData(array)), - http.protected.get("/api/pty", "v2.pty.list").json(200, locationData(array)), - http.protected - .post("/api/pty", "v2.pty.create") - .at((ctx) => ({ path: "/api/pty", headers: ctx.headers(), body: controlledPtyInput("HTTP API V2 PTY") })) - .json(200, locationData(object)), - http.protected - .get("/api/pty/{ptyID}", "v2.pty.get") - .at((ctx) => ({ path: route("/api/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected - .put("/api/pty/{ptyID}", "v2.pty.update") - .at((ctx) => ({ - path: route("/api/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), - headers: ctx.headers(), - body: { title: "missing" }, - })) - .json(404, object), - http.protected - .delete("/api/pty/{ptyID}", "v2.pty.remove") - .at((ctx) => ({ path: route("/api/pty/{ptyID}", { ptyID: "pty_httpapi_missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected - .post("/api/pty/{ptyID}/connect-token", "v2.pty.connectToken") - .at((ctx) => ({ - path: route("/api/pty/{ptyID}/connect-token", { ptyID: "pty_httpapi_missing" }), - headers: { ...ctx.headers(), "x-opencode-ticket": "1" }, - })) - .json(404, object), - http.protected - .get("/api/pty/{ptyID}/connect", "v2.pty.connect") - .at((ctx) => ({ - path: route("/api/pty/{ptyID}/connect", { ptyID: "pty_httpapi_missing" }), - headers: ctx.headers(), - })) - .status(404, undefined), - http.protected.get("/api/reference", "v2.reference.list").json(200, object), - http.protected - .get("/api/provider/{providerID}", "v2.provider.get") - .at((ctx) => ({ path: route("/api/provider/{providerID}", { providerID: "missing" }), headers: ctx.headers() })) - .json(404, object), - http.protected.get("/api/permission/request", "v2.permission.request.list").json(200, (body) => { - object(body) - object(body.location) - array(body.data) - }), - http.protected.get("/api/question/request", "v2.question.request.list").json(200, (body) => { - object(body) - object(body.location) - array(body.data) - }), - http.protected.get("/api/form/request", "v2.form.request.list").json(200, (body) => { - object(body) - object(body.location) - array(body.data) - }), - http.protected - .get("/api/session/{sessionID}/form", "v2.session.form.list") - .seeded((ctx) => ctx.session({ title: "Form list owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/form", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, data(array)), - http.protected - .post("/api/session/{sessionID}/form", "v2.session.form.create") - .seeded((ctx) => ctx.session({ title: "Form create owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/form", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { - title: "External form", - fields: [{ key: "authorization", type: "external", url: "https://example.com/form" }], - }, - })) - .json(200, (body) => { - object(body) - object(body.data) - check(typeof body.data.id === "string", "form create should return an ID") - array(body.data.fields) - object(body.data.fields[0]) - check(body.data.fields[0].type === "external", "form create should preserve the external field") - }), - http.protected - .get("/api/session/{sessionID}/form/{formID}", "v2.session.form.get") - .seeded((ctx) => ctx.session({ title: "Form get owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/form/{formID}", { sessionID: ctx.state.id, formID: "frm_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/form/{formID}/state", "v2.session.form.state") - .seeded((ctx) => ctx.session({ title: "Form state owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/form/{formID}/state", { - sessionID: ctx.state.id, - formID: "frm_httpapi_missing", - }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/form/{formID}/reply", "v2.session.form.reply") - .seeded((ctx) => ctx.session({ title: "Form reply owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/form/{formID}/reply", { - sessionID: ctx.state.id, - formID: "frm_httpapi_missing", - }), - headers: ctx.headers(), - body: { answer: {} }, - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/form/{formID}/cancel", "v2.session.form.cancel") - .seeded((ctx) => ctx.session({ title: "Form cancel owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/form/{formID}/cancel", { - sessionID: ctx.state.id, - formID: "frm_httpapi_missing", - }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/permission", "v2.session.permission.create") - .seeded((ctx) => ctx.session({ title: "Permission create owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/permission", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { action: "read", resources: [".env"] }, - })) - .json(200, (body) => { - object(body) - object(body.data) - check(typeof body.data.id === "string", "permission create should return an ID") - check(body.data.effect === "ask", "permission create should create a pending request") - }), - http.protected - .get("/api/session/{sessionID}/permission", "v2.session.permission.list") - .seeded((ctx) => ctx.session({ title: "Permission list owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/permission", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, data(array)), - http.protected - .get("/api/session/{sessionID}/permission/{requestID}", "v2.session.permission.get") - .seeded((ctx) => ctx.session({ title: "Permission get owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/permission/{requestID}", { - sessionID: ctx.state.id, - requestID: "per_httpapi_missing", - }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/question", "v2.session.question.list") - .seeded((ctx) => ctx.session({ title: "Question list owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/question", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, data(array)), - http.protected - .post("/api/session/{sessionID}/permission/{requestID}/reply", "v2.session.permission.reply") - .seeded((ctx) => ctx.session({ title: "Permission owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/permission/{requestID}/reply", { - sessionID: ctx.state.id, - requestID: "per_httpapi_missing", - }), - headers: ctx.headers(), - body: { reply: "once" }, - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/question/{requestID}/reply", "v2.session.question.reply") - .seeded((ctx) => ctx.session({ title: "Question reply owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/question/{requestID}/reply", { - sessionID: ctx.state.id, - requestID: "que_httpapi_missing", - }), - headers: ctx.headers(), - body: { answers: [] }, - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/question/{requestID}/reject", "v2.session.question.reject") - .seeded((ctx) => ctx.session({ title: "Question reject owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/question/{requestID}/reject", { - sessionID: ctx.state.id, - requestID: "que_httpapi_missing", - }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected.get("/api/permission/saved", "v2.permission.saved.list").json(200, (body) => { - object(body) - array(body.data) - }), - http.protected - .delete("/api/permission/saved/{id}", "v2.permission.saved.remove") - .at((ctx) => ({ path: route("/api/permission/saved/{id}", { id: "psv_httpapi_missing" }), headers: ctx.headers() })) - .status(204, undefined), - http.protected - .get("/api/session", "v2.session.list") - .at((ctx) => ({ path: "/api/session?roots=true", headers: ctx.headers() })) - .json(200, (body) => { - object(body) - array(body.data) - object(body.cursor) - }), - http.protected - .get("/api/session", "v2.session.list.filters") - .at((ctx) => ({ - path: `/api/session?${new URLSearchParams({ - limit: "2", - order: "asc", - path: ".", - roots: "false", - start: "0", - search: "missing", - directory: ctx.directory ?? "", - })}`, - headers: ctx.headers(), - })) - .json(200, (body) => { - object(body) - array(body.data) - object(body.cursor) - }), - http.protected - .get("/api/session", "v2.session.list.cursor") - .at((ctx) => ({ - path: `/api/session?${new URLSearchParams({ - limit: "2", - cursor: cursor({ - order: "desc", - directory: ctx.directory, - anchor: { id: "ses_httpapi_missing", time: 0, direction: "next" }, - }), - })}`, - headers: ctx.headers(), - })) - .json(200, (body) => { - object(body) - array(body.data) - object(body.cursor) - }), - http.protected - .get("/api/session", "v2.session.list.cursor.invalid") - .at((ctx) => ({ - path: `/api/session?${new URLSearchParams({ - cursor: "invalid", - })}`, - headers: ctx.headers(), - })) - .status(400, undefined), - http.protected.get("/api/session/active", "v2.session.active").json(200, data(object)), - http.protected - .post("/api/session", "v2.session.create") - .at((ctx) => ({ - path: "/api/session", - headers: { ...ctx.headers(), "content-type": "application/json" }, - body: {}, - })) - .json(200, data(object)), - http.protected - .get("/api/session/{sessionID}", "v2.session.get") - .seeded((ctx) => ctx.session({ title: "Session get" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, data(object)), - http.protected - .post("/api/session/{sessionID}/agent", "v2.session.switchAgent") - .seeded((ctx) => ctx.session({ title: "Switch agent" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/agent", { sessionID: ctx.state.id }), - headers: { ...ctx.headers(), "content-type": "application/json" }, - body: { agent: "plan" }, - })) - .status(204, undefined), - http.protected - .post("/api/session/{sessionID}/model", "v2.session.switchModel") - .seeded((ctx) => ctx.session({ title: "Switch model" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/model", { sessionID: ctx.state.id }), - headers: { ...ctx.headers(), "content-type": "application/json" }, - body: { model: { providerID: "opencode", id: "big-pickle" } }, - })) - .status(204, undefined), - http.protected - .get("/api/session/{sessionID}/context", "v2.session.context") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/context", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/pending", "v2.session.pending.list") - .seeded((ctx) => ctx.session({ title: "Pending list owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/pending", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, data(array)), - http.protected - .post("/api/session/{sessionID}/revert/stage", "v2.session.revert.stage") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/revert/stage", { sessionID: "ses_httpapi_missing" }), - headers: { ...ctx.headers(), "content-type": "application/json" }, - body: { messageID: "msg_httpapi_missing" }, - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/revert/clear", "v2.session.revert.clear") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/revert/clear", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/revert/commit", "v2.session.revert.commit") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/revert/commit", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/message", "v2.session.messages") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/message", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/message", "v2.session.messages.params") - .at((ctx) => ({ - path: `${route("/api/session/{sessionID}/message", { sessionID: "ses_httpapi_missing" })}?${new URLSearchParams({ - limit: "2", - order: "asc", - })}`, - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/message", "v2.session.messages.cursor") - .at((ctx) => ({ - path: `${route("/api/session/{sessionID}/message", { sessionID: "ses_httpapi_missing" })}?${new URLSearchParams({ - limit: "2", - directory: ctx.directory ?? "", - cursor: cursor({ id: "msg_httpapi_missing", time: 0, order: "desc", direction: "next" }), - })}`, - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/message", "v2.session.messages.cursor.invalid") - .seeded((ctx) => ctx.session({ title: "Invalid message cursor owner" })) - .at((ctx) => ({ - path: `${route("/api/session/{sessionID}/message", { sessionID: ctx.state.id })}?${new URLSearchParams({ - cursor: cursor({ id: "msg_httpapi_missing", time: 0, order: "desc", direction: "next" }), - order: "asc", - })}`, - headers: ctx.headers(), - })) - .status(400, undefined), - http.protected - .get("/api/session/{sessionID}/history", "v2.session.history") - .seeded((ctx) => ctx.session({ title: "Session history" })) - .at((ctx) => ({ - path: `${route("/api/session/{sessionID}/history", { sessionID: ctx.state.id })}?${new URLSearchParams({ - after: "0", - limit: "2", - })}`, - headers: ctx.headers(), - })) - .json(200, (body) => { - object(body) - array(body.data) - check(typeof body.hasMore === "boolean", "Expected a history exhaustion signal") - }), - http.protected - .get("/api/session/{sessionID}/history", "v2.session.history.missing") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/history", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .get("/api/session/{sessionID}/history", "v2.session.history.invalid") - .seeded((ctx) => ctx.session({ title: "Invalid history sequence" })) - .at((ctx) => ({ - path: `${route("/api/session/{sessionID}/history", { sessionID: ctx.state.id })}?after=-1`, - headers: ctx.headers(), - })) - .json(400, object), - http.protected - .get("/api/session/{sessionID}/event", "v2.session.events.missing") - .at((ctx) => ({ - path: `${route("/api/session/{sessionID}/event", { sessionID: "ses_httpapi_missing" })}?after=0`, - headers: ctx.headers(), - })) - .status(404, undefined), - http.protected - .post("/api/session/{sessionID}/interrupt", "v2.session.interrupt") - .seeded((ctx) => ctx.session({ title: "Interrupt session" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/interrupt", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .status(204, undefined), - http.protected - .get("/api/session/{sessionID}/message/{messageID}", "v2.session.message.missing") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/message/{messageID}", { - sessionID: "ses_httpapi_missing", - messageID: "msg_httpapi_missing", - }), - headers: ctx.headers(), - })) - .json(404, object), - http.protected - .post("/api/session/{sessionID}/prompt", "v2.session.prompt.invalid") - .seeded((ctx) => ctx.session({ title: "Invalid prompt owner" })) - .at((ctx) => ({ - path: route("/api/session/{sessionID}/prompt", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: {}, - })) - .status(400, undefined), - http.protected - .post("/api/session/{sessionID}/compact", "v2.session.compact") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/compact", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .status(404, undefined), - http.protected - .post("/api/session/{sessionID}/wait", "v2.session.wait") - .at((ctx) => ({ - path: route("/api/session/{sessionID}/wait", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .status(404, undefined), - http.protected - .get("/session", "session.list") - .seeded((ctx) => ctx.session({ title: "List me" })) - .at((ctx) => ({ path: "/session?roots=true", headers: ctx.headers() })) - .json(200, (body, ctx) => { - array(body) - check( - body.some((item) => isRecord(item) && item.id === ctx.state.id && item.title === "List me"), - "seeded session should be listed", - ) - }), - http.protected - .get("/session/status", "session.status") - .seeded((ctx) => ctx.session({ title: "Status session" })) - .json(200, object), - http.protected - .post("/session", "session.create") - .at((ctx) => ({ path: "/session", headers: ctx.headers(), body: { title: "Created session" } })) - .json(200, (body, ctx) => { - object(body) - check(body.title === "Created session", "created session should use requested title") - check(body.directory === ctx.directory, "created session should use scenario directory") - }), - http.protected - .get("/session/{sessionID}", "session.get") - .seeded((ctx) => ctx.session({ title: "Get me" })) - .at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json(200, (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "should return requested session") - check(body.title === "Get me", "should preserve seeded title") - }), - http.protected - .get("/session/{sessionID}", "session.get.missing") - .at((ctx) => ({ - path: route("/session/{sessionID}", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .status(404), - http.protected - .patch("/session/{sessionID}", "session.update") - .seeded((ctx) => ctx.session({ title: "Before rename" })) - .at((ctx) => ({ - path: route("/session/{sessionID}", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { title: "After rename" }, - })) - .json(200, (body) => { - object(body) - check(body.title === "After rename", "updated session should use new title") - }), - http.protected - .patch("/session/{sessionID}", "session.update.invalid") - .at((ctx) => ({ - path: route("/session/{sessionID}", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - body: { title: 1 }, - })) - .status(400), - http.protected - .delete("/session/{sessionID}", "session.delete") - .seeded((ctx) => ctx.session({ title: "Delete me" })) - .at((ctx) => ({ path: route("/session/{sessionID}", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - check(body === true, "delete should return true") - check((yield* ctx.sessionGet(ctx.state.id)) === undefined, "deleted session should not remain in storage") - }), - ), - http.protected - .get("/session/{sessionID}/children", "session.children") - .seeded((ctx) => - Effect.gen(function* () { - const parent = yield* ctx.session({ title: "Parent" }) - const child = yield* ctx.session({ title: "Child", parentID: parent.id }) - return { parent, child } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/children", { sessionID: ctx.state.parent.id }), - headers: ctx.headers(), - })) - .json(200, (body, ctx) => { - array(body) - check( - body.some((item) => isRecord(item) && item.id === ctx.state.child.id && item.parentID === ctx.state.parent.id), - "children should include seeded child", - ) - }), - http.protected - .get("/session/{sessionID}/diff", "session.diff") - .seeded((ctx) => ctx.session({ title: "Diff session" })) - .at((ctx) => ({ path: route("/session/{sessionID}/diff", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json(200, array), - http.protected - .get("/session/{sessionID}/message", "session.messages") - .seeded((ctx) => ctx.session({ title: "Messages session" })) - .at((ctx) => ({ path: route("/session/{sessionID}/message", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json(200, (body) => { - array(body) - check(body.length === 0, "new session should have no messages") - }), - http.protected - .get("/session/{sessionID}/message/{messageID}", "session.message") - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Message get session" }) - const message = yield* ctx.message(session.id, { text: "read me" }) - return { session, message } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/message/{messageID}", { - sessionID: ctx.state.session.id, - messageID: ctx.state.message.info.id, - }), - headers: ctx.headers(), - })) - .json(200, (body, ctx) => { - object(body) - check(isRecord(body.info) && body.info.id === ctx.state.message.info.id, "should return requested message") - check( - Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.id === ctx.state.message.part.id), - "message should include seeded part", - ) - }), - http.protected - .patch("/session/{sessionID}/message/{messageID}/part/{partID}", "part.update") - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Part update session" }) - const message = yield* ctx.message(session.id, { text: "before" }) - return { session, message } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/message/{messageID}/part/{partID}", { - sessionID: ctx.state.session.id, - messageID: ctx.state.message.info.id, - partID: ctx.state.message.part.id, - }), - headers: ctx.headers(), - body: { ...ctx.state.message.part, text: "after" }, - })) - .json(200, (body) => { - object(body) - check(body.type === "text" && body.text === "after", "updated part should be returned") - }), - http.protected - .delete("/session/{sessionID}/message/{messageID}/part/{partID}", "part.delete") - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Part delete session" }) - const message = yield* ctx.message(session.id, { text: "delete part" }) - return { session, message } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/message/{messageID}/part/{partID}", { - sessionID: ctx.state.session.id, - messageID: ctx.state.message.info.id, - partID: ctx.state.message.part.id, - }), - headers: ctx.headers(), - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - check(body === true, "delete part should return true") - const messages = yield* ctx.messages(ctx.state.session.id) - check(messages[0]?.parts.length === 0, "deleted part should not remain on message") - }), - ), - http.protected - .delete("/session/{sessionID}/message/{messageID}", "session.deleteMessage") - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Message delete session" }) - const message = yield* ctx.message(session.id, { text: "delete message" }) - return { session, message } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/message/{messageID}", { - sessionID: ctx.state.session.id, - messageID: ctx.state.message.info.id, - }), - headers: ctx.headers(), - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - check(body === true, "delete message should return true") - check((yield* ctx.messages(ctx.state.session.id)).length === 0, "deleted message should not remain") - }), - ), - http.protected - .post("/session/{sessionID}/fork", "session.fork") - .seeded((ctx) => ctx.session({ title: "Fork source" })) - .at((ctx) => ({ - path: route("/session/{sessionID}/fork", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: {}, - })) - .json(200, (body) => { - object(body) - check(typeof body.id === "string", "fork should return a session") - }), - http.protected - .post("/session/{sessionID}/abort", "session.abort") - .seeded((ctx) => ctx.session({ title: "Abort session" })) - .at((ctx) => ({ path: route("/session/{sessionID}/abort", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json(200, (body) => { - check(body === true, "abort should return true") - }), - http.protected - .post("/session/{sessionID}/abort", "session.abort.missing") - .at((ctx) => ({ - path: route("/session/{sessionID}/abort", { sessionID: "ses_httpapi_missing" }), - headers: ctx.headers(), - })) - .json(200, (body) => { - check(body === true, "missing session abort should remain a no-op success") - }), - http.protected - .post("/session/{sessionID}/init", "session.init") - .preserveState() - .withLlm() - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Init session" }) - const message = yield* ctx.message(session.id, { text: "initialize" }) - yield* ctx.llmText("initialized") - yield* ctx.llmText("initialized") - return { session, message } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/init", { sessionID: ctx.state.session.id }), - headers: ctx.headers(), - body: { providerID: "test", modelID: "test-model", messageID: ctx.state.message.info.id }, - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - check(body === true, "init should return true") - yield* ctx.llmWait(1) - }), - ), - http.protected - .post("/session/{sessionID}/message", "session.prompt") - .preserveState() - .withLlm() - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "LLM prompt session" }) - yield* ctx.llmText("fake assistant") - yield* ctx.llmText("fake assistant") - return session - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/message", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { - agent: "build", - model: { providerID: "test", modelID: "test-model" }, - parts: [{ type: "text", text: "hello llm" }], - }, - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - object(body) - check(isRecord(body.info) && body.info.role === "assistant", "prompt should return assistant message") - check( - Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.text === "fake assistant"), - "assistant message should use fake LLM text", - ) - yield* ctx.llmWait(1) - }), - ), - http.protected - .post("/session/{sessionID}/prompt_async", "session.prompt_async") - .preserveState() - .withLlm() - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Async prompt session" }) - yield* ctx.llmText("fake async assistant") - yield* ctx.llmText("fake async assistant") - return session - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/prompt_async", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { - agent: "build", - model: { providerID: "test", modelID: "test-model" }, - parts: [{ type: "text", text: "hello async" }], - }, - })) - .status(204, (ctx) => - Effect.gen(function* () { - yield* ctx.llmWait(1) - }), - ), - http.protected - .post("/session/{sessionID}/command", "session.command") - .preserveState() - .withLlm() - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Command session" }) - yield* ctx.llmText("command done") - yield* ctx.llmText("command done") - return session - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/command", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { command: "init", arguments: "", model: "test/test-model" }, - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - object(body) - check(isRecord(body.info) && body.info.role === "assistant", "command should return assistant message") - yield* ctx.llmWait(1) - }), - ), - http.protected - .post("/session/{sessionID}/shell", "session.shell") - .preserveState() - .seeded((ctx) => ctx.session({ title: "Shell session" })) - .at((ctx) => ({ - path: route("/session/{sessionID}/shell", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { agent: "build", model: { providerID: "test", modelID: "test-model" }, command: "printf shell-ok" }, - })) - .json(200, (body) => { - object(body) - check(isRecord(body.info) && body.info.role === "assistant", "shell should return assistant message") - check( - Array.isArray(body.parts) && body.parts.some((part) => isRecord(part) && part.type === "tool"), - "shell should return a tool part", - ) - }), - http.protected - .post("/session/{sessionID}/summarize", "session.summarize") - .preserveState() - .withLlm() - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Summarize session" }) - yield* ctx.message(session.id, { text: "summarize this work" }) - const summary = [ - "## Objective", - "- Exercise session summarize.", - "", - "## Important Details", - "- Use fake LLM.", - "- Keep route local.", - "- Test fixture: test/server/httpapi-exercise/index.ts.", - "", - "## Work State", - "- Completed: Summary generated.", - "- Active: (none)", - "- Blocked: (none)", - "", - "## Next Move", - "1. (none)", - ].join("\n") - yield* ctx.llmText(summary) - yield* ctx.llmText(summary) - return session - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/summarize", { sessionID: ctx.state.id }), - headers: ctx.headers(), - body: { providerID: "test", modelID: "test-model", auto: false }, - })) - .jsonEffect(200, (body, ctx) => - Effect.gen(function* () { - check(body === true, "summarize should return true") - const messages = yield* ctx.messages(ctx.state.id) - check( - messages.some((message) => message.info.role === "assistant" && message.info.summary === true), - "summarize should create a summary assistant message", - ) - yield* ctx.llmWait(1) - }), - ), - http.protected - .post("/session/{sessionID}/revert", "session.revert") - .seeded((ctx) => - Effect.gen(function* () { - const session = yield* ctx.session({ title: "Revert session" }) - const message = yield* ctx.message(session.id, { text: "revert me" }) - return { session, message } - }), - ) - .at((ctx) => ({ - path: route("/session/{sessionID}/revert", { sessionID: ctx.state.session.id }), - headers: ctx.headers(), - body: { messageID: ctx.state.message.info.id }, - })) - .json(200, (body, ctx) => { - object(body) - check(body.id === ctx.state.session.id, "revert should return the session") - check( - isRecord(body.revert) && body.revert.messageID === ctx.state.message.info.id, - "revert should record reverted message", - ) - }), - http.protected - .post("/session/{sessionID}/unrevert", "session.unrevert") - .seeded((ctx) => ctx.session({ title: "Unrevert session" })) - .at((ctx) => ({ - path: route("/session/{sessionID}/unrevert", { sessionID: ctx.state.id }), - headers: ctx.headers(), - })) - .json(200, (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "unrevert should return the session") - }), - http.protected - .post("/session/{sessionID}/permissions/{permissionID}", "permission.respond") - .seeded((ctx) => ctx.session({ title: "Deprecated permission session" })) - .at((ctx) => ({ - path: route("/session/{sessionID}/permissions/{permissionID}", { - sessionID: ctx.state.id, - permissionID: "per_httpapi_deprecated", - }), - headers: ctx.headers(), - body: { response: "once" }, - })) - .json(404, object), - http.protected - .post("/session/{sessionID}/share", "session.share") - .seeded((ctx) => ctx.session({ title: "Share session" })) - .at((ctx) => ({ path: route("/session/{sessionID}/share", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json(200, (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "share should return the session") - }), - http.protected - .delete("/session/{sessionID}/share", "session.unshare") - .seeded((ctx) => ctx.session({ title: "Unshare session" })) - .at((ctx) => ({ path: route("/session/{sessionID}/share", { sessionID: ctx.state.id }), headers: ctx.headers() })) - .json(200, (body, ctx) => { - object(body) - check(body.id === ctx.state.id, "unshare should return the session") - }), - http.protected - .post("/tui/append-prompt", "tui.appendPrompt") - .at((ctx) => ({ path: "/tui/append-prompt", headers: ctx.headers(), body: { text: "hello" } })) - .json(200, boolean), - http.protected - .post("/tui/select-session", "tui.selectSession.invalid") - .at((ctx) => ({ path: "/tui/select-session", headers: ctx.headers(), body: { sessionID: "invalid" } })) - .status(400), - http.protected.post("/tui/open-help", "tui.openHelp").json(200, boolean), - http.protected.post("/tui/open-sessions", "tui.openSessions").json(200, boolean), - http.protected.post("/tui/open-themes", "tui.openThemes").json(200, boolean), - http.protected.post("/tui/open-models", "tui.openModels").json(200, boolean), - http.protected.post("/tui/submit-prompt", "tui.submitPrompt").json(200, boolean), - http.protected.post("/tui/clear-prompt", "tui.clearPrompt").json(200, boolean), - http.protected - .post("/tui/execute-command", "tui.executeCommand") - .at((ctx) => ({ path: "/tui/execute-command", headers: ctx.headers(), body: { command: "agent_cycle" } })) - .json(200, boolean), - http.protected - .post("/tui/show-toast", "tui.showToast") - .at((ctx) => ({ - path: "/tui/show-toast", - headers: ctx.headers(), - body: { title: "Exercise", message: "covered", variant: "info", duration: 1000 }, - })) - .json(200, boolean), - http.protected - .post("/tui/publish", "tui.publish") - .at((ctx) => ({ - path: "/tui/publish", - headers: ctx.headers(), - body: { type: "tui.prompt.append", properties: { text: "published" } }, - })) - .json(200, boolean), - http.protected - .post("/tui/select-session", "tui.selectSession") - .seeded((ctx) => ctx.session({ title: "TUI select" })) - .at((ctx) => ({ path: "/tui/select-session", headers: ctx.headers(), body: { sessionID: ctx.state.id } })) - .json(200, boolean), - http.protected - .post("/tui/control/response", "tui.control.response") - .at((ctx) => ({ path: "/tui/control/response", headers: ctx.headers(), body: { ok: true } })) - .json(200, boolean), - http.protected - .get("/tui/control/next", "tui.control.next") - .seeded((ctx) => ctx.tuiRequest({ path: "/tui/exercise", body: { text: "queued" } })) - .json(200, (body) => { - object(body) - check(body.path === "/tui/exercise", "control next should return queued path") - object(body.body) - check(body.body.text === "queued", "control next should return queued body") - }), - http.protected - .post("/global/upgrade", "global.upgrade") - .global() - .probe({ path: "/global/upgrade", body: { target: 1 } }) - .at(() => ({ path: "/global/upgrade", body: { target: 1 } })) - .status(400), -] - -const llmScenarios = new Set([ - "session.init", - "session.prompt", - "session.prompt_async", - "session.command", - "session.summarize", -]) - -const main = Effect.gen(function* () { - const options = parseOptions(Bun.argv.slice(2)) - const modules = yield* Effect.promise(() => runtime()) - yield* Effect.addFinalizer(() => - Effect.promise(async () => { - await disposeApps() - await modules.disposeAllInstances() - }).pipe(Effect.andThen(cleanupExercisePaths)), - ) - const effectRoutes = routeKeys(OpenApi.fromApi(modules.PublicApi)) - const selected = selectedScenarios(options, scenarios) - const missing = effectRoutes.filter((route) => !scenarios.some((scenario) => route === routeKey(scenario))) - const extra = scenarios.filter((scenario) => !effectRoutes.includes(routeKey(scenario))) - - for (const scenario of scenarios) { - if (scenario.kind === "active" && llmScenarios.has(scenario.name) && !scenario.project?.llm) { - return yield* Effect.fail(new Error(`${scenario.name} must use TestLLMServer via .withLlm()`)) - } - } - - printHeader(options, effectRoutes, selected, missing, extra, { - database: exerciseDatabasePath, - global: exerciseGlobalRoot, - }) - - const results = - options.mode === "coverage" - ? selected.map(coverageResult) - : yield* Effect.forEach( - selected, - (scenario) => - Effect.gen(function* () { - if (options.progress) console.log(`${color.dim}RUN ${routeKey(scenario)} ${scenario.name}${color.reset}`) - return yield* runScenario(options)(scenario) - }), - { concurrency: 1 }, - ) - printResults(results, missing, extra) - - if (results.some((result) => result.status === "fail")) - return yield* Effect.fail(new Error("one or more scenarios failed")) - if (options.failOnSkip && results.some((result) => result.status === "skip")) - return yield* Effect.fail(new Error("one or more scenarios are skipped")) - if (options.failOnMissing && missing.length > 0) - return yield* Effect.fail(new Error("one or more routes have no scenario")) - return undefined -}) - -Effect.runPromise(main.pipe(Effect.provide(TestLLMServer.layer), Effect.scoped)).then( - () => process.exit(0), - (error: unknown) => { - console.error(`${color.red}${message(error)}${color.reset}`) - process.exit(1) - }, -) diff --git a/packages/opencode/test/server/httpapi-exercise/report.ts b/packages/opencode/test/server/httpapi-exercise/report.ts deleted file mode 100644 index 1bc4aef33b22..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/report.ts +++ /dev/null @@ -1,63 +0,0 @@ -import { Duration } from "effect" -import { indent, pad } from "./assertions" -import { routeKey } from "./routing" -import type { Options, Result, Scenario } from "./types" - -export const color = { - dim: "\x1b[2m", - green: "\x1b[32m", - red: "\x1b[31m", - yellow: "\x1b[33m", - cyan: "\x1b[36m", - reset: "\x1b[0m", -} - -export function printHeader( - options: Options, - effectRoutes: string[], - selected: Scenario[], - missing: string[], - extra: Scenario[], - paths: { database: string; global: string }, -) { - console.log(`${color.cyan}HttpApi exerciser${color.reset}`) - console.log(`${color.dim}db=${paths.database}${color.reset}`) - console.log(`${color.dim}global=${paths.global}${color.reset}`) - console.log( - `${color.dim}mode=${options.mode} selected=${selected.length} scenarioTimeout=${Duration.format(options.scenarioTimeout)} effectRoutes=${effectRoutes.length} missing=${missing.length} extra=${extra.length}${color.reset}`, - ) - console.log("") -} - -export function printResults(results: Result[], missing: string[], extra: Scenario[]) { - for (const result of results) { - if (result.status === "pass") { - console.log( - `${color.green}PASS${color.reset} ${pad(result.scenario.method, 6)} ${pad(result.scenario.path, 48)} ${result.scenario.name}`, - ) - continue - } - if (result.status === "skip") { - console.log( - `${color.yellow}SKIP${color.reset} ${pad(result.scenario.method, 6)} ${pad(result.scenario.path, 48)} ${result.scenario.name} ${color.dim}${result.scenario.reason}${color.reset}`, - ) - continue - } - console.log( - `${color.red}FAIL${color.reset} ${pad(result.scenario.method, 6)} ${pad(result.scenario.path, 48)} ${result.scenario.name}`, - ) - console.log(`${color.red}${indent(result.message)}${color.reset}`) - } - if (missing.length > 0) { - console.log("\nMissing scenarios") - for (const route of missing) console.log(`${color.red}MISS${color.reset} ${route}`) - } - if (extra.length > 0) { - console.log("\nExtra scenarios") - for (const scenario of extra) - console.log(`${color.yellow}EXTRA${color.reset} ${routeKey(scenario)} ${scenario.name}`) - } - console.log( - `\n${color.dim}summary pass=${results.filter((result) => result.status === "pass").length} fail=${results.filter((result) => result.status === "fail").length} skip=${results.filter((result) => result.status === "skip").length} missing=${missing.length} extra=${extra.length}${color.reset}`, - ) -} diff --git a/packages/opencode/test/server/httpapi-exercise/routing.ts b/packages/opencode/test/server/httpapi-exercise/routing.ts deleted file mode 100644 index 9e432af2e3bf..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/routing.ts +++ /dev/null @@ -1,96 +0,0 @@ -import { Duration } from "effect" -import { OpenApiMethods, type OpenApiSpec, type Options, type Result, type Scenario } from "./types" - -type ScenarioTimeout = `${number} ${Duration.Unit}` - -const durationUnits = new Set([ - "nano", - "nanos", - "micro", - "micros", - "milli", - "millis", - "second", - "seconds", - "minute", - "minutes", - "hour", - "hours", - "day", - "days", - "week", - "weeks", -]) - -export function routeKeys(spec: OpenApiSpec) { - return Object.entries(spec.paths ?? {}) - .flatMap(([path, item]) => - OpenApiMethods.filter((method) => item[method]).map((method) => `${method.toUpperCase()} ${path}`), - ) - .sort() -} - -export function routeKey(scenario: Scenario) { - return `${scenario.method} ${scenario.path}` -} - -export function coverageResult(scenario: Scenario): Result { - if (scenario.kind === "todo") return { status: "skip", scenario } - return { status: "pass", scenario } -} - -export function parseOptions(args: string[]): Options { - const mode = option(args, "--mode") ?? "effect" - if (mode !== "effect" && mode !== "coverage" && mode !== "auth") throw new Error(`invalid --mode ${mode}`) - return { - mode, - include: option(args, "--include"), - startAt: option(args, "--start-at"), - stopAt: option(args, "--stop-at"), - failOnMissing: args.includes("--fail-on-missing"), - failOnSkip: args.includes("--fail-on-skip"), - scenarioTimeout: parseScenarioTimeout(option(args, "--scenario-timeout") ?? "30 seconds"), - progress: args.includes("--progress"), - trace: args.includes("--trace"), - } -} - -export function matches(options: Options, scenario: Scenario) { - if (!options.include) return true - return ( - scenario.name.includes(options.include) || - scenario.path.includes(options.include) || - scenario.method.includes(options.include.toUpperCase()) - ) -} - -export function selectedScenarios(options: Options, scenarios: Scenario[]) { - const included = scenarios.filter((scenario) => matches(options, scenario)) - const start = options.startAt ? included.findIndex((scenario) => matchesName(options.startAt!, scenario)) : 0 - const end = options.stopAt - ? included.findIndex((scenario) => matchesName(options.stopAt!, scenario)) - : included.length - 1 - if (start === -1) throw new Error(`--start-at matched no scenario: ${options.startAt}`) - if (end === -1) throw new Error(`--stop-at matched no scenario: ${options.stopAt}`) - return included.slice(start, end + 1) -} - -function matchesName(value: string, scenario: Scenario) { - return scenario.name.includes(value) || scenario.path.includes(value) || scenario.method.includes(value.toUpperCase()) -} - -function option(args: string[], name: string) { - const index = args.indexOf(name) - if (index === -1) return undefined - return args[index + 1] -} - -function parseScenarioTimeout(input: string) { - if (!isScenarioTimeout(input)) throw new Error(`invalid --scenario-timeout ${input}`) - return Duration.fromInputUnsafe(input) -} - -function isScenarioTimeout(input: string): input is ScenarioTimeout { - const [amount, unit, extra] = input.trim().split(/\s+/) - return extra === undefined && amount !== undefined && Number.isFinite(Number(amount)) && durationUnits.has(unit ?? "") -} diff --git a/packages/opencode/test/server/httpapi-exercise/runner.ts b/packages/opencode/test/server/httpapi-exercise/runner.ts deleted file mode 100644 index 203921e918a8..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/runner.ts +++ /dev/null @@ -1,263 +0,0 @@ -import { Flag } from "@opencode-ai/core/flag/flag" -import { ConfigV1 } from "@opencode-ai/core/v1/config/config" -import { SessionV1 } from "@opencode-ai/core/v1/session" -import { Cause, Duration, Effect, Layer, Scope } from "effect" -import { TestLLMServer } from "../../lib/llm-server" -import { MessageID, PartID } from "../../../src/session/schema" -import { call, callAuthProbe, disposeApps } from "./backend" -import { original } from "./environment" -import { runtime } from "./runtime" -import type { ActiveScenario, Options, ProjectOptions, Result, Scenario, ScenarioContext, SeededContext } from "./types" -import { ProviderV2 } from "@opencode-ai/core/provider" -import { ModelV2 } from "@opencode-ai/core/model" - -export function runScenario(options: Options) { - return (scenario: Scenario) => { - if (scenario.kind === "todo") return Effect.succeed({ status: "skip", scenario } as Result) - return runActive(options, scenario).pipe( - Effect.timeoutOrElse({ - duration: options.scenarioTimeout, - orElse: () => Effect.die(new Error(`scenario timed out after ${Duration.format(options.scenarioTimeout)}`)), - }), - Effect.as({ status: "pass", scenario } as Result), - Effect.catchCause((cause) => Effect.succeed({ status: "fail" as const, scenario, message: Cause.pretty(cause) })), - Effect.scoped, - ) - } -} - -function runActive(options: Options, scenario: ActiveScenario) { - if (options.mode === "auth") return runAuth(scenario) - - return withContext(options, scenario, "shared", (ctx) => - Effect.gen(function* () { - yield* trace(options, scenario, "request start") - const result = yield* call(scenario, ctx) - yield* trace(options, scenario, `response ${result.status}`) - yield* trace(options, scenario, "expect start") - yield* scenario.expect(ctx, result) - yield* trace(options, scenario, "expect done") - }), - ) -} - -function runAuth(scenario: ActiveScenario) { - return Effect.gen(function* () { - const result = yield* callAuthProbe(scenario, "missing") - if (scenario.auth === "protected") { - if (result.status !== 401) throw new Error(`auth expected 401, got ${result.status}`) - const authed = yield* callAuthProbe(scenario, "valid") - if (authed.status === 401) throw new Error("auth rejected valid credentials") - return - } - - if (result.status === 401) throw new Error("auth expected public access, got 401") - if (result.timedOut) throw new Error("auth expected public access, probe timed out") - }) -} - -function withContext( - options: Options, - scenario: ActiveScenario, - label: string, - use: (ctx: SeededContext) => Effect.Effect, -) { - return Effect.acquireRelease( - Effect.gen(function* () { - yield* trace(options, scenario, `${label} context acquire start`) - const llm = scenario.project?.llm ? yield* TestLLMServer : undefined - const project = scenario.project - const dir = project - ? yield* Effect.promise(async () => (await runtime()).tmpdir(projectOptions(project, llm?.url))) - : undefined - yield* trace(options, scenario, `${label} context acquire done`) - return { dir, llm } - }), - (ctx) => - Effect.gen(function* () { - yield* trace(options, scenario, `${label} tmpdir cleanup start`) - yield* Effect.promise(async () => { - await ctx.dir?.[Symbol.asyncDispose]() - }).pipe(Effect.ignore) - yield* trace(options, scenario, `${label} tmpdir cleanup done`) - }), - ).pipe( - Effect.flatMap((context) => - Effect.gen(function* () { - yield* trace(options, scenario, `${label} runtime start`) - const modules = yield* Effect.promise(() => runtime()) - const scope = yield* Scope.Scope - const app = yield* Layer.buildWithMemoMap(modules.AppLayer, modules.memoMap, scope) - yield* trace(options, scenario, `${label} runtime done`) - const path = context.dir?.path - const instance = path - ? yield* trace(options, scenario, `${label} instance load start`).pipe( - Effect.andThen( - modules.InstanceStore.Service.use((store) => store.load({ directory: path })).pipe( - Effect.provide(app), - Effect.catchCause((cause) => - Effect.sleep("100 millis").pipe( - Effect.andThen( - modules.InstanceStore.Service.use((store) => store.load({ directory: path })).pipe( - Effect.provide(app), - ), - ), - Effect.catchCause(() => Effect.failCause(cause)), - ), - ), - ), - ), - Effect.tap(() => trace(options, scenario, `${label} instance load done`)), - ) - : undefined - const run = (effect: Effect.Effect) => - effect.pipe(Effect.provideService(modules.InstanceRef, instance), Effect.provide(app)) - const directory = () => { - if (!context.dir?.path) throw new Error("scenario needs a project directory") - return context.dir.path - } - const llm = () => { - if (!context.llm) throw new Error("scenario needs fake LLM") - return context.llm - } - const base: ScenarioContext = { - directory: context.dir?.path, - headers: (extra) => ({ - ...(context.dir?.path ? { "x-opencode-directory": context.dir.path } : {}), - ...extra, - }), - file: (name, content) => - Effect.promise(() => { - return Bun.write(`${directory()}/${name}`, content) - }).pipe(Effect.asVoid), - session: (input) => - run(modules.Session.Service.use((svc) => svc.create({ title: input?.title, parentID: input?.parentID }))), - sessionGet: (sessionID) => - run(modules.Session.Service.use((svc) => svc.get(sessionID))).pipe( - Effect.catchCause(() => Effect.succeed(undefined)), - ), - project: () => - Effect.sync(() => { - if (!instance) throw new Error("scenario needs a project directory") - return instance.project - }), - message: (sessionID, input) => - Effect.gen(function* () { - const info: SessionV1.User = { - id: MessageID.ascending(), - sessionID, - role: "user", - time: { created: Date.now() }, - agent: "build", - model: { - providerID: ProviderV2.ID.opencode, - modelID: ModelV2.ID.make("test"), - }, - } - const part: SessionV1.TextPart = { - id: PartID.ascending(), - sessionID, - messageID: info.id, - type: "text", - text: input?.text ?? "hello", - } - yield* run( - modules.Session.Service.use((svc) => - Effect.gen(function* () { - yield* svc.updateMessage(info) - yield* svc.updatePart(part) - }), - ), - ) - return { info, part } - }), - messages: (sessionID) => - run(modules.Session.Service.use((svc) => svc.messages({ sessionID }).pipe(Effect.orDie))), - worktree: (input) => run(modules.Worktree.Service.use((svc) => svc.create(input).pipe(Effect.orDie))), - worktreeRemove: (directory) => - run(modules.Worktree.Service.use((svc) => svc.remove({ directory })).pipe(Effect.ignore)), - llmText: (value) => Effect.suspend(() => llm().text(value)), - llmWait: (count) => Effect.suspend(() => llm().wait(count)), - tuiRequest: (request) => Effect.sync(() => modules.Tui.submitTuiRequest(request)), - } - yield* trace(options, scenario, `${label} seed start`) - const state = yield* scenario.seed(base) - yield* trace(options, scenario, `${label} seed done`) - yield* trace(options, scenario, `${label} use start`) - const result = yield* use({ ...base, state }) - yield* trace(options, scenario, `${label} use done`) - return result - }).pipe(Effect.ensuring(context.llm ? context.llm.reset : Effect.void)), - ), - Effect.ensuring(scenario.reset ? resetState : Effect.void), - ) -} - -function trace(options: Options, scenario: ActiveScenario, phase: string) { - return Effect.sync(() => { - if (!options.trace) return - console.log(`[trace] ${scenario.name}: ${phase}`) - }) -} - -function projectOptions( - project: ProjectOptions, - llmUrl: string | undefined, -): { git?: boolean; config?: Partial } { - if (!project.llm || !llmUrl) return { git: project.git, config: project.config } - const fake = fakeLlmConfig(llmUrl) - return { - git: project.git, - config: { - ...fake, - ...project.config, - provider: { - ...fake.provider, - ...project.config?.provider, - }, - }, - } -} - -function fakeLlmConfig(url: string): Partial { - return { - model: "test/test-model", - small_model: "test/test-model", - provider: { - test: { - name: "Test", - id: "test", - env: [], - npm: "@ai-sdk/openai-compatible", - models: { - "test-model": { - id: "test-model", - name: "Test Model", - attachment: false, - reasoning: false, - temperature: false, - tool_call: true, - release_date: "2025-01-01", - limit: { context: 100000, output: 10000 }, - cost: { input: 0, output: 0 }, - options: {}, - }, - }, - options: { - apiKey: "test-key", - baseURL: url, - }, - }, - }, - } -} - -const resetState = Effect.promise(async () => { - const modules = await runtime() - Flag.OPENCODE_SERVER_PASSWORD = original.OPENCODE_SERVER_PASSWORD - Flag.OPENCODE_SERVER_USERNAME = original.OPENCODE_SERVER_USERNAME - await disposeApps() - await modules.disposeAllInstances() - await modules.resetDatabase() - await Bun.sleep(25) -}) diff --git a/packages/opencode/test/server/httpapi-exercise/runtime.ts b/packages/opencode/test/server/httpapi-exercise/runtime.ts deleted file mode 100644 index 40d87f9d8417..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/runtime.ts +++ /dev/null @@ -1,46 +0,0 @@ -export type Runtime = { - PublicApi: (typeof import("../../../src/server/routes/instance/httpapi/public"))["PublicApi"] - HttpApiApp: (typeof import("../../../src/server/routes/instance/httpapi/server"))["HttpApiApp"] - AppLayer: (typeof import("../../../src/effect/app-runtime"))["AppLayer"] - memoMap: import("effect").Layer.MemoMap - InstanceRef: (typeof import("../../../src/effect/instance-ref"))["InstanceRef"] - InstanceStore: (typeof import("../../../src/project/instance-store"))["InstanceStore"] - Session: (typeof import("../../../src/session/session"))["Session"] - Worktree: (typeof import("../../../src/worktree"))["Worktree"] - Tui: typeof import("../../../src/server/shared/tui-control") - disposeAllInstances: (typeof import("../../fixture/fixture"))["disposeAllInstances"] - tmpdir: (typeof import("../../fixture/fixture"))["tmpdir"] - resetDatabase: (typeof import("../../fixture/db"))["resetDatabase"] -} - -let runtimePromise: Promise | undefined - -export function runtime() { - return (runtimePromise ??= (async () => { - const publicApi = await import("../../../src/server/routes/instance/httpapi/public") - const httpApiServer = await import("../../../src/server/routes/instance/httpapi/server") - const appRuntime = await import("../../../src/effect/app-runtime") - const { Layer } = await import("effect") - const instanceRef = await import("../../../src/effect/instance-ref") - const instanceStore = await import("../../../src/project/instance-store") - const session = await import("../../../src/session/session") - const worktree = await import("../../../src/worktree") - const tui = await import("../../../src/server/shared/tui-control") - const fixture = await import("../../fixture/fixture") - const db = await import("../../fixture/db") - return { - PublicApi: publicApi.PublicApi, - HttpApiApp: httpApiServer.HttpApiApp, - AppLayer: appRuntime.AppLayer, - memoMap: Layer.makeMemoMapUnsafe(), - InstanceRef: instanceRef.InstanceRef, - InstanceStore: instanceStore.InstanceStore, - Session: session.Session, - Worktree: worktree.Worktree, - Tui: tui, - disposeAllInstances: fixture.disposeAllInstances, - tmpdir: fixture.tmpdir, - resetDatabase: db.resetDatabase, - } - })()) -} diff --git a/packages/opencode/test/server/httpapi-exercise/types.ts b/packages/opencode/test/server/httpapi-exercise/types.ts deleted file mode 100644 index e68024e0df1f..000000000000 --- a/packages/opencode/test/server/httpapi-exercise/types.ts +++ /dev/null @@ -1,115 +0,0 @@ -import type { Duration, Effect } from "effect" -import { ConfigV1 } from "@opencode-ai/core/v1/config/config" -import { SessionV1 } from "@opencode-ai/core/v1/session" -import type { Project } from "../../../src/project/project" -import type { Worktree } from "../../../src/worktree" -import type { SessionID } from "../../../src/session/schema" - -export const OpenApiMethods = ["get", "post", "put", "delete", "patch"] as const -export const Methods = ["GET", "POST", "PUT", "DELETE", "PATCH"] as const - -export type Method = (typeof Methods)[number] -export type OpenApiMethod = (typeof OpenApiMethods)[number] -export type Mode = "effect" | "coverage" | "auth" -export type CaptureMode = "full" | "stream" -export type AuthPolicy = "protected" | "public" | "public-bypass" | "ticket-bypass" -export type ProjectOptions = { git?: boolean; config?: Partial; llm?: boolean } -export type OpenApiSpec = { paths?: Record>> } -export type JsonObject = Record - -export type Options = { - mode: Mode - include: string | undefined - startAt: string | undefined - stopAt: string | undefined - failOnMissing: boolean - failOnSkip: boolean - scenarioTimeout: Duration.Duration - progress: boolean - trace: boolean -} - -export type RequestSpec = { - path: string - headers?: Record - body?: unknown -} - -export type CallResult = { - status: number - contentType: string - body: unknown - text: string - timedOut: boolean -} - -export type BackendApp = { - request(input: string | URL | Request, init?: RequestInit): Response | Promise -} - -/** Effect-native helpers available while setting up and asserting a scenario. */ -export type ScenarioContext = { - directory: string | undefined - headers: (extra?: Record) => Record - file: (name: string, content: string) => Effect.Effect - session: (input?: { title?: string; parentID?: SessionID }) => Effect.Effect - sessionGet: (sessionID: SessionID) => Effect.Effect - project: () => Effect.Effect - message: (sessionID: SessionID, input?: { text?: string }) => Effect.Effect - messages: (sessionID: SessionID) => Effect.Effect - worktree: (input?: { name?: string }) => Effect.Effect - worktreeRemove: (directory: string) => Effect.Effect - llmText: (value: string) => Effect.Effect - llmWait: (count: number) => Effect.Effect - tuiRequest: (request: { path: string; body: unknown }) => Effect.Effect -} - -/** Scenario context after `.seeded(...)`; `state` preserves the seed return type in the DSL. */ -export type SeededContext = ScenarioContext & { - state: S -} - -export type Scenario = ActiveScenario | TodoScenario -export type ActiveScenario = { - kind: "active" - method: Method - path: string - name: string - project: ProjectOptions | undefined - seed: (ctx: ScenarioContext) => Effect.Effect - request: (ctx: SeededContext) => RequestSpec - authProbe: RequestSpec | undefined - expect: (ctx: SeededContext, result: CallResult) => Effect.Effect - capture: CaptureMode - reset: boolean - auth: AuthPolicy -} - -export type BuilderState = { - method: Method - path: string - name: string - project: ProjectOptions | undefined - seed: (ctx: ScenarioContext) => Effect.Effect - request: (ctx: SeededContext) => RequestSpec - authProbe: RequestSpec | undefined - capture: CaptureMode - reset: boolean - auth: AuthPolicy -} - -export type TodoScenario = { - kind: "todo" - method: Method - path: string - name: string - reason: string -} - -export type Result = - | { status: "pass"; scenario: ActiveScenario } - | { status: "fail"; scenario: ActiveScenario; message: string } - | { status: "skip"; scenario: TodoScenario } - -export type SessionInfo = { id: SessionID; title: string; parentID?: SessionID } -export type MessageSeed = { info: SessionV1.User; part: SessionV1.TextPart }