mirror of
https://github.com/anomalyco/opencode.git
synced 2026-08-11 20:19:53 -04:00
Compare commits
4 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c5ac6ba4f3 | |||
| 20af1f5e79 | |||
| 8daf912fbf | |||
| 3d545f960b |
@@ -8,6 +8,7 @@
|
||||
"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",
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
await import("../test/server/httpapi-exercise/index")
|
||||
@@ -0,0 +1,64 @@
|
||||
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")
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
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<unknown>, options: CallOptions = {}) {
|
||||
return Effect.promise(async () =>
|
||||
capture(await app(await runtime(), options).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<void> }
|
||||
|
||||
const appCache: Partial<Record<string, CachedApp>> = {}
|
||||
|
||||
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<unknown>) {
|
||||
const spec = scenario.request(ctx, ctx.state)
|
||||
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<CallResult> {
|
||||
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)
|
||||
}
|
||||
@@ -0,0 +1,210 @@
|
||||
import { Effect } from "effect"
|
||||
import { looksJson } from "./assertions"
|
||||
import type {
|
||||
ActiveScenario,
|
||||
AuthPolicy,
|
||||
BuilderState,
|
||||
CallResult,
|
||||
Comparison,
|
||||
Method,
|
||||
ProjectOptions,
|
||||
RequestSpec,
|
||||
ScenarioContext,
|
||||
SeededContext,
|
||||
TodoScenario,
|
||||
} from "./types"
|
||||
|
||||
class ScenarioBuilder<S = undefined> {
|
||||
private readonly state: BuilderState<S>
|
||||
|
||||
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",
|
||||
mutates: false,
|
||||
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<S>["request"]) {
|
||||
return this.clone({ request })
|
||||
}
|
||||
|
||||
probe(authProbe: RequestSpec) {
|
||||
return this.clone({ authProbe })
|
||||
}
|
||||
|
||||
mutating() {
|
||||
return this.clone({ mutates: true })
|
||||
}
|
||||
|
||||
preserveDatabase() {
|
||||
return this.clone({ reset: false })
|
||||
}
|
||||
|
||||
stream() {
|
||||
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<S>, result: CallResult) => Effect.Effect<void>,
|
||||
compare: Comparison = "status",
|
||||
) {
|
||||
return this.done(compare, (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<S>) => void, compare: Comparison = "json") {
|
||||
return this.jsonEffect(status, inspect ? (body, ctx) => Effect.sync(() => inspect(body, ctx)) : undefined, compare)
|
||||
}
|
||||
|
||||
/** Assert JSON status/content-type plus optional Effect assertions, e.g. DB side effects. */
|
||||
jsonEffect(
|
||||
status = 200,
|
||||
inspect?: (body: unknown, ctx: SeededContext<S>) => Effect.Effect<void>,
|
||||
compare: Comparison = "json",
|
||||
) {
|
||||
return this.done(compare, (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<BuilderState<S>>) {
|
||||
const builder = new ScenarioBuilder<S>(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<Next>(seed: (ctx: ScenarioContext) => Effect.Effect<Next>) {
|
||||
const builder = new ScenarioBuilder<Next>(this.state.method, this.state.path, this.state.name, this.state.auth)
|
||||
Object.assign(builder.state, this.state, { seed })
|
||||
return builder
|
||||
}
|
||||
|
||||
private done(
|
||||
compare: Comparison,
|
||||
expect: (ctx: SeededContext<S>, result: CallResult) => Effect.Effect<void>,
|
||||
): 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, seeded) => state.request({ ...ctx, state: seeded as S }),
|
||||
// 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,
|
||||
capture: state.capture,
|
||||
mutates: state.mutates,
|
||||
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<string, string>) {
|
||||
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 } : {}),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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)
|
||||
})
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,66 @@
|
||||
import { Duration } from "effect"
|
||||
import { indent, pad } from "./assertions"
|
||||
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}`,
|
||||
)
|
||||
}
|
||||
|
||||
function routeKey(scenario: Scenario) {
|
||||
return `${scenario.method} ${scenario.path}`
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
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<string>([
|
||||
"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 ?? "")
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
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 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"
|
||||
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, ctx.state, 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<A, E>(
|
||||
options: Options,
|
||||
scenario: ActiveScenario,
|
||||
label: string,
|
||||
use: (ctx: SeededContext<unknown>) => Effect.Effect<A, E>,
|
||||
) {
|
||||
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 = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
|
||||
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<ConfigV1.Info> } {
|
||||
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<ConfigV1.Info> {
|
||||
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)
|
||||
})
|
||||
@@ -0,0 +1,49 @@
|
||||
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"]
|
||||
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"]
|
||||
resetDatabase: (typeof import("../../fixture/db"))["resetDatabase"]
|
||||
}
|
||||
|
||||
let runtimePromise: Promise<Runtime> | 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 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")
|
||||
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,
|
||||
Project: project.Project,
|
||||
Tui: tui,
|
||||
disposeAllInstances: fixture.disposeAllInstances,
|
||||
tmpdir: fixture.tmpdir,
|
||||
resetDatabase: db.resetDatabase,
|
||||
}
|
||||
})())
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
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
|
||||
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<ConfigV1.Info>; llm?: boolean }
|
||||
export type OpenApiSpec = { paths?: Record<string, Partial<Record<OpenApiMethod, unknown>>> }
|
||||
export type JsonObject = Record<string, unknown>
|
||||
|
||||
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<string, string>
|
||||
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<Response>
|
||||
}
|
||||
|
||||
/** Effect-native helpers available while setting up and asserting a scenario. */
|
||||
export type ScenarioContext = {
|
||||
directory: string | undefined
|
||||
headers: (extra?: Record<string, string>) => Record<string, string>
|
||||
file: (name: string, content: string) => Effect.Effect<void>
|
||||
session: (input?: { title?: string; parentID?: SessionID }) => Effect.Effect<SessionInfo>
|
||||
sessionGet: (sessionID: SessionID) => Effect.Effect<SessionInfo | undefined>
|
||||
project: () => Effect.Effect<Project.Info>
|
||||
message: (sessionID: SessionID, input?: { text?: string }) => Effect.Effect<MessageSeed>
|
||||
messages: (sessionID: SessionID) => Effect.Effect<SessionV1.WithParts[]>
|
||||
worktree: (input?: { name?: string }) => Effect.Effect<Worktree.Info>
|
||||
worktreeRemove: (directory: string) => Effect.Effect<void>
|
||||
llmText: (value: string) => Effect.Effect<void>
|
||||
llmWait: (count: number) => Effect.Effect<void>
|
||||
tuiRequest: (request: { path: string; body: unknown }) => Effect.Effect<void>
|
||||
}
|
||||
|
||||
/** Scenario context after `.seeded(...)`; `state` preserves the seed return type in the DSL. */
|
||||
export type SeededContext<S> = 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<unknown>
|
||||
request: (ctx: ScenarioContext, state: unknown) => RequestSpec
|
||||
authProbe: RequestSpec | undefined
|
||||
expect: (ctx: ScenarioContext, state: unknown, result: CallResult) => Effect.Effect<void>
|
||||
compare: Comparison
|
||||
capture: CaptureMode
|
||||
mutates: boolean
|
||||
reset: boolean
|
||||
auth: AuthPolicy
|
||||
}
|
||||
|
||||
export type BuilderState<S> = {
|
||||
method: Method
|
||||
path: string
|
||||
name: string
|
||||
project: ProjectOptions | undefined
|
||||
seed: (ctx: ScenarioContext) => Effect.Effect<S>
|
||||
request: (ctx: SeededContext<S>) => RequestSpec
|
||||
authProbe: RequestSpec | undefined
|
||||
capture: CaptureMode
|
||||
mutates: boolean
|
||||
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 }
|
||||
@@ -53,6 +53,7 @@ import { DialogModel } from "./component/dialog-model"
|
||||
import { useConnected } from "./component/use-connected"
|
||||
import { DialogMcp } from "./component/dialog-mcp"
|
||||
import { DialogStatus } from "./component/dialog-status"
|
||||
import { DialogConfig } from "./component/dialog-config"
|
||||
import { DialogDebug } from "./component/dialog-debug"
|
||||
import { DialogPair, type DialogPairCredentials } from "./component/dialog-pair"
|
||||
import { createOpencodeClient } from "@opencode-ai/sdk/v2/client"
|
||||
@@ -218,7 +219,9 @@ function fromV1(config: TuiConfigV1.Resolved): Config.Info {
|
||||
}
|
||||
|
||||
function isConfigInterface(config: Config.Interface | TuiConfigV1.Resolved): config is Config.Interface {
|
||||
return "get" in config && typeof config.get === "function" && "update" in config && typeof config.update === "function"
|
||||
return (
|
||||
"get" in config && typeof config.get === "function" && "update" in config && typeof config.update === "function"
|
||||
)
|
||||
}
|
||||
|
||||
export const run = Effect.fn("Tui.run")(function* (input: TuiInput) {
|
||||
@@ -477,7 +480,8 @@ function App(props: {
|
||||
}) {
|
||||
const log = useLog({ component: "app" })
|
||||
const startup = useTuiStartup()
|
||||
const config = useConfig().data
|
||||
const configContext = useConfig()
|
||||
const config = configContext.data
|
||||
const route = useRoute()
|
||||
const dimensions = useTerminalDimensions()
|
||||
const renderer = useRenderer()
|
||||
@@ -587,10 +591,12 @@ function App(props: {
|
||||
|
||||
renderer.clearSelection()
|
||||
}
|
||||
const [terminalTitleEnabled, setTerminalTitleEnabled] = createSignal(kv.get("terminal_title_enabled", true))
|
||||
const [pasteSummaryEnabled, setPasteSummaryEnabled] = createSignal(
|
||||
kv.get("paste_summary_enabled", true),
|
||||
)
|
||||
const [terminalTitleEnabled, setTerminalTitleEnabled] = kv.signal("terminal_title_enabled", true)
|
||||
const [pasteSummaryEnabled, setPasteSummaryEnabled] = kv.signal("paste_summary_enabled", true)
|
||||
|
||||
createEffect(() => {
|
||||
renderer.useMouse = !Flag.OPENCODE_DISABLE_MOUSE && config.mouse
|
||||
})
|
||||
|
||||
// Update terminal window title based on current route and session
|
||||
createEffect(() => {
|
||||
@@ -849,6 +855,16 @@ function App(props: {
|
||||
},
|
||||
category: "Integration",
|
||||
},
|
||||
{
|
||||
name: "opencode.settings",
|
||||
title: "Open settings",
|
||||
slashName: "settings",
|
||||
enabled: configContext.writable,
|
||||
run: () => {
|
||||
dialog.replace(() => <DialogConfig />)
|
||||
},
|
||||
category: "System",
|
||||
},
|
||||
{
|
||||
name: "opencode.status",
|
||||
title: "View status",
|
||||
|
||||
@@ -0,0 +1,354 @@
|
||||
import { TextAttributes } from "@opentui/core"
|
||||
import { useTerminalDimensions } from "@opentui/solid"
|
||||
import { createMemo, createSignal, onMount, Show } from "solid-js"
|
||||
import { useConfig } from "../config"
|
||||
import { useTheme } from "../context/theme"
|
||||
import { useDialog } from "../ui/dialog"
|
||||
import { DialogSelect } from "../ui/dialog-select"
|
||||
import { useToast } from "../ui/toast"
|
||||
|
||||
type Setting = {
|
||||
title: string
|
||||
category: string
|
||||
description: string
|
||||
detail?: string
|
||||
path: string[]
|
||||
default: unknown
|
||||
values?: readonly unknown[]
|
||||
labels?: readonly string[]
|
||||
step?: number
|
||||
min?: number
|
||||
max?: number
|
||||
format?: (value: unknown) => string
|
||||
}
|
||||
|
||||
const settings: Setting[] = [
|
||||
{
|
||||
title: "Theme",
|
||||
category: "Appearance",
|
||||
description: "Interface color theme",
|
||||
detail:
|
||||
"Choose the color theme used throughout OpenCode. Custom themes discovered from your config directory appear here alongside the built-in themes.",
|
||||
path: ["theme", "name"],
|
||||
default: "opencode",
|
||||
},
|
||||
{
|
||||
title: "Color mode",
|
||||
category: "Appearance",
|
||||
description: "Terminal color preference",
|
||||
detail:
|
||||
"Choose how OpenCode selects its colors. System follows your terminal preference, while dark and light keep the interface in a fixed mode.",
|
||||
path: ["theme", "mode"],
|
||||
default: "system",
|
||||
values: ["system", "dark", "light"],
|
||||
},
|
||||
{
|
||||
title: "Animations",
|
||||
category: "Appearance",
|
||||
description: "Interface motion",
|
||||
path: ["animations"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Tips",
|
||||
category: "Appearance",
|
||||
description: "Home screen hints",
|
||||
path: ["hints", "tips"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Onboarding",
|
||||
category: "Appearance",
|
||||
description: "Getting-started guidance",
|
||||
path: ["hints", "onboarding"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Sidebar",
|
||||
category: "Session",
|
||||
description: "Session sidebar visibility",
|
||||
path: ["session", "sidebar"],
|
||||
default: "auto",
|
||||
values: ["hide", "auto"],
|
||||
},
|
||||
{
|
||||
title: "Scrollbar",
|
||||
category: "Session",
|
||||
description: "Transcript scrollbar",
|
||||
path: ["session", "scrollbar"],
|
||||
default: false,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Thinking",
|
||||
category: "Session",
|
||||
description: "Model reasoning by default",
|
||||
path: ["session", "thinking"],
|
||||
default: "hide",
|
||||
values: ["hide", "show"],
|
||||
},
|
||||
{
|
||||
title: "Grouping",
|
||||
category: "Session",
|
||||
description: "Related transcript items",
|
||||
path: ["session", "grouping"],
|
||||
default: "auto",
|
||||
values: ["none", "auto"],
|
||||
},
|
||||
{
|
||||
title: "Layout",
|
||||
category: "Diffs",
|
||||
description: "Diff presentation",
|
||||
path: ["diffs", "view"],
|
||||
default: "auto",
|
||||
values: ["auto", "split", "unified"],
|
||||
},
|
||||
{
|
||||
title: "Wrapping",
|
||||
category: "Diffs",
|
||||
description: "Long diff lines",
|
||||
path: ["diffs", "wrap"],
|
||||
default: "word",
|
||||
values: ["none", "word"],
|
||||
},
|
||||
{
|
||||
title: "File tree",
|
||||
category: "Diffs",
|
||||
description: "Diff file navigation",
|
||||
path: ["diffs", "tree"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Single patch",
|
||||
category: "Diffs",
|
||||
description: "Only the selected patch",
|
||||
path: ["diffs", "single"],
|
||||
default: false,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Scroll speed",
|
||||
category: "Input",
|
||||
description: "Distance per input tick",
|
||||
path: ["scroll", "speed"],
|
||||
default: 3,
|
||||
step: 0.25,
|
||||
min: 0.25,
|
||||
max: 10,
|
||||
format: (value) => Number(value).toFixed(2),
|
||||
},
|
||||
{
|
||||
title: "Acceleration",
|
||||
category: "Input",
|
||||
description: "Repeated scrolling",
|
||||
path: ["scroll", "acceleration"],
|
||||
default: false,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Mouse",
|
||||
category: "Input",
|
||||
description: "Terminal mouse capture",
|
||||
path: ["mouse"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Editor context",
|
||||
category: "Input",
|
||||
description: "Active selection in prompts",
|
||||
path: ["prompt", "editor"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Large pastes",
|
||||
category: "Input",
|
||||
description: "Paste display style",
|
||||
path: ["prompt", "paste"],
|
||||
default: "compact",
|
||||
values: ["compact", "full"],
|
||||
},
|
||||
{
|
||||
title: "Leader timeout",
|
||||
category: "Input",
|
||||
description: "Wait after leader key",
|
||||
path: ["leader", "timeout"],
|
||||
default: 2000,
|
||||
step: 250,
|
||||
min: 250,
|
||||
max: 10000,
|
||||
format: (value) => `${value} ms`,
|
||||
},
|
||||
{
|
||||
title: "Attention",
|
||||
category: "Alerts",
|
||||
description: "Alerts when input is needed",
|
||||
path: ["attention", "enabled"],
|
||||
default: false,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Notifications",
|
||||
category: "Alerts",
|
||||
description: "System notifications",
|
||||
path: ["attention", "notifications"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Sounds",
|
||||
category: "Alerts",
|
||||
description: "Attention sounds",
|
||||
path: ["attention", "sound"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
{
|
||||
title: "Volume",
|
||||
category: "Alerts",
|
||||
description: "Attention sound level",
|
||||
path: ["attention", "volume"],
|
||||
default: 0.4,
|
||||
step: 0.1,
|
||||
min: 0,
|
||||
max: 1,
|
||||
format: (value) => `${Math.round(Number(value) * 100)}%`,
|
||||
},
|
||||
{
|
||||
title: "Window title",
|
||||
category: "Terminal",
|
||||
description: "Update terminal title",
|
||||
path: ["terminal", "title"],
|
||||
default: true,
|
||||
values: [false, true],
|
||||
labels: ["off", "on"],
|
||||
},
|
||||
]
|
||||
|
||||
export function DialogConfig() {
|
||||
const config = useConfig()
|
||||
const dialog = useDialog()
|
||||
const toast = useToast()
|
||||
const themeState = useTheme()
|
||||
const { theme } = themeState
|
||||
const dimensions = useTerminalDimensions()
|
||||
const [selected, setSelected] = createSignal(settings[0])
|
||||
const [saving, setSaving] = createSignal(false)
|
||||
onMount(() => {
|
||||
dialog.setSize("xlarge")
|
||||
dialog.setCentered(true)
|
||||
})
|
||||
|
||||
const value = (setting: Setting) => {
|
||||
const current = setting.path.reduce<unknown>((result, key) => {
|
||||
if (!result || typeof result !== "object") return undefined
|
||||
return (result as Record<string, unknown>)[key]
|
||||
}, config.data)
|
||||
if (setting.path.join(".") === "theme.name") return current ?? themeState.selected
|
||||
return current ?? setting.default
|
||||
}
|
||||
const values = (setting: Setting) =>
|
||||
setting.path.join(".") === "theme.name"
|
||||
? Object.keys(themeState.all()).sort((a, b) => a.localeCompare(b, undefined, { sensitivity: "base" }))
|
||||
: setting.values
|
||||
const display = (setting: Setting) => {
|
||||
const current = value(setting)
|
||||
if (setting.format) return setting.format(current)
|
||||
const index = setting.values?.indexOf(current)
|
||||
return index === undefined || index < 0 ? String(current) : (setting.labels?.[index] ?? String(current))
|
||||
}
|
||||
const options = createMemo(() =>
|
||||
settings.map((setting) => ({
|
||||
title: setting.title,
|
||||
category: setting.category,
|
||||
value: setting,
|
||||
footer: selected() === setting ? `‹ ${display(setting)} ›` : ` ${display(setting)} `,
|
||||
})),
|
||||
)
|
||||
const split = createMemo(() => dimensions().width >= 110)
|
||||
const height = createMemo(() => Math.max(8, Math.min(36, dimensions().height - 12)))
|
||||
|
||||
async function change(setting: Setting, direction: number) {
|
||||
if (saving()) return
|
||||
const current = value(setting)
|
||||
const choices = values(setting)
|
||||
const next = choices
|
||||
? choices[(choices.indexOf(current) + direction + choices.length) % choices.length]
|
||||
: Math.min(setting.max!, Math.max(setting.min!, Number(current) + direction * setting.step!))
|
||||
if (next === current) return
|
||||
setSaving(true)
|
||||
await config
|
||||
.update((draft) => {
|
||||
const parent = setting.path.slice(0, -1).reduce<Record<string, unknown>>((result, key) => {
|
||||
if (!result[key] || typeof result[key] !== "object") result[key] = {}
|
||||
return result[key] as Record<string, unknown>
|
||||
}, draft)
|
||||
parent[setting.path.at(-1)!] = next
|
||||
})
|
||||
.catch(toast.error)
|
||||
.finally(() => setSaving(false))
|
||||
}
|
||||
|
||||
return (
|
||||
<box flexDirection="row" height={height() + 1}>
|
||||
<box width={split() ? "54%" : "100%"}>
|
||||
<DialogSelect
|
||||
title="Settings"
|
||||
options={options()}
|
||||
renderFilter={false}
|
||||
hideClose={split()}
|
||||
maxHeight={height() - 2}
|
||||
onMove={(option) => setSelected(option.value)}
|
||||
onSelect={(option) => void change(option.value, 1)}
|
||||
bindings={[
|
||||
{ key: "left", desc: "Previous value", group: "Settings", cmd: () => void change(selected(), -1) },
|
||||
{ key: "right", desc: "Next value", group: "Settings", cmd: () => void change(selected(), 1) },
|
||||
]}
|
||||
/>
|
||||
</box>
|
||||
<Show when={split()}>
|
||||
<box
|
||||
position="relative"
|
||||
top={-1}
|
||||
width="46%"
|
||||
height={height() + 2}
|
||||
paddingTop={1}
|
||||
paddingLeft={2}
|
||||
paddingRight={2}
|
||||
backgroundColor={theme.backgroundElement}
|
||||
>
|
||||
<box flexDirection="row" justifyContent="space-between">
|
||||
<text fg={theme.primary} attributes={TextAttributes.BOLD}>
|
||||
{selected().title}
|
||||
</text>
|
||||
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
|
||||
esc
|
||||
</text>
|
||||
</box>
|
||||
<box paddingTop={1}>
|
||||
<text fg={theme.text} wrapMode="word">
|
||||
{selected().detail ?? selected().description}
|
||||
</text>
|
||||
</box>
|
||||
</box>
|
||||
</Show>
|
||||
</box>
|
||||
)
|
||||
}
|
||||
@@ -179,6 +179,7 @@ export function resolve(input: Info, options: { terminalSuspend: boolean }): Res
|
||||
const ConfigContext = createContext<{
|
||||
data: Resolved
|
||||
update: Interface["update"]
|
||||
writable: boolean
|
||||
}>()
|
||||
|
||||
export function ConfigProvider(props: {
|
||||
@@ -195,7 +196,9 @@ export function ConfigProvider(props: {
|
||||
setConfig(reconcile(resolve(info, props.options ?? { terminalSuspend: true })))
|
||||
return info
|
||||
}
|
||||
return <ConfigContext.Provider value={{ data: config, update }}>{props.children}</ConfigContext.Provider>
|
||||
return (
|
||||
<ConfigContext.Provider value={{ data: config, update, writable: !!host }}>{props.children}</ConfigContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useConfig() {
|
||||
|
||||
@@ -129,6 +129,15 @@ export const { use: useTheme, provider: ThemeProvider } = createSimpleContext({
|
||||
if (theme) setStore("active", theme)
|
||||
})
|
||||
|
||||
createEffect(() => {
|
||||
const mode = config.theme?.mode
|
||||
if (mode === "dark" || mode === "light") {
|
||||
pin(mode)
|
||||
return
|
||||
}
|
||||
if (mode === "system" && store.lock !== undefined) free()
|
||||
})
|
||||
|
||||
function syncCustomThemes() {
|
||||
return themes
|
||||
.discover()
|
||||
|
||||
@@ -6,8 +6,13 @@ import { useToast } from "../../ui/toast"
|
||||
import { useSDK } from "../../context/sdk"
|
||||
import { errorMessage } from "../../util/error"
|
||||
import { DialogFork } from "./dialog-fork"
|
||||
import type { PromptInfo } from "../../prompt/history"
|
||||
|
||||
export function DialogMessage(props: { messageID: string; sessionID: string }) {
|
||||
export function DialogMessage(props: {
|
||||
messageID: string
|
||||
sessionID: string
|
||||
setPrompt?: (prompt: PromptInfo) => void
|
||||
}) {
|
||||
const data = useData()
|
||||
const clipboard = useClipboard()
|
||||
const toast = useToast()
|
||||
@@ -22,9 +27,26 @@ export function DialogMessage(props: { messageID: string; sessionID: string }) {
|
||||
title: "Revert",
|
||||
value: "session.revert",
|
||||
description: "undo messages and file changes",
|
||||
onSelect: async (dialog) => {
|
||||
await sdk.api.session
|
||||
.revert.stage({ sessionID: props.sessionID, messageID: props.messageID })
|
||||
onSelect: (dialog) => {
|
||||
const value = message()
|
||||
if (value?.type === "user") {
|
||||
props.setPrompt?.({
|
||||
text: value.text,
|
||||
files: value.files?.map((file) => ({
|
||||
uri: file.source.type === "uri" ? file.source.uri : `data:${file.mime};base64,${file.data}`,
|
||||
name: file.name,
|
||||
description: file.description,
|
||||
mention: file.mention ? { ...file.mention } : undefined,
|
||||
})),
|
||||
agents: value.agents?.map((agent) => ({
|
||||
name: agent.name,
|
||||
mention: agent.mention ? { ...agent.mention } : undefined,
|
||||
})),
|
||||
pasted: [],
|
||||
})
|
||||
}
|
||||
void sdk.api.session.revert
|
||||
.stage({ sessionID: props.sessionID, messageID: props.messageID })
|
||||
.catch((error) => toast.show({ message: errorMessage(error), variant: "error", duration: 5000 }))
|
||||
dialog.clear()
|
||||
},
|
||||
|
||||
@@ -1468,6 +1468,7 @@ function UserMessage(props: { message: SessionMessageUser }) {
|
||||
)
|
||||
const dialog = useDialog()
|
||||
const renderer = useRenderer()
|
||||
const promptRef = usePromptRef()
|
||||
|
||||
return (
|
||||
<Show when={props.message.text.trim() || files().length}>
|
||||
@@ -1486,7 +1487,13 @@ function UserMessage(props: { message: SessionMessageUser }) {
|
||||
}}
|
||||
onMouseUp={() => {
|
||||
if (renderer.getSelection()?.getSelectedText()) return
|
||||
dialog.replace(() => <DialogMessage messageID={props.message.id} sessionID={ctx.sessionID} />)
|
||||
dialog.replace(() => (
|
||||
<DialogMessage
|
||||
messageID={props.message.id}
|
||||
sessionID={ctx.sessionID}
|
||||
setPrompt={(value) => promptRef.current?.set(value)}
|
||||
/>
|
||||
))
|
||||
}}
|
||||
paddingTop={1}
|
||||
paddingBottom={1}
|
||||
|
||||
@@ -51,6 +51,8 @@ export interface DialogSelectProps<T> {
|
||||
}[]
|
||||
bindings?: readonly Binding<Renderable, KeyEvent>[]
|
||||
current?: T
|
||||
hideClose?: boolean
|
||||
maxHeight?: number
|
||||
}
|
||||
|
||||
export interface DialogSelectOption<T = any> {
|
||||
@@ -212,7 +214,7 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
})
|
||||
|
||||
const dimensions = useTerminalDimensions()
|
||||
const height = createMemo(() => Math.min(rows(), Math.floor(dimensions().height / 2) - 6))
|
||||
const height = createMemo(() => Math.min(rows(), props.maxHeight ?? Math.floor(dimensions().height / 2) - 6))
|
||||
|
||||
const selected = createMemo(() => flat()[store.selected])
|
||||
|
||||
@@ -565,9 +567,11 @@ export function DialogSelect<T>(props: DialogSelectProps<T>) {
|
||||
{props.title}
|
||||
</text>
|
||||
)}
|
||||
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
|
||||
esc
|
||||
</text>
|
||||
<Show when={!props.hideClose}>
|
||||
<text fg={theme.textMuted} onMouseUp={() => dialog.clear()}>
|
||||
esc
|
||||
</text>
|
||||
</Show>
|
||||
</box>
|
||||
<Show when={props.renderFilter !== false}>
|
||||
<box paddingTop={1}>
|
||||
@@ -789,7 +793,11 @@ function Option(props: {
|
||||
</text>
|
||||
<Show when={props.footer}>
|
||||
<box flexShrink={0}>
|
||||
<text fg={props.active && !props.muted ? fg : theme.textMuted}>{props.footer}</text>
|
||||
{typeof props.footer === "string" ? (
|
||||
<text fg={props.active && !props.muted ? fg : theme.textMuted}>{props.footer}</text>
|
||||
) : (
|
||||
props.footer
|
||||
)}
|
||||
</box>
|
||||
</Show>
|
||||
</>
|
||||
|
||||
Reference in New Issue
Block a user