Merge remote-tracking branch 'upstream/dev' into refactor-shells
This commit is contained in:
commit
b1d9c57655
74 changed files with 1991 additions and 802 deletions
|
|
@ -55,6 +55,8 @@ const it = testEffect(layer)
|
|||
const load = () => Effect.runPromise(Config.Service.use((svc) => svc.get()).pipe(Effect.scoped, Effect.provide(layer)))
|
||||
const save = (config: Config.Info) =>
|
||||
Effect.runPromise(Config.Service.use((svc) => svc.update(config)).pipe(Effect.scoped, Effect.provide(layer)))
|
||||
const saveGlobal = (config: Config.Info) =>
|
||||
Effect.runPromise(Config.Service.use((svc) => svc.updateGlobal(config)).pipe(Effect.scoped, Effect.provide(layer)))
|
||||
const clear = (wait = false) =>
|
||||
Effect.runPromise(Config.Service.use((svc) => svc.invalidate(wait)).pipe(Effect.scoped, Effect.provide(layer)))
|
||||
const listDirs = () =>
|
||||
|
|
@ -142,6 +144,106 @@ test("loads JSON config file", async () => {
|
|||
})
|
||||
})
|
||||
|
||||
test("loads shell config field", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await writeConfig(dir, {
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
shell: "bash",
|
||||
})
|
||||
},
|
||||
})
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
const config = await load()
|
||||
expect(config.shell).toBe("bash")
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("updates config and preserves empty shell sentinel", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await writeConfig(
|
||||
dir,
|
||||
{
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
shell: "bash",
|
||||
},
|
||||
"config.json",
|
||||
)
|
||||
},
|
||||
})
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
await save({ shell: "" })
|
||||
|
||||
const writtenConfig = await Filesystem.readJson<{ shell?: string }>(path.join(tmp.path, "config.json"))
|
||||
expect(writtenConfig.shell).toBe("")
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("updates global config and omits empty shell key in json", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await writeConfig(dir, {
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
shell: "bash",
|
||||
})
|
||||
},
|
||||
})
|
||||
|
||||
const prev = Global.Path.config
|
||||
;(Global.Path as { config: string }).config = tmp.path
|
||||
await clear(true)
|
||||
|
||||
try {
|
||||
await saveGlobal({ shell: "" })
|
||||
|
||||
const writtenConfig = await Filesystem.readJson<{ shell?: string }>(path.join(tmp.path, "opencode.json"))
|
||||
expect("shell" in writtenConfig).toBe(false)
|
||||
} finally {
|
||||
;(Global.Path as { config: string }).config = prev
|
||||
await clear(true)
|
||||
}
|
||||
})
|
||||
|
||||
test("updates global config and omits empty shell key in jsonc", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
await Filesystem.write(
|
||||
path.join(dir, "opencode.jsonc"),
|
||||
JSON.stringify({
|
||||
$schema: "https://opencode.ai/config.json",
|
||||
shell: "bash",
|
||||
model: "test/model",
|
||||
}),
|
||||
)
|
||||
},
|
||||
})
|
||||
|
||||
const prev = Global.Path.config
|
||||
;(Global.Path as { config: string }).config = tmp.path
|
||||
await clear(true)
|
||||
|
||||
try {
|
||||
await saveGlobal({ shell: "" })
|
||||
|
||||
const file = path.join(tmp.path, "opencode.jsonc")
|
||||
const writtenConfig = await Filesystem.readText(file)
|
||||
const parsed = ConfigParse.schema(Config.Info.zod, ConfigParse.jsonc(writtenConfig, file), file)
|
||||
expect(writtenConfig).not.toContain('"shell"')
|
||||
expect(parsed.shell).toBeUndefined()
|
||||
expect(parsed.model).toBe("test/model")
|
||||
} finally {
|
||||
;(Global.Path as { config: string }).config = prev
|
||||
await clear(true)
|
||||
}
|
||||
})
|
||||
|
||||
test("loads formatter boolean config", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
init: async (dir) => {
|
||||
|
|
@ -886,7 +988,6 @@ test("installs dependencies in writable OPENCODE_CONFIG_DIR", async () => {
|
|||
const noopNpm = Layer.mock(Npm.Service)({
|
||||
install: () => Effect.void,
|
||||
add: () => Effect.die("not implemented"),
|
||||
outdated: () => Effect.succeed(false),
|
||||
which: () => Effect.succeed(Option.none()),
|
||||
})
|
||||
const testLayer = Config.layer.pipe(
|
||||
|
|
|
|||
|
|
@ -69,64 +69,46 @@ describe("installation", () => {
|
|||
expect(result).toBe("4.0.0-beta.1")
|
||||
})
|
||||
|
||||
test("reads npm versions via npm view", async () => {
|
||||
const calls: string[][] = []
|
||||
const layer = testLayer(
|
||||
() => {
|
||||
throw new Error("unexpected http request")
|
||||
},
|
||||
(cmd, args) => {
|
||||
calls.push([cmd, ...args])
|
||||
if (cmd === "npm" && args[0] === "view") return '"1.5.0"\n'
|
||||
return ""
|
||||
},
|
||||
)
|
||||
test("reads npm versions via registry", async () => {
|
||||
const calls: string[] = []
|
||||
const layer = testLayer((request) => {
|
||||
calls.push(request.url)
|
||||
return jsonResponse({ version: "1.5.0" })
|
||||
})
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Installation.Service.use((svc) => svc.latest("npm")).pipe(Effect.provide(layer)),
|
||||
)
|
||||
expect(result).toBe("1.5.0")
|
||||
expect(calls).toContainEqual(["npm", "view", `opencode-ai@${InstallationChannel}`, "version", "--json"])
|
||||
expect(calls).toContain(`https://registry.npmjs.org/opencode-ai/${InstallationChannel}`)
|
||||
})
|
||||
|
||||
test("reads npm versions via bun pm view", async () => {
|
||||
const calls: string[][] = []
|
||||
const layer = testLayer(
|
||||
() => {
|
||||
throw new Error("unexpected http request")
|
||||
},
|
||||
(cmd, args) => {
|
||||
calls.push([cmd, ...args])
|
||||
if (cmd === "bun" && args[0] === "pm") return '"1.6.0"\n'
|
||||
return ""
|
||||
},
|
||||
)
|
||||
test("reads bun versions via registry", async () => {
|
||||
const calls: string[] = []
|
||||
const layer = testLayer((request) => {
|
||||
calls.push(request.url)
|
||||
return jsonResponse({ version: "1.6.0" })
|
||||
})
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Installation.Service.use((svc) => svc.latest("bun")).pipe(Effect.provide(layer)),
|
||||
)
|
||||
expect(result).toBe("1.6.0")
|
||||
expect(calls).toContainEqual(["bun", "pm", "view", `opencode-ai@${InstallationChannel}`, "version", "--json"])
|
||||
expect(calls).toContain(`https://registry.npmjs.org/opencode-ai/${InstallationChannel}`)
|
||||
})
|
||||
|
||||
test("reads npm versions via pnpm view", async () => {
|
||||
const calls: string[][] = []
|
||||
const layer = testLayer(
|
||||
() => {
|
||||
throw new Error("unexpected http request")
|
||||
},
|
||||
(cmd, args) => {
|
||||
calls.push([cmd, ...args])
|
||||
if (cmd === "pnpm" && args[0] === "view") return '"1.7.0"\n'
|
||||
return ""
|
||||
},
|
||||
)
|
||||
test("reads pnpm versions via registry", async () => {
|
||||
const calls: string[] = []
|
||||
const layer = testLayer((request) => {
|
||||
calls.push(request.url)
|
||||
return jsonResponse({ version: "1.7.0" })
|
||||
})
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Installation.Service.use((svc) => svc.latest("pnpm")).pipe(Effect.provide(layer)),
|
||||
)
|
||||
expect(result).toBe("1.7.0")
|
||||
expect(calls).toContainEqual(["pnpm", "view", `opencode-ai@${InstallationChannel}`, "version", "--json"])
|
||||
expect(calls).toContain(`https://registry.npmjs.org/opencode-ai/${InstallationChannel}`)
|
||||
})
|
||||
|
||||
test("reads scoop manifest versions", async () => {
|
||||
|
|
|
|||
|
|
@ -1,143 +0,0 @@
|
|||
import fs from "fs/promises"
|
||||
import path from "path"
|
||||
import { describe, expect, test } from "bun:test"
|
||||
import { Effect, Layer, Stream } from "effect"
|
||||
import { NodeFileSystem } from "@effect/platform-node"
|
||||
import { AppFileSystem } from "@opencode-ai/core/filesystem"
|
||||
import { Global } from "@opencode-ai/core/global"
|
||||
import { EffectFlock } from "@opencode-ai/core/util/effect-flock"
|
||||
import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process"
|
||||
import { Npm } from "@opencode-ai/core/npm"
|
||||
import { tmpdir } from "./fixture/fixture"
|
||||
|
||||
const win = process.platform === "win32"
|
||||
const encoder = new TextEncoder()
|
||||
function mockSpawner(handler: (cmd: string, args: readonly string[]) => string = () => "") {
|
||||
const spawner = ChildProcessSpawner.make((command) => {
|
||||
const std = ChildProcess.isStandardCommand(command) ? command : undefined
|
||||
const output = handler(std?.command ?? "", std?.args ?? [])
|
||||
return Effect.succeed(
|
||||
ChildProcessSpawner.makeHandle({
|
||||
pid: ChildProcessSpawner.ProcessId(0),
|
||||
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(0)),
|
||||
isRunning: Effect.succeed(false),
|
||||
kill: () => Effect.void,
|
||||
stdin: { [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") } as any,
|
||||
stdout: output ? Stream.make(encoder.encode(output)) : Stream.empty,
|
||||
stderr: Stream.empty,
|
||||
all: Stream.empty,
|
||||
getInputFd: () => ({ [Symbol.for("effect/Sink/TypeId")]: Symbol.for("effect/Sink/TypeId") }) as any,
|
||||
getOutputFd: () => Stream.empty,
|
||||
unref: Effect.succeed(Effect.void),
|
||||
}),
|
||||
)
|
||||
})
|
||||
return Layer.succeed(ChildProcessSpawner.ChildProcessSpawner, spawner)
|
||||
}
|
||||
|
||||
function testLayer(spawnHandler?: (cmd: string, args: readonly string[]) => string) {
|
||||
return Npm.layer.pipe(
|
||||
Layer.provide(mockSpawner(spawnHandler)),
|
||||
Layer.provide(EffectFlock.layer),
|
||||
Layer.provide(AppFileSystem.layer),
|
||||
Layer.provide(Global.layer),
|
||||
Layer.provide(NodeFileSystem.layer),
|
||||
)
|
||||
}
|
||||
|
||||
const writePackage = (dir: string, pkg: Record<string, unknown>) =>
|
||||
Bun.write(
|
||||
path.join(dir, "package.json"),
|
||||
JSON.stringify({
|
||||
version: "1.0.0",
|
||||
...pkg,
|
||||
}),
|
||||
)
|
||||
|
||||
describe("Npm.sanitize", () => {
|
||||
test("keeps normal scoped package specs unchanged", () => {
|
||||
expect(Npm.sanitize("@opencode/acme")).toBe("@opencode/acme")
|
||||
expect(Npm.sanitize("@opencode/acme@1.0.0")).toBe("@opencode/acme@1.0.0")
|
||||
expect(Npm.sanitize("prettier")).toBe("prettier")
|
||||
})
|
||||
|
||||
test("handles git https specs", () => {
|
||||
const spec = "acme@git+https://github.com/opencode/acme.git"
|
||||
const expected = win ? "acme@git+https_//github.com/opencode/acme.git" : spec
|
||||
expect(Npm.sanitize(spec)).toBe(expected)
|
||||
})
|
||||
})
|
||||
|
||||
describe("Npm.install", () => {
|
||||
test("respects omit from project .npmrc", async () => {
|
||||
await using tmp = await tmpdir()
|
||||
|
||||
await writePackage(tmp.path, {
|
||||
name: "fixture",
|
||||
dependencies: {
|
||||
"prod-pkg": "file:./prod-pkg",
|
||||
},
|
||||
devDependencies: {
|
||||
"dev-pkg": "file:./dev-pkg",
|
||||
},
|
||||
})
|
||||
await Bun.write(path.join(tmp.path, ".npmrc"), "omit=dev\n")
|
||||
await fs.mkdir(path.join(tmp.path, "prod-pkg"))
|
||||
await fs.mkdir(path.join(tmp.path, "dev-pkg"))
|
||||
await writePackage(path.join(tmp.path, "prod-pkg"), { name: "prod-pkg" })
|
||||
await writePackage(path.join(tmp.path, "dev-pkg"), { name: "dev-pkg" })
|
||||
|
||||
await Npm.install(tmp.path)
|
||||
|
||||
await expect(fs.stat(path.join(tmp.path, "node_modules", "prod-pkg"))).resolves.toBeDefined()
|
||||
await expect(fs.stat(path.join(tmp.path, "node_modules", "dev-pkg"))).rejects.toThrow()
|
||||
})
|
||||
})
|
||||
|
||||
describe("Npm.outdated", () => {
|
||||
test("checks latest via npm view", async () => {
|
||||
const calls: string[][] = []
|
||||
const layer = testLayer((cmd, args) => {
|
||||
calls.push([cmd, ...args])
|
||||
if (cmd === "npm" && args[0] === "view") return '"2.0.0"\n'
|
||||
return ""
|
||||
})
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Npm.Service.use((svc) => svc.outdated("example", "1.0.0")).pipe(Effect.provide(layer)),
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(calls).toContainEqual(["npm", "view", "example", "dist-tags.latest", "--json"])
|
||||
})
|
||||
|
||||
test("keeps range comparison behavior", async () => {
|
||||
const layer = testLayer((cmd, args) => {
|
||||
if (cmd === "npm" && args[0] === "view") return '"2.3.0"\n'
|
||||
return ""
|
||||
})
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Npm.Service.use((svc) => svc.outdated("example", "^2.0.0")).pipe(Effect.provide(layer)),
|
||||
)
|
||||
|
||||
expect(result).toBe(false)
|
||||
})
|
||||
|
||||
test("falls back when npm view is unavailable", async () => {
|
||||
const calls: string[][] = []
|
||||
const layer = testLayer((cmd, args) => {
|
||||
calls.push([cmd, ...args])
|
||||
if (cmd === "pnpm" && args[0] === "view") return '"2.0.0"\n'
|
||||
return ""
|
||||
})
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
Npm.Service.use((svc) => svc.outdated("example", "1.0.0")).pipe(Effect.provide(layer)),
|
||||
)
|
||||
|
||||
expect(result).toBe(true)
|
||||
expect(calls).toContainEqual(["npm", "view", "example", "dist-tags.latest", "--json"])
|
||||
expect(calls).toContainEqual(["pnpm", "view", "example", "dist-tags.latest", "--json"])
|
||||
})
|
||||
})
|
||||
|
|
@ -67,3 +67,38 @@ describe("pty shell args", () => {
|
|||
)
|
||||
}
|
||||
})
|
||||
|
||||
describe("pty configured shell", () => {
|
||||
test(
|
||||
"uses configured shell for default PTY command",
|
||||
async () => {
|
||||
const configured = process.platform === "win32" ? Bun.which("pwsh") || Bun.which("powershell") : Bun.which("bash")
|
||||
if (!configured) return
|
||||
|
||||
await using dir = await tmpdir({
|
||||
config: { shell: Shell.name(configured) },
|
||||
})
|
||||
await Instance.provide({
|
||||
directory: dir.path,
|
||||
fn: () =>
|
||||
AppRuntime.runPromise(
|
||||
Effect.gen(function* () {
|
||||
const pty = yield* Pty.Service
|
||||
const info = yield* pty.create({ title: "configured" })
|
||||
try {
|
||||
if (process.platform === "win32") {
|
||||
expect(info.command.toLowerCase()).toBe(configured.toLowerCase())
|
||||
} else {
|
||||
expect(info.command).toBe(configured)
|
||||
}
|
||||
expect(info.args).toEqual(process.platform === "win32" ? [] : ["-l"])
|
||||
} finally {
|
||||
yield* pty.remove(info.id)
|
||||
}
|
||||
}),
|
||||
),
|
||||
})
|
||||
},
|
||||
{ timeout: 30000 },
|
||||
)
|
||||
})
|
||||
|
|
|
|||
50
packages/opencode/test/server/httpapi-event.test.ts
Normal file
50
packages/opencode/test/server/httpapi-event.test.ts
Normal file
|
|
@ -0,0 +1,50 @@
|
|||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import type { UpgradeWebSocket } from "hono/ws"
|
||||
import { Flag } from "@opencode-ai/core/flag/flag"
|
||||
import { Instance } from "../../src/project/instance"
|
||||
import { InstanceRoutes } from "../../src/server/routes/instance"
|
||||
import { EventPaths } from "../../src/server/routes/instance/httpapi/event"
|
||||
import { Log } from "../../src/util"
|
||||
import { resetDatabase } from "../fixture/db"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
void Log.init({ print: false })
|
||||
|
||||
const original = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
|
||||
const websocket = (() => () => new Response(null, { status: 501 })) as unknown as UpgradeWebSocket
|
||||
|
||||
function app() {
|
||||
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
|
||||
return InstanceRoutes(websocket)
|
||||
}
|
||||
|
||||
async function readFirstChunk(response: Response) {
|
||||
if (!response.body) throw new Error("missing response body")
|
||||
const reader = response.body.getReader()
|
||||
const result = await Promise.race([
|
||||
reader.read(),
|
||||
new Promise<never>((_, reject) => setTimeout(() => reject(new Error("timed out waiting for event")), 5_000)),
|
||||
])
|
||||
await reader.cancel()
|
||||
return new TextDecoder().decode(result.value)
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = original
|
||||
await Instance.disposeAll()
|
||||
await resetDatabase()
|
||||
})
|
||||
|
||||
describe("event HttpApi bridge", () => {
|
||||
test("serves event stream through experimental Effect route", async () => {
|
||||
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
|
||||
const response = await app().request(EventPaths.event, { headers: { "x-opencode-directory": tmp.path } })
|
||||
|
||||
expect(response.status).toBe(200)
|
||||
expect(response.headers.get("content-type")).toContain("text/event-stream")
|
||||
expect(response.headers.get("cache-control")).toBe("no-cache, no-transform")
|
||||
expect(response.headers.get("x-accel-buffering")).toBe("no")
|
||||
expect(response.headers.get("x-content-type-options")).toBe("nosniff")
|
||||
expect(await readFirstChunk(response)).toContain('data: {"type":"server.connected","properties":{}}\n\n')
|
||||
})
|
||||
})
|
||||
74
packages/opencode/test/server/httpapi-pty.test.ts
Normal file
74
packages/opencode/test/server/httpapi-pty.test.ts
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import type { UpgradeWebSocket } from "hono/ws"
|
||||
import { Flag } from "@opencode-ai/core/flag/flag"
|
||||
import { PtyID } from "../../src/pty/schema"
|
||||
import { Instance } from "../../src/project/instance"
|
||||
import { InstanceRoutes } from "../../src/server/routes/instance"
|
||||
import { PtyPaths } from "../../src/server/routes/instance/httpapi/pty"
|
||||
import { Log } from "../../src/util"
|
||||
import { resetDatabase } from "../fixture/db"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
void Log.init({ print: false })
|
||||
|
||||
const original = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
|
||||
const websocket = (() => () => new Response(null, { status: 501 })) as unknown as UpgradeWebSocket
|
||||
const testPty = process.platform === "win32" ? test.skip : test
|
||||
|
||||
function app() {
|
||||
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
|
||||
return InstanceRoutes(websocket)
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = original
|
||||
await Instance.disposeAll()
|
||||
await resetDatabase()
|
||||
})
|
||||
|
||||
describe("pty HttpApi bridge", () => {
|
||||
testPty("serves PTY JSON routes through experimental Effect routes", async () => {
|
||||
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
|
||||
const headers = { "x-opencode-directory": tmp.path }
|
||||
const list = await app().request(PtyPaths.list, { headers })
|
||||
expect(list.status).toBe(200)
|
||||
expect(await list.json()).toEqual([])
|
||||
|
||||
const created = await app().request(PtyPaths.create, {
|
||||
method: "POST",
|
||||
headers: { ...headers, "content-type": "application/json" },
|
||||
body: JSON.stringify({ command: "/usr/bin/env", args: ["sh", "-c", "sleep 5"], title: "demo" }),
|
||||
})
|
||||
expect(created.status).toBe(200)
|
||||
const info = await created.json()
|
||||
|
||||
try {
|
||||
expect(info).toMatchObject({ title: "demo", command: "/usr/bin/env", status: "running" })
|
||||
|
||||
const found = await app().request(PtyPaths.get.replace(":ptyID", info.id), { headers })
|
||||
expect(found.status).toBe(200)
|
||||
expect(await found.json()).toMatchObject({ id: info.id, title: "demo" })
|
||||
|
||||
const updated = await app().request(PtyPaths.update.replace(":ptyID", info.id), {
|
||||
method: "PUT",
|
||||
headers: { ...headers, "content-type": "application/json" },
|
||||
body: JSON.stringify({ title: "renamed", size: { cols: 80, rows: 24 } }),
|
||||
})
|
||||
expect(updated.status).toBe(200)
|
||||
expect(await updated.json()).toMatchObject({ id: info.id, title: "renamed" })
|
||||
} finally {
|
||||
await app().request(PtyPaths.remove.replace(":ptyID", info.id), { method: "DELETE", headers })
|
||||
}
|
||||
|
||||
const missing = await app().request(PtyPaths.get.replace(":ptyID", info.id), { headers })
|
||||
expect(missing.status).toBe(404)
|
||||
})
|
||||
|
||||
test("returns 404 for missing PTY websocket before upgrade", async () => {
|
||||
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
|
||||
const response = await app().request(PtyPaths.connect.replace(":ptyID", PtyID.ascending()), {
|
||||
headers: { "x-opencode-directory": tmp.path },
|
||||
})
|
||||
expect(response.status).toBe(404)
|
||||
})
|
||||
})
|
||||
79
packages/opencode/test/server/httpapi-tui.test.ts
Normal file
79
packages/opencode/test/server/httpapi-tui.test.ts
Normal file
|
|
@ -0,0 +1,79 @@
|
|||
import { afterEach, describe, expect, test } from "bun:test"
|
||||
import type { Context } from "hono"
|
||||
import type { UpgradeWebSocket } from "hono/ws"
|
||||
import { Flag } from "@opencode-ai/core/flag/flag"
|
||||
import { SessionID } from "../../src/session/schema"
|
||||
import { Instance } from "../../src/project/instance"
|
||||
import { InstanceRoutes } from "../../src/server/routes/instance"
|
||||
import { TuiPaths } from "../../src/server/routes/instance/httpapi/tui"
|
||||
import { callTui } from "../../src/server/routes/instance/tui"
|
||||
import { Log } from "../../src/util"
|
||||
import { resetDatabase } from "../fixture/db"
|
||||
import { tmpdir } from "../fixture/fixture"
|
||||
|
||||
void Log.init({ print: false })
|
||||
|
||||
const original = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
|
||||
const websocket = (() => () => new Response(null, { status: 501 })) as unknown as UpgradeWebSocket
|
||||
|
||||
function app() {
|
||||
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
|
||||
return InstanceRoutes(websocket)
|
||||
}
|
||||
|
||||
async function expectTrue(path: string, headers: Record<string, string>, body?: unknown) {
|
||||
const response = await app().request(path, {
|
||||
method: "POST",
|
||||
headers: { ...headers, "content-type": "application/json" },
|
||||
body: JSON.stringify(body ?? {}),
|
||||
})
|
||||
expect(response.status).toBe(200)
|
||||
expect(await response.json()).toBe(true)
|
||||
}
|
||||
|
||||
afterEach(async () => {
|
||||
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = original
|
||||
await Instance.disposeAll()
|
||||
await resetDatabase()
|
||||
})
|
||||
|
||||
describe("tui HttpApi bridge", () => {
|
||||
test("serves TUI command and event routes through experimental Effect routes", async () => {
|
||||
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
|
||||
const headers = { "x-opencode-directory": tmp.path }
|
||||
|
||||
await expectTrue(TuiPaths.appendPrompt, headers, { text: "hello" })
|
||||
await expectTrue(TuiPaths.openHelp, headers)
|
||||
await expectTrue(TuiPaths.openSessions, headers)
|
||||
await expectTrue(TuiPaths.openThemes, headers)
|
||||
await expectTrue(TuiPaths.openModels, headers)
|
||||
await expectTrue(TuiPaths.submitPrompt, headers)
|
||||
await expectTrue(TuiPaths.clearPrompt, headers)
|
||||
await expectTrue(TuiPaths.executeCommand, headers, { command: "agent_cycle" })
|
||||
await expectTrue(TuiPaths.showToast, headers, { message: "Saved", variant: "success" })
|
||||
await expectTrue(TuiPaths.publish, headers, {
|
||||
type: "tui.prompt.append",
|
||||
properties: { text: "from publish" },
|
||||
})
|
||||
|
||||
const missing = await app().request(TuiPaths.selectSession, {
|
||||
method: "POST",
|
||||
headers: { ...headers, "content-type": "application/json" },
|
||||
body: JSON.stringify({ sessionID: SessionID.descending() }),
|
||||
})
|
||||
expect(missing.status).toBe(404)
|
||||
})
|
||||
|
||||
test("serves TUI control queue through experimental Effect routes", async () => {
|
||||
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
|
||||
const pending = callTui({ req: { json: async () => ({ value: 1 }), path: "/demo" } } as unknown as Context)
|
||||
const headers = { "x-opencode-directory": tmp.path }
|
||||
|
||||
const next = await app().request(TuiPaths.controlNext, { headers })
|
||||
expect(next.status).toBe(200)
|
||||
expect(await next.json()).toEqual({ path: "/demo", body: { value: 1 } })
|
||||
|
||||
await expectTrue(TuiPaths.controlResponse, headers, { ok: true })
|
||||
expect(await pending).toEqual({ ok: true })
|
||||
})
|
||||
})
|
||||
|
|
@ -316,9 +316,11 @@ const addSubtask = (sessionID: SessionID, messageID: MessageID, model = ref) =>
|
|||
})
|
||||
|
||||
const boot = Effect.fn("test.boot")(function* (input?: { title?: string }) {
|
||||
const config = yield* Config.Service
|
||||
const prompt = yield* SessionPrompt.Service
|
||||
const run = yield* SessionRunState.Service
|
||||
const sessions = yield* Session.Service
|
||||
yield* config.get()
|
||||
const chat = yield* sessions.create(input ?? { title: "Pinned" })
|
||||
return { prompt, run, sessions, chat }
|
||||
})
|
||||
|
|
@ -1078,6 +1080,32 @@ unix("shell completes a fast command on the preferred shell", () =>
|
|||
),
|
||||
)
|
||||
|
||||
unix(
|
||||
"shell uses configured shell over env shell",
|
||||
() =>
|
||||
withSh(() =>
|
||||
provideTmpdirInstance(
|
||||
(_dir) =>
|
||||
Effect.gen(function* () {
|
||||
if (!Bun.which("bash")) return
|
||||
|
||||
const { prompt, chat } = yield* boot()
|
||||
const result = yield* prompt.shell({
|
||||
sessionID: chat.id,
|
||||
agent: "build",
|
||||
command: "[[ 1 -eq 1 ]] && printf configured",
|
||||
})
|
||||
|
||||
const tool = completedTool(result.parts)
|
||||
if (!tool) return
|
||||
expect(tool.state.output).toContain("configured")
|
||||
}),
|
||||
{ git: true, config: { ...cfg, shell: "bash" } },
|
||||
),
|
||||
),
|
||||
30_000,
|
||||
)
|
||||
|
||||
unix("shell commands can change directory after startup", () =>
|
||||
provideTmpdirInstance(
|
||||
(dir) =>
|
||||
|
|
@ -1263,6 +1291,45 @@ it.live(
|
|||
3_000,
|
||||
)
|
||||
|
||||
unix(
|
||||
"command ! expansion uses configured shell over env shell",
|
||||
() =>
|
||||
withSh(() =>
|
||||
provideTmpdirServer(
|
||||
({ llm }) =>
|
||||
Effect.gen(function* () {
|
||||
if (!Bun.which("bash")) return
|
||||
|
||||
const { prompt, chat } = yield* boot()
|
||||
yield* llm.text("done")
|
||||
|
||||
const result = yield* prompt.command({
|
||||
sessionID: chat.id,
|
||||
command: "probe",
|
||||
arguments: "",
|
||||
})
|
||||
|
||||
expect(result.info.role).toBe("assistant")
|
||||
const inputs = yield* llm.inputs
|
||||
expect(JSON.stringify(inputs.at(-1)?.messages)).toContain("configured")
|
||||
}),
|
||||
{
|
||||
git: true,
|
||||
config: (url) => ({
|
||||
...providerCfg(url),
|
||||
shell: "bash",
|
||||
command: {
|
||||
probe: {
|
||||
template: "Probe: !`[[ 1 -eq 1 ]] && printf configured`",
|
||||
},
|
||||
},
|
||||
}),
|
||||
},
|
||||
),
|
||||
),
|
||||
30_000,
|
||||
)
|
||||
|
||||
unix(
|
||||
"cancel interrupts shell and resolves cleanly",
|
||||
() =>
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
|
|||
import path from "path"
|
||||
import { Shell } from "../../src/shell/shell"
|
||||
import { Filesystem } from "../../src/util"
|
||||
import { which } from "../../src/util/which"
|
||||
|
||||
const withShell = async (shell: string | undefined, fn: () => void | Promise<void>) => {
|
||||
const prev = process.env.SHELL
|
||||
|
|
@ -39,6 +40,20 @@ describe("shell", () => {
|
|||
expect(Shell.posix("C:/tools/pwsh.exe")).toBe(false)
|
||||
})
|
||||
|
||||
test("falls back when configured shell cannot be resolved", async () => {
|
||||
await withShell(undefined, async () => {
|
||||
const preferred = Shell.preferred()
|
||||
const acceptable = Shell.acceptable()
|
||||
expect(Shell.preferred("opencode-missing-shell")).toBe(preferred)
|
||||
expect(Shell.acceptable("opencode-missing-shell")).toBe(acceptable)
|
||||
})
|
||||
})
|
||||
|
||||
test("falls back for terminal-only acceptable shells", () => {
|
||||
expect(Shell.name(Shell.acceptable("fish"))).not.toBe("fish")
|
||||
expect(Shell.name(Shell.acceptable("nu"))).not.toBe("nu")
|
||||
})
|
||||
|
||||
if (process.platform === "win32") {
|
||||
test("rejects blacklisted shells case-insensitively", async () => {
|
||||
await withShell("NU.EXE", async () => {
|
||||
|
|
@ -62,8 +77,19 @@ describe("shell", () => {
|
|||
})
|
||||
})
|
||||
|
||||
test("resolves bare bash to Git Bash before PATH", async () => {
|
||||
const bash = Shell.gitbash()
|
||||
if (!bash) return
|
||||
expect(Shell.acceptable("bash")).toBe(bash)
|
||||
expect(Shell.preferred("bash")).toBe(bash)
|
||||
await withShell("bash", async () => {
|
||||
expect(Shell.acceptable()).toBe(bash)
|
||||
expect(Shell.preferred()).toBe(bash)
|
||||
})
|
||||
})
|
||||
|
||||
test("resolves bare PowerShell shells", async () => {
|
||||
const shell = Bun.which("pwsh") || Bun.which("powershell")
|
||||
const shell = which("pwsh") || which("powershell")
|
||||
if (!shell) return
|
||||
await withShell(path.win32.basename(shell), async () => {
|
||||
expect(Shell.preferred()).toBe(shell)
|
||||
|
|
|
|||
|
|
@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test"
|
|||
import { Effect, Layer, ManagedRuntime } from "effect"
|
||||
import os from "os"
|
||||
import path from "path"
|
||||
import { Config } from "../../src/config"
|
||||
import { Shell } from "../../src/shell/shell"
|
||||
import { ShellToolID } from "../../src/tool/shell/id"
|
||||
import { ShellTool } from "../../src/tool/shell"
|
||||
|
|
@ -22,6 +23,7 @@ const runtime = ManagedRuntime.make(
|
|||
AppFileSystem.defaultLayer,
|
||||
Plugin.defaultLayer,
|
||||
Truncate.defaultLayer,
|
||||
Config.defaultLayer,
|
||||
Agent.defaultLayer,
|
||||
),
|
||||
)
|
||||
|
|
@ -158,6 +160,33 @@ describe("tool.shell", () => {
|
|||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("falls back from terminal-only configured shell", async () => {
|
||||
await using tmp = await tmpdir({
|
||||
config: { shell: "fish" },
|
||||
})
|
||||
await Instance.provide({
|
||||
directory: tmp.path,
|
||||
fn: async () => {
|
||||
const bash = await initBash()
|
||||
const fallback = Shell.name(Shell.acceptable("fish"))
|
||||
expect(fallback).not.toBe("fish")
|
||||
expect(bash.description).toContain(fallback)
|
||||
|
||||
const result = await Effect.runPromise(
|
||||
bash.execute(
|
||||
{
|
||||
command: "echo fallback",
|
||||
description: "Echo fallback text",
|
||||
},
|
||||
ctx,
|
||||
),
|
||||
)
|
||||
expect(result.metadata.exit).toBe(0)
|
||||
expect(result.output).toContain("fallback")
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe("tool.shell permissions", () => {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue