Merge remote-tracking branch 'upstream/dev' into refactor-shells

This commit is contained in:
LukeParkerDev 2026-04-27 08:59:39 +10:00
commit 5a7e69b325
88 changed files with 2959 additions and 1699 deletions

View file

@ -55,6 +55,14 @@ async function defaultModel() {
return run((provider) => provider.defaultModel())
}
async function markPluginDependenciesReady(dir: string) {
await mkdir(path.join(dir, "node_modules"), { recursive: true })
await Bun.write(
path.join(dir, "package-lock.json"),
JSON.stringify({ packages: { "": { dependencies: { "@opencode-ai/plugin": "0.0.0" } } } }),
)
}
function paid(providers: Awaited<ReturnType<typeof list>>) {
const item = providers[ProviderID.make("opencode")]
expect(item).toBeDefined()
@ -2439,8 +2447,11 @@ test("cloudflare-ai-gateway forwards config metadata options", async () => {
test("plugin config providers persist after instance dispose", async () => {
await using tmp = await tmpdir({
init: async (dir) => {
const root = path.join(dir, ".opencode", "plugin")
const configDir = path.join(dir, ".opencode")
const root = path.join(configDir, "plugin")
await mkdir(root, { recursive: true })
await markPluginDependenciesReady(configDir)
await markPluginDependenciesReady(Global.Path.config)
await Bun.write(
path.join(root, "demo-provider.ts"),
[

View file

@ -1,10 +1,13 @@
import { afterEach, describe, expect, test } from "bun:test"
import type { UpgradeWebSocket } from "hono/ws"
import { Effect } from "effect"
import { Flag } from "@opencode-ai/core/flag/flag"
import { GlobalBus } from "@/bus/global"
import { Instance } from "../../src/project/instance"
import { InstanceRoutes } from "../../src/server/routes/instance"
import { ExperimentalPaths } from "../../src/server/routes/instance/httpapi/experimental"
import { Session } from "../../src/session"
import { Database } from "../../src/storage"
import { Log } from "../../src/util"
import { Worktree } from "../../src/worktree"
import { resetDatabase } from "../fixture/db"
@ -14,12 +17,21 @@ void Log.init({ print: false })
const original = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
const websocket = (() => () => new Response(null, { status: 501 })) as unknown as UpgradeWebSocket
const testWorktreeMutations = process.platform === "win32" ? test.skip : test
function app() {
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
return InstanceRoutes(websocket)
}
function runSession<A, E>(fx: Effect.Effect<A, E, Session.Service>) {
return Effect.runPromise(fx.pipe(Effect.provide(Session.defaultLayer)))
}
function createSession(input?: Session.CreateInput) {
return runSession(Session.Service.use((svc) => svc.create(input)))
}
async function waitReady(directory: string) {
return await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
@ -61,9 +73,10 @@ describe("experimental HttpApi", () => {
})
const headers = { "x-opencode-directory": tmp.path }
const [consoleState, consoleOrgs, toolIDs, worktrees, resources] = await Promise.all([
const [consoleState, consoleOrgs, toolList, toolIDs, worktrees, resources] = await Promise.all([
app().request(ExperimentalPaths.console, { headers }),
app().request(ExperimentalPaths.consoleOrgs, { headers }),
app().request(`${ExperimentalPaths.tool}?provider=opencode&model=gpt-5`, { headers }),
app().request(ExperimentalPaths.toolIDs, { headers }),
app().request(ExperimentalPaths.worktree, { headers }),
app().request(ExperimentalPaths.resource, { headers }),
@ -78,6 +91,15 @@ describe("experimental HttpApi", () => {
expect(consoleOrgs.status).toBe(200)
expect(await consoleOrgs.json()).toEqual({ orgs: [] })
expect(toolList.status).toBe(200)
expect(await toolList.json()).toContainEqual(
expect.objectContaining({
id: "bash",
description: expect.any(String),
parameters: expect.any(Object),
}),
)
expect(toolIDs.status).toBe(200)
expect(await toolIDs.json()).toContain("bash")
@ -88,7 +110,70 @@ describe("experimental HttpApi", () => {
expect(await resources.json()).toEqual({})
})
test("serves worktree mutations through Hono bridge", async () => {
test("serves Console org switch through Hono bridge", async () => {
await using tmp = await tmpdir({ config: { formatter: false, lsp: false } })
Database.Client()
.$client.prepare(
"INSERT INTO account (id, email, url, access_token, refresh_token, time_created, time_updated) VALUES (?, ?, ?, ?, ?, ?, ?)",
)
.run(
"account-test",
"test@example.com",
"https://console.example.com",
"access",
"refresh",
Date.now(),
Date.now(),
)
const switched = await app().request(ExperimentalPaths.consoleSwitch, {
method: "POST",
headers: { "x-opencode-directory": tmp.path, "content-type": "application/json" },
body: JSON.stringify({ accountID: "account-test", orgID: "org-test" }),
})
expect(switched.status).toBe(200)
expect(await switched.json()).toBe(true)
})
test("serves global session list through Hono bridge", async () => {
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
const first = await Instance.provide({
directory: tmp.path,
fn: async () => createSession({ title: "page-one" }),
})
await new Promise((resolve) => setTimeout(resolve, 5))
const second = await Instance.provide({
directory: tmp.path,
fn: async () => createSession({ title: "page-two" }),
})
const headers = { "x-opencode-directory": tmp.path }
const page = await app().request(
`${ExperimentalPaths.session}?${new URLSearchParams({ directory: tmp.path, limit: "1" })}`,
{ headers },
)
expect(page.status).toBe(200)
expect(page.headers.get("x-next-cursor")).toBeTruthy()
const body = (await page.json()) as Session.GlobalInfo[]
expect(body.map((session) => session.id)).toEqual([second.id])
expect(body[0].project?.id).toBe(second.projectID)
const next = await app().request(
`${ExperimentalPaths.session}?${new URLSearchParams({
directory: tmp.path,
limit: "10",
cursor: body[0].time.updated.toString(),
})}`,
{ headers },
)
expect(next.status).toBe(200)
expect(((await next.json()) as Session.GlobalInfo[]).map((session) => session.id)).toContain(first.id)
})
testWorktreeMutations("serves worktree mutations through Hono bridge", async () => {
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }

View file

@ -0,0 +1,280 @@
import { afterEach, describe, expect, test } from "bun:test"
import type { UpgradeWebSocket } from "hono/ws"
import { Effect } from "effect"
import { Flag } from "@opencode-ai/core/flag/flag"
import { PermissionID } from "../../src/permission/schema"
import { ModelID, ProviderID } from "../../src/provider/schema"
import { Instance } from "../../src/project/instance"
import { InstanceRoutes } from "../../src/server/routes/instance"
import { SessionPaths } from "../../src/server/routes/instance/httpapi/session"
import { Session } from "../../src/session"
import { MessageID, PartID, type SessionID } from "../../src/session/schema"
import { MessageV2 } from "../../src/session/message-v2"
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)
}
function runSession<A, E>(fx: Effect.Effect<A, E, Session.Service>) {
return Effect.runPromise(fx.pipe(Effect.provide(Session.defaultLayer)))
}
function pathFor(path: string, params: Record<string, string>) {
return Object.entries(params).reduce((result, [key, value]) => result.replace(`:${key}`, value), path)
}
async function createSession(directory: string, input?: Session.CreateInput) {
return Instance.provide({
directory,
fn: async () => runSession(Session.Service.use((svc) => svc.create(input))),
})
}
async function createTextMessage(directory: string, sessionID: SessionID, text: string) {
return Instance.provide({
directory,
fn: async () =>
runSession(
Effect.gen(function* () {
const svc = yield* Session.Service
const info = yield* svc.updateMessage({
id: MessageID.ascending(),
role: "user",
sessionID,
agent: "build",
model: { providerID: ProviderID.make("test"), modelID: ModelID.make("test") },
time: { created: Date.now() },
})
const part = yield* svc.updatePart({
id: PartID.ascending(),
sessionID,
messageID: info.id,
type: "text",
text,
})
return { info, part }
}),
),
})
}
async function json<T>(response: Response) {
if (response.status !== 200) throw new Error(await response.text())
return (await response.json()) as T
}
afterEach(async () => {
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = original
await Instance.disposeAll()
await resetDatabase()
})
describe("session HttpApi", () => {
test("serves read routes through Hono bridge", async () => {
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
const headers = { "x-opencode-directory": tmp.path }
const parent = await createSession(tmp.path, { title: "parent" })
const child = await createSession(tmp.path, { title: "child", parentID: parent.id })
const message = await createTextMessage(tmp.path, parent.id, "hello")
await createTextMessage(tmp.path, parent.id, "world")
expect(
(await json<Session.Info[]>(await app().request(`${SessionPaths.list}?roots=true`, { headers }))).map(
(item) => item.id,
),
).toContain(parent.id)
expect(await json<Record<string, unknown>>(await app().request(SessionPaths.status, { headers }))).toEqual({})
expect(
await json<Session.Info>(await app().request(pathFor(SessionPaths.get, { sessionID: parent.id }), { headers })),
).toMatchObject({ id: parent.id, title: "parent" })
expect(
(
await json<Session.Info[]>(
await app().request(pathFor(SessionPaths.children, { sessionID: parent.id }), { headers }),
)
).map((item) => item.id),
).toEqual([child.id])
expect(
await json<unknown[]>(await app().request(pathFor(SessionPaths.todo, { sessionID: parent.id }), { headers })),
).toEqual([])
expect(
await json<unknown[]>(await app().request(pathFor(SessionPaths.diff, { sessionID: parent.id }), { headers })),
).toEqual([])
const messages = await app().request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?limit=1`, {
headers,
})
const messagePage = await json<MessageV2.WithParts[]>(messages)
const nextCursor = messages.headers.get("x-next-cursor")
expect(nextCursor).toBeTruthy()
expect(messagePage[0]?.parts[0]).toMatchObject({ type: "text" })
expect(
(
await app().request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?before=${nextCursor}`, {
headers,
})
).status,
).toBe(400)
expect(
(
await app().request(`${pathFor(SessionPaths.messages, { sessionID: parent.id })}?limit=1&before=invalid`, {
headers,
})
).status,
).toBe(400)
expect(
await json<MessageV2.WithParts>(
await app().request(pathFor(SessionPaths.message, { sessionID: parent.id, messageID: message.info.id }), {
headers,
}),
),
).toMatchObject({ info: { id: message.info.id } })
})
test("serves lifecycle mutation routes through Hono bridge", async () => {
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false, share: "disabled" } })
const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
const created = await json<Session.Info>(
await app().request(SessionPaths.create, {
method: "POST",
headers,
body: JSON.stringify({ title: "created" }),
}),
)
expect(created.title).toBe("created")
const updated = await json<Session.Info>(
await app().request(pathFor(SessionPaths.update, { sessionID: created.id }), {
method: "PATCH",
headers,
body: JSON.stringify({ title: "updated", time: { archived: 1 } }),
}),
)
expect(updated).toMatchObject({ id: created.id, title: "updated", time: { archived: 1 } })
const forked = await json<Session.Info>(
await app().request(pathFor(SessionPaths.fork, { sessionID: created.id }), {
method: "POST",
headers,
body: JSON.stringify({}),
}),
)
expect(forked.id).not.toBe(created.id)
expect(
await json<boolean>(
await app().request(pathFor(SessionPaths.abort, { sessionID: created.id }), { method: "POST", headers }),
),
).toBe(true)
expect(
await json<boolean>(
await app().request(pathFor(SessionPaths.remove, { sessionID: created.id }), { method: "DELETE", headers }),
),
).toBe(true)
})
test("serves message mutation routes through Hono bridge", async () => {
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
const session = await createSession(tmp.path, { title: "messages" })
const first = await createTextMessage(tmp.path, session.id, "first")
const second = await createTextMessage(tmp.path, session.id, "second")
const updated = await json<MessageV2.Part>(
await app().request(
pathFor(SessionPaths.updatePart, {
sessionID: session.id,
messageID: first.info.id,
partID: first.part.id,
}),
{
method: "PATCH",
headers,
body: JSON.stringify({ ...first.part, text: "updated" }),
},
),
)
expect(updated).toMatchObject({ id: first.part.id, type: "text", text: "updated" })
expect(
await json<boolean>(
await app().request(
pathFor(SessionPaths.deletePart, {
sessionID: session.id,
messageID: first.info.id,
partID: first.part.id,
}),
{ method: "DELETE", headers },
),
),
).toBe(true)
expect(
await json<boolean>(
await app().request(pathFor(SessionPaths.deleteMessage, { sessionID: session.id, messageID: second.info.id }), {
method: "DELETE",
headers,
}),
),
).toBe(true)
})
test("serves remaining non-LLM session mutation routes through Hono bridge", async () => {
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
const session = await createSession(tmp.path, { title: "remaining" })
expect(
await json<Session.Info>(
await app().request(pathFor(SessionPaths.revert, { sessionID: session.id }), {
method: "POST",
headers,
body: JSON.stringify({ messageID: MessageID.ascending() }),
}),
),
).toMatchObject({ id: session.id })
expect(
await json<Session.Info>(
await app().request(pathFor(SessionPaths.unrevert, { sessionID: session.id }), {
method: "POST",
headers,
}),
),
).toMatchObject({ id: session.id })
expect(
await json<boolean>(
await app().request(
pathFor(SessionPaths.permissions, {
sessionID: session.id,
permissionID: String(PermissionID.ascending()),
}),
{
method: "POST",
headers,
body: JSON.stringify({ response: "once" }),
},
),
),
).toBe(true)
})
})

View file

@ -0,0 +1,84 @@
import { afterEach, describe, expect, test } from "bun:test"
import type { UpgradeWebSocket } from "hono/ws"
import { Effect } from "effect"
import { Flag } from "@opencode-ai/core/flag/flag"
import { Instance } from "../../src/project/instance"
import { InstanceRoutes } from "../../src/server/routes/instance"
import { SyncPaths } from "../../src/server/routes/instance/httpapi/sync"
import { Session } from "../../src/session"
import { Log } from "../../src/util"
import { resetDatabase } from "../fixture/db"
import { tmpdir } from "../fixture/fixture"
void Log.init({ print: false })
const originalHttpApi = Flag.OPENCODE_EXPERIMENTAL_HTTPAPI
const originalWorkspaces = Flag.OPENCODE_EXPERIMENTAL_WORKSPACES
const websocket = (() => () => new Response(null, { status: 501 })) as unknown as UpgradeWebSocket
function app() {
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = true
return InstanceRoutes(websocket)
}
function runSession<A, E>(fx: Effect.Effect<A, E, Session.Service>) {
return Effect.runPromise(fx.pipe(Effect.provide(Session.defaultLayer)))
}
afterEach(async () => {
Flag.OPENCODE_EXPERIMENTAL_HTTPAPI = originalHttpApi
Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = originalWorkspaces
await Instance.disposeAll()
await resetDatabase()
})
describe("sync HttpApi", () => {
test("serves sync routes through Hono bridge", async () => {
Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
await using tmp = await tmpdir({ git: true, config: { formatter: false, lsp: false } })
const headers = { "x-opencode-directory": tmp.path, "content-type": "application/json" }
const session = await Instance.provide({
directory: tmp.path,
fn: async () => runSession(Session.Service.use((svc) => svc.create({ title: "sync" }))),
})
const started = await app().request(SyncPaths.start, { method: "POST", headers })
expect(started.status).toBe(200)
expect(await started.json()).toBe(true)
const history = await app().request(SyncPaths.history, {
method: "POST",
headers,
body: JSON.stringify({}),
})
expect(history.status).toBe(200)
const rows = (await history.json()) as Array<{
id: string
aggregate_id: string
seq: number
type: string
data: Record<string, unknown>
}>
expect(rows.map((row) => row.aggregate_id)).toContain(session.id)
const replayed = await app().request(SyncPaths.replay, {
method: "POST",
headers,
body: JSON.stringify({
directory: tmp.path,
events: rows
.filter((row) => row.aggregate_id === session.id)
.map((row) => ({
id: row.id,
aggregateID: row.aggregate_id,
seq: row.seq,
type: row.type,
data: row.data,
})),
}),
})
expect(replayed.status).toBe(200)
expect(await replayed.json()).toEqual({ sessionID: session.id })
})
})

View file

@ -1,7 +1,14 @@
import { afterEach, describe, expect, test } from "bun:test"
import { Context } from "effect"
import { mkdir } from "node:fs/promises"
import path from "node:path"
import { Context, Effect } from "effect"
import { Flag } from "@opencode-ai/core/flag/flag"
import { registerAdaptor } from "../../src/control-plane/adaptors"
import type { WorkspaceAdaptor } from "../../src/control-plane/types"
import { Workspace } from "../../src/control-plane/workspace"
import { ExperimentalHttpApiServer } from "../../src/server/routes/instance/httpapi/server"
import { WorkspacePaths } from "../../src/server/routes/instance/httpapi/workspace"
import { Session } from "../../src/session"
import { Log } from "../../src/util"
import { resetDatabase } from "../fixture/db"
import { tmpdir } from "../fixture/fixture"
@ -10,19 +17,50 @@ import { Instance } from "../../src/project/instance"
void Log.init({ print: false })
const context = Context.empty() as Context.Context<unknown>
const originalWorkspaces = Flag.OPENCODE_EXPERIMENTAL_WORKSPACES
function request(path: string, directory: string) {
function request(path: string, directory: string, init: RequestInit = {}) {
const headers = new Headers(init.headers)
headers.set("x-opencode-directory", directory)
return ExperimentalHttpApiServer.webHandler().handler(
new Request(`http://localhost${path}`, {
headers: {
"x-opencode-directory": directory,
},
...init,
headers,
}),
context,
)
}
function runSession<A, E>(fx: Effect.Effect<A, E, Session.Service>) {
return Effect.runPromise(fx.pipe(Effect.provide(Session.defaultLayer)))
}
function localAdaptor(directory: string): WorkspaceAdaptor {
return {
name: "Local Test",
description: "Create a local test workspace",
configure(info) {
return {
...info,
name: "local-test",
directory,
}
},
async create() {
await mkdir(directory, { recursive: true })
},
async remove() {},
target() {
return {
type: "local" as const,
directory,
}
},
}
}
afterEach(async () => {
Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = originalWorkspaces
await Instance.disposeAll()
await resetDatabase()
})
@ -52,4 +90,43 @@ describe("workspace HttpApi", () => {
expect(status.status).toBe(200)
expect(await status.json()).toEqual([])
})
test("serves mutation endpoints", async () => {
Flag.OPENCODE_EXPERIMENTAL_WORKSPACES = true
await using tmp = await tmpdir({ git: true })
await Instance.provide({
directory: tmp.path,
fn: async () =>
registerAdaptor(Instance.project.id, "local-test", localAdaptor(path.join(tmp.path, ".workspace"))),
})
const created = await request(WorkspacePaths.list, tmp.path, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ type: "local-test", branch: null, extra: null }),
})
expect(created.status).toBe(200)
const workspace = (await created.json()) as Workspace.Info
expect(workspace).toMatchObject({ type: "local-test", name: "local-test" })
const session = await Instance.provide({
directory: tmp.path,
fn: async () => runSession(Session.Service.use((svc) => svc.create({}))),
})
const restored = await request(WorkspacePaths.sessionRestore.replace(":id", workspace.id), tmp.path, {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ sessionID: session.id }),
})
expect(restored.status).toBe(200)
expect((await restored.json()) as { total: number }).toMatchObject({ total: expect.any(Number) })
const removed = await request(WorkspacePaths.remove.replace(":id", workspace.id), tmp.path, { method: "DELETE" })
expect(removed.status).toBe(200)
expect(await removed.json()).toMatchObject({ id: workspace.id })
const listed = await request(WorkspacePaths.list, tmp.path)
expect(listed.status).toBe(200)
expect(await listed.json()).toEqual([])
})
})

View file

@ -873,6 +873,79 @@ describe("session.message-v2.toModelMessage", () => {
])
})
test("preserves OpenRouter reasoning details through provider transform", async () => {
const assistantID = "m-assistant"
const openrouterModel: Provider.Model = {
...model,
id: ModelID.make("deepseek/deepseek-v4-pro"),
providerID: ProviderID.make("openrouter"),
api: {
id: "deepseek/deepseek-v4-pro",
url: "https://openrouter.ai/api/v1",
npm: "@openrouter/ai-sdk-provider",
},
capabilities: {
...model.capabilities,
reasoning: true,
interleaved: { field: "reasoning_details" },
},
}
const reasoningDetails = [
{
type: "reasoning.text",
text: "thinking",
format: "unknown",
index: 0,
},
]
const input: MessageV2.WithParts[] = [
{
info: assistantInfo(assistantID, "m-parent", undefined, {
providerID: openrouterModel.providerID,
modelID: openrouterModel.id,
}),
parts: [
{
...basePart(assistantID, "a1"),
type: "reasoning",
text: "thinking",
time: { start: 0 },
metadata: {
openrouter: {
reasoning_details: reasoningDetails,
},
},
},
{
...basePart(assistantID, "a2"),
type: "text",
text: "answer",
},
] as MessageV2.Part[],
},
]
expect(
ProviderTransform.message(await MessageV2.toModelMessages(input, openrouterModel), openrouterModel, {}),
).toStrictEqual([
{
role: "assistant",
content: [
{
type: "reasoning",
text: "thinking",
providerOptions: {
openrouter: {
reasoning_details: reasoningDetails,
},
},
},
{ type: "text", text: "answer" },
],
},
])
})
test("splits assistant messages on step-start boundaries", async () => {
const assistantID = "m-assistant"