mini: add reconnect, forms, and shared targets (#37811)

Centralize session target resolution for mini and noninteractive
run paths. Recover from transport drops, replace questions with
forms, and keep tool/catalog state location-scoped with live
progress and theme discovery.
This commit is contained in:
Simon Klee 2026-07-19 22:45:10 +02:00 committed by GitHub
commit 925c2423de
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
65 changed files with 5631 additions and 4292 deletions

View file

@ -17,11 +17,14 @@ describe("run catalog shared", () => {
}) as never,
)
await expect(waitForDefaultModel({ sdk: client, directory: "/tmp" })).resolves.toEqual({
await expect(waitForDefaultModel({ sdk: client, location: { directory: "/tmp" } })).resolves.toEqual({
providerID: "openai",
modelID: "gpt-5",
})
expect(selected).toHaveBeenCalledWith({ location: { directory: "/tmp" } })
expect(selected).toHaveBeenCalledWith(
{ location: { directory: "/tmp", workspace: undefined } },
{ signal: expect.any(AbortSignal) },
)
})
test("loads visible project references from the current reference catalog", async () => {
@ -31,23 +34,23 @@ describe("run catalog shared", () => {
Promise.resolve({
location: { directory: "/tmp", project: { id: "proj_1", directory: "/tmp" } },
data: [
{
name: "effect",
path: "/repos/effect",
description: "Effect v4 sources",
source: { type: "local", path: "/repos/effect" },
},
{
name: "secret",
path: "/repos/secret",
hidden: true,
source: { type: "local", path: "/repos/secret" },
},
{
name: "effect",
path: "/repos/effect",
description: "Effect v4 sources",
source: { type: "local", path: "/repos/effect" },
},
{
name: "secret",
path: "/repos/secret",
hidden: true,
source: { type: "local", path: "/repos/secret" },
},
],
}) as never,
)
const references = await loadRunReferences(client, "/tmp")
const references = await loadRunReferences(client, { directory: "/tmp" })
expect(list).toHaveBeenCalledWith({ location: { directory: "/tmp" } })
expect(references).toMatchObject([{ name: "effect", path: "/repos/effect", description: "Effect v4 sources" }])
@ -103,21 +106,9 @@ describe("run catalog shared", () => {
name: "OpenAI",
models: {
"gpt-5": {
id: "gpt-5",
providerID: "openai",
name: "Little Frank",
capabilities: expect.objectContaining({ tools: true }),
cost: {
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
},
limit: {
context: 128000,
output: 8192,
},
status: "active",
variants: {

View file

@ -1,31 +1,34 @@
import { describe, expect, test } from "bun:test"
import type { SessionMessageAssistantTool } from "@opencode-ai/client/promise"
import { entryBody, entryCanStream, entryDone } from "../../src/mini/entry.body"
import type { MiniToolPart, StreamCommit, ToolSnapshot } from "../../src/mini/types"
import type { StreamCommit, ToolSnapshot } from "../../src/mini/types"
function commit(input: Partial<StreamCommit> & Pick<StreamCommit, "kind" | "text" | "phase" | "source">): StreamCommit {
return input
}
function toolPart(
tool: string,
state: MiniToolPart["state"],
id = `${tool}-1`,
messageID = `msg-${tool}`,
): MiniToolPart {
name: string,
state: SessionMessageAssistantTool["state"],
id = `${name}-1`,
): SessionMessageAssistantTool {
return {
id,
sessionID: "session-1",
messageID,
type: "tool",
callID: `call-${id}`,
tool,
id,
name,
state,
} as MiniToolPart
time:
state.status === "streaming"
? { created: 1 }
: state.status === "completed" || state.status === "error"
? { created: 1, ran: 1, completed: 2 }
: { created: 1, ran: 1 },
}
}
function toolCommit(input: {
tool: string
state: MiniToolPart["state"]
state: SessionMessageAssistantTool["state"]
phase?: StreamCommit["phase"]
toolState?: StreamCommit["toolState"]
text?: string
@ -38,8 +41,11 @@ function toolCommit(input: {
phase: input.phase ?? "final",
source: "tool",
tool: input.tool,
toolState: input.toolState ?? "completed",
part: toolPart(input.tool, input.state, input.id, input.messageID),
toolState:
input.toolState ??
(input.state.status === "error" ? "error" : input.state.status === "completed" ? "completed" : "running"),
messageID: input.messageID,
part: toolPart(input.tool, input.state, input.id),
})
}
@ -62,13 +68,13 @@ describe("run entry body", () => {
text: "Shell exited with code 7",
phase: "final",
source: "tool",
tool: "bash",
tool: "shell",
toolState: "error",
toolError: "Shell exited with code 7",
shell: { callID: "sh_failed", command: "false" },
shell: { command: "false" },
}),
),
).toEqual({ type: "text", content: "✖ bash failed: Shell exited with code 7" })
).toEqual({ type: "text", content: "✖ shell failed: Shell exited with code 7" })
})
test("renders assistant, reasoning, and user entries in their display formats", () => {
@ -136,13 +142,11 @@ describe("run entry body", () => {
state: {
status: "completed",
input: {
filePath: "src/a.ts",
path: "src/a.ts",
content: "const x = 1\n",
},
output: "",
title: "",
metadata: {},
time: { start: 1, end: 2 },
structured: {},
content: [],
},
}),
snapshot: {
@ -159,14 +163,12 @@ describe("run entry body", () => {
state: {
status: "completed",
input: {
filePath: "src/a.ts",
path: "src/a.ts",
},
output: "",
title: "",
metadata: {
diff: "@@ -1 +1 @@\n-old\n+new\n",
structured: {
files: [{ file: "src/a.ts", status: "modified", patch: "@@ -1 +1 @@\n-old\n+new\n" }],
},
time: { start: 1, end: 2 },
content: [],
},
}),
snapshot: {
@ -181,25 +183,22 @@ describe("run entry body", () => {
},
},
{
name: "keeps completed apply_patch tool finals structured",
name: "keeps completed patch tool finals structured",
commit: toolCommit({
tool: "apply_patch",
tool: "patch",
state: {
status: "completed",
input: {},
output: "",
title: "",
metadata: {
content: [],
structured: {
files: [
{
type: "update",
filePath: "src/a.ts",
relativePath: "src/a.ts",
status: "modified",
file: "src/a.ts",
patch: "@@ -1 +1 @@\n-old\n+new\n",
},
],
},
time: { start: 1, end: 2 },
},
}),
snapshot: {
@ -215,22 +214,16 @@ describe("run entry body", () => {
},
},
] satisfies Array<{ name: string; commit: StreamCommit; snapshot: ToolSnapshot }>) {
if (item.name === "keeps completed apply_patch tool finals structured") {
test.skip(item.name, () => {
expect(structured(item.commit)).toEqual(item.snapshot)
})
continue
}
test(item.name, () => {
expect(structured(item.commit)).toEqual(item.snapshot)
})
}
test("keeps running task tool state out of scrollback", () => {
test("keeps running subagent tool state out of scrollback", () => {
expect(
entryBody(
toolCommit({
tool: "task",
tool: "subagent",
phase: "start",
toolState: "running",
text: "running inspect reducer",
@ -238,9 +231,10 @@ describe("run entry body", () => {
status: "running",
input: {
description: "Inspect reducer",
subagent_type: "explore",
agent: "explore",
},
time: { start: 1 },
structured: { sessionID: "ses-child-1", status: "running" },
content: [],
},
}),
),
@ -249,29 +243,23 @@ describe("run entry body", () => {
})
})
test("promotes task results to markdown and falls back to structured task summaries", () => {
test("promotes subagent results to markdown and falls back to structured summaries", () => {
expect(
entryBody(
toolCommit({
tool: "task",
tool: "subagent",
state: {
status: "completed",
input: {
description: "Inspect reducer",
subagent_type: "explore",
agent: "explore",
},
title: "",
output: [
'<task id="child-1" state="completed">',
"<task_result>",
"# Findings\n\n- Footer stays live",
"</task_result>",
"</task>",
].join("\n"),
metadata: {
sessionId: "child-1",
content: [{ type: "text", text: "# Findings\n\n- Footer stays live" }],
structured: {
sessionID: "ses-child-1",
status: "completed",
output: "# Findings\n\n- Footer stays live",
},
time: { start: 1, end: 2 },
},
}),
),
@ -283,27 +271,25 @@ describe("run entry body", () => {
expect(
structured(
toolCommit({
tool: "task",
tool: "subagent",
state: {
status: "completed",
input: {
description: "Inspect reducer",
subagent_type: "explore",
agent: "explore",
},
title: "",
output: ['<task id="child-1" state="completed">', "<task_result>", "", "</task_result>", "</task>"].join(
"\n",
),
metadata: {
sessionId: "child-1",
content: [],
structured: {
sessionID: "ses-child-1",
status: "completed",
output: "",
},
time: { start: 1, end: 2 },
},
}),
),
).toEqual({
kind: "task",
title: "# Explore Task",
title: "# Explore Subagent",
rows: ["Inspect reducer"],
tail: "",
})
@ -316,7 +302,7 @@ describe("run entry body", () => {
text: "partial output",
phase: "progress",
source: "tool",
tool: "bash",
tool: "shell",
partID: "tool-2",
}),
)
@ -332,7 +318,7 @@ describe("run entry body", () => {
text: "partial output",
phase: "progress",
source: "tool",
tool: "bash",
tool: "shell",
}),
body,
),
@ -344,35 +330,30 @@ describe("run entry body", () => {
text: "output",
phase: "progress",
source: "tool",
tool: "bash",
tool: "shell",
toolState: "completed",
}),
),
).toBe(true)
})
test.skip("formats completed bash output with a blank line after the command and no trailing blank row", () => {
test("formats completed shell output with a blank line after the command and no trailing blank row", () => {
const output = ["/tmp/demo", "git status", "On branch demo", "nothing to commit, working tree clean", ""].join("\n")
expect(
entryBody(
toolCommit({
tool: "bash",
tool: "shell",
phase: "progress",
toolState: "completed",
text: ["/tmp/demo", "git status", "On branch demo", "nothing to commit, working tree clean", ""].join("\n"),
text: output,
state: {
status: "completed",
input: {
command: "git status",
workdir: "/tmp/demo",
},
output: ["/tmp/demo", "git status", "On branch demo", "nothing to commit, working tree clean", ""].join(
"\n",
),
title: "git status",
metadata: {
exitCode: 0,
},
time: { start: 1, end: 2 },
content: [{ type: "text", text: output }],
structured: { exit: 0, truncated: false },
},
}),
),
@ -382,11 +363,11 @@ describe("run entry body", () => {
})
})
test.skip("renders command-only bash starts without the shell header", () => {
test("renders command-only shell starts without the shell header", () => {
expect(
entryBody(
toolCommit({
tool: "bash",
tool: "shell",
phase: "start",
toolState: "running",
text: "running shell",
@ -395,7 +376,8 @@ describe("run entry body", () => {
input: {
command: "ls",
},
time: { start: 1 },
structured: {},
content: [],
},
}),
),
@ -413,11 +395,10 @@ describe("run entry body", () => {
text: "running shell",
phase: "start",
source: "tool",
tool: "bash",
tool: "shell",
partID: "shell:call-1",
toolState: "running",
shell: {
callID: "call-1",
command: "pwd",
},
}),
@ -434,11 +415,10 @@ describe("run entry body", () => {
text: "/tmp/demo\n",
phase: "progress",
source: "tool",
tool: "bash",
tool: "shell",
partID: "shell:call-1",
toolState: "completed",
shell: {
callID: "call-1",
command: "pwd",
},
}),
@ -449,29 +429,25 @@ describe("run entry body", () => {
})
})
test.skip("falls back to patch summary when apply_patch has no visible diff items", () => {
test("falls back to patch summary when patch has no visible diff items", () => {
expect(
entryBody(
toolCommit({
tool: "apply_patch",
tool: "patch",
state: {
status: "completed",
input: {
patchText: "*** Begin Patch\n*** End Patch",
},
output: "",
title: "",
metadata: {
content: [],
structured: {
files: [
{
type: "update",
filePath: "src/a.ts",
relativePath: "src/a.ts",
diff: "@@ -1 +1 @@\n-old\n+new\n",
status: "modified",
file: "src/a.ts",
},
],
},
time: { start: 1, end: 2 },
},
}),
),
@ -481,34 +457,29 @@ describe("run entry body", () => {
})
})
test.skip("suppresses redundant patched rows when apply_patch also created a file", () => {
test("suppresses redundant patched rows when patch also created a file", () => {
expect(
entryBody(
toolCommit({
tool: "apply_patch",
tool: "patch",
state: {
status: "completed",
input: {
patchText: "*** Begin Patch\n*** End Patch",
},
output: "",
title: "",
metadata: {
content: [],
structured: {
files: [
{
type: "update",
filePath: "src/a.ts",
relativePath: "src/a.ts",
diff: "@@ -1 +1 @@\n-old\n+new\n",
status: "modified",
file: "src/a.ts",
},
{
type: "add",
filePath: "README-demo.md",
relativePath: "README-demo.md",
status: "added",
file: "README-demo.md",
},
],
},
time: { start: 1, end: 2 },
},
}),
),
@ -531,9 +502,9 @@ describe("run entry body", () => {
pattern: "**/*tool*",
path: "/tmp/demo/run",
},
error: "No such file or directory: '/tmp/demo/run'",
metadata: {},
time: { start: 1, end: 2 },
error: { type: "unknown", message: "No such file or directory: '/tmp/demo/run'" },
structured: {},
content: [],
},
}),
),
@ -543,6 +514,31 @@ describe("run entry body", () => {
})
})
test("renders bounded structured output for completed unknown tools without text", () => {
const body = entryBody(
toolCommit({
tool: "mcp_custom",
phase: "final",
toolState: "completed",
text: "",
state: {
status: "completed",
input: { target: "demo" },
structured: {
result: { ok: true, nested: { values: Array.from({ length: 40 }, (_, index) => ({ index })) } },
large: "x".repeat(8_000),
},
content: [],
},
}),
)
expect(body).toMatchObject({ type: "code", filetype: "json" })
expect(body.type === "code" ? body.content : "").toContain('"ok": true')
expect(body.type === "code" ? body.content : "").toContain("[truncated]")
expect(body.type === "code" ? body.content.length : Infinity).toBeLessThanOrEqual(4_096)
})
test("renders interrupted assistant finals as text", () => {
expect(
entryBody(

View file

@ -1,12 +1,19 @@
import { resolve, type Info, type Resolved } from "../../../src/config/v1"
import { TuiKeybind } from "../../../src/config/v1/keybind"
import { resolve, type Info, type Resolved } from "../../../src/config"
import { TuiKeybind } from "../../../src/config/keybind"
type ResolvedInput = Omit<Info, "attention" | "keybinds" | "leader_timeout"> & {
type ResolvedInput = Omit<Info, "attention" | "keybinds" | "leader"> & {
attention?: Partial<Resolved["attention"]>
keybinds?: Partial<TuiKeybind.Keybinds>
leader_timeout?: number
}
export function createTuiResolvedConfig(input: ResolvedInput = {}) {
return resolve(input, { terminalSuspend: process.platform !== "win32" })
const { leader_timeout, ...current } = input
return resolve(
{
...current,
leader: leader_timeout === undefined ? undefined : { timeout: leader_timeout },
},
{ terminalSuspend: process.platform !== "win32" },
)
}

View file

@ -1,7 +1,7 @@
/** @jsxImportSource @opentui/solid */
import { testRender } from "@opentui/solid"
import { Keymap } from "../../src/context/keymap"
import { resolve } from "../../src/config/v1"
import { resolve } from "../../src/config"
import { expect, test } from "bun:test"
import { createSignal } from "solid-js"
import { RunFooterView } from "../../src/mini/footer.view"
@ -14,7 +14,6 @@ test("down opens subagents from an empty prompt", async () => {
status: "",
queue: 0,
model: "gpt-5",
duration: "",
usage: "",
first: false,
interrupt: 0,
@ -25,8 +24,6 @@ test("down opens subagents from an empty prompt", async () => {
tabs: [
{
sessionID: "subagent-1",
partID: "part-1",
callID: "call-1",
label: "Explore",
description: "Inspect the keymap",
status: "running",
@ -35,7 +32,7 @@ test("down opens subagents from an empty prompt", async () => {
],
details: {},
permissions: [],
questions: [],
forms: [],
})
const config = resolve(
{ keybinds: { editor_open: "none", session_queued_prompts: "none" } },
@ -45,7 +42,7 @@ test("down opens subagents from an empty prompt", async () => {
return (
<Keymap.Provider config={config}>
<RunFooterView
directory="/tmp"
directory={() => "/tmp"}
findFiles={async () => []}
agents={() => []}
references={() => []}
@ -59,11 +56,10 @@ test("down opens subagents from an empty prompt", async () => {
subagent={subagents}
theme={() => RUN_THEME_FALLBACK}
tuiConfig={config}
agent="opencode"
onSubmit={() => true}
onPermissionReply={() => {}}
onQuestionReply={() => {}}
onQuestionReject={() => {}}
onFormReply={() => {}}
onFormCancel={() => {}}
onCycle={() => {}}
onInterrupt={() => false}
onEditorOpen={async () => undefined}

View file

@ -0,0 +1,25 @@
import { expect, test } from "bun:test"
import { coalesceProgressCommit } from "../../src/mini/footer"
import type { StreamCommit } from "../../src/mini/types"
function progress(input: Partial<StreamCommit> = {}): StreamCommit {
return {
kind: "tool",
source: "tool",
phase: "progress",
text: "one",
messageID: "msg_1",
partID: "part_1",
tool: "shell",
toolState: "running",
...input,
}
}
test("coalesces progress only within the same message and tool state", () => {
expect(coalesceProgressCommit(progress(), progress({ messageID: "msg_2" }))).toBeUndefined()
expect(coalesceProgressCommit(progress(), progress({ toolState: "completed" }))).toBeUndefined()
expect(coalesceProgressCommit(progress(), progress({ text: "two", directory: "/latest" }))).toEqual(
progress({ text: "onetwo", directory: "/latest" }),
)
})

View file

@ -3,7 +3,7 @@ import { expect, test } from "bun:test"
import { BoxRenderable, RGBA, type RootRenderable } from "@opentui/core"
import { testRender } from "@opentui/solid"
import { createSignal } from "solid-js"
import type { QuestionV2Request } from "@opencode-ai/client/promise"
import type { FormInfo } from "@opencode-ai/client/promise"
import { Keymap } from "../../src/context/keymap"
import {
RUN_COMMAND_PANEL_ROWS,
@ -30,7 +30,6 @@ import type {
RunTuiConfig,
StreamCommit,
} from "../../src/mini/types"
import { RunQuestionBody } from "../../src/mini/footer.question"
import { selectedCommand } from "../../src/mini/footer.prompt"
import { RejectField } from "../../src/mini/footer.permission"
import { createTuiResolvedConfig } from "./fixture/tui-runtime"
@ -42,8 +41,6 @@ function command(input: { name: string; description: string; source?: "command"
name: input.name,
description: input.description,
source: input.source,
template: "",
hints: [],
} satisfies RunCommand
}
@ -55,51 +52,11 @@ function model(input: {
variants?: Record<string, Record<string, never>>
}) {
return {
id: input.id,
providerID: "opencode",
api: {
id: "opencode",
url: "https://opencode.ai",
npm: "@ai-sdk/openai-compatible",
},
name: input.name,
capabilities: {
temperature: true,
reasoning: true,
attachment: true,
toolcall: true,
input: {
text: true,
audio: false,
image: true,
video: false,
pdf: true,
},
output: {
text: true,
audio: false,
image: false,
video: false,
pdf: false,
},
interleaved: false,
},
cost: {
input: input.cost ?? 1,
output: 1,
cache: {
read: 0,
write: 0,
},
},
limit: {
context: 128000,
output: 8192,
},
status: input.status ?? "active",
options: {},
headers: {},
release_date: "2026-01-01",
variants: input.variants,
} satisfies RunProvider["models"][string]
}
@ -108,9 +65,6 @@ function provider() {
return {
id: "opencode",
name: "opencode",
source: "api",
env: [],
options: {},
models: {
"gpt-5": model({ id: "gpt-5", name: "GPT-5", variants: { high: {}, minimal: {} } }),
"gpt-free": model({ id: "gpt-free", name: "GPT Free", cost: 0 }),
@ -127,8 +81,6 @@ function subagent(input: {
}) {
return {
sessionID: input.sessionID,
partID: `part-${input.sessionID}`,
callID: `call-${input.sessionID}`,
label: input.label,
description: input.description,
status: input.status ?? "running",
@ -142,7 +94,6 @@ function footerState(input: Partial<FooterState> = {}) {
status: "",
queue: 0,
model: "gpt-5",
duration: "",
usage: "",
first: false,
interrupt: 0,
@ -165,11 +116,13 @@ async function renderFooter(
state?: Partial<FooterState>
onCycle?: () => void
onSubmit?: (prompt: RunPrompt) => boolean
view?: FooterView
onFormReply?: (input: unknown) => void
} = {},
) {
const [view] = createSignal<FooterView>({ type: "prompt" })
const [view, setView] = createSignal<FooterView>(input.view ?? { type: "prompt" })
const [subagents] = createSignal<FooterSubagentState>(
input.subagents ?? { tabs: [], details: {}, permissions: [], questions: [] },
input.subagents ?? { tabs: [], details: {}, permissions: [], forms: [] },
)
const state = footerState(input.state)
const config = input.tuiConfig ?? tuiConfig
@ -177,7 +130,7 @@ async function renderFooter(
return (
<Keymap.Provider config={config}>
<RunFooterView
directory="/tmp"
directory={() => "/tmp"}
findFiles={async () => []}
agents={() => []}
references={() => []}
@ -191,11 +144,10 @@ async function renderFooter(
subagent={subagents}
theme={input.theme ?? (() => RUN_THEME_FALLBACK)}
tuiConfig={config}
agent="opencode"
onSubmit={input.onSubmit ?? (() => true)}
onPermissionReply={() => {}}
onQuestionReply={() => {}}
onQuestionReject={() => {}}
onFormReply={(value) => input.onFormReply?.(value)}
onFormCancel={() => {}}
onCycle={input.onCycle ?? (() => {})}
onInterrupt={() => false}
onEditorOpen={async () => undefined}
@ -223,6 +175,7 @@ async function renderFooter(
return {
...app,
setView,
cleanup() {
app.renderer.currentFocusedRenderable?.blur()
app.renderer.currentFocusedEditor?.blur()
@ -231,6 +184,57 @@ async function renderFooter(
}
}
test("direct footer preserves a partial multi-field form draft across permission preemption", async () => {
const request: FormInfo = {
id: "frm_preempted",
sessionID: "ses_child",
title: "Deployment",
fields: [
{ key: "service", type: "string", title: "Service", required: true },
{ key: "notes", type: "string", title: "Notes", required: true },
],
}
const app = await renderFooter({
height: 16,
view: { type: "form", request },
})
try {
await app.renderOnce()
"api".split("").forEach((key) => app.mockInput.pressKey(key))
app.mockInput.pressEnter()
await app.renderOnce()
"keep this draft".split("").forEach((key) => app.mockInput.pressKey(key))
expect(app.renderer.currentFocusedEditor?.plainText).toBe("keep this draft")
app.setView({
type: "permission",
request: {
id: "per_preempting",
sessionID: "ses_child",
action: "read",
resources: ["src/index.ts"],
},
})
await app.renderOnce()
expect(app.captureCharFrame()).toContain("Permission required")
app.setView({ type: "form", request })
await app.renderOnce()
expect(app.captureCharFrame()).toContain("2/2")
expect(app.renderer.currentFocusedEditor?.plainText).toBe("keep this draft")
app.setView({ type: "prompt" })
await app.renderOnce()
app.setView({ type: "form", request })
await app.renderOnce()
expect(app.captureCharFrame()).toContain("1/2")
expect(app.renderer.currentFocusedEditor?.plainText).toBe("")
} finally {
app.cleanup()
}
})
function expectPaletteList(list: BoxRenderable, selectedIndex: number) {
expect(list.backgroundColor.toInts()).toEqual((RUN_THEME_FALLBACK.footer.shade as RGBA).toInts())
expect((list.getChildren()[selectedIndex] as BoxRenderable).backgroundColor.toInts()).toEqual(
@ -310,13 +314,13 @@ test("run entry content updates when live commit text changes", async () => {
source: "tool",
messageID: "msg-1",
partID: "part-1",
tool: "bash",
tool: "shell",
})
const app = await testRender(
() => (
<box width={80} height={4}>
<RunEntryContent commit={commit()} theme={RUN_THEME_FALLBACK} width={80} />
<RunEntryContent commit={commit()} theme={RUN_THEME_FALLBACK} />
</box>
),
{
@ -336,7 +340,7 @@ test("run entry content updates when live commit text changes", async () => {
source: "tool",
messageID: "msg-1",
partID: "part-1",
tool: "bash",
tool: "shell",
})
await app.renderOnce()
@ -669,9 +673,7 @@ test("direct subagent panel closes when moving up from the first item", async ()
})
test("direct queued prompt panel renders pending prompt actions", async () => {
const [prompts] = createSignal([
{ messageID: "m-1", partID: "p-1", prompt: { text: "fix the auth test", parts: [] } },
])
const [prompts] = createSignal([{ messageID: "m-1", prompt: { text: "fix the auth test", parts: [] } }])
const app = await testRender(
() => (
@ -874,9 +876,11 @@ test("selectedCommand backfills the catalog source for bound drafts", () => {
source: "skill",
})
// Plain commands stay untagged.
expect(selectedCommand("/deploy prod", { name: "deploy", arguments: "" }, [
command({ name: "deploy", description: "Deploy" }),
])).toEqual({ name: "deploy", arguments: "prod" })
expect(
selectedCommand("/deploy prod", { name: "deploy", arguments: "" }, [
command({ name: "deploy", description: "Deploy" }),
]),
).toEqual({ name: "deploy", arguments: "prod" })
})
test("direct footer tags skill slash submissions with their catalog source", async () => {
@ -936,7 +940,9 @@ test.skip("direct footer skill picker inserts an editable bound skill command",
app.mockInput.pressEnter()
await app.renderOnce()
expect(submits).toEqual([{ text: "/new task", parts: [], command: { name: "new", arguments: "task", source: "skill" } }])
expect(submits).toEqual([
{ text: "/new task", parts: [], command: { name: "new", arguments: "task", source: "skill" } },
])
} finally {
app.cleanup()
}
@ -981,7 +987,6 @@ test("direct footer shows editable prompts and additional queued work while runn
status: "",
queue: 3,
model: "gpt-5",
duration: "",
usage: "",
first: false,
interrupt: 0,
@ -992,13 +997,13 @@ test("direct footer shows editable prompts and additional queued work while runn
tabs: [subagent({ sessionID: "s-1", label: "Explore", description: "Inspect auth flow" })],
details: {},
permissions: [],
questions: [],
forms: [],
})
function Harness() {
return (
<Keymap.Provider config={tuiConfig}>
<RunFooterView
directory="/tmp"
directory={() => "/tmp"}
findFiles={async () => []}
agents={() => []}
references={() => []}
@ -1013,16 +1018,13 @@ test("direct footer shows editable prompts and additional queued work while runn
state={state}
view={view}
subagent={subagents}
queuedPrompts={() => [
{ messageID: "m-queued", partID: "p-queued", prompt: { text: "follow up", parts: [] } },
]}
queuedPrompts={() => [{ messageID: "m-queued", prompt: { text: "follow up", parts: [] } }]}
theme={() => RUN_THEME_FALLBACK}
tuiConfig={tuiConfig}
agent="opencode"
onSubmit={() => true}
onPermissionReply={() => {}}
onQuestionReply={() => {}}
onQuestionReject={() => {}}
onFormReply={() => {}}
onFormCancel={() => {}}
onCycle={() => {}}
onInterrupt={() => false}
onEditorOpen={async () => undefined}
@ -1098,7 +1100,7 @@ test("direct footer always offers backgrounding for a foreground subagent", asyn
tabs: [subagent({ sessionID: "s-1", label: "Explore", description: "Inspect auth flow" })],
details: {},
permissions: [],
questions: [],
forms: [],
},
width: 160,
})
@ -1125,7 +1127,7 @@ test("direct footer hides the subagent hint when only completed subagents remain
tabs: [subagent({ sessionID: "s-1", label: "Explore", description: "Inspect auth flow", status: "completed" })],
details: {},
permissions: [],
questions: [],
forms: [],
},
width: 160,
})
@ -1191,109 +1193,6 @@ test("direct footer mode label keeps left padding without a status pill", async
}
})
test("direct question body separates single-select checkmark from label", async () => {
const request = {
id: "question-1",
sessionID: "session-1",
questions: [
{
question: "Which categorical concept is often described as a universal way to combine two objects?",
header: "Universal Product",
options: [
{ label: "Product", description: "A product comes with projections." },
{ label: "Equalizer", description: "An equalizer selects morphisms where arrows agree." },
],
},
],
} satisfies QuestionV2Request
const replies: unknown[] = []
const app = await testRender(
() => (
<box width={100} height={12}>
<RunQuestionBody
request={request}
theme={RUN_THEME_FALLBACK.footer}
onReply={(input) => {
replies.push(input)
}}
onReject={() => {}}
/>
</box>
),
{
width: 100,
height: 12,
},
)
try {
app.mockInput.pressEnter()
await app.renderOnce()
expect(replies).toHaveLength(1)
expect(app.captureCharFrame()).toContain("Product ✓")
} finally {
app.renderer.destroy()
}
})
// OpenTUI currently segfaults while tearing down this textarea-backed keymap renderer.
// Re-enable after the runtime fix.
test.skip("direct custom answer submits through keymap return binding", async () => {
const question = {
id: "question-1",
sessionID: "session-1",
questions: [
{
question: "Which answer should I use?",
header: "Answer",
options: [{ label: "Provided", description: "Use the listed answer." }],
custom: true,
},
],
} satisfies QuestionV2Request
const questions: unknown[] = []
function Harness() {
return (
<Keymap.Provider config={tuiConfig}>
<RunQuestionBody
request={question}
theme={RUN_THEME_FALLBACK.footer}
onReply={(input) => {
questions.push(input)
}}
onReject={() => {}}
/>
</Keymap.Provider>
)
}
const app = await testRender(
() => (
<box width={100} height={18}>
<Harness />
</box>
),
{ width: 100, height: 18, kittyKeyboard: true },
)
try {
await app.renderOnce()
app.mockInput.pressKey("2")
await app.renderOnce()
"typed".split("").forEach((key) => app.mockInput.pressKey(key))
await app.renderOnce()
app.mockInput.pressEnter()
await app.renderOnce()
expect(questions).toEqual([{ requestID: "question-1", answers: [["typed"]] }])
} finally {
app.renderer.currentFocusedRenderable?.blur()
app.renderer.currentFocusedEditor?.blur()
app.renderer.destroy()
}
})
test("direct permission rejection submits through keymap return binding", async () => {
let text = ""
const submits: string[] = []

View file

@ -0,0 +1,66 @@
import { describe, expect, test } from "bun:test"
import type { FormField, FormInfo } from "@opencode-ai/client/promise"
import {
createFormBodyState,
formAcknowledge,
formAnswer,
formCommitInput,
formPick,
formReply,
formSetExternalReady,
formSetField,
formSetSelected,
formUnsupported,
formValidate,
} from "../../src/mini/form.shared"
function request(fields: FormField[]): FormInfo {
return { id: "frm_1", sessionID: "ses_1", title: "Input", fields: fields as FormInfo["fields"] }
}
describe("Mini form state", () => {
test("builds every supported answer and preserves owner location", () => {
const form = request([
{ key: "choice", type: "string", options: [{ value: "fast", label: "Fast" }], default: "fast" },
{ key: "count", type: "number" },
{ key: "whole", type: "integer", default: 2 },
{ key: "enabled", type: "boolean", default: false },
{ key: "tags", type: "multiselect", options: [], custom: true },
{ key: "external", type: "external", url: "https://example.com/action" },
])
let state = formSetField(createFormBodyState(form), form, 1)
state = formCommitInput(state, form, "1.5")
state = formSetField(state, form, 4)
state = formSetSelected(state, 0)
state = formPick(state, form)
state = formCommitInput(state, form, "custom")
state = formSetField(state, form, 5)
state = formAcknowledge(formSetExternalReady(state, "external"), form)
const answer = { choice: "fast", count: 1.5, whole: 2, enabled: false, tags: ["custom"], external: true }
expect(formAnswer(form, state)).toEqual(answer)
expect(formReply({ ...form, location: { directory: "/tmp", workspaceID: "wrk_1" } }, state)).toEqual({
sessionID: "ses_1",
formID: "frm_1",
answer,
location: { directory: "/tmp", workspaceID: "wrk_1" },
})
})
test("rejects invalid and deliberately unsupported shapes", () => {
const invalid = request([
{ key: "required", type: "string", required: true },
{ key: "external", type: "external", url: "https://example.com" },
])
expect(formValidate(invalid, createFormBodyState(invalid))).toContain("Answer required")
expect(formUnsupported(request([{ key: "value", type: "string", pattern: "^a" }]))).toContain("Pattern")
expect(
formUnsupported(
request([
{ key: "toggle", type: "boolean" },
{ key: "value", type: "string", when: [{ key: "toggle", op: "eq", value: true }] },
]),
),
).toContain("Conditional")
})
})

View file

@ -1,5 +1,4 @@
import { describe, expect, test } from "bun:test"
import type { PermissionV2Request } from "@opencode-ai/client/promise"
import {
createPermissionBodyState,
permissionAlwaysLines,
@ -9,8 +8,9 @@ import {
permissionReject,
permissionRun,
} from "../../src/mini/permission.shared"
import type { MiniPermissionRequest } from "../../src/mini/types"
function req(input: Partial<PermissionV2Request> = {}): PermissionV2Request {
function req(input: Partial<MiniPermissionRequest> = {}): MiniPermissionRequest {
return {
id: "perm-1",
sessionID: "session-1",
@ -22,23 +22,29 @@ function req(input: Partial<PermissionV2Request> = {}): PermissionV2Request {
}
}
function body() {
return createPermissionBodyState(req())
}
describe("run permission shared", () => {
test("replies immediately for allow once", () => {
const out = permissionRun(createPermissionBodyState("perm-1"), "perm-1", "once")
const out = permissionRun(body(), "perm-1", "once")
expect(out.reply).toEqual({
sessionID: "session-1",
requestID: "perm-1",
reply: "once",
})
})
test("requires confirmation for allow always", () => {
const next = permissionRun(createPermissionBodyState("perm-1"), "perm-1", "always")
const next = permissionRun(body(), "perm-1", "always")
expect(next.state.stage).toBe("always")
expect(next.state.selected).toBe("confirm")
expect(next.reply).toBeUndefined()
expect(permissionRun(next.state, "perm-1", "confirm").reply).toEqual({
sessionID: "session-1",
requestID: "perm-1",
reply: "always",
})
@ -50,11 +56,12 @@ describe("run permission shared", () => {
})
test("builds trimmed reject replies and stage transitions", () => {
const next = permissionRun(createPermissionBodyState("perm-1"), "perm-1", "reject")
const next = permissionRun(body(), "perm-1", "reject")
expect(next.state.stage).toBe("reject")
const out = permissionReject({ ...next.state, message: " use rg " }, "perm-1")
expect(out).toEqual({
sessionID: "session-1",
requestID: "perm-1",
reply: "reject",
message: "use rg",
@ -65,7 +72,7 @@ describe("run permission shared", () => {
selected: "reject",
})
expect(permissionEscape(createPermissionBodyState("perm-1"))).toMatchObject({
expect(permissionEscape(body())).toMatchObject({
stage: "reject",
selected: "reject",
})
@ -76,15 +83,23 @@ describe("run permission shared", () => {
})
})
test.skip("maps supported permission types into display info", () => {
test("maps supported permission types into display info", () => {
expect(
permissionInfo(
req({
action: "bash",
metadata: {
input: {
command: "git status --short",
action: "shell",
source: { type: "tool", messageID: "msg-shell", callID: "call-shell" },
tool: {
type: "tool",
id: "call-shell",
name: "shell",
state: {
status: "running",
input: { command: "git status --short" },
structured: {},
content: [],
},
time: { created: 1, ran: 1 },
},
}),
),
@ -93,21 +108,6 @@ describe("run permission shared", () => {
lines: ["$ git status --short"],
})
expect(
permissionInfo(
req({
action: "task",
metadata: {
description: "investigate stream",
subagent_type: "general",
},
}),
),
).toMatchObject({
title: "General Task",
lines: ["◉ investigate stream"],
})
expect(
permissionInfo(
req({
@ -130,6 +130,61 @@ describe("run permission shared", () => {
})
})
test("prefers canonical request metadata over source tool metadata", () => {
expect(
permissionInfo(
req({
action: "websearch",
metadata: { provider: "parallel" },
source: { type: "tool", messageID: "msg-search", callID: "call-search" },
tool: {
type: "tool",
id: "call-search",
name: "websearch",
state: {
status: "running",
input: { query: "current releases" },
structured: { provider: "exa", retained: true },
content: [],
},
time: { created: 1, ran: 1 },
},
}),
),
).toMatchObject({
title: 'Parallel Web Search "current releases"',
lines: ["Query: current releases"],
})
})
test("uses source patch text when an edit has no generated diff", () => {
expect(
permissionInfo(
req({
action: "edit",
resources: ["src/index.ts"],
source: { type: "tool", messageID: "msg-edit", callID: "call-edit" },
tool: {
type: "tool",
id: "call-edit",
name: "edit",
state: {
status: "running",
input: { patchText: "*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+new\n*** End Patch" },
structured: {},
content: [],
},
time: { created: 1, ran: 1 },
},
}),
),
).toMatchObject({
title: "Edit src/index.ts",
diff: undefined,
patch: "*** Begin Patch\n*** Update File: src/index.ts\n@@\n-old\n+new\n*** End Patch",
})
})
test("formats always-allow copy for wildcard and explicit patterns", () => {
expect(permissionAlwaysLines(req({ action: "bash", save: ["*"] }))).toEqual([
"This will allow bash until OpenCode is restarted.",

View file

@ -1,115 +0,0 @@
import { describe, expect, test } from "bun:test"
import type { QuestionV2Request } from "@opencode-ai/client/promise"
import {
createQuestionBodyState,
questionConfirm,
questionReject,
questionSave,
questionSelect,
questionSetSelected,
questionStoreCustom,
questionSubmit,
questionSync,
} from "../../src/mini/question.shared"
function req(input: Partial<QuestionV2Request> = {}): QuestionV2Request {
return {
id: "question-1",
sessionID: "session-1",
questions: [
{
question: "Mode?",
header: "Mode",
options: [{ label: "chunked", description: "Incremental output" }],
multiple: false,
},
],
...input,
}
}
describe("run question shared", () => {
test("replies immediately for a single-select question", () => {
const out = questionSelect(createQuestionBodyState("question-1"), req())
expect(out.reply).toEqual({
requestID: "question-1",
answers: [["chunked"]],
})
})
test("advances multi-question flows and submits from confirm", () => {
const ask = req({
questions: [
{
question: "Mode?",
header: "Mode",
options: [{ label: "chunked", description: "Incremental output" }],
multiple: false,
},
{
question: "Output?",
header: "Output",
options: [
{ label: "yes", description: "Show tool output" },
{ label: "no", description: "Hide tool output" },
],
multiple: false,
},
],
})
let state = questionSelect(createQuestionBodyState("question-1"), ask).state
expect(state.tab).toBe(1)
state = questionSetSelected(state, 1)
state = questionSelect(state, ask).state
expect(questionConfirm(ask, state)).toBe(true)
expect(questionSubmit(ask, state)).toEqual({
requestID: "question-1",
answers: [["chunked"], ["no"]],
})
})
test("toggles answers for multiple-choice questions", () => {
const ask = req({
questions: [
{
question: "Tags?",
header: "Tags",
options: [{ label: "bug", description: "Bug fix" }],
multiple: true,
},
],
})
let state = questionSelect(createQuestionBodyState("question-1"), ask).state
expect(state.answers).toEqual([["bug"]])
state = questionSelect(state, ask).state
expect(state.answers).toEqual([[]])
})
test("stores and submits custom answers", () => {
let state = questionSetSelected(createQuestionBodyState("question-1"), 1)
let next = questionSelect(state, req())
expect(next.state.editing).toBe(true)
state = questionStoreCustom(next.state, 0, " custom mode ")
next = questionSave(state, req())
expect(next.reply).toEqual({
requestID: "question-1",
answers: [["custom mode"]],
})
})
test("resets state when the request id changes and builds reject payloads", () => {
const state = questionSetSelected(createQuestionBodyState("question-1"), 1)
expect(questionSync(state, "question-1")).toBe(state)
expect(questionSync(state, "question-2")).toEqual(createQuestionBodyState("question-2"))
expect(questionReject(req())).toEqual({
requestID: "question-1",
})
})
})

View file

@ -1,7 +1,7 @@
import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"
import { OpenCode } from "@opencode-ai/client/promise"
import type { Resolved } from "../../src/config/v1"
import { resolveDiffStyle, resolveModelInfo, resolveRunTuiConfig } from "../../src/mini/runtime.boot"
import type { Resolved } from "../../src/config"
import { resolveModelInfo, resolveRunTuiConfig } from "../../src/mini/runtime.boot"
import { createTuiResolvedConfig } from "./fixture/tui-runtime"
function ok<T>(data: T) {
@ -66,7 +66,6 @@ function model(id: string, providerID: string, context: number, variants: string
function config(input?: {
leader?: string
leaderTimeout?: number
diff_style?: "auto" | "stacked"
bindings?: Partial<{
commandList: string[]
variantCycle: string[]
@ -80,7 +79,6 @@ function config(input?: {
}): Resolved {
const bind = input?.bindings
return createTuiResolvedConfig({
diff_style: input?.diff_style,
leader_timeout: input?.leaderTimeout,
keybinds: {
...(input?.leader && { leader: input.leader }),
@ -119,7 +117,7 @@ describe("run runtime boot", () => {
const result = await resolveRunTuiConfig(input)
expect(result.keybinds.get("leader")?.[0]?.key).toBe("ctrl+g")
expect(result.leader_timeout).toBe(2000)
expect(result.leader.timeout).toBe(2000)
expect(result.keybinds.get("command.palette.show")?.[0]?.key).toBe("ctrl+p")
expect(result.keybinds.get("variant.cycle").map((item) => item.key)).toEqual(["ctrl+t", "alt+t"])
expect(result.keybinds.get("session.interrupt")?.[0]?.key).toBe("ctrl+c")
@ -134,8 +132,7 @@ describe("run runtime boot", () => {
const result = await resolveRunTuiConfig(Promise.reject(new Error("boom")))
expect(result.keybinds.get("leader")?.[0]?.key).toBe("ctrl+x")
expect(result.leader_timeout).toBe(2000)
expect(result.diff_style).toBe("auto")
expect(result.leader.timeout).toBe(2000)
expect(result.keybinds.get("command.palette.show")?.[0]?.key).toBe("ctrl+p")
expect(result.keybinds.get("variant.cycle")?.[0]?.key).toBe("ctrl+t")
expect(result.keybinds.get("session.interrupt")?.[0]?.key).toBe("escape")
@ -152,10 +149,18 @@ describe("run runtime boot", () => {
expect(result.keybinds.get("leader")).toEqual([])
})
test("reads diff style and falls back to auto", async () => {
await expect(resolveDiffStyle(config({ diff_style: "stacked" }))).resolves.toBe("stacked")
test("preserves current theme mode, leader, and thinking config", async () => {
const result = await resolveRunTuiConfig(
createTuiResolvedConfig({
theme: { mode: "light" },
leader_timeout: 450,
session: { thinking: "hide" },
}),
)
await expect(resolveDiffStyle(Promise.reject(new Error("boom")))).resolves.toBe("auto")
expect(result.theme).toEqual({ mode: "light" })
expect(result.leader.timeout).toBe(450)
expect(result.session?.thinking).toBe("hide")
})
test("loads v2 providers and models for model selector data", async () => {
@ -165,32 +170,16 @@ describe("run runtime boot", () => {
const providerList = spyOn(sdk.provider, "list").mockImplementation(() => ok({ data: providers }) as never)
spyOn(sdk.model, "list").mockImplementation(() => ok({ data: models }) as never)
await expect(resolveModelInfo(sdk, "/workspace", { providerID: "openai", modelID: "gpt-5" })).resolves.toEqual({
await expect(resolveModelInfo(sdk, { directory: "/workspace" })).resolves.toEqual({
providers: [
{
id: "openai",
name: "OpenAI",
models: {
"gpt-5": {
id: "gpt-5",
providerID: "openai",
name: "gpt-5",
capabilities: {
tools: true,
input: ["text"],
output: ["text"],
},
cost: {
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
},
limit: {
context: 128000,
output: 8192,
},
status: "active",
variants: {
@ -201,55 +190,10 @@ describe("run runtime boot", () => {
},
},
],
variants: ["high", "minimal"],
limits: {
"openai/gpt-5": 128000,
},
})
expect(providerList).toHaveBeenCalledWith(
{
location: {
directory: "/workspace",
},
},
)
})
test("loads context limits across v2 providers", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
const providers = [provider("openai", "OpenAI"), provider("anthropic", "Anthropic")]
const models = [model("gpt-5", "openai", 128000, ["high", "minimal"]), model("sonnet", "anthropic", 200000)]
spyOn(sdk.provider, "list").mockImplementation(() => ok({ data: providers }) as never)
spyOn(sdk.model, "list").mockImplementation(() => ok({ data: models }) as never)
await expect(resolveModelInfo(sdk, "/workspace", { providerID: "openai", modelID: "gpt-5" })).resolves.toEqual({
providers: [
expect.objectContaining({
id: "openai",
name: "OpenAI",
models: expect.objectContaining({
"gpt-5": expect.objectContaining({
variants: {
high: {},
minimal: {},
},
}),
}),
}),
expect.objectContaining({
id: "anthropic",
name: "Anthropic",
models: expect.objectContaining({
sonnet: expect.objectContaining({
variants: {},
}),
}),
}),
],
variants: ["high", "minimal"],
limits: {
"openai/gpt-5": 128000,
"anthropic/sonnet": 200000,
expect(providerList).toHaveBeenCalledWith({
location: {
directory: "/workspace",
},
})
})

View file

@ -1,41 +1,9 @@
import { afterEach, describe, expect, mock, spyOn, test } from "bun:test"
import { OpenCode } from "@opencode-ai/client/promise"
import { runMiniFrontend } from "../../src/mini"
import { runInteractiveDeferredMode, runInteractiveMode } from "../../src/mini/runtime"
import type { FooterApi, FooterEvent, MiniHost, RunProvider } from "../../src/mini/types"
const provider: RunProvider = {
id: "openai",
name: "OpenAI",
models: {
"gpt-5": {
id: "gpt-5",
providerID: "openai",
name: "Little Frank",
capabilities: {
tools: true,
input: ["text"],
output: ["text"],
},
cost: {
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
},
limit: {
context: 128000,
output: 8192,
},
status: "active",
variants: {},
},
},
}
const transportProviders: RunProvider[][] = []
import { runInteractiveDeferredMode } from "../../src/mini/runtime"
import type { LifecycleInput } from "../../src/mini/runtime.lifecycle"
import type { FooterApi, FooterEvent, MiniHost } from "../../src/mini/types"
import { createTuiResolvedConfig } from "./fixture/tui-runtime"
function defer<T>() {
let resolve!: (value: T | PromiseLike<T>) => void
@ -51,18 +19,18 @@ function ok<T>(data: T) {
function host(): MiniHost {
return {
terminal: { stdin: process.stdin, cleanup() {} },
terminal: { stdin: process.stdin },
platform: "linux",
stdout: { write() {} },
files: { readText: async () => "" },
editor: { open: async () => undefined },
paths: { home: "/home/test", state: "/tmp/state", log: "/tmp/log" },
paths: { home: "/home/test" },
signals: {
sigint: { subscribe: () => () => {} },
sigusr2: { subscribe: () => () => {} },
},
startup: { showTiming: false, now: () => 0 },
diagnostics: { pid: 1, cwd: "/tmp", argv: [] },
diagnostics: {},
preferences: {
resolveVariant: async () => undefined,
saveVariant: async () => {},
@ -123,36 +91,101 @@ function footer(events: FooterEvent[] = []): FooterApi {
afterEach(() => {
mock.restore()
transportProviders.length = 0
})
describe("run interactive runtime", () => {
test("leaves host terminal cleanup to the caller when startup fails before renderer creation", async () => {
test("routes form responses to their owners with global location and local settlement", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
const inputHost = host()
let cleaned = 0
inputHost.terminal.cleanup = () => {
cleaned++
}
inputHost.preferences.resolveVariant = async () => {
throw new Error("preference failed")
}
const api = footer()
const streamStarted = defer<void>()
let lifecycle!: LifecycleInput
const settled: Array<{ sessionID: string; formID: string }> = []
spyOn(sdk.provider, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.model, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.agent, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.reference, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.command, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.skill, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
const reply = spyOn(sdk.form, "reply").mockImplementation(() => ok(undefined))
await expect(
runMiniFrontend({
host: inputHost,
const task = runInteractiveDeferredMode(
{
host: host(),
sdk,
directory: "/tmp",
resolveAgent: async () => "build",
session: async () => ({ id: "ses-never" }),
target: async () => ({
sessionID: "ses_root",
location: { directory: "/tmp", project: { id: "pro-1", directory: "/tmp" } },
agent: "build",
model: { providerID: "test", modelID: "model" },
variant: undefined,
resume: false,
}),
agent: "build",
model: undefined,
model: { providerID: "test", modelID: "model" },
variant: undefined,
files: [],
thinking: false,
}),
).rejects.toThrow("preference failed")
expect(cleaned).toBe(0)
},
{
createRuntimeLifecycle: async (input) => {
lifecycle = input
return {
footer: api,
onResize: () => () => {},
refreshTheme: () => {},
resetForReplay: () => Promise.resolve(),
close: () => Promise.resolve(),
}
},
streamTransport: Promise.resolve({
createSessionTransport: async () => {
streamStarted.resolve()
return {
runPromptTurn: async () => {},
interruptActiveTurn: async () => {},
selectSubagent: () => {},
settleForm: (sessionID: string, formID: string) => settled.push({ sessionID, formID }),
replayOnResize: async () => false,
close: async () => {},
}
},
formatUnknownError: (error: unknown) => (error instanceof Error ? error.message : String(error)),
}),
},
)
await streamStarted.promise
await lifecycle.onFormReply({
sessionID: "global",
formID: "frm_global",
answer: { value: "yes" },
location: { directory: "/remote work", workspaceID: "wrk_1" },
})
expect(reply).toHaveBeenCalledWith(
{
sessionID: "global",
formID: "frm_global",
answer: { value: "yes" },
location: { directory: "/remote work", workspaceID: "wrk_1" },
},
{
headers: {
"x-opencode-directory": "%2Fremote%20work",
"x-opencode-workspace": "wrk_1",
},
},
)
expect(settled).toEqual([{ sessionID: "global", formID: "frm_global" }])
reply.mockImplementationOnce(() => Promise.reject({ _tag: "FormInvalidAnswerError", message: "Invalid answer" }))
await expect(
lifecycle.onFormReply({ sessionID: "ses_child", formID: "frm_invalid", answer: { value: 3 } }),
).rejects.toEqual({ _tag: "FormInvalidAnswerError", message: "Invalid answer" })
expect(settled.some((item) => item.formID === "frm_invalid")).toBe(false)
api.close()
await task
})
test("resolves the deferred session only after first paint", async () => {
@ -174,11 +207,18 @@ describe("run interactive runtime", () => {
host: host(),
sdk,
directory: "/tmp",
resolveAgent: async () => "build",
session: async () => {
target: async () => {
resolved++
api.close()
return { id: "ses-deferred", title: "Deferred" }
return {
sessionID: "ses-deferred",
sessionTitle: "Deferred",
location: { directory: "/tmp", project: { id: "pro-1", directory: "/tmp" } },
agent: "build",
model: { providerID: "openai", modelID: "gpt-5" },
variant: undefined,
resume: false,
}
},
agent: "build",
model: { providerID: "openai", modelID: "gpt-5" },
@ -277,8 +317,15 @@ describe("run interactive runtime", () => {
host: host(),
sdk,
directory: "/tmp",
resolveAgent: async () => "build",
session: async () => ({ id: "ses-resume", title: "Resume", resume: true }),
target: async () => ({
sessionID: "ses-resume",
sessionTitle: "Resume",
location: { directory: "/tmp", project: { id: "pro-1", directory: "/tmp" } },
agent: "review",
model: { providerID: "openai", modelID: "gpt-5" },
variant: "high",
resume: true,
}),
agent: "build",
model: undefined,
variant: undefined,
@ -308,6 +355,7 @@ describe("run interactive runtime", () => {
type: "history",
history: [{ text: "previous prompt", parts: [] }],
})
expect(events).toContainEqual({ type: "agent", agent: "review" })
expect(events).toContainEqual({
type: "model",
model: "Little Frank · OpenAI · high",
@ -315,294 +363,56 @@ describe("run interactive runtime", () => {
})
})
test("waits for provider metadata before eager replay transport bootstrap", async () => {
const providersStarted = defer<void>()
const providers = defer<void>()
const lifecycleModels: unknown[] = []
test("aborts deferred resume history on close and uses the cached exit title", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
spyOn(sdk.provider, "list").mockImplementation(async () => {
providersStarted.resolve()
await providers.promise
return ok({
location: {
directory: "/tmp",
},
data: [
{
id: "openai",
name: "OpenAI",
api: {
type: "native",
settings: {},
},
request: {
headers: {},
body: {},
},
},
],
}) as never
})
spyOn(sdk.model, "list").mockImplementation(
() =>
ok({
location: {
directory: "/tmp",
},
data: [
{
id: "gpt-5",
providerID: "openai",
name: "Little Frank",
api: {
id: "openai",
type: "native",
settings: {},
},
capabilities: {
tools: true,
input: ["text"],
output: ["text"],
},
request: {
headers: {},
body: {},
},
variants: [],
time: {
released: 1,
},
cost: [
{
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
},
],
status: "active",
enabled: true,
limit: {
context: 128000,
output: 8192,
},
},
],
}) as never,
)
spyOn(sdk.message, "list").mockImplementation(() =>
ok({
data: [
{
id: "msg-user-1",
type: "user",
text: "hello",
time: {
created: 1,
},
},
],
cursor: {},
}),
)
spyOn(sdk.session, "get").mockImplementation(
() =>
ok({
id: "ses-1",
projectID: "pro-1",
title: "Session",
cost: 0,
tokens: {
input: 0,
output: 0,
reasoning: 0,
cache: {
read: 0,
write: 0,
},
},
time: {
created: 1,
updated: 1,
},
location: {
directory: "/tmp",
},
model: {
providerID: "openai",
id: "gpt-5",
},
}) as never,
)
spyOn(sdk.agent, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.reference, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.command, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.skill, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
const task = runInteractiveMode(
{
host: host(),
sdk,
directory: "/tmp",
sessionID: "ses-1",
sessionTitle: "Session",
resume: true,
replay: true,
replayLimit: 100,
agent: "build",
model: undefined,
variant: undefined,
files: [],
thinking: true,
},
{
createRuntimeLifecycle: async (input) => {
lifecycleModels.push(input.model)
return {
footer: footer(),
onResize: () => () => {},
refreshTheme: () => {},
resetForReplay: () => Promise.resolve(),
close: () => Promise.resolve(),
}
},
streamTransport: Promise.resolve({
createSessionTransport: async (input: { providers?: () => RunProvider[]; footer: FooterApi }) => {
transportProviders.push(input.providers?.() ?? [])
setTimeout(() => {
input.footer.close()
}, 0)
return {
runPromptTurn: async () => {},
interruptActiveTurn: async () => {},
selectSubagent: () => {},
replayOnResize: async () => false,
close: async () => {},
}
},
formatUnknownError: (error: unknown) => (error instanceof Error ? error.message : String(error)),
}),
},
)
await providersStarted.promise
expect(transportProviders).toEqual([])
providers.resolve()
await task
expect(lifecycleModels).toEqual([{ providerID: "openai", modelID: "gpt-5" }])
expect(transportProviders).toEqual([[provider]])
})
test("defers catalog-selected model resolution until after first paint", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
const defaultStarted = defer<void>()
const releaseDefault = defer<void>()
const lifecycleStarted = defer<void>()
const painted = defer<void>()
const modelShown = defer<void>()
let defaultRequested = false
const events: FooterEvent[] = []
const api = footer(events)
api.idle = () => painted.promise
const event = api.event
api.event = (value) => {
event(value)
if (value.type !== "model") return
modelShown.resolve()
api.close()
}
spyOn(sdk.model, "default").mockImplementation(async () => {
defaultRequested = true
defaultStarted.resolve()
await releaseDefault.promise
return ok({
location: { directory: "/tmp" },
data: { id: "catalog-default-test-model", providerID: "openai" },
}) as never
})
spyOn(sdk.provider, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.model, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.agent, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.reference, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.command, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
spyOn(sdk.skill, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
const task = runInteractiveMode(
{
host: host(),
sdk,
directory: "/tmp",
sessionID: "ses-fresh",
resume: false,
agent: "build",
model: undefined,
variant: undefined,
files: [],
thinking: false,
},
{
createRuntimeLifecycle: async (input) => {
expect(input.model).toBeUndefined()
lifecycleStarted.resolve()
return {
footer: api,
onResize: () => () => {},
refreshTheme: () => {},
resetForReplay: () => Promise.resolve(),
close: () => Promise.resolve(),
}
},
streamTransport: Promise.resolve({
createSessionTransport: async () => ({
runPromptTurn: async () => {},
interruptActiveTurn: async () => {},
selectSubagent: () => {},
replayOnResize: async () => false,
close: async () => {},
}),
formatUnknownError: (error: unknown) => (error instanceof Error ? error.message : String(error)),
}),
},
)
await lifecycleStarted.promise
expect(defaultRequested).toBe(false)
painted.resolve()
await defaultStarted.promise
releaseDefault.resolve()
await modelShown.promise
await task
expect(events.find((event) => event.type === "model")).toEqual({
type: "model",
model: "catalog-default-test-model · openai",
selection: { providerID: "openai", modelID: "catalog-default-test-model" },
})
})
test("does not start deferred work after the footer closes", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
const lifecycleStarted = defer<void>()
const painted = defer<void>()
const readsStarted = defer<void>()
const api = footer()
api.idle = () => painted.promise
const defaultModel = spyOn(sdk.model, "default")
let reads = 0
let aborted = 0
let closedTitle: string | undefined
const pending = (signal: AbortSignal | undefined) =>
new Promise<never>((_resolve, reject) => {
reads++
if (reads === 2) readsStarted.resolve()
signal?.addEventListener(
"abort",
() => {
aborted++
reject(new Error("resume history aborted"))
},
{ once: true },
)
})
const messages = spyOn(sdk.message, "list").mockImplementation(
(_request, options) => pending(options?.signal) as never,
)
const session = spyOn(sdk.session, "get").mockImplementation(
(_request, options) => pending(options?.signal) as never,
)
const response = { location: { directory: "/tmp" }, data: [] }
spyOn(sdk.provider, "list").mockResolvedValue(response as never)
spyOn(sdk.model, "list").mockResolvedValue(response as never)
spyOn(sdk.agent, "list").mockResolvedValue(response as never)
spyOn(sdk.reference, "list").mockResolvedValue(response as never)
spyOn(sdk.command, "list").mockResolvedValue(response as never)
spyOn(sdk.skill, "list").mockResolvedValue(response as never)
const task = runInteractiveMode(
const task = runInteractiveDeferredMode(
{
host: host(),
sdk,
directory: "/tmp",
sessionID: "ses-closed",
resume: false,
target: async () => ({
sessionID: "ses-resume-abort",
sessionTitle: "Cached title",
location: { directory: "/tmp", project: { id: "pro-1", directory: "/tmp" } },
agent: "build",
model: undefined,
variant: undefined,
resume: true,
}),
agent: "build",
model: undefined,
variant: undefined,
@ -610,168 +420,89 @@ describe("run interactive runtime", () => {
thinking: false,
},
{
createRuntimeLifecycle: async () => {
lifecycleStarted.resolve()
return {
footer: api,
onResize: () => () => {},
refreshTheme: () => {},
resetForReplay: () => Promise.resolve(),
close: () => Promise.resolve(),
}
},
createRuntimeLifecycle: async () => ({
footer: api,
onResize: () => () => {},
refreshTheme: () => {},
resetForReplay: () => Promise.resolve(),
close: async (input) => {
closedTitle = input.sessionTitle
},
}),
},
)
await lifecycleStarted.promise
painted.resolve()
await readsStarted.promise
api.close()
painted.resolve()
await task
expect(defaultModel).not.toHaveBeenCalled()
expect(aborted).toBe(2)
expect(messages).toHaveBeenCalledWith(
{ sessionID: "ses-resume-abort", limit: 200, order: "desc" },
{ signal: expect.any(AbortSignal) },
)
expect(session).toHaveBeenCalledTimes(1)
expect(session).toHaveBeenCalledWith({ sessionID: "ses-resume-abort" }, { signal: expect.any(AbortSignal) })
expect(closedTitle).toBe("Cached title")
})
test("searches files through the V2 file API", async () => {
test("adopts the deferred target location for catalogs, files, and runtime placement", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
const lifecycleStarted = defer<void>()
const painted = defer<void>()
const api = footer()
const find = spyOn(sdk.file, "find").mockImplementation(
() =>
ok({
location: { directory: "/tmp", project: { id: "proj_1", directory: "/tmp" } },
data: [{ path: "src/index.ts", type: "file" }],
}) as never,
)
api.idle = () => painted.promise
let targets = 0
let getDirectory: (() => string) | undefined
let findFiles: ((query: string) => Promise<string[]>) | undefined
let transportLocation: unknown
const response = { location: { directory: "/session", workspaceID: "work-1" }, data: [] }
const providerList = spyOn(sdk.provider, "list").mockResolvedValue(response as never)
const modelList = spyOn(sdk.model, "list").mockResolvedValue(response as never)
const agentList = spyOn(sdk.agent, "list").mockResolvedValue(response as never)
const referenceList = spyOn(sdk.reference, "list").mockResolvedValue(response as never)
const commandList = spyOn(sdk.command, "list").mockResolvedValue(response as never)
const skillList = spyOn(sdk.skill, "list").mockResolvedValue(response as never)
const fileFind = spyOn(sdk.file, "find").mockResolvedValue({
location: {
directory: "/session",
workspaceID: "work-1",
project: { id: "pro-1", directory: "/session" },
},
data: [{ path: "src/index.ts", type: "file" }],
} as never)
await runInteractiveMode(
const task = runInteractiveDeferredMode(
{
host: host(),
sdk,
directory: "/tmp",
sessionID: "ses-files",
resume: false,
agent: "build",
directory: "/launch",
target: async () => {
targets++
return {
sessionID: "ses-target",
location: {
directory: "/session",
workspaceID: "work-1",
project: { id: "location-project", directory: "/session" },
},
agent: "review",
model: { providerID: "openai", modelID: "gpt-5" },
variant: "high",
resume: false,
}
},
agent: undefined,
model: undefined,
variant: undefined,
files: [],
thinking: false,
},
{
createRuntimeLifecycle: async (input) => {
await expect(input.findFiles("index")).resolves.toEqual(["src/index.ts"])
api.close()
return {
footer: api,
onResize: () => () => {},
refreshTheme: () => {},
resetForReplay: () => Promise.resolve(),
close: () => Promise.resolve(),
}
},
},
)
expect(find).toHaveBeenCalledWith({ query: "index", type: "file", location: { directory: "/tmp" } })
})
test.skip("retains last-known-good state across failed coalesced refreshes and retries later", async () => {
const sdk = OpenCode.make({ baseUrl: "https://opencode.test" })
const refreshGate = defer<void>()
let providerCalls = 0
let modelCalls = 0
let agentCalls = 0
let referenceCalls = 0
const events: FooterEvent[] = []
const api = footer(events)
spyOn(sdk.provider, "list").mockImplementation(async () => {
providerCalls++
if (providerCalls === 2) {
await refreshGate.promise
throw new Error("provider refresh failed")
}
return ok({
location: { directory: "/tmp" },
data: [
{
id: "openai",
name: providerCalls >= 3 ? "OpenAI refreshed" : "OpenAI",
api: { type: "native", settings: {} },
request: { headers: {}, body: {} },
},
],
}) as never
})
spyOn(sdk.model, "list").mockImplementation(() => {
modelCalls++
return ok({
location: { directory: "/tmp" },
data: [
{
id: "gpt-5",
providerID: "openai",
name: "Little Frank",
api: { id: "openai", type: "native", settings: {} },
capabilities: { tools: true, input: ["text"], output: ["text"] },
request: { headers: {}, body: {} },
variants:
modelCalls >= 4 ? [] : [{ id: modelCalls >= 3 ? "high" : "low", settings: {}, headers: {}, body: {} }],
time: { released: 1 },
cost: [{ input: 0, output: 0, cache: { read: 0, write: 0 } }],
status: "active",
enabled: true,
limit: { context: modelCalls >= 3 ? 256000 : 128000, output: 8192 },
},
],
}) as never
})
spyOn(sdk.agent, "list").mockImplementation(async () => {
agentCalls++
if (agentCalls === 2) throw new Error("agent refresh failed")
return ok({
location: { directory: "/tmp" },
data: [{ id: "build", description: agentCalls >= 3 ? "Refreshed agent" : "Agent", mode: "primary" }],
}) as never
})
spyOn(sdk.reference, "list").mockImplementation(() => {
referenceCalls++
return ok({
location: { directory: "/tmp" },
data: [
{ name: "effect", path: "/effect", description: referenceCalls >= 3 ? "Refreshed reference" : "Reference" },
],
}) as never
})
spyOn(sdk.command, "list").mockImplementation(
() => ok({ location: { directory: "/tmp" }, data: [{ name: "check", description: "Check" }] }) as never,
)
spyOn(sdk.skill, "list").mockImplementation(() => ok({ location: { directory: "/tmp" }, data: [] }) as never)
let finalProviders: RunProvider[] = []
let finalLimits: Record<string, number> = {}
let retainedProviders: RunProvider[] = []
let retainedLimits: Record<string, number> = {}
let retainedCatalog: FooterEvent | undefined
let selectedDefault: unknown
let selectDefault: (() => unknown) | undefined
let selectVariant: ((variant: string | undefined) => unknown) | undefined
let defaultRefreshVariants: FooterEvent | undefined
await runInteractiveMode(
{
host: host(),
sdk,
directory: "/tmp",
sessionID: "ses-1",
sessionTitle: "Session",
resume: false,
agent: "build",
model: { providerID: "openai", modelID: "gpt-5" },
variant: "low",
files: [],
thinking: false,
},
{
createRuntimeLifecycle: async (input) => {
selectDefault = () => input.onVariantSelect?.(undefined)
selectVariant = (variant) => input.onVariantSelect?.(variant)
getDirectory = input.getDirectory
findFiles = input.findFiles
lifecycleStarted.resolve()
return {
footer: api,
onResize: () => () => {},
@ -782,33 +513,8 @@ describe("run interactive runtime", () => {
},
streamTransport: Promise.resolve({
createSessionTransport: async (input) => {
while (
!events.some(
(event) => event.type === "variants" && event.variants.includes("low") && event.current === "low",
)
)
await Bun.sleep(0)
selectedDefault = await Promise.resolve(selectDefault?.())
input.onCatalogRefresh?.()
input.onCatalogRefresh?.()
input.onCatalogRefresh?.()
while (providerCalls < 2) await Bun.sleep(0)
refreshGate.resolve()
await new Promise((resolve) => setTimeout(resolve, 0))
retainedProviders = input.providers?.() ?? []
retainedLimits = input.limits()
retainedCatalog = events.filter((event) => event.type === "catalog").at(-1)
input.onCatalogRefresh?.()
input.onCatalogRefresh?.()
while (providerCalls < 3 || modelCalls < 3 || agentCalls < 3) await Bun.sleep(0)
await new Promise((resolve) => setTimeout(resolve, 0))
defaultRefreshVariants = events.filter((event) => event.type === "variants").at(-1)
await Promise.resolve(selectVariant?.("high"))
input.onCatalogRefresh?.()
while (providerCalls < 4 || modelCalls < 4) await Bun.sleep(0)
await new Promise((resolve) => setTimeout(resolve, 0))
finalProviders = input.providers?.() ?? []
finalLimits = input.limits()
transportLocation = input.location
await findFiles?.("index")
setTimeout(() => input.footer.close(), 0)
return {
runPromptTurn: async () => {},
@ -818,33 +524,26 @@ describe("run interactive runtime", () => {
close: async () => {},
}
},
formatUnknownError: (error: unknown) => (error instanceof Error ? error.message : String(error)),
formatUnknownError: (error: unknown) => String(error),
}),
},
)
expect(providerCalls).toBe(4)
expect(modelCalls).toBe(4)
expect(retainedProviders[0]?.name).toBe("OpenAI")
expect(retainedProviders[0]?.models["gpt-5"]?.variants).toEqual({ low: {} })
expect(retainedLimits["openai/gpt-5"]).toBe(128000)
expect(retainedCatalog).toMatchObject({
agents: [{ name: "build", description: "Agent" }],
references: [{ name: "effect", description: "Reference" }],
})
expect(selectedDefault).toMatchObject({ variant: undefined })
expect(defaultRefreshVariants).toMatchObject({ variants: ["high"], current: undefined })
expect(finalProviders[0]?.name).toBe("OpenAI refreshed")
expect(finalProviders[0]?.models["gpt-5"]?.variants).toEqual({})
expect(finalLimits["openai/gpt-5"]).toBe(256000)
expect(events.filter((event) => event.type === "variants").at(-1)).toMatchObject({
variants: [],
current: undefined,
})
expect(events.filter((event) => event.type === "catalog").at(-1)).toMatchObject({
agents: [{ name: "build", description: "Refreshed agent" }],
references: [{ name: "effect", description: "Refreshed reference" }],
commands: [{ name: "check", description: "Check" }],
})
await lifecycleStarted.promise
expect(targets).toBe(0)
expect(getDirectory?.()).toBe("/launch")
painted.resolve()
await task
const query = { location: { directory: "/session", workspace: "work-1" } }
expect(getDirectory?.()).toBe("/session")
expect(transportLocation).toMatchObject({ directory: "/session", workspaceID: "work-1" })
expect(providerList).toHaveBeenCalledWith(query, { signal: expect.any(AbortSignal) })
expect(modelList).toHaveBeenCalledWith(query, { signal: expect.any(AbortSignal) })
expect(agentList).toHaveBeenCalledWith(query, { signal: expect.any(AbortSignal) })
expect(referenceList).toHaveBeenCalledWith(query, { signal: expect.any(AbortSignal) })
expect(commandList).toHaveBeenCalledWith(query, { signal: expect.any(AbortSignal) })
expect(skillList).toHaveBeenCalledWith(query, { signal: expect.any(AbortSignal) })
expect(fileFind).toHaveBeenCalledWith({ query: "index", type: "file", ...query })
})
})

View file

@ -1,9 +1,11 @@
import { afterEach, expect, test } from "bun:test"
import type { SessionMessageAssistantTool } from "@opencode-ai/client/promise"
import { RGBA, SyntaxStyle } from "@opentui/core"
import { MockTreeSitterClient, createTestRenderer, type TestRenderer } from "@opentui/core/testing"
import { RunScrollbackStream } from "../../src/mini/scrollback.surface"
import { entryGroupKey } from "../../src/mini/scrollback.writer"
import { RUN_THEME_FALLBACK, type RunTheme } from "../../src/mini/theme"
import type { MiniToolPart, StreamCommit } from "../../src/mini/types"
import type { StreamCommit } from "../../src/mini/types"
type ClaimedCommit = {
snapshot: {
@ -218,16 +220,19 @@ function error(text: string): StreamCommit {
}
}
function toolPart(tool: string, state: Record<string, unknown>, id: string, messageID: string): MiniToolPart {
function toolPart(name: string, state: SessionMessageAssistantTool["state"], id: string): SessionMessageAssistantTool {
return {
id,
sessionID: "session-1",
messageID,
type: "tool",
callID: `call-${id}`,
tool,
id,
name,
state,
} as MiniToolPart
time:
state.status === "streaming"
? { created: 1 }
: state.status === "completed" || state.status === "error"
? { created: 1, ran: 1, completed: 2 }
: { created: 1, ran: 1 },
}
}
function toolCommit(input: {
@ -235,7 +240,7 @@ function toolCommit(input: {
phase: StreamCommit["phase"]
toolState?: StreamCommit["toolState"]
text?: string
state?: Record<string, unknown>
state?: SessionMessageAssistantTool["state"]
id?: string
messageID?: string
}): StreamCommit {
@ -251,10 +256,23 @@ function toolCommit(input: {
messageID,
tool: input.tool,
...(input.toolState ? { toolState: input.toolState } : {}),
...(input.state ? { part: toolPart(input.tool, input.state, id, messageID) } : {}),
...(input.state ? { part: toolPart(input.tool, input.state, id) } : {}),
}
}
test("scopes repeated tool part IDs to their assistant messages", () => {
const first = toolCommit({
tool: "read",
phase: "start",
id: "call-repeated",
messageID: "msg-one",
toolState: "running",
})
const second = { ...first, messageID: "msg-two" }
expect(entryGroupKey(first)).not.toBe(entryGroupKey(second))
})
test("finalizes markdown tables for streamed and coalesced input", async () => {
const text =
"| Column 1 | Column 2 | Column 3 |\n|---|---|---|\n| Row 1 | Value 1 | Value 2 |\n| Row 2 | Value 3 | Value 4 |"
@ -342,7 +360,8 @@ test("renders question summaries without boilerplate footer copy", async () => {
},
],
},
time: { start: 1 },
structured: {},
content: [],
},
}),
final: toolCommit({
@ -361,10 +380,10 @@ test("renders question summaries without boilerplate footer copy", async () => {
},
],
},
metadata: {
structured: {
answers: [["Bug fix"]],
},
time: { start: 1, end: 2100 },
content: [],
},
}),
},
@ -436,7 +455,8 @@ test("inserts spacers for new visible groups", async () => {
input: {
pattern: "**/run.ts",
},
time: { start: 1 },
structured: {},
content: [],
},
}),
)
@ -526,13 +546,13 @@ test.skipIf(process.platform === "win32")(
},
)
test.skip("coalesces same-line tool progress into one snapshot", async () => {
test("coalesces same-line tool progress into one snapshot", async () => {
const out = await setup()
try {
await out.scrollback.append(toolCommit({ tool: "bash", phase: "progress", text: "abc" }))
await out.scrollback.append(toolCommit({ tool: "bash", phase: "progress", text: "def" }))
await out.scrollback.append(toolCommit({ tool: "bash", phase: "final", text: "", toolState: "completed" }))
await out.scrollback.append(toolCommit({ tool: "shell", phase: "progress", text: "abc" }))
await out.scrollback.append(toolCommit({ tool: "shell", phase: "progress", text: "def" }))
await out.scrollback.append(toolCommit({ tool: "shell", phase: "final", text: "", toolState: "completed" }))
const commits = claim(out.renderer)
try {
@ -546,102 +566,7 @@ test.skip("coalesces same-line tool progress into one snapshot", async () => {
}
})
test.skip("omits the current directory from bash titles", async () => {
const out = await setup()
try {
await out.scrollback.append(
toolCommit({
tool: "bash",
phase: "start",
toolState: "running",
state: {
status: "running",
input: {
command: "pwd",
workdir: process.cwd(),
},
time: { start: 1 },
},
}),
)
const commits = claim(out.renderer)
try {
expect(render(commits)).toContain("$ pwd")
expect(render(commits)).not.toContain("Running in .")
} finally {
destroy(commits)
}
} finally {
out.scrollback.destroy()
}
})
test.skip("renders completed bash output with one blank line after the command and before the next group", async () => {
const out = await setup()
try {
const lines: string[] = []
const take = () => {
const commits = claim(out.renderer)
try {
lines.push(...commits.flatMap((commit) => renderRows(commit).flatMap((row) => row.split("\n"))))
} finally {
destroy(commits)
}
}
await out.scrollback.append(user("/fmt bash"))
take()
await out.scrollback.append(
toolCommit({
tool: "bash",
phase: "start",
toolState: "running",
state: {
status: "running",
input: {
command: "git status",
workdir: "/tmp/demo",
},
time: { start: 1 },
},
}),
)
take()
await out.scrollback.append(
toolCommit({
tool: "bash",
phase: "progress",
toolState: "completed",
text: ["/tmp/demo", "git status", "On branch demo", "nothing to commit, working tree clean", ""].join("\n"),
state: {
status: "completed",
input: {
command: "git status",
workdir: "/tmp/demo",
},
time: { start: 1, end: 2 },
},
}),
)
take()
await out.scrollback.append(assistant("oc-run-dev ahead 1"))
await out.scrollback.complete()
take()
const output = lines.join("\n")
expect(output).toContain("# Running in /tmp/demo\n$ git status")
expect(output).toContain("$ git status\n\nOn branch demo")
expect(output).toContain("nothing to commit, working tree clean\n\noc-run-dev ahead 1")
expect(output).not.toContain("nothing to commit, working tree clean\n\n\noc-run-dev ahead 1")
} finally {
out.scrollback.destroy()
}
})
test.skip("inserts a spacer before the next tool after completed multiline bash output", async () => {
test("does not double-space before completed shell output when inline tool headers intervene", async () => {
const out = await setup()
try {
@ -657,83 +582,7 @@ test.skip("inserts a spacer before the next tool after completed multiline bash
await out.scrollback.append(
toolCommit({
tool: "bash",
phase: "start",
toolState: "running",
state: {
status: "running",
input: {
command: "pwd; ls -la",
workdir: "/tmp/demo",
},
time: { start: 1 },
},
}),
)
take()
await out.scrollback.append(
toolCommit({
tool: "bash",
phase: "progress",
toolState: "completed",
text: ["/tmp/demo", "pwd; ls -la", "/tmp/demo", "total 4", "", ""].join("\n"),
state: {
status: "completed",
input: {
command: "pwd; ls -la",
workdir: "/tmp/demo",
},
output: ["/tmp/demo", "pwd; ls -la", "/tmp/demo", "total 4", "", ""].join("\n"),
title: "pwd; ls -la",
metadata: {
exitCode: 0,
},
time: { start: 1, end: 2 },
},
}),
)
take()
await out.scrollback.append(
toolCommit({
tool: "glob",
phase: "start",
toolState: "running",
state: {
status: "running",
input: {
pattern: "**/*tool*",
path: "src/cli/cmd",
},
time: { start: 3 },
},
}),
)
take()
const output = lines.join("\n")
expect(output).toContain('total 4\n\n✱ Glob "**/*tool*" in src/cli/cmd')
} finally {
out.scrollback.destroy()
}
})
test.skip("does not double-space before completed bash output when inline tool headers intervene", async () => {
const out = await setup()
try {
const lines: string[] = []
const take = () => {
const commits = claim(out.renderer)
try {
lines.push(...commits.flatMap((commit) => renderRows(commit).flatMap((row) => row.split("\n"))))
} finally {
destroy(commits)
}
}
await out.scrollback.append(
toolCommit({
tool: "bash",
tool: "shell",
phase: "start",
toolState: "running",
state: {
@ -742,7 +591,8 @@ test.skip("does not double-space before completed bash output when inline tool h
command: "ls",
workdir: "src/cli/cmd/run",
},
time: { start: 1 },
structured: {},
content: [],
},
}),
)
@ -758,7 +608,8 @@ test.skip("does not double-space before completed bash output when inline tool h
pattern: "**/*tool*",
path: "src/cli/cmd/run",
},
time: { start: 2 },
structured: {},
content: [],
},
}),
)
@ -774,14 +625,15 @@ test.skip("does not double-space before completed bash output when inline tool h
pattern: "tool",
path: "src/cli/cmd/run",
},
time: { start: 3 },
structured: {},
content: [],
},
}),
)
take()
await out.scrollback.append(
toolCommit({
tool: "bash",
tool: "shell",
phase: "progress",
toolState: "completed",
text: ["src/cli/cmd/run", "ls", "demo.ts", "entry.body.ts", "", ""].join("\n"),
@ -791,12 +643,8 @@ test.skip("does not double-space before completed bash output when inline tool h
command: "ls",
workdir: "src/cli/cmd/run",
},
output: ["src/cli/cmd/run", "ls", "demo.ts", "entry.body.ts", "", ""].join("\n"),
title: "ls",
metadata: {
exitCode: 0,
},
time: { start: 1, end: 4 },
content: [{ type: "text", text: ["src/cli/cmd/run", "ls", "demo.ts", "entry.body.ts", "", ""].join("\n") }],
structured: { exit: 0, truncated: false },
},
}),
)
@ -810,105 +658,6 @@ test.skip("does not double-space before completed bash output when inline tool h
}
})
test.skip("does not emit blank patch snapshots between edit and task", async () => {
const out = await setup()
try {
const lines: string[] = []
const take = () => {
const commits = claim(out.renderer)
try {
lines.push(...commits.flatMap((commit) => renderRows(commit).flatMap((row) => row.split("\n"))))
} finally {
destroy(commits)
}
}
await out.scrollback.append(
toolCommit({
tool: "edit",
phase: "final",
toolState: "completed",
state: {
status: "completed",
input: {
filePath: "src/demo-format.ts",
},
output: "",
title: "edit",
metadata: {
diff: "@@ -1 +1 @@\n-export const demo = 1\n+export const demo = 42\n",
},
time: { start: 1, end: 2 },
},
}),
)
take()
await out.scrollback.append(
toolCommit({
tool: "apply_patch",
phase: "final",
toolState: "completed",
state: {
status: "completed",
input: {
patchText: "*** Begin Patch\n*** End Patch",
},
output: "",
title: "apply_patch",
metadata: {
files: [
{
type: "update",
filePath: "src/demo-format.ts",
relativePath: "src/demo-format.ts",
diff: "@@ -1 +1 @@\n-export const demo = 1\n+export const demo = 42\n",
deletions: 1,
},
{
type: "add",
filePath: "README-demo.md",
relativePath: "README-demo.md",
},
],
},
time: { start: 2, end: 3 },
},
}),
)
take()
await out.scrollback.append(
toolCommit({
tool: "task",
phase: "final",
toolState: "completed",
state: {
status: "completed",
input: {
description: "Scan run/* for reducer touchpoints",
subagent_type: "explore",
},
output: "",
title: "task",
metadata: {
sessionId: "sub_demo_1",
},
time: { start: 3, end: 4 },
},
}),
)
take()
const output = lines.join("\n")
expect(output).toContain("+ Created README-demo.md")
expect(output).not.toContain("~ Patched src/demo-format.ts")
expect(output).toContain("+ Created README-demo.md\n\n# Explore Task")
expect(output).not.toContain("+ Created README-demo.md\n\n\n# Explore Task")
} finally {
out.scrollback.destroy()
}
})
test("renders plain errors with one blank line before and after the error block", async () => {
const out = await setup()
@ -957,10 +706,11 @@ test("renders structured write finals once as code blocks", async () => {
state: {
status: "running",
input: {
filePath: "src/a.ts",
path: "src/a.ts",
content: "const x = 1\nconst y = 2\n",
},
time: { start: 1 },
structured: {},
content: [],
},
}),
)
@ -976,11 +726,11 @@ test("renders structured write finals once as code blocks", async () => {
state: {
status: "completed",
input: {
filePath: "src/a.ts",
path: "src/a.ts",
content: "const x = 1\nconst y = 2\n",
},
metadata: {},
time: { start: 1, end: 2 },
structured: {},
content: [],
},
}),
)
@ -999,51 +749,3 @@ test("renders structured write finals once as code blocks", async () => {
out.scrollback.destroy()
}
})
test("renders promoted task markdown without a leading blank row", async () => {
const out = await setup()
try {
await out.scrollback.append(
toolCommit({
tool: "task",
phase: "final",
toolState: "completed",
state: {
status: "completed",
input: {
description: "Explore run.ts",
subagent_type: "explore",
},
output: [
'<task id="child-1" state="completed">',
"<task_result>",
"Location: `/tmp/run.ts`",
"",
"Summary:",
"- Local interactive mode",
"- Attach mode",
"</task_result>",
"</task>",
].join("\n"),
metadata: {
sessionId: "child-1",
},
time: { start: 1, end: 2 },
},
}),
)
const commits = claim(out.renderer)
try {
const output = render(commits)
expect(output.startsWith("\n")).toBe(false)
expect(output).toContain("Summary:")
expect(output).toContain("Local interactive mode")
} finally {
destroy(commits)
}
} finally {
out.scrollback.destroy()
}
})

View file

@ -193,7 +193,8 @@ describe("run session shared", () => {
}),
)
const out = await resolveCurrentSession(client, "ses_1")
const controller = new AbortController()
const out = await resolveCurrentSession(client, "ses_1", controller.signal)
expect(out.model).toEqual({ providerID: "openai", modelID: "gpt-5" })
expect(out.variant).toBe("high")
@ -213,5 +214,10 @@ describe("run session shared", () => {
},
],
})
expect(client.message.list).toHaveBeenCalledWith(
{ sessionID: "ses_1", limit: 200, order: "desc" },
{ signal: controller.signal },
)
expect(client.session.get).toHaveBeenCalledWith({ sessionID: "ses_1" }, { signal: controller.signal })
})
})

File diff suppressed because it is too large Load diff

View file

@ -71,9 +71,6 @@ test("returns syntax styles and indexed splash colors", async () => {
expectIndexed(theme.splash.left)
expectIndexed(theme.splash.right)
expectIndexed(theme.splash.leftShadow)
expectIndexed(theme.splash.rightShadow)
expectIndexed(theme.block.highlight)
expectIndexed(theme.block.warning)
expectRgba(theme.footer.highlight)
expectRgba(theme.footer.statusAccent)
expectRgba(theme.footer.surface)
@ -96,8 +93,6 @@ test("keeps footer surfaces exact while scrollback stays palette matched", async
expect(expectRgba(theme.footer.border).toInts()).toEqual(expectRgba(exact.border).toInts())
expect(expectRgba(theme.footer.pane).toInts()).toEqual(expectRgba(exact.backgroundMenu).toInts())
expect(expectRgba(theme.footer.selected).intent).toBe("rgb")
expectIndexed(theme.block.highlight)
expectIndexed(theme.block.warning)
} finally {
theme.block.syntax?.destroy()
}

View file

@ -1,34 +1,15 @@
import { describe, expect, test } from "bun:test"
import { toolInlineInfo, toolOutputText, toolView } from "../../src/mini/tool"
import { normalizeTool, toolOutputText } from "../../src/mini/tool"
describe("Mini tool presentation", () => {
test("renders the renamed shell tool with the shell rule", () => {
const part = {
id: "part-shell",
sessionID: "session-shell",
messageID: "message-shell",
callID: "call-shell",
tool: "shell",
state: {
status: "pending" as const,
input: { command: "pwd" },
},
} as const
expect(toolView(part.tool)).toEqual({ output: true, final: false })
expect(toolInlineInfo(part)).toMatchObject({ icon: "$", title: "pwd", mode: "block" })
})
test("uses non-empty V2 shell output without the model-facing status", () => {
test("uses V2 shell output without the model-facing status", () => {
expect(
toolOutputText("shell", [
{ type: "text", text: "mini-output\n" },
{ type: "text", text: "Command exited with code 0." },
]),
).toBe("mini-output\n")
})
test("keeps empty V2 shell output empty", () => {
expect(
toolOutputText("shell", [
{ type: "text", text: "" },
@ -36,4 +17,59 @@ describe("Mini tool presentation", () => {
]),
).toBe("")
})
test("normalizes only persisted tool aliases into current fields", () => {
expect(
normalizeTool({
type: "tool",
id: "call-patch",
name: "apply_patch",
state: {
status: "completed",
input: { patchText: "*** Begin Patch\n*** End Patch" },
structured: {
files: [
{
type: "update",
filePath: "/tmp/project/src/a.ts",
relativePath: "src/a.ts",
diff: "@@ -1 +1 @@\n-old\n+new",
},
],
},
content: [{ type: "text", text: "patched" }],
},
time: { created: 1, ran: 1, completed: 2 },
}),
).toMatchObject({
name: "patch",
state: {
structured: {
files: [
{
status: "modified",
file: "src/a.ts",
patch: "@@ -1 +1 @@\n-old\n+new",
},
],
},
content: [{ type: "text", text: "patched" }],
},
})
expect(
normalizeTool({
type: "tool",
id: "call-subagent",
name: "task",
state: {
status: "running",
input: { subagent_type: "explore", description: "Inspect" },
structured: {},
content: [],
},
time: { created: 1, ran: 1 },
}),
).toMatchObject({ name: "subagent", state: { input: { agent: "explore" } } })
})
})

View file

@ -12,56 +12,9 @@ const providers: RunProvider[] = [
{
id: "openai",
name: "OpenAI",
source: "api",
env: [],
options: {},
models: {
"gpt-5": {
id: "gpt-5",
providerID: "openai",
api: {
id: "gpt-5",
url: "https://openai.test",
npm: "@ai-sdk/openai",
},
name: "GPT-5",
capabilities: {
temperature: true,
reasoning: true,
attachment: true,
toolcall: true,
input: {
text: true,
audio: false,
image: false,
video: false,
pdf: false,
},
output: {
text: true,
audio: false,
image: false,
video: false,
pdf: false,
},
interleaved: false,
},
cost: {
input: 0,
output: 0,
cache: {
read: 0,
write: 0,
},
},
limit: {
context: 128000,
output: 8192,
},
status: "active",
options: {},
headers: {},
release_date: "2026-01-01",
},
},
},
@ -100,5 +53,4 @@ describe("run variant shared", () => {
expect(pickVariant(model, session)).toBe("minimal")
})
})

View file

@ -3,7 +3,7 @@ import { mkdir, writeFile } from "node:fs/promises"
import path from "node:path"
import type { TerminalColors } from "@opentui/core"
import { DEFAULT_THEMES, addTheme, allThemes, hasTheme, resolveTheme } from "../src/theme"
import { discoverThemes } from "../src/context/theme"
import { discoverThemes, themeDirectories } from "../src/theme/discovery"
import { terminalMode } from "../src/theme/system"
import { tmpdir } from "./fixture/fixture"
@ -80,3 +80,18 @@ test("custom theme precedence follows directory order", async () => {
await expect(discoverThemes([global, project])).resolves.toEqual({ custom: { source: "project" } })
})
test("theme directories include global config before project directories", async () => {
await using tmp = await tmpdir()
const global = path.join(tmp.path, "global")
const project = path.join(tmp.path, "repo", "package")
await mkdir(path.join(global, "themes"), { recursive: true })
await mkdir(path.join(project, ".opencode", "themes"), { recursive: true })
await writeFile(path.join(global, "themes", "global.json"), JSON.stringify({ source: "global" }))
await writeFile(path.join(project, ".opencode", "themes", "project.json"), JSON.stringify({ source: "project" }))
await expect(discoverThemes(themeDirectories(global, project))).resolves.toEqual({
global: { source: "global" },
project: { source: "project" },
})
})