mini: move frontend into tui package (#37754)

This commit is contained in:
Simon Klee 2026-07-19 14:12:22 +02:00 committed by GitHub
commit c50554d907
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
80 changed files with 2365 additions and 1488 deletions

View file

@ -5,7 +5,7 @@ import { ServerConnection } from "../../services/server-connection"
export default Runtime.handler(Commands.commands.mini, (input) =>
Effect.gen(function* () {
const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import("../../mini/mini"))
const { runMini, validateMiniTerminal } = yield* Effect.promise(() => import("../../mini"))
yield* Effect.promise(async () => validateMiniTerminal())
const serverURL = Option.getOrUndefined(input.server)
const server = yield* ServerConnection.resolve({ server: serverURL, standalone: input.standalone })

View file

@ -0,0 +1,209 @@
import type { MiniFrontendInput } from "@opencode-ai/tui/mini"
import { Flag } from "@opencode-ai/core/flag/flag"
import { Global } from "@opencode-ai/core/global"
import fs from "node:fs"
import { mkdir, readFile, writeFile } from "node:fs/promises"
import path from "node:path"
import { ReadStream } from "node:tty"
export const INTERACTIVE_INPUT_ERROR = "opencode mini requires a controlling terminal for input"
export type InteractiveStdin = {
stdin: NodeJS.ReadStream
cleanup(): void
}
type MiniHost = MiniFrontendInput["host"]
type ModelState = Record<string, unknown> & {
variant?: Record<string, string | undefined>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value)
}
function state(value: unknown): ModelState {
if (!isRecord(value)) return {}
const variant = isRecord(value.variant)
? Object.fromEntries(
Object.entries(value.variant).flatMap(([key, item]) =>
typeof item === "string" ? ([[key, item]] as const) : [],
),
)
: undefined
return { ...value, variant }
}
function variantKey(model: NonNullable<MiniFrontendInput["model"]>) {
return `${model.providerID}/${model.modelID}`
}
function preferences(statePath: string): MiniHost["preferences"] {
const file = path.join(statePath, "model.json")
const read = () =>
readFile(file, "utf8")
.then((value) => state(JSON.parse(value)))
.catch(() => state(undefined))
return {
async resolveVariant(model) {
if (!model) return
return (await read()).variant?.[variantKey(model)]
},
async saveVariant(model, variant) {
if (!model) return
const current = await read()
const next = { ...current.variant }
if (variant) next[variantKey(model)] = variant
if (!variant) delete next[variantKey(model)]
await mkdir(path.dirname(file), { recursive: true })
.then(() => writeFile(file, JSON.stringify({ ...current, variant: next }, null, 2)))
.catch(() => {})
},
}
}
function signal(name: "SIGINT" | "SIGUSR2"): MiniHost["signals"]["sigint"] {
return {
subscribe(listener) {
let subscribed = true
process.on(name, listener)
return () => {
if (!subscribed) return
subscribed = false
process.off(name, listener)
}
},
}
}
function createTrace(
logPath: string,
diagnostics: Pick<MiniHost["diagnostics"], "pid" | "cwd" | "argv">,
): MiniHost["diagnostics"]["trace"] {
if (!process.env.OPENCODE_DIRECT_TRACE) return
const stamp = new Date()
.toISOString()
.replace(/[-:]/g, "")
.replace(/\.\d+Z$/, "Z")
const target = path.join(logPath, "direct", `${stamp}-${diagnostics.pid}.jsonl`)
const text = (data: unknown) =>
JSON.stringify(data, (_key, value) => (typeof value === "bigint" ? String(value) : value), 0)
fs.mkdirSync(path.dirname(target), { recursive: true })
fs.writeFileSync(
path.join(logPath, "direct", "latest.json"),
text({
time: new Date().toISOString(),
...diagnostics,
path: target,
}) + "\n",
)
const trace = {
write(type: string, data?: unknown) {
fs.appendFileSync(
target,
text({
time: new Date().toISOString(),
pid: diagnostics.pid,
type,
data,
}) + "\n",
)
},
}
trace.write("trace.start", {
argv: diagnostics.argv,
cwd: diagnostics.cwd,
path: target,
})
return trace
}
function openTerminalStdin(target: string): NodeJS.ReadStream {
return new ReadStream(fs.openSync(target, "r"))
}
export function resolveInteractiveStdin(
stdin: NodeJS.ReadStream = process.stdin,
open: (target: string) => NodeJS.ReadStream = openTerminalStdin,
platform: NodeJS.Platform = process.platform,
): InteractiveStdin {
if (stdin.isTTY) return { stdin, cleanup() {} }
const target = platform === "win32" ? "CONIN$" : "/dev/tty"
try {
const source = open(target)
let cleaned = false
return {
stdin: source,
cleanup() {
if (cleaned) return
cleaned = true
source.destroy()
},
}
} catch (error) {
throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })
}
}
/** @internal Exported for owner-local resource cleanup tests. */
export async function usingInteractiveStdin<T>(
run: (terminal: InteractiveStdin) => Promise<T>,
resolve: () => InteractiveStdin = resolveInteractiveStdin,
) {
const terminal = resolve()
try {
return await run(terminal)
} finally {
terminal.cleanup()
}
}
/** @internal Exported for owner-local host capability tests. */
export function createMiniHost(input: {
terminal: InteractiveStdin
directory: string
paths?: MiniHost["paths"]
}): MiniHost {
const paths = input.paths ?? {
home: Global.Path.home,
state: Global.Path.state,
log: Global.Path.log,
}
const diagnostics = {
pid: process.pid,
cwd: input.directory,
argv: process.argv.slice(2),
}
return {
terminal: input.terminal,
platform: process.platform,
stdout: {
write(value) {
process.stdout.write(value)
},
},
files: {
readText: (url) => readFile(new URL(url), "utf8"),
},
editor: {
async open(options) {
const { openEditor } = await import("@opencode-ai/tui/editor")
return openEditor(options)
},
},
paths,
signals: {
sigint: signal("SIGINT"),
sigusr2: signal("SIGUSR2"),
},
startup: {
showTiming: Flag.OPENCODE_SHOW_TTFD,
now: () => performance.now(),
},
diagnostics: {
...diagnostics,
trace: createTrace(paths.log, diagnostics),
},
preferences: preferences(paths.state),
}
}

View file

@ -1,11 +1,11 @@
import { Service } from "@opencode-ai/client/effect/service"
import { OpenCode, type OpenCodeClient } from "@opencode-ai/client/promise"
import { ServerConnection } from "../services/server-connection"
import { waitForCatalogReady } from "./catalog.shared"
import { INTERACTIVE_INPUT_ERROR, resolveInteractiveStdin } from "./runtime.stdin"
import type { RunInput, RunTuiConfig } from "./types"
import { readStdin } from "../util/io"
import type { MiniFrontendInput } from "@opencode-ai/tui/mini"
import { setTimeout } from "node:timers/promises"
import { ServerConnection } from "./services/server-connection"
import { waitForCatalogReady } from "./services/catalog"
import { readStdin } from "./util/io"
import { createMiniHost, INTERACTIVE_INPUT_ERROR, usingInteractiveStdin } from "./mini-host"
export type MiniCommandInput = {
server: ServerConnection.Resolved
@ -18,59 +18,67 @@ export type MiniCommandInput = {
replay?: boolean
replayLimit?: number
demo?: boolean
tuiConfig?: RunTuiConfig | Promise<RunTuiConfig>
tuiConfig?: MiniFrontendInput["tuiConfig"]
}
type Session = Awaited<ReturnType<OpenCodeClient["session"]["get"]>>
export async function runMini(input: MiniCommandInput) {
validate(input)
const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)
const runtimeTask = import("./runtime")
const directory = localDirectory()
type Model = MiniFrontendInput["model"]
class MiniInputError extends Error {}
export async function runMini(input: MiniCommandInput) {
try {
const sdk = OpenCode.make({
baseUrl: input.server.endpoint.url,
headers: Service.headers(input.server.endpoint),
})
const model = parseModel(input.model)
let agentTask: Promise<string | undefined> | undefined
const resolveAgent = () => {
agentTask ??= validateAgent(sdk, directory, input.agent)
return agentTask
}
const resolveSession = async () => {
const [agent, selected] = await Promise.all([resolveAgent(), selectSession(sdk, directory, input)])
const readyModel =
model ?? (selected?.model ? { providerID: selected.model.providerID, modelID: selected.model.id } : undefined)
if (readyModel) await waitForCatalogReady({ sdk, directory, model: readyModel })
const session = selected ?? (await createSession(sdk, directory, agent, model))
return { id: session.id, title: session.title, resume: selected !== undefined }
}
const create = (
_sdk: OpenCodeClient,
next: { agent: string | undefined; model: RunInput["model"]; variant: string | undefined },
) => createSession(sdk, directory, next.agent, next.model, next.variant)
const runtime = await runtimeTask
await runtime.runInteractiveDeferredMode({
sdk,
directory,
resolveAgent,
session: resolveSession,
createSession: create,
agent: input.agent,
model,
variant: undefined,
files: [],
initialInput,
thinking: true,
replay: input.replay ?? true,
replayLimit: input.replayLimit,
demo: input.demo,
tuiConfig: input.tuiConfig,
validate(input)
const result = await usingInteractiveStdin(async (terminal) => {
const initialInput = mergeInput(process.stdin.isTTY ? undefined : await readStdin(), input.prompt)
const frontendTask = import("@opencode-ai/tui/mini")
const directory = localDirectory()
const sdk = OpenCode.make({
baseUrl: input.server.endpoint.url,
headers: Service.headers(input.server.endpoint),
})
const model = parseModel(input.model)
let agentTask: Promise<string | undefined> | undefined
const resolveAgent = () => {
agentTask ??= validateAgent(sdk, directory, input.agent)
return agentTask
}
const resolveSession = async () => {
const [agent, selected] = await Promise.all([resolveAgent(), selectSession(sdk, directory, input)])
const readyModel =
model ?? (selected?.model ? { providerID: selected.model.providerID, modelID: selected.model.id } : undefined)
if (readyModel) await waitForCatalogReady({ sdk, directory, model: readyModel })
const session = selected ?? (await createSession(sdk, directory, agent, model))
return { id: session.id, title: session.title, resume: selected !== undefined }
}
const create = (
_sdk: OpenCodeClient,
next: { agent: string | undefined; model: Model; variant: string | undefined },
) => createSession(sdk, directory, next.agent, next.model, next.variant)
const frontend = await frontendTask
return frontend.runMiniFrontend({
host: createMiniHost({ terminal, directory }),
sdk,
directory,
resolveAgent,
session: resolveSession,
createSession: create,
agent: input.agent,
model,
variant: undefined,
files: [],
initialInput,
thinking: true,
replay: input.replay ?? true,
replayLimit: input.replayLimit,
demo: input.demo,
tuiConfig: input.tuiConfig,
})
})
if (result.exitCode !== 0) process.exit(result.exitCode)
} catch (error) {
if (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR) fail(error.message)
if (error instanceof MiniInputError || (error instanceof Error && error.message === INTERACTIVE_INPUT_ERROR))
fail(error.message)
throw error
}
}
@ -92,7 +100,6 @@ function validate(input: MiniCommandInput) {
fail("--replay-limit must be a positive integer")
}
if (input.fork && !input.continue && !input.session) fail("--fork requires --continue or --session")
resolveInteractiveStdin().cleanup?.()
}
function localDirectory(): string {
@ -101,15 +108,15 @@ function localDirectory(): string {
process.chdir(root)
return process.cwd()
} catch {
fail(`Failed to change directory to ${root}`)
throw new MiniInputError(`Failed to change directory to ${root}`)
}
}
function parseModel(value?: string): RunInput["model"] {
function parseModel(value?: string): Model {
if (!value) return
const [providerID, ...rest] = value.split("/")
const modelID = rest.join("/")
if (!providerID || !modelID) fail("--model must use the format provider/model")
if (!providerID || !modelID) throw new MiniInputError("--model must use the format provider/model")
return { providerID, modelID }
}
@ -144,7 +151,7 @@ async function selectSession(sdk: OpenCodeClient, directory: string, input: Mini
.list({ directory, parentID: null, limit: 1, order: "desc" })
.then((result) => result.data[0])
: undefined)
if (input.session && !selected) fail("Session not found")
if (input.session && !selected) throw new MiniInputError("Session not found")
if (!selected) return
if (!input.fork) return selected
return sdk.session.fork({ sessionID: selected.id })
@ -154,7 +161,7 @@ async function createSession(
sdk: OpenCodeClient,
directory: string,
agent: string | undefined,
model: RunInput["model"],
model: Model,
variant?: string,
): Promise<Session> {
if (model) await waitForCatalogReady({ sdk, directory, model })

View file

@ -1,159 +0,0 @@
import type {
AgentListOutput,
CommandListOutput,
ModelListOutput,
OpenCodeClient,
ProviderListOutput,
SkillListOutput,
} from "@opencode-ai/client/promise"
import type { RunAgent, RunCommand, RunProvider, RunReference } from "./types"
type CurrentAgent = AgentListOutput["data"][number]
type CurrentCommand = CommandListOutput["data"][number]
type CurrentSkill = SkillListOutput["data"][number]
type CurrentProvider = ProviderListOutput["data"][number]
type CurrentModel = ModelListOutput["data"][number]
function location(directory: string, workspace?: string) {
return {
location: {
directory,
workspace,
},
}
}
function defaultCost(model: CurrentModel) {
const picked = model.cost.find((cost) => cost.tier === undefined) ?? model.cost[0]
if (!picked) {
return undefined
}
return {
...picked,
input: model.cost.every((cost) => cost.input === 0) ? 0 : picked.input,
}
}
export function runAgent(input: CurrentAgent): RunAgent {
return {
id: input.id,
name: input.name,
description: input.description,
mode: input.mode,
hidden: input.hidden,
}
}
export function runCommand(input: CurrentCommand): RunCommand {
return {
name: input.name,
description: input.description,
}
}
export function runSkill(input: CurrentSkill): RunCommand {
return {
name: input.id,
description: input.description,
source: "skill",
}
}
export function runProviders(providers: CurrentProvider[], models: CurrentModel[]): RunProvider[] {
const grouped = new Map<string, RunProvider>()
for (const provider of providers) {
grouped.set(provider.id, {
id: provider.id,
name: provider.name,
models: {},
})
}
for (const model of models) {
const provider = grouped.get(model.providerID) ?? {
id: model.providerID,
name: model.providerID,
models: {},
}
provider.models[model.id] = {
id: model.id,
providerID: model.providerID,
name: model.name,
capabilities: model.capabilities,
cost: defaultCost(model),
limit: model.limit,
status: model.status,
variants: Object.fromEntries((model.variants ?? []).map((variant) => [variant.id, {}])),
}
grouped.set(provider.id, provider)
}
return [...grouped.values()]
}
// A location boots its plugins in a deferred background batch after the layer
// is built, so first-turn model resolution can observe empty catalog state.
// For explicit --model flows, wait for that exact ref to appear before prompt
// admission. On timeout, return and let the real execution error surface.
export async function waitForCatalogReady(input: {
sdk: OpenCodeClient
directory: string
workspace?: string
model: { providerID: string; modelID: string }
timeoutMs?: number
}) {
const deadline = Date.now() + (input.timeoutMs ?? 5_000)
while (Date.now() < deadline) {
const models = await input.sdk.model
.list(location(input.directory, input.workspace))
.then((result) => result.data)
.catch(() => undefined)
if (models?.some((model) => model.providerID === input.model.providerID && model.id === input.model.modelID)) return
await new Promise((resolve) => setTimeout(resolve, 25))
}
}
export async function waitForDefaultModel(input: {
sdk: OpenCodeClient
directory: string
timeoutMs?: number
active?: () => boolean
}): Promise<{ providerID: string; modelID: string } | undefined> {
const deadline = Date.now() + (input.timeoutMs ?? 5_000)
while (Date.now() < deadline && (input.active?.() ?? true)) {
const model = await input.sdk.model
.default(location(input.directory))
.then((result) => result.data)
.catch(() => undefined)
if (model) return { providerID: model.providerID, modelID: model.id }
await new Promise((resolve) => setTimeout(resolve, 25))
}
}
export async function loadRunAgents(sdk: OpenCodeClient, directory: string): Promise<RunAgent[]> {
const result = await sdk.agent.list(location(directory))
return result.data.map(runAgent)
}
export async function loadRunCommands(sdk: OpenCodeClient, directory: string): Promise<RunCommand[]> {
const [commands, skills] = await Promise.all([
sdk.command.list(location(directory)),
sdk.skill.list(location(directory)),
])
return [...commands.data.map(runCommand), ...skills.data.filter((skill) => skill.slash !== false).map(runSkill)]
}
export async function loadRunReferences(sdk: OpenCodeClient, directory: string): Promise<RunReference[]> {
const result = await sdk.reference.list(location(directory))
return result.data.filter((reference) => !reference.hidden)
}
export async function loadRunProviders(sdk: OpenCodeClient, directory: string): Promise<RunProvider[]> {
const [providers, models] = await Promise.all([
sdk.provider.list(location(directory)),
sdk.model.list(location(directory)),
])
return runProviders([...providers.data], [...models.data])
}

File diff suppressed because it is too large Load diff

View file

@ -1,205 +0,0 @@
import { toolEntryBody } from "./tool"
import type { RunEntryBody, StreamCommit } from "./types"
export type EntryFlags = {
startOnNewLine: boolean
trailingNewline: boolean
}
export const RUN_ENTRY_NONE: RunEntryBody = {
type: "none",
}
export function cleanRunText(text: string): string {
return text.replace(/\r\n/g, "\n").replace(/\r/g, "\n")
}
function textBody(content: string): RunEntryBody {
if (!content) {
return RUN_ENTRY_NONE
}
return {
type: "text",
content,
}
}
function codeBody(content: string, filetype?: string): RunEntryBody {
if (!content) {
return RUN_ENTRY_NONE
}
return {
type: "code",
content,
filetype,
}
}
function markdownBody(content: string): RunEntryBody {
if (!content) {
return RUN_ENTRY_NONE
}
return {
type: "markdown",
content,
}
}
function userBody(raw: string): RunEntryBody {
if (!raw.trim()) {
return RUN_ENTRY_NONE
}
const lead = raw.match(/^\n+/)?.[0] ?? ""
const body = lead ? raw.slice(lead.length) : raw
return textBody(`${lead} ${body}`)
}
function reasoningBody(raw: string): RunEntryBody {
const clean = raw.replace(/\[REDACTED\]/g, "")
if (!clean) {
return RUN_ENTRY_NONE
}
const lead = clean.match(/^\n+/)?.[0] ?? ""
const body = lead ? clean.slice(lead.length) : clean
const mark = "Thinking:"
if (body.startsWith(mark)) {
return codeBody(`${lead}_Thinking:_ ${body.slice(mark.length).trimStart()}`, "markdown")
}
return codeBody(clean, "markdown")
}
function systemBody(raw: string, phase: StreamCommit["phase"]): RunEntryBody {
return textBody(phase === "progress" ? raw : raw.trim())
}
export function entryFlags(commit: StreamCommit): EntryFlags {
if (commit.summary) {
return {
startOnNewLine: true,
trailingNewline: false,
}
}
if (commit.kind === "user") {
return {
startOnNewLine: true,
trailingNewline: false,
}
}
if (commit.kind === "tool") {
if (commit.phase === "progress") {
return {
startOnNewLine: false,
trailingNewline: false,
}
}
return {
startOnNewLine: true,
trailingNewline: true,
}
}
if (commit.kind === "assistant" || commit.kind === "reasoning") {
if (commit.phase === "progress") {
return {
startOnNewLine: false,
trailingNewline: false,
}
}
return {
startOnNewLine: true,
trailingNewline: true,
}
}
if (commit.kind === "error") {
return {
startOnNewLine: true,
trailingNewline: false,
}
}
return {
startOnNewLine: true,
trailingNewline: true,
}
}
export function entryDone(commit: StreamCommit): boolean {
if (commit.kind === "assistant" || commit.kind === "reasoning") {
return commit.phase === "final"
}
if (commit.kind === "tool") {
return commit.phase === "final" || (commit.phase === "progress" && commit.toolState === "completed")
}
return true
}
export function entryCanStream(commit: StreamCommit, body: RunEntryBody): boolean {
if (commit.phase !== "progress") {
return false
}
if (body.type === "none") {
return false
}
if (commit.kind === "tool") {
return commit.toolState !== "completed"
}
return commit.kind === "assistant" || commit.kind === "reasoning"
}
export function entryBody(commit: StreamCommit): RunEntryBody {
if (commit.summary) {
return RUN_ENTRY_NONE
}
const raw = cleanRunText(commit.text)
if (commit.kind === "user") {
return userBody(raw)
}
if (commit.kind === "tool") {
return toolEntryBody(commit, raw) ?? RUN_ENTRY_NONE
}
if (commit.kind === "assistant") {
if (commit.phase === "start") {
return RUN_ENTRY_NONE
}
if (commit.phase === "final") {
return commit.interrupted ? textBody("assistant interrupted") : RUN_ENTRY_NONE
}
return markdownBody(raw)
}
if (commit.kind === "reasoning") {
if (commit.phase === "start") {
return RUN_ENTRY_NONE
}
if (commit.phase === "final") {
return commit.interrupted ? textBody("reasoning interrupted") : RUN_ENTRY_NONE
}
return reasoningBody(raw)
}
return systemBody(raw, commit.phase)
}

File diff suppressed because it is too large Load diff

View file

@ -1,352 +0,0 @@
/** @jsxImportSource @opentui/solid */
import { TextAttributes, type ColorInput } from "@opentui/core"
import { useTerminalDimensions } from "@opentui/solid"
import { createEffect, createMemo, createSignal, type Accessor } from "solid-js"
import { transparent, type RunFooterTheme } from "./theme"
import { Locale } from "@opencode-ai/tui/util/locale"
import { stringWidth } from "@opencode-ai/tui/util/string-width"
export const FOOTER_MENU_ROWS = 8
export type RunFooterMenuItem = {
display: string
description?: string
category?: string
footer?: string
}
type RunFooterMenuRow =
| { type: "header"; label: string }
| { type: "item"; item: RunFooterMenuItem; index: number }
| { type: "spacer" }
function maxOffset(count: number, limit: number) {
return Math.max(0, count - limit)
}
function previewMargin(limit: number) {
return Math.max(0, Math.min(2, Math.floor((limit - 1) / 2)))
}
function revealOffset(value: number, input: { count: number; limit: number; selected: number }) {
const max = maxOffset(input.count, input.limit)
if (input.selected < value) {
return Math.min(max, input.selected)
}
if (input.selected >= value + input.limit) {
return Math.min(max, input.selected - input.limit + 1)
}
return Math.min(max, value)
}
function moveOffset(value: number, input: { count: number; limit: number; selected: number; dir: -1 | 1 }) {
const max = maxOffset(input.count, input.limit)
const margin = previewMargin(input.limit)
if (input.dir < 0 && input.selected < value + margin) {
return Math.max(0, Math.min(max, input.selected - margin))
}
if (input.dir > 0 && input.selected > value + input.limit - margin - 1) {
return Math.min(max, input.selected - input.limit + margin + 1)
}
return Math.min(max, value)
}
export function createFooterMenuState(input: { count: Accessor<number>; limit?: number }) {
const [selected, setSelected] = createSignal(0)
const [offset, setOffset] = createSignal(0)
const limit = () => input.limit ?? FOOTER_MENU_ROWS
const rows = createMemo(() => Math.max(1, Math.min(limit(), input.count())))
const reveal = (index: number) => {
const count = input.count()
if (count === 0) {
setSelected(0)
setOffset(0)
return
}
const next = Math.max(0, Math.min(count - 1, index))
setSelected(next)
setOffset((value) => revealOffset(value, { count, limit: limit(), selected: next }))
}
const reset = () => {
setSelected(0)
setOffset(0)
}
createEffect(() => {
const count = input.count()
if (count === 0) {
reset()
return
}
if (selected() >= count) {
setSelected(count - 1)
}
setOffset((value) => revealOffset(value, { count, limit: limit(), selected: selected() }))
})
const move = (dir: -1 | 1) => {
const count = input.count()
if (count === 0) {
reset()
return
}
const next = Math.max(0, Math.min(count - 1, selected() + dir))
setSelected(next)
setOffset((value) => moveOffset(value, { count, limit: limit(), selected: next, dir }))
}
return {
selected,
offset,
rows,
reveal,
reset,
move,
}
}
export function RunFooterMenu(props: {
theme: Accessor<RunFooterTheme>
items: Accessor<RunFooterMenuItem[]>
selected: Accessor<number>
offset: Accessor<number>
rows: Accessor<number>
limit?: number
empty?: string
border?: boolean
paddingLeft?: number
paddingRight?: number
grouped?: boolean
background?: boolean
headerColor?: ColorInput
}) {
const term = useTerminalDimensions()
const limit = () => props.limit ?? FOOTER_MENU_ROWS
const border = () => props.border ?? true
const [groupOffset, setGroupOffset] = createSignal(0)
let previous = -1
const groupedRows = createMemo<RunFooterMenuRow[]>(() => {
const all: RunFooterMenuRow[] = []
let category = ""
props.items().forEach((item, index) => {
if (item.category && item.category !== category) {
if (all.length > 0) {
all.push({ type: "spacer" })
}
category = item.category
all.push({ type: "header", label: item.category })
}
all.push({ type: "item", item, index })
})
return all
})
createEffect(() => {
if (!props.grouped) {
return
}
const all = groupedRows()
const selected = all.findIndex((item) => item.type === "item" && item.index === props.selected())
if (all.length === 0 || selected === -1) {
setGroupOffset(0)
previous = props.selected()
return
}
const dir = props.selected() === previous + 1 ? 1 : props.selected() === previous - 1 ? -1 : undefined
setGroupOffset((value) =>
dir
? moveOffset(value, { count: all.length, limit: limit(), selected, dir })
: revealOffset(value, { count: all.length, limit: limit(), selected }),
)
previous = props.selected()
})
const rows = createMemo<RunFooterMenuRow[]>(() => {
if (!props.grouped) {
return props
.items()
.slice(props.offset(), props.offset() + limit())
.map((item, index) => ({
type: "item",
item,
index: index + props.offset(),
}))
}
const all = groupedRows()
const start = Math.max(0, Math.min(groupOffset(), all.length - limit()))
return all.slice(start, start + limit())
})
const descriptionColumn = createMemo(() => {
const width = Math.max(
0,
...props
.items()
.filter((item) => item.description)
.map((item) => stringWidth(item.display)),
)
return width === 0 ? 0 : width + 2
})
const descriptionPad = (item: RunFooterMenuItem) => {
if (!item.description) {
return ""
}
return " ".repeat(Math.max(1, descriptionColumn() - stringWidth(item.display)))
}
const descriptionText = (item: RunFooterMenuItem) => {
if (!item.description) {
return
}
const footerWidth = item.footer ? stringWidth(item.footer) + 1 : 0
const available =
term().width -
(border() ? 1 : 0) -
(props.paddingLeft ?? 1) -
(props.paddingRight ?? 0) -
descriptionColumn() -
footerWidth -
4
return Locale.truncate(item.description, Math.max(12, available))
}
return (
<box
width="100%"
height={props.rows()}
backgroundColor={props.background ? props.theme().shade : transparent}
flexDirection="column"
>
{rows().length === 0 ? (
<box
paddingRight={0}
flexDirection="row"
backgroundColor={props.background ? props.theme().shade : transparent}
>
{border() ? (
<text fg={props.theme().border} wrapMode="none">
</text>
) : undefined}
<box
flexGrow={1}
flexShrink={1}
paddingLeft={props.paddingLeft ?? 1}
paddingRight={props.paddingRight ?? 0}
backgroundColor={props.background ? props.theme().shade : transparent}
>
<text fg={props.theme().muted} wrapMode="none" truncate>
{props.empty ?? "No matching items"}
</text>
</box>
</box>
) : (
rows().map((row) => {
if (row.type === "spacer") {
return <box height={1} flexShrink={0} />
}
if (row.type === "header") {
return (
<box paddingLeft={props.paddingLeft ?? 1} paddingRight={props.paddingRight ?? 1}>
<text
fg={props.headerColor ?? props.theme().highlight}
attributes={TextAttributes.BOLD}
wrapMode="none"
truncate
>
{row.label}
</text>
</box>
)
}
const active = () => row.index === props.selected()
const background = () =>
active()
? props.background
? props.theme().selected
: props.theme().shade
: props.background
? props.theme().shade
: transparent
return (
<box paddingRight={0} flexDirection="row" backgroundColor={background()}>
{border() ? (
<text fg={props.theme().highlight} bg={background()} wrapMode="none">
{active() ? "▌" : " "}
</text>
) : undefined}
<box
flexGrow={1}
flexShrink={1}
paddingLeft={props.paddingLeft ?? 1}
paddingRight={props.paddingRight ?? 0}
backgroundColor={background()}
>
<box width="100%" flexDirection="row" justifyContent="space-between" gap={1}>
<box flexDirection="row" gap={0} flexGrow={1} flexShrink={1}>
<text
fg={active() ? props.theme().selectedText : props.theme().text}
attributes={active() ? TextAttributes.BOLD : undefined}
wrapMode="none"
truncate
flexShrink={0}
>
{row.item.display}
</text>
{row.item.description ? (
<>
<text
fg={active() ? props.theme().selectedText : props.theme().muted}
wrapMode="none"
flexShrink={0}
>
{descriptionPad(row.item)}
</text>
<text
fg={active() ? props.theme().selectedText : props.theme().muted}
wrapMode="none"
truncate
flexGrow={1}
flexShrink={1}
>
{descriptionText(row.item)}
</text>
</>
) : undefined}
</box>
{row.item.footer ? (
<text
fg={active() ? props.theme().selectedText : props.theme().muted}
attributes={active() ? TextAttributes.BOLD : undefined}
wrapMode="none"
truncate
flexShrink={0}
>
{row.item.footer}
</text>
) : undefined}
</box>
</box>
</box>
)
})
)}
</box>
)
}

View file

@ -1,474 +0,0 @@
// Permission UI body for the direct-mode footer.
//
// Renders inside the footer when the reducer pushes a FooterView of type
// "permission". Uses a three-stage state machine (permission.shared.ts):
//
// permission → shows the request with Allow once / Always / Reject buttons
// always → confirmation step before granting permanent access
// reject → text field for the rejection message
//
// Keyboard: left/right to select, enter to confirm, esc to reject.
// The diff view (when available) uses the same diff component as scrollback
// tool snapshots.
/** @jsxImportSource @opentui/solid */
import type { TextareaRenderable } from "@opentui/core"
import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
import { For, Match, Show, Switch, createEffect, createMemo, createSignal } from "solid-js"
import type { PermissionV2Request } from "@opencode-ai/client/promise"
import {
createPermissionBodyState,
permissionAlwaysLines,
permissionCancel,
permissionEscape,
permissionHover,
permissionInfo,
permissionLabel,
permissionOptions,
permissionReject,
permissionRun,
permissionShift,
type PermissionOption,
} from "./permission.shared"
import { footerWidthPolicy } from "./footer.width"
import { toolFiletype } from "./tool"
import { transparent, type RunBlockTheme, type RunFooterTheme } from "./theme"
import type { PermissionReply, RunDiffStyle } from "./types"
function buttons(
list: PermissionOption[],
selected: PermissionOption,
theme: RunFooterTheme,
disabled: boolean,
onHover: (option: PermissionOption) => void,
onSelect: (option: PermissionOption) => void,
) {
return (
<box flexDirection="row" gap={1} flexShrink={0}>
<For each={list}>
{(option) => (
<box
paddingLeft={1}
paddingRight={1}
backgroundColor={option === selected ? theme.highlight : transparent}
onMouseOver={() => {
if (!disabled) onHover(option)
}}
onMouseUp={() => {
if (!disabled) onSelect(option)
}}
>
<text fg={option === selected ? theme.surface : theme.muted}>{permissionLabel(option)}</text>
</box>
)}
</For>
</box>
)
}
/** @internal Exported to test managed textarea submission without permission navigation. */
export function RejectField(props: {
theme: RunFooterTheme
text: string
disabled: boolean
onChange: (text: string) => void
onConfirm: () => void
onCancel: () => void
}) {
let area: TextareaRenderable | undefined
createEffect(() => {
if (!area || area.isDestroyed) {
return
}
if (area.plainText !== props.text) {
area.setText(props.text)
area.cursorOffset = props.text.length
}
queueMicrotask(() => {
if (!area || area.isDestroyed || props.disabled) {
return
}
area.focus()
})
})
return (
<textarea
width="100%"
minHeight={1}
maxHeight={3}
wrapMode="word"
placeholder="Tell OpenCode what to do differently"
placeholderColor={props.theme.muted}
textColor={props.theme.text}
focusedTextColor={props.theme.text}
backgroundColor={props.theme.surface}
focusedBackgroundColor={props.theme.surface}
cursorColor={props.theme.text}
focused={!props.disabled}
onSubmit={props.onConfirm}
onContentChange={() => {
if (!area || area.isDestroyed) {
return
}
props.onChange(area.plainText)
}}
onKeyDown={(event) => {
if (event.name === "escape") {
event.preventDefault()
props.onCancel()
return
}
}}
ref={(item) => {
area = item
}}
/>
)
}
export function RunPermissionBody(props: {
request: PermissionV2Request
theme: RunFooterTheme
block: RunBlockTheme
diffStyle?: RunDiffStyle
onReply: (input: PermissionReply) => void | Promise<void>
}) {
const dims = useTerminalDimensions()
const [state, setState] = createSignal(createPermissionBodyState(props.request.id))
const info = createMemo(() => permissionInfo(props.request))
const ft = createMemo(() => toolFiletype(info().file))
const narrow = createMemo(() => footerWidthPolicy(dims().width).dialog.narrow)
const opts = createMemo(() =>
permissionOptions(state().stage).filter((option) => option !== "always" || (props.request.save?.length ?? 0) > 0),
)
const busy = createMemo(() => state().submitting)
const title = createMemo(() => {
if (state().stage === "always") {
return "Always allow"
}
if (state().stage === "reject") {
return "Reject permission"
}
return "Permission required"
})
createEffect(() => {
const id = props.request.id
if (state().requestID === id) {
return
}
setState(createPermissionBodyState(id))
})
const shift = (dir: -1 | 1) => {
setState((prev) => permissionShift(prev, dir, opts()))
}
const submit = async (next: PermissionReply) => {
setState((prev) => ({
...prev,
submitting: true,
}))
try {
await props.onReply(next)
} catch {
setState((prev) => ({
...prev,
submitting: false,
}))
}
}
const run = (option: PermissionOption) => {
const cur = state()
const next = permissionRun(cur, props.request.id, option)
if (next.state !== cur) {
setState(next.state)
}
if (!next.reply) {
return
}
void submit(next.reply)
}
const reject = () => {
const next = permissionReject(state(), props.request.id)
if (!next) {
return
}
void submit(next)
}
const cancelReject = () => {
setState((prev) => permissionCancel(prev))
}
useKeyboard((event) => {
const cur = state()
if (cur.stage === "reject") {
return
}
if (cur.submitting) {
if (["left", "right", "h", "l", "tab", "return", "escape"].includes(event.name)) {
event.preventDefault()
}
return
}
if (event.name === "tab") {
shift(event.shift ? -1 : 1)
event.preventDefault()
return
}
if (event.name === "left" || event.name === "h") {
shift(-1)
event.preventDefault()
return
}
if (event.name === "right" || event.name === "l") {
shift(1)
event.preventDefault()
return
}
if (event.name === "return") {
run(state().selected)
event.preventDefault()
return
}
if (event.name !== "escape") {
return
}
setState((prev) => permissionEscape(prev))
event.preventDefault()
})
return (
<box width="100%" height="100%" flexDirection="column" backgroundColor={props.theme.surface}>
<box
flexDirection="column"
gap={1}
paddingLeft={1}
paddingRight={2}
paddingTop={1}
paddingBottom={1}
flexShrink={0}
>
<box flexDirection="row" gap={1} paddingLeft={1}>
<text fg={state().stage === "reject" ? props.theme.error : props.theme.warning}></text>
<text fg={props.theme.text}>{title()}</text>
</box>
<Switch>
<Match when={state().stage === "permission"}>
<box flexDirection="row" gap={1} paddingLeft={2}>
<text fg={props.theme.muted} flexShrink={0}>
{info().icon}
</text>
<text fg={props.theme.text} wrapMode="word">
{info().title}
</text>
</box>
</Match>
<Match when={state().stage === "reject"}>
<box paddingLeft={1}>
<text fg={props.theme.muted}>Tell OpenCode what to do differently</text>
</box>
</Match>
</Switch>
</box>
<Show
when={state().stage !== "reject"}
fallback={
<box width="100%" flexGrow={1} flexShrink={1} justifyContent="flex-end">
<box
flexDirection={narrow() ? "column" : "row"}
flexShrink={0}
backgroundColor={props.theme.line}
paddingTop={1}
paddingLeft={2}
paddingRight={3}
paddingBottom={1}
justifyContent={narrow() ? "flex-start" : "space-between"}
alignItems={narrow() ? "flex-start" : "center"}
gap={1}
>
<box width={narrow() ? "100%" : undefined} flexGrow={1} flexShrink={1}>
<RejectField
theme={props.theme}
text={state().message}
disabled={busy()}
onChange={(text) => {
setState((prev) => ({
...prev,
message: text,
}))
}}
onConfirm={reject}
onCancel={cancelReject}
/>
</box>
<Show
when={!busy()}
fallback={
<text fg={props.theme.muted} wrapMode="word" flexShrink={0}>
Waiting for permission event...
</text>
}
>
<box flexDirection="row" gap={2} flexShrink={0}>
<text fg={props.theme.text}>
enter <span style={{ fg: props.theme.muted }}>confirm</span>
</text>
<text fg={props.theme.text}>
esc <span style={{ fg: props.theme.muted }}>cancel</span>
</text>
</box>
</Show>
</box>
</box>
}
>
<box width="100%" flexGrow={1} flexShrink={1} paddingLeft={1} paddingRight={3} paddingBottom={1}>
<Switch>
<Match when={state().stage === "permission"}>
<scrollbox
width="100%"
height="100%"
verticalScrollbarOptions={{
trackOptions: {
backgroundColor: props.theme.surface,
foregroundColor: props.theme.line,
},
}}
>
<box width="100%" flexDirection="column" gap={1}>
<Show
when={info().diff}
fallback={
<box width="100%" flexDirection="column" gap={1} paddingLeft={1}>
<For each={info().lines}>
{(line) => (
<text fg={props.theme.text} wrapMode="word">
{line}
</text>
)}
</For>
</box>
}
>
<diff
diff={info().diff!}
view="unified"
filetype={ft()}
syntaxStyle={props.block.syntax}
showLineNumbers={true}
width="100%"
wrapMode="word"
fg={props.theme.text}
addedBg={props.block.diffAddedBg}
removedBg={props.block.diffRemovedBg}
contextBg={props.block.diffContextBg}
addedSignColor={props.block.diffHighlightAdded}
removedSignColor={props.block.diffHighlightRemoved}
lineNumberFg={props.block.diffLineNumber}
lineNumberBg={props.block.diffContextBg}
addedLineNumberBg={props.block.diffAddedLineNumberBg}
removedLineNumberBg={props.block.diffRemovedLineNumberBg}
/>
</Show>
<Show when={!info().diff && info().lines.length === 0}>
<box paddingLeft={1}>
<text fg={props.theme.muted}>No diff provided</text>
</box>
</Show>
</box>
</scrollbox>
</Match>
<Match when={true}>
<scrollbox
width="100%"
height="100%"
verticalScrollbarOptions={{
trackOptions: {
backgroundColor: props.theme.surface,
foregroundColor: props.theme.line,
},
}}
>
<box width="100%" flexDirection="column" gap={1} paddingLeft={1}>
<For each={permissionAlwaysLines(props.request)}>
{(line) => (
<text fg={props.theme.text} wrapMode="word">
{line}
</text>
)}
</For>
</box>
</scrollbox>
</Match>
</Switch>
</box>
<box
flexDirection={narrow() ? "column" : "row"}
flexShrink={0}
backgroundColor={props.theme.pane}
gap={1}
paddingTop={1}
paddingLeft={2}
paddingRight={3}
paddingBottom={1}
justifyContent={narrow() ? "flex-start" : "space-between"}
alignItems={narrow() ? "flex-start" : "center"}
>
{buttons(
opts(),
state().selected,
props.theme,
busy(),
(option) => {
setState((prev) => permissionHover(prev, option))
},
run,
)}
<Show
when={!busy()}
fallback={
<text fg={props.theme.muted} wrapMode="word" flexShrink={0}>
Waiting for permission event...
</text>
}
>
<box flexDirection="row" gap={2} flexShrink={0}>
<text fg={props.theme.text}>
{"⇆"} <span style={{ fg: props.theme.muted }}>select</span>
</text>
<text fg={props.theme.text}>
enter <span style={{ fg: props.theme.muted }}>confirm</span>
</text>
<text fg={props.theme.text}>
esc <span style={{ fg: props.theme.muted }}>{state().stage === "always" ? "cancel" : "reject"}</span>
</text>
</box>
</Show>
</box>
</Show>
</box>
)
}

File diff suppressed because it is too large Load diff

View file

@ -1,573 +0,0 @@
// Question UI body for the direct-mode footer.
//
// Renders inside the footer when the reducer pushes a FooterView of type
// "question". Supports single-question and multi-question flows:
//
// Single question: options list with up/down selection, digit shortcuts,
// and optional custom text input.
//
// Multi-question: tabbed interface where each question is a tab, plus a
// final "Confirm" tab that shows all answers for review. Tab/shift-tab
// or left/right to navigate between questions.
//
// All state logic lives in question.shared.ts as a pure state machine.
// This component just renders it and dispatches keyboard events.
/** @jsxImportSource @opentui/solid */
import type { TextareaRenderable } from "@opentui/core"
import { useKeyboard, useTerminalDimensions } from "@opentui/solid"
import { For, Show, createEffect, createMemo, createSignal } from "solid-js"
import type { QuestionV2Request } from "@opencode-ai/client/promise"
import {
createQuestionBodyState,
questionConfirm,
questionCustom,
questionInfo,
questionInput,
questionMove,
questionOther,
questionPicked,
questionReject,
questionSave,
questionSelect,
questionSetEditing,
questionSetSelected,
questionSetSubmitting,
questionSetTab,
questionSingle,
questionStoreCustom,
questionSubmit,
questionSync,
questionTabs,
questionTotal,
} from "./question.shared"
import { footerWidthPolicy } from "./footer.width"
import type { RunFooterTheme } from "./theme"
import type { QuestionReject, QuestionReply } from "./types"
export function RunQuestionBody(props: {
request: QuestionV2Request
theme: RunFooterTheme
onReply: (input: QuestionReply) => void | Promise<void>
onReject: (input: QuestionReject) => void | Promise<void>
}) {
const dims = useTerminalDimensions()
const [state, setState] = createSignal(createQuestionBodyState(props.request.id))
const single = createMemo(() => questionSingle(props.request))
const confirm = createMemo(() => questionConfirm(props.request, state()))
const info = createMemo(() => questionInfo(props.request, state()))
const input = createMemo(() => questionInput(state()))
const other = createMemo(() => questionOther(props.request, state()))
const picked = createMemo(() => questionPicked(state()))
const disabled = createMemo(() => state().submitting)
const narrow = createMemo(() => footerWidthPolicy(dims().width).dialog.narrow)
const verb = createMemo(() => {
if (confirm()) {
return "submit"
}
if (info()?.multiple) {
return "toggle"
}
if (single()) {
return "submit"
}
return "confirm"
})
let area: TextareaRenderable | undefined
createEffect(() => {
setState((prev) => questionSync(prev, props.request.id))
})
const setTab = (tab: number) => {
setState((prev) => questionSetTab(prev, tab))
}
const move = (dir: -1 | 1) => {
setState((prev) => questionMove(prev, props.request, dir))
}
const beginReply = async (input: QuestionReply) => {
setState((prev) => questionSetSubmitting(prev, true))
try {
await props.onReply(input)
} catch {
setState((prev) => questionSetSubmitting(prev, false))
}
}
const beginReject = async (input: QuestionReject) => {
setState((prev) => questionSetSubmitting(prev, true))
try {
await props.onReject(input)
} catch {
setState((prev) => questionSetSubmitting(prev, false))
}
}
const saveCustom = () => {
const cur = state()
const next = questionSave(cur, props.request)
if (next.state !== cur) {
setState(next.state)
}
if (!next.reply) {
return
}
void beginReply(next.reply)
}
const choose = (selected: number) => {
const base = state()
const cur = questionSetSelected(base, selected)
const next = questionSelect(cur, props.request)
if (next.state !== base) {
setState(next.state)
}
if (!next.reply) {
return
}
void beginReply(next.reply)
}
const mark = (selected: number) => {
setState((prev) => questionSetSelected(prev, selected))
}
const select = () => {
const cur = state()
const next = questionSelect(cur, props.request)
if (next.state !== cur) {
setState(next.state)
}
if (!next.reply) {
return
}
void beginReply(next.reply)
}
const submit = () => {
void beginReply(questionSubmit(props.request, state()))
}
const reject = () => {
void beginReject(questionReject(props.request))
}
useKeyboard((event) => {
const cur = state()
if (cur.submitting) {
event.preventDefault()
return
}
if (cur.editing) {
if (event.name === "escape") {
setState((prev) => questionSetEditing(prev, false))
event.preventDefault()
return
}
return
}
if (!single() && (event.name === "left" || event.name === "h")) {
setTab((cur.tab - 1 + questionTabs(props.request)) % questionTabs(props.request))
event.preventDefault()
return
}
if (!single() && (event.name === "right" || event.name === "l")) {
setTab((cur.tab + 1) % questionTabs(props.request))
event.preventDefault()
return
}
if (!single() && event.name === "tab") {
const dir = event.shift ? -1 : 1
setTab((cur.tab + dir + questionTabs(props.request)) % questionTabs(props.request))
event.preventDefault()
return
}
if (questionConfirm(props.request, cur)) {
if (event.name === "return") {
submit()
event.preventDefault()
return
}
if (event.name === "escape") {
reject()
event.preventDefault()
}
return
}
const total = questionTotal(props.request, cur)
const max = Math.min(total, 9)
const digit = Number(event.name)
if (!Number.isNaN(digit) && digit >= 1 && digit <= max) {
choose(digit - 1)
event.preventDefault()
return
}
if (event.name === "up" || event.name === "k") {
move(-1)
event.preventDefault()
return
}
if (event.name === "down" || event.name === "j") {
move(1)
event.preventDefault()
return
}
if (event.name === "return") {
select()
event.preventDefault()
return
}
if (event.name === "escape") {
reject()
event.preventDefault()
}
})
createEffect(() => {
if (!state().editing || !area || area.isDestroyed) {
return
}
if (area.plainText !== input()) {
area.setText(input())
area.cursorOffset = input().length
}
queueMicrotask(() => {
if (!area || area.isDestroyed || !state().editing) {
return
}
area.focus()
area.cursorOffset = area.plainText.length
})
})
return (
<box width="100%" height="100%" flexDirection="column">
<box
flexDirection="column"
gap={1}
paddingLeft={1}
paddingRight={3}
paddingTop={1}
flexGrow={1}
flexShrink={1}
backgroundColor={props.theme.surface}
>
<Show when={!single()}>
<box flexDirection="row" gap={1} paddingLeft={1} flexShrink={0}>
<For each={props.request.questions}>
{(item, index) => {
const active = () => state().tab === index()
const answered = () => (state().answers[index()]?.length ?? 0) > 0
return (
<box
paddingLeft={1}
paddingRight={1}
backgroundColor={active() ? props.theme.highlight : props.theme.surface}
onMouseUp={() => {
if (!disabled()) setTab(index())
}}
>
<text fg={active() ? props.theme.surface : answered() ? props.theme.text : props.theme.muted}>
{item.header}
</text>
</box>
)
}}
</For>
<box
paddingLeft={1}
paddingRight={1}
backgroundColor={confirm() ? props.theme.highlight : props.theme.surface}
onMouseUp={() => {
if (!disabled()) setTab(props.request.questions.length)
}}
>
<text fg={confirm() ? props.theme.surface : props.theme.muted}>Confirm</text>
</box>
</box>
</Show>
<Show
when={!confirm()}
fallback={
<box width="100%" flexGrow={1} flexShrink={1} paddingLeft={1}>
<scrollbox
width="100%"
height="100%"
verticalScrollbarOptions={{
trackOptions: {
backgroundColor: props.theme.surface,
foregroundColor: props.theme.line,
},
}}
>
<box width="100%" flexDirection="column" gap={1}>
<box paddingLeft={1}>
<text fg={props.theme.text}>Review</text>
</box>
<For each={props.request.questions}>
{(item, index) => {
const value = () => state().answers[index()]?.join(", ") ?? ""
const answered = () => Boolean(value())
return (
<box paddingLeft={1}>
<text wrapMode="word">
<span style={{ fg: props.theme.muted }}>{item.header}:</span>{" "}
<span style={{ fg: answered() ? props.theme.text : props.theme.error }}>
{answered() ? value() : "(not answered)"}
</span>
</text>
</box>
)
}}
</For>
</box>
</scrollbox>
</box>
}
>
<box width="100%" flexGrow={1} flexShrink={1} paddingLeft={1} gap={1}>
<box>
<text fg={props.theme.text} wrapMode="word">
{info()?.question}
{info()?.multiple ? " (select all that apply)" : ""}
</text>
</box>
<box flexGrow={1} flexShrink={1}>
<scrollbox
width="100%"
height="100%"
verticalScrollbarOptions={{
trackOptions: {
backgroundColor: props.theme.surface,
foregroundColor: props.theme.line,
},
}}
>
<box width="100%" flexDirection="column">
<For each={info()?.options ?? []}>
{(item, index) => {
const active = () => state().selected === index()
const hit = () => state().answers[state().tab]?.includes(item.label) ?? false
return (
<box
flexDirection="column"
gap={0}
onMouseOver={() => {
if (!disabled()) {
mark(index())
}
}}
onMouseDown={() => {
if (!disabled()) {
mark(index())
}
}}
onMouseUp={() => {
if (!disabled()) {
choose(index())
}
}}
>
<box flexDirection="row">
<box backgroundColor={active() ? props.theme.line : undefined} paddingRight={1}>
<text fg={active() ? props.theme.highlight : props.theme.muted}>{`${index() + 1}.`}</text>
</box>
<box backgroundColor={active() ? props.theme.line : undefined}>
<text
fg={active() ? props.theme.highlight : hit() ? props.theme.success : props.theme.text}
>
{info()?.multiple ? `[${hit() ? "✓" : " "}] ${item.label}` : item.label}
</text>
</box>
<Show when={!info()?.multiple}>
<text fg={props.theme.success}>{hit() ? " ✓" : ""}</text>
</Show>
</box>
<box paddingLeft={3}>
<text fg={props.theme.muted} wrapMode="word">
{item.description}
</text>
</box>
</box>
)
}}
</For>
<Show when={questionCustom(props.request, state())}>
<box
flexDirection="column"
gap={0}
onMouseOver={() => {
if (!disabled()) {
mark(info()?.options.length ?? 0)
}
}}
onMouseDown={() => {
if (!disabled()) {
mark(info()?.options.length ?? 0)
}
}}
onMouseUp={() => {
if (!disabled()) {
choose(info()?.options.length ?? 0)
}
}}
>
<box flexDirection="row">
<box backgroundColor={other() ? props.theme.line : undefined} paddingRight={1}>
<text
fg={other() ? props.theme.highlight : props.theme.muted}
>{`${(info()?.options.length ?? 0) + 1}.`}</text>
</box>
<box backgroundColor={other() ? props.theme.line : undefined}>
<text
fg={other() ? props.theme.highlight : picked() ? props.theme.success : props.theme.text}
>
{info()?.multiple
? `[${picked() ? "✓" : " "}] Type your own answer`
: "Type your own answer"}
</text>
</box>
<Show when={!info()?.multiple}>
<text fg={props.theme.success}>{picked() ? " ✓" : ""}</text>
</Show>
</box>
<Show
when={state().editing}
fallback={
<Show when={input()}>
<box paddingLeft={3}>
<text fg={props.theme.muted} wrapMode="word">
{input()}
</text>
</box>
</Show>
}
>
<box paddingLeft={3}>
<textarea
width="100%"
minHeight={1}
maxHeight={4}
wrapMode="word"
placeholder="Type your own answer"
placeholderColor={props.theme.muted}
textColor={props.theme.text}
focusedTextColor={props.theme.text}
backgroundColor={props.theme.surface}
focusedBackgroundColor={props.theme.surface}
cursorColor={props.theme.text}
focused={!disabled()}
onSubmit={saveCustom}
onContentChange={() => {
if (!area || area.isDestroyed || disabled()) {
return
}
const text = area.plainText
setState((prev) => questionStoreCustom(prev, prev.tab, text))
}}
ref={(item) => {
area = item
}}
/>
</box>
</Show>
</box>
</Show>
</box>
</scrollbox>
</box>
</box>
</Show>
</box>
<box
flexDirection={narrow() ? "column" : "row"}
flexShrink={0}
gap={1}
paddingLeft={2}
paddingRight={3}
paddingBottom={1}
justifyContent={narrow() ? "flex-start" : "space-between"}
alignItems={narrow() ? "flex-start" : "center"}
>
<Show
when={!disabled()}
fallback={
<text fg={props.theme.muted} wrapMode="word">
Waiting for question event...
</text>
}
>
<box
flexDirection={narrow() ? "column" : "row"}
gap={narrow() ? 1 : 2}
flexShrink={0}
width={narrow() ? "100%" : undefined}
>
<Show
when={!state().editing}
fallback={
<>
<text fg={props.theme.text}>
enter <span style={{ fg: props.theme.muted }}>save</span>
</text>
<text fg={props.theme.text}>
esc <span style={{ fg: props.theme.muted }}>cancel</span>
</text>
</>
}
>
<Show when={!single()}>
<text fg={props.theme.text}>
{"⇆"} <span style={{ fg: props.theme.muted }}>tab</span>
</text>
</Show>
<Show when={!confirm()}>
<text fg={props.theme.text}>
{"↑↓"} <span style={{ fg: props.theme.muted }}>select</span>
</text>
</Show>
<text fg={props.theme.text}>
enter <span style={{ fg: props.theme.muted }}>{verb()}</span>
</text>
<text fg={props.theme.text}>
esc <span style={{ fg: props.theme.muted }}>dismiss</span>
</text>
</Show>
</box>
</Show>
</box>
</box>
)
}

View file

@ -1,190 +0,0 @@
/** @jsxImportSource @opentui/solid */
import type { ScrollBoxRenderable } from "@opentui/core"
import { useKeyboard } from "@opentui/solid"
import { registerOpencodeSpinner } from "@opencode-ai/tui/component/register-spinner"
import { Show, createMemo, indexArray } from "solid-js"
import { SPINNER_FRAMES } from "@opencode-ai/tui/component/spinner"
import { RunEntryContent, separatorRows } from "./scrollback.writer"
import type { FooterSubagentDetail, FooterSubagentTab, RunDiffStyle } from "./types"
import type { RunFooterTheme, RunTheme } from "./theme"
registerOpencodeSpinner()
export const SUBAGENT_INSPECTOR_ROWS = 14
function statusColor(theme: RunFooterTheme, status: FooterSubagentTab["status"]) {
if (status === "completed") {
return theme.highlight
}
if (status === "cancelled") {
return theme.muted
}
if (status === "error") {
return theme.error
}
return theme.highlight
}
function statusIcon(status: FooterSubagentTab["status"]) {
if (status === "completed") {
return "●"
}
if (status === "cancelled") {
return "○"
}
if (status === "error") {
return "◍"
}
return "◔"
}
export function RunFooterSubagentBody(props: {
active: () => boolean
theme: () => RunTheme
tab: () => FooterSubagentTab | undefined
index: () => number
total: () => number
detail: () => FooterSubagentDetail | undefined
width: () => number
diffStyle?: RunDiffStyle
onCycle: (dir: -1 | 1) => void
onClose: () => void
// Formatted interrupt shortcut from the registered keymap binding; the
// command itself is dispatched through the keymap in footer.view.
interrupt?: () => string | undefined
}) {
const theme = createMemo(() => props.theme())
const footer = createMemo(() => theme().footer)
const tab = createMemo(() => props.tab())
const commits = createMemo(() => props.detail()?.commits ?? [])
const opts = createMemo(() => ({ diffStyle: props.diffStyle }))
const scrollbar = createMemo(() => ({
trackOptions: {
backgroundColor: footer().surface,
foregroundColor: footer().line,
},
}))
const title = createMemo(() => {
const current = tab()
if (!current) {
return ""
}
return current.description || current.title || current.label
})
const subtitle = createMemo(() => {
const current = tab()
if (!current || title() === current.label) {
return ""
}
return current.label
})
const rows = indexArray(commits, (commit, index) => (
<box flexDirection="column" gap={0} flexShrink={0}>
{index > 0 && separatorRows(commits()[index - 1], commit()) > 0 ? <box height={1} flexShrink={0} /> : null}
<RunEntryContent commit={commit()} theme={theme()} opts={opts()} width={props.width()} />
</box>
))
let scroll: ScrollBoxRenderable | undefined
const interruptHint = createMemo(() => {
if (tab()?.status !== "running") return undefined
return props.interrupt?.()
})
useKeyboard((event) => {
if (!props.active()) {
return
}
if (event.name === "escape") {
event.preventDefault()
props.onClose()
return
}
if (event.name === "tab" && !event.shift) {
event.preventDefault()
props.onCycle(1)
return
}
if (event.name === "up" || event.name === "k") {
event.preventDefault()
scroll?.scrollBy(-1)
return
}
if (event.name === "down" || event.name === "j") {
event.preventDefault()
scroll?.scrollBy(1)
}
})
return (
<box width="100%" height="100%" flexDirection="column" backgroundColor={footer().surface}>
<box paddingTop={1} paddingLeft={1} paddingRight={3} paddingBottom={1} flexDirection="column" flexGrow={1}>
<Show when={tab()}>
{(current) => (
<box width="100%" flexDirection="row" gap={1} paddingBottom={1} flexShrink={0}>
{current().status === "running" ? (
<box flexShrink={0}>
<spinner frames={SPINNER_FRAMES} interval={80} color={statusColor(footer(), current().status)} />
</box>
) : (
<text fg={statusColor(footer(), current().status)} wrapMode="none" truncate flexShrink={0}>
{statusIcon(current().status)}
</text>
)}
<text fg={footer().text} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
{title()}
<Show when={subtitle().length > 0}>
<span style={{ fg: footer().muted }}>{" " + subtitle()}</span>
</Show>
</text>
<Show when={interruptHint()}>
{(hint) => (
<text fg={footer().muted} wrapMode="none" truncate flexShrink={0}>
{hint()} interrupt
</text>
)}
</Show>
<Show when={props.total() > 1 && props.index() > 0}>
<text fg={footer().muted} wrapMode="none" truncate flexShrink={0}>
{props.index()} of {props.total()}
</text>
</Show>
</box>
)}
</Show>
<scrollbox
width="100%"
height="100%"
stickyScroll={true}
stickyStart="bottom"
verticalScrollbarOptions={scrollbar()}
ref={(item) => {
scroll = item
}}
>
<box width="100%" flexDirection="column" gap={0}>
{commits().length > 0 ? (
rows()
) : (
<text fg={footer().muted} wrapMode="word">
No subagent activity yet
</text>
)}
</box>
</scrollbox>
</box>
</box>
)
}

File diff suppressed because it is too large Load diff

View file

@ -1,902 +0,0 @@
// Footer layout
//
// Renders the footer region as a compact vertical stack:
// 1. Single-line composer or active footer body
// 2. Optional autocomplete/menu panels below the composer
// 3. A statusline-style footer row carrying state, hints, and model info
//
// All state comes from the parent RunFooter through SolidJS signals.
// The view itself is stateless except for derived memos.
/** @jsxImportSource @opentui/solid */
import { useTerminalDimensions } from "@opentui/solid"
import { For, Match, Show, Switch, createEffect, createMemo, createSignal, onCleanup } from "solid-js"
import { registerOpencodeSpinner } from "@opencode-ai/tui/component/register-spinner"
import { createColors, createFrames } from "@opencode-ai/tui/ui/spinner"
import {
RUN_SUBAGENT_PANEL_ROWS,
RunCommandMenuBody,
RunModelSelectBody,
RunQueuedPromptSelectBody,
RunSkillSelectBody,
RunSubagentSelectBody,
RunVariantSelectBody,
} from "./footer.command"
import { FOOTER_MENU_ROWS, RunFooterMenu } from "./footer.menu"
import { RunFooterSubagentBody } from "./footer.subagent"
import { RunPromptBody, createPromptState } from "./footer.prompt"
import { RunPermissionBody } from "./footer.permission"
import { RunQuestionBody } from "./footer.question"
import { footerWidthPolicy } from "./footer.width"
import { Keymap } from "@opencode-ai/tui/context/keymap"
import type {
FooterPromptRoute,
FooterQueuedPrompt,
FooterState,
FooterSubagentState,
FooterView,
PermissionReply,
QuestionReject,
QuestionReply,
RunAgent,
RunCommand,
RunDiffStyle,
RunInput,
RunPrompt,
RunProvider,
RunReference,
RunTuiConfig,
} from "./types"
import type { RunTheme } from "./theme"
import { modelInfo } from "./variant.shared"
registerOpencodeSpinner()
const EMPTY_BORDER = {
topLeft: "",
bottomLeft: "",
vertical: "",
topRight: "",
bottomRight: "",
horizontal: " ",
bottomT: "",
topT: "",
cross: "",
leftT: "",
rightT: "",
}
type RunFooterViewProps = {
directory: string
findFiles: (query: string) => Promise<string[]>
agents: () => RunAgent[]
references: () => RunReference[]
commands: () => RunCommand[] | undefined
providers: () => RunProvider[] | undefined
currentModel: () => RunInput["model"]
variants: () => string[]
currentVariant: () => string | undefined
state: () => FooterState
view?: () => FooterView
subagent?: () => FooterSubagentState
queuedPrompts?: () => FooterQueuedPrompt[]
theme: () => RunTheme
diffStyle?: RunDiffStyle
tuiConfig: RunTuiConfig
history?: () => RunPrompt[]
agent: string
onSubmit: (input: RunPrompt) => boolean
onPermissionReply: (input: PermissionReply) => void | Promise<void>
onQuestionReply: (input: QuestionReply) => void | Promise<void>
onQuestionReject: (input: QuestionReject) => void | Promise<void>
onCycle: () => void
onInterrupt: () => boolean
onBackground?: () => void
onEditorOpen: (input: { value: string }) => Promise<string | undefined>
onInputClear: () => void
onExitRequest?: () => boolean
onRequestExit?: (fn: (() => boolean) | undefined) => void
onExit: () => void
onModelSelect: (model: NonNullable<RunInput["model"]>) => void
onVariantSelect: (variant: string | undefined) => void
onRows: (rows: number) => void
onLayout: (input: { route: FooterPromptRoute; autocomplete: boolean; subagentRows: number }) => void
onStatus: (text: string) => void
onSubagentSelect?: (sessionID: string | undefined) => void
onSubagentInterrupt?: (sessionID: string) => void
onQueuedRemove: (messageID: string) => Promise<boolean>
}
export { TEXTAREA_MIN_ROWS, TEXTAREA_MAX_ROWS } from "./footer.prompt"
export function RunFooterView(props: RunFooterViewProps) {
const term = useTerminalDimensions()
const width = createMemo(() => term().width)
const responsive = createMemo(() => footerWidthPolicy(width()))
const active = createMemo<FooterView>(() => props.view?.() ?? { type: "prompt" })
const subagent = createMemo<FooterSubagentState>(() => {
return (
props.subagent?.() ?? {
tabs: [],
details: {},
permissions: [],
questions: [],
}
)
})
const [route, setRoute] = createSignal<FooterPromptRoute>({ type: "composer" })
const [subagentMenuRows, setSubagentMenuRows] = createSignal(RUN_SUBAGENT_PANEL_ROWS)
const queuedPrompts = createMemo(() => props.queuedPrompts?.() ?? [])
const skills = createMemo(() => (props.commands() ?? []).filter((item) => item.source === "skill"))
const prompt = createMemo(() => active().type === "prompt" && route().type === "composer")
const selectingSubagent = createMemo(() => active().type === "prompt" && route().type === "subagent-menu")
const selectingQueued = createMemo(() => active().type === "prompt" && route().type === "queued-menu")
const inspecting = createMemo(() => active().type === "prompt" && route().type === "subagent")
const commanding = createMemo(() => active().type === "prompt" && route().type === "command")
const skilling = createMemo(() => active().type === "prompt" && route().type === "skill")
const modeling = createMemo(() => active().type === "prompt" && route().type === "model")
const varianting = createMemo(() => active().type === "prompt" && route().type === "variant")
const panel = createMemo(
() =>
active().type === "permission" ||
active().type === "question" ||
selectingQueued() ||
selectingSubagent() ||
commanding() ||
skilling() ||
modeling() ||
varianting(),
)
const selected = createMemo(() => {
const current = route()
return current.type === "subagent" ? current.sessionID : undefined
})
const tabs = createMemo(() => subagent().tabs)
const activeTabs = createMemo(() => tabs().filter((item) => item.status === "running"))
const selectedTab = createMemo(() => tabs().find((item) => item.sessionID === selected()))
const selectedIndex = createMemo(() => {
const sessionID = selected()
if (!sessionID) {
return 0
}
return tabs().findIndex((item) => item.sessionID === sessionID) + 1
})
const foregroundSubagents = createMemo(() => activeTabs().some((item) => !item.background))
const model = createMemo(() => {
const current = props.currentModel()
return current ? modelInfo(props.providers(), current) : { model: props.state().model, provider: undefined }
})
const detail = createMemo(() => {
const current = route()
return current.type === "subagent" ? subagent().details[current.sessionID] : undefined
})
const shortcuts = Keymap.useShortcuts()
const command = () => shortcuts.get("command.palette.show") ?? ""
const subagentShortcut = () => shortcuts.get("session.child.first") ?? ""
const queuedShortcut = () => shortcuts.get("session.queued_prompts") ?? ""
const backgroundShortcut = () => shortcuts.get("session.background") ?? ""
const subagentInterruptShortcut = () => shortcuts.get("subagent.interrupt") ?? ""
const interrupt = () => shortcuts.get("session.interrupt") ?? ""
const variantCycle = () => shortcuts.all("variant.cycle") ?? ""
const clearShortcut = () => shortcuts.get("prompt.clear") ?? ""
const busy = createMemo(() => props.state().phase === "running")
const armed = createMemo(() => props.state().interrupt > 0)
const exiting = createMemo(() => props.state().exit > 0)
const queue = createMemo(() => props.state().queue)
const usage = createMemo(() => props.state().usage)
const interruptLabel = createMemo(() => {
if (!interrupt()) {
return
}
return interrupt() === "escape" ? "esc" : interrupt()
})
const runTheme = createMemo(() => props.theme())
const theme = createMemo(() => runTheme().footer)
const block = createMemo(() => runTheme().block)
const spin = createMemo(() => {
return {
frames: createFrames({
color: theme().highlight,
style: "blocks",
inactiveFactor: 0.6,
minAlpha: 0.3,
}),
color: createColors({
color: theme().highlight,
style: "blocks",
inactiveFactor: 0.6,
minAlpha: 0.3,
}),
}
})
const permission = createMemo<Extract<FooterView, { type: "permission" }> | undefined>(() => {
const view = active()
return view.type === "permission" ? view : undefined
})
const question = createMemo<Extract<FooterView, { type: "question" }> | undefined>(() => {
const view = active()
return view.type === "question" ? view : undefined
})
const promptView = createMemo(() => {
if (active().type !== "prompt") {
return active().type
}
const current = route()
return current.type === "composer" ? "prompt" : current.type
})
const openCommand = () => {
setRoute({ type: "command" })
props.onSubagentSelect?.(undefined)
}
const openModel = () => {
setRoute({ type: "model" })
props.onSubagentSelect?.(undefined)
}
const openSkillMenu = () => {
if (props.commands() && skills().length === 0) {
return
}
setRoute({ type: "skill" })
props.onSubagentSelect?.(undefined)
}
const openVariant = () => {
setRoute({ type: "variant" })
props.onSubagentSelect?.(undefined)
}
const openSubagentMenu = () => {
if (tabs().length === 0) {
return
}
setRoute({ type: "subagent-menu" })
props.onSubagentSelect?.(undefined)
}
const openQueuedMenu = () => {
if (queuedPrompts().length === 0) return
setRoute({ type: "queued-menu" })
props.onSubagentSelect?.(undefined)
}
const closePanel = () => {
setRoute({ type: "composer" })
}
const openTab = (sessionID: string) => {
setRoute({ type: "subagent", sessionID })
props.onSubagentSelect?.(sessionID)
}
const closeTab = () => {
setRoute({ type: "composer" })
props.onSubagentSelect?.(undefined)
}
const cycleTab = (dir: -1 | 1) => {
if (tabs().length === 0) {
return
}
const routeState = route()
const current =
routeState.type === "subagent" ? tabs().findIndex((item) => item.sessionID === routeState.sessionID) : -1
const index = current === -1 ? 0 : (current + dir + tabs().length) % tabs().length
const next = tabs()[index]
if (!next) {
return
}
openTab(next.sessionID)
}
const composer = createPromptState({
directory: props.directory,
findFiles: props.findFiles,
agents: props.agents,
references: props.references,
commands: props.commands,
tuiConfig: props.tuiConfig,
state: props.state,
view: promptView,
prompt,
width,
theme,
history: props.history,
onSubmit: props.onSubmit,
onCycle: props.onCycle,
onInterrupt: props.onInterrupt,
onEditorOpen: props.onEditorOpen,
onInputClear: props.onInputClear,
onExitRequest: props.onExitRequest,
onExit: props.onExit,
onSkillMenu: openSkillMenu,
onRows: props.onRows,
onStatus: props.onStatus,
})
const shell = createMemo(() => prompt() && composer.shell())
const menu = createMemo(() => prompt() && composer.visible())
const stateStatus = createMemo(() => props.state().status.trim())
const modeLabel = createMemo(() => {
if (exiting()) {
return "EXIT"
}
return shell() ? "SHELL" : "BUILD"
})
const modeColor = createMemo(() => {
if (exiting()) {
return theme().error
}
if (shell()) {
return theme().warning
}
return theme().highlight
})
const statusText = createMemo(() => {
if (exiting()) {
return `Press ${clearShortcut() || "ctrl+c"} again to exit`
}
if (busy()) {
return armed() ? "again to interrupt" : "interrupt"
}
if (stateStatus().length > 0) {
return stateStatus()
}
return shell() ? "Shell mode" : ""
})
const activityMeta = createMemo(() => {
if (!responsive().statusline.showActivityMeta || usage().length === 0) {
return ""
}
return usage()
})
const modelStatus = createMemo(() => {
const current = props.currentModel()
if (!prompt() || shell() || !current) {
return
}
return {
model: model().model,
variant: props.currentVariant(),
provider: undefined,
// Prefer without provider, but keep it on the shared width policy if we add it back.
}
})
const statusColor = createMemo(() => {
if (exiting()) {
return theme().error
}
if (armed()) {
return theme().highlight
}
if (busy() || stateStatus().length > 0) {
return theme().text
}
return theme().muted
})
const statuslineBackground = createMemo(() => theme().status)
const hasActivityMeta = createMemo(() => activityMeta().length > 0)
const hasModelStatus = createMemo(() => responsive().statusline.showModel && Boolean(modelStatus()))
const contextHints = createMemo(() => {
if (!prompt() || shell() || !responsive().statusline.showContextHints) {
return []
}
const items: Array<{ kind: string; key: string; label: string }> = []
if (foregroundSubagents() && backgroundShortcut()) {
items.push({ kind: "background", key: backgroundShortcut(), label: "background" })
}
if (queuedPrompts().length > 0 && queuedShortcut()) {
items.push({ kind: "queued", key: queuedShortcut(), label: `${queue()} queued` })
}
if (activeTabs().length > 0 && subagentShortcut()) {
items.push({ kind: "subagents", key: subagentShortcut(), label: "subagents" })
}
const limit = responsive().statusline.contextHintLimit
return limit === undefined ? items : items.slice(0, limit)
})
const hasContextHints = createMemo(() => contextHints().length > 0)
const commandHint = createMemo(() => {
if (!prompt() || !responsive().statusline.showCommandHint) {
return
}
if (shell()) {
return { key: "esc", label: "normal" }
}
if (command()) {
return { key: command(), label: "cmd" }
}
})
const sectionSeparator = () => <span style={{ fg: theme().muted }}>· </span>
createEffect(() => {
props.onRequestExit?.(composer.requestExit)
})
onCleanup(() => {
props.onRequestExit?.(undefined)
})
Keymap.createLayer(() => ({
enabled: active().type === "prompt" && route().type === "composer" && !composer.visible(),
commands: [
{
id: "command.palette.show",
title: "Open command palette",
group: "Prompt",
run: openCommand,
},
{
id: "variant.cycle",
title: "Cycle model variant",
group: "Model",
run: props.onCycle,
},
],
}))
Keymap.createLayer(() => ({
enabled: active().type === "prompt" && route().type === "composer" && foregroundSubagents() && !!props.onBackground,
priority: 1,
commands: [
{
id: "session.background",
title: "Background subagents",
group: "Session",
run: () => props.onBackground?.(),
},
],
}))
Keymap.createLayer(() => ({
enabled: active().type === "prompt" && route().type === "composer" && tabs().length > 0,
commands: [
{
id: "session.child.first",
title: "View subagents",
group: "Session",
run: openSubagentMenu,
},
],
}))
Keymap.createLayer(() => ({
enabled: active().type === "prompt" && route().type === "composer" && queuedPrompts().length > 0,
commands: [
{
id: "session.queued_prompts",
title: "Manage queued prompts",
group: "Session",
run: openQueuedMenu,
},
],
}))
Keymap.createLayer(() => ({
enabled:
active().type === "prompt" &&
route().type === "subagent" &&
selectedTab()?.status === "running" &&
!!props.onSubagentInterrupt,
priority: 1,
commands: [
{
id: "subagent.interrupt",
title: "Interrupt subagent",
group: "Session",
bind: "ctrl+d",
run: () => {
const current = selectedTab()
if (current?.status !== "running") {
return
}
props.onSubagentInterrupt?.(current.sessionID)
},
},
],
}))
createEffect(() => {
const current = route()
if (current.type !== "subagent") {
return
}
if (tabs().some((item) => item.sessionID === current.sessionID)) {
return
}
closeTab()
})
createEffect(() => {
if (route().type !== "subagent-menu") {
return
}
if (tabs().length > 0) {
return
}
closePanel()
})
createEffect(() => {
if (route().type !== "queued-menu" || queuedPrompts().length > 0) return
closePanel()
})
createEffect(() => {
if (active().type === "prompt") {
return
}
const current = route()
if (
current.type !== "command" &&
current.type !== "skill" &&
current.type !== "model" &&
current.type !== "variant" &&
current.type !== "queued-menu" &&
current.type !== "subagent-menu"
) {
return
}
closePanel()
})
createEffect(() => {
props.onLayout({
route: route(),
autocomplete: menu(),
subagentRows: subagentMenuRows(),
})
})
return (
<box
width="100%"
height="100%"
border={false}
backgroundColor="transparent"
flexDirection="column"
gap={0}
padding={0}
>
<Show when={panel() || inspecting()}>
<box width="100%" height={1} flexShrink={0} backgroundColor="transparent" />
</Show>
<Show
when={inspecting()}
fallback={
<box width="100%" flexDirection="column" gap={0}>
<For each={[promptView()]}>
{() => (
<box
width="100%"
flexShrink={0}
border={panel() || prompt() ? false : ["left"]}
borderColor={panel() || prompt() ? undefined : theme().highlight}
customBorderChars={
panel() || prompt()
? undefined
: {
...EMPTY_BORDER,
vertical: "█",
}
}
>
<box
width="100%"
flexGrow={1}
paddingLeft={0}
paddingRight={0}
paddingTop={0}
flexDirection="column"
backgroundColor={panel() || prompt() ? "transparent" : theme().surface}
gap={0}
>
<box width="100%" flexGrow={1} flexShrink={1} flexDirection="column">
<Switch>
<Match when={active().type === "prompt" && route().type === "composer"}>
<RunPromptBody
theme={theme}
background={() => runTheme().background}
placeholder={composer.placeholder}
onSubmit={composer.onSubmit}
onKeyDown={composer.onKeyDown}
onContentChange={composer.onContentChange}
bind={composer.bind}
/>
</Match>
<Match when={selectingSubagent()}>
<RunSubagentSelectBody
theme={theme}
tabs={tabs}
current={selected}
onClose={closePanel}
onSelect={openTab}
onRows={setSubagentMenuRows}
/>
</Match>
<Match when={selectingQueued()}>
<RunQueuedPromptSelectBody
theme={theme}
prompts={queuedPrompts}
onClose={closePanel}
onDelete={(item) => void props.onQueuedRemove(item.messageID)}
onEdit={async (item) => {
if (!(await props.onQueuedRemove(item.messageID))) return
closePanel()
queueMicrotask(() => composer.replacePrompt(item.prompt))
}}
onRows={setSubagentMenuRows}
/>
</Match>
<Match when={commanding()}>
<RunCommandMenuBody
theme={theme}
commands={props.commands}
subagents={tabs}
queued={queuedPrompts}
variants={props.variants}
variantCycle={variantCycle()}
onClose={closePanel}
onModel={openModel}
onEditor={() => {
closePanel()
void composer.openEditor()
}}
onSkill={openSkillMenu}
onSubagent={openSubagentMenu}
onQueued={openQueuedMenu}
onVariant={openVariant}
onVariantCycle={() => {
props.onCycle()
closePanel()
}}
onCommand={(name) => {
composer.submitText(`/${name}`)
closePanel()
}}
onNew={() => {
composer.submitText("/new")
closePanel()
}}
onExit={props.onExit}
/>
</Match>
<Match when={skilling()}>
<RunSkillSelectBody
theme={theme}
commands={props.commands}
onClose={closePanel}
onSelect={(name) => {
composer.replacePrompt({
text: `/${name} `,
parts: [],
command: {
name,
arguments: "",
source: "skill",
},
})
closePanel()
}}
/>
</Match>
<Match when={modeling()}>
<RunModelSelectBody
theme={theme}
providers={props.providers}
current={props.currentModel}
onClose={closePanel}
onSelect={(model) => {
props.onModelSelect(model)
closePanel()
}}
/>
</Match>
<Match when={varianting()}>
<RunVariantSelectBody
theme={theme}
variants={props.variants}
current={props.currentVariant}
onClose={closePanel}
onSelect={(variant) => {
props.onVariantSelect(variant)
closePanel()
}}
/>
</Match>
<Match when={active().type === "permission"}>
<RunPermissionBody
request={permission()!.request}
theme={theme()}
block={block()}
diffStyle={props.diffStyle}
onReply={props.onPermissionReply}
/>
</Match>
<Match when={active().type === "question"}>
<RunQuestionBody
request={question()!.request}
theme={theme()}
onReply={props.onQuestionReply}
onReject={props.onQuestionReject}
/>
</Match>
</Switch>
</box>
</box>
</box>
)}
</For>
<Show when={!panel() && menu()}>
<RunFooterMenu
theme={theme}
items={composer.options}
selected={composer.selected}
offset={composer.offset}
rows={composer.rows}
limit={FOOTER_MENU_ROWS}
border={false}
paddingLeft={0}
/>
</Show>
<Show when={!panel() && !menu()}>
<box
width="100%"
height={1}
flexDirection="row"
gap={0}
flexShrink={0}
backgroundColor={statuslineBackground()}
>
<box paddingLeft={1} paddingRight={1} backgroundColor={theme().statusAccent} flexShrink={0}>
<text wrapMode="none" truncate>
<span style={{ fg: modeColor(), bold: true }}>{modeLabel()}</span>
</text>
</box>
<box
flexDirection="row"
gap={1}
flexGrow={1}
flexShrink={1}
minWidth={12}
paddingLeft={1}
paddingRight={1}
backgroundColor="transparent"
>
<Show when={busy() && !exiting()}>
<box flexShrink={0}>
<spinner color={spin().color} frames={spin().frames} interval={40} />
</box>
</Show>
<text fg={statusColor()} wrapMode="none" truncate flexGrow={1} flexShrink={1}>
<Show when={busy() && !exiting()} fallback={statusText()}>
<Show when={interruptLabel()}>
{(label) => <span style={{ fg: armed() ? statusColor() : theme().muted }}>{label()} </span>}
</Show>
{statusText()}
</Show>
</text>
</box>
<Show when={activityMeta().length > 0}>
<box paddingRight={1} backgroundColor="transparent" flexShrink={1}>
<text fg={theme().muted} wrapMode="none" truncate>
{activityMeta()}
</text>
</box>
</Show>
<Show when={responsive().statusline.showModel && modelStatus()}>
{(info) => (
<box paddingRight={1} backgroundColor="transparent" flexShrink={0}>
<text fg={theme().text} wrapMode="none">
{info().model}
<Show when={info().provider}>
{(provider) => <span style={{ fg: theme().muted }}> {provider()}</span>}
</Show>
<Show when={info().variant}>
{(variant) => (
<>
<span style={{ fg: theme().warning, bold: true }}> {variant()}</span>
</>
)}
</Show>
</text>
</box>
)}
</Show>
<For each={contextHints()}>
{(hint, index) => (
<box paddingRight={1} backgroundColor="transparent" flexShrink={0} maxWidth={24}>
<text fg={theme().text} wrapMode="none" truncate>
<Show when={index() > 0 || ((hasActivityMeta() || hasModelStatus()) && index() === 0)}>
{sectionSeparator()}
</Show>
<span style={{ fg: theme().text }}>{hint.key}</span>{" "}
<span style={{ fg: theme().muted }}>{hint.label}</span>
</text>
</box>
)}
</For>
<Show when={commandHint()}>
{(hint) => (
<box paddingRight={1} backgroundColor="transparent" flexShrink={0} maxWidth={18}>
<text fg={theme().text} wrapMode="none" truncate>
<Show when={hasActivityMeta() || hasModelStatus() || hasContextHints()}>
{sectionSeparator()}
</Show>
<span style={{ fg: theme().text }}>{hint().key}</span>{" "}
<span style={{ fg: theme().muted }}>{hint().label}</span>
</text>
</box>
)}
</Show>
</box>
</Show>
</box>
}
>
<box
width="100%"
flexGrow={1}
flexShrink={1}
border={["left"]}
borderColor={theme().highlight}
customBorderChars={{
...EMPTY_BORDER,
vertical: "┃",
}}
>
<RunFooterSubagentBody
active={inspecting}
theme={runTheme}
tab={selectedTab}
index={selectedIndex}
total={() => tabs().length}
detail={detail}
width={width}
diffStyle={props.diffStyle}
onCycle={cycleTab}
onClose={closeTab}
interrupt={() => subagentInterruptShortcut() || undefined}
/>
</box>
</Show>
</box>
)
}

View file

@ -1,27 +0,0 @@
// Shared responsive width policy
const FOOTER_WIDTH_BREAKPOINTS = {
compact: 80,
commandHint: 66,
model: 120,
spacious: 150,
} as const
export function footerWidthPolicy(width: number) {
const compact = width >= FOOTER_WIDTH_BREAKPOINTS.compact
const model = width >= FOOTER_WIDTH_BREAKPOINTS.model
const spacious = width >= FOOTER_WIDTH_BREAKPOINTS.spacious
return {
dialog: {
narrow: !compact,
},
statusline: {
showActivityMeta: compact,
showCommandHint: width >= FOOTER_WIDTH_BREAKPOINTS.commandHint,
showContextHints: compact,
contextHintLimit: !compact ? 0 : spacious ? undefined : model ? 2 : 1,
showModel: model,
},
}
}

View file

@ -1 +0,0 @@
export { runMini, validateMiniTerminal, mergeInput as mergeInteractiveInput, type MiniCommandInput } from "./mini"

View file

@ -1,260 +0,0 @@
// Pure state machine for the permission UI.
//
// Lives outside the JSX component so it can be tested independently. The
// machine has three stages:
//
// permission → initial view with Allow once / Always / Reject options
// always → confirmation step (Confirm / Cancel)
// reject → text input for rejection message
//
// permissionRun() is the main transition: given the current state and the
// selected option, it returns a new state and optionally a PermissionReply
// to send to the SDK. The component calls this on enter/click.
//
// permissionInfo() extracts display info (icon, title, lines, diff) from
// the request, delegating to tool.ts for tool-specific formatting.
import type { PermissionV2Request } from "@opencode-ai/client/promise"
import type { PermissionReply } from "./types"
import { toolPath, toolPermissionInfo } from "./tool"
type Dict = Record<string, unknown>
export type PermissionStage = "permission" | "always" | "reject"
export type PermissionOption = "once" | "always" | "reject" | "confirm" | "cancel"
export type PermissionBodyState = {
requestID: string
stage: PermissionStage
selected: PermissionOption
message: string
submitting: boolean
}
export type PermissionInfo = {
icon: string
title: string
lines: string[]
diff?: string
file?: string
}
export type PermissionStep = {
state: PermissionBodyState
reply?: PermissionReply
}
function dict(v: unknown): Dict {
if (!v || typeof v !== "object" || Array.isArray(v)) {
return {}
}
return { ...v }
}
function text(v: unknown): string {
return typeof v === "string" ? v : ""
}
function data(request: PermissionV2Request): Dict {
const meta = dict(request.metadata)
return {
...meta,
...dict(meta.input),
}
}
function patterns(request: PermissionV2Request): string[] {
return request.resources.filter((item): item is string => typeof item === "string")
}
export function createPermissionBodyState(requestID: string): PermissionBodyState {
return {
requestID,
stage: "permission",
selected: "once",
message: "",
submitting: false,
}
}
export function permissionOptions(stage: PermissionStage): PermissionOption[] {
if (stage === "permission") {
return ["once", "always", "reject"]
}
if (stage === "always") {
return ["confirm", "cancel"]
}
return []
}
export function permissionInfo(request: PermissionV2Request): PermissionInfo {
const pats = patterns(request)
const input = data(request)
const info = toolPermissionInfo(request.action, input, dict(request.metadata), pats)
if (info) {
return info
}
if (request.action === "external_directory") {
const meta = dict(request.metadata)
const raw = text(meta.parentDir) || text(meta.filepath) || pats[0] || ""
const dir = raw.includes("*") ? raw.slice(0, raw.indexOf("*")).replace(/[\\/]+$/, "") : raw
return {
icon: "←",
title: `Access external directory ${toolPath(dir, { home: true })}`,
lines: pats.map((item) => `- ${item}`),
}
}
if (request.action === "doom_loop") {
return {
icon: "⟳",
title: "Continue after repeated failures",
lines: ["This keeps the session running despite repeated failures."],
}
}
return {
icon: "⚙",
title: `Call tool ${request.action}`,
lines: [`Tool: ${request.action}`],
}
}
export function permissionAlwaysLines(request: PermissionV2Request): string[] {
const save = request.save ?? []
if (save.length === 1 && save[0] === "*") {
return [`This will allow ${request.action} until OpenCode is restarted.`]
}
return [
"This will allow the following patterns until OpenCode is restarted.",
...save.map((item) => `- ${item}`),
]
}
export function permissionLabel(option: PermissionOption): string {
if (option === "once") return "Allow once"
if (option === "always") return "Allow always"
if (option === "reject") return "Reject"
if (option === "confirm") return "Confirm"
return "Cancel"
}
export function permissionReply(requestID: string, reply: PermissionReply["reply"], message?: string): PermissionReply {
return {
requestID,
reply,
...(message && message.trim() ? { message: message.trim() } : {}),
}
}
export function permissionShift(
state: PermissionBodyState,
dir: -1 | 1,
list = permissionOptions(state.stage),
): PermissionBodyState {
if (list.length === 0) {
return state
}
const idx = Math.max(0, list.indexOf(state.selected))
const selected = list[(idx + dir + list.length) % list.length]
return {
...state,
selected,
}
}
export function permissionHover(state: PermissionBodyState, option: PermissionOption): PermissionBodyState {
return {
...state,
selected: option,
}
}
export function permissionRun(state: PermissionBodyState, requestID: string, option: PermissionOption): PermissionStep {
if (state.submitting) {
return { state }
}
if (state.stage === "permission") {
if (option === "always") {
return {
state: {
...state,
stage: "always",
selected: "confirm",
},
}
}
if (option === "reject") {
return {
state: {
...state,
stage: "reject",
selected: "reject",
},
}
}
return {
state,
reply: permissionReply(requestID, "once"),
}
}
if (state.stage !== "always") {
return { state }
}
if (option === "cancel") {
return {
state: {
...state,
stage: "permission",
selected: "always",
},
}
}
return {
state,
reply: permissionReply(requestID, "always"),
}
}
export function permissionReject(state: PermissionBodyState, requestID: string): PermissionReply | undefined {
if (state.submitting) {
return undefined
}
return permissionReply(requestID, "reject", state.message)
}
export function permissionCancel(state: PermissionBodyState): PermissionBodyState {
return {
...state,
stage: "permission",
selected: "reject",
}
}
export function permissionEscape(state: PermissionBodyState): PermissionBodyState {
if (state.stage === "always") {
return {
...state,
stage: "permission",
selected: "always",
}
}
return {
...state,
stage: "reject",
selected: "reject",
}
}

View file

@ -1,157 +0,0 @@
import type { RunPromptPart } from "./types"
type Mention = Extract<RunPromptPart, { type: "file" | "agent" }>
export function resolveEditorSlashValue(text: string) {
const head = slashHead(text)
if (!head || head.name.toLowerCase() !== "editor") {
return text
}
return head.arguments
}
export function realignEditorPromptParts(content: string, parts: RunPromptPart[]): RunPromptPart[] {
const matches = new Map<number, Mention | undefined>()
const used: Array<{ start: number; end: number }> = []
for (const [index, part] of parts.entries()) {
if (part.type !== "file" && part.type !== "agent") {
continue
}
const text = promptPartText(part)
if (!text) {
continue
}
const start = findPromptPartIndex(content, text, used, promptPartStart(part))
if (start === -1) {
matches.set(index, undefined)
continue
}
const end = start + text.length
used.push({ start, end })
matches.set(index, updatePromptPart(part, start, end, text))
}
const next: RunPromptPart[] = []
for (const [index, part] of parts.entries()) {
if (part.type !== "file" && part.type !== "agent") {
next.push(part)
continue
}
if (!promptPartText(part)) {
next.push(part)
continue
}
const match = matches.get(index)
if (match) {
next.push(match)
}
}
return next
}
function slashHead(text: string) {
if (!text.startsWith("/")) {
return
}
for (let i = 1; i < text.length; i++) {
switch (text[i]) {
case " ":
case "\t":
case "\n":
return {
name: text.slice(1, i),
arguments: text.slice(i + 1),
}
}
}
return {
name: text.slice(1),
arguments: "",
}
}
function promptPartText(part: Mention) {
if (part.type === "agent") {
return part.source?.value
}
return part.source?.text.value
}
function promptPartStart(part: Mention) {
if (part.type === "agent") {
return part.source?.start ?? Number.POSITIVE_INFINITY
}
return part.source?.text.start ?? Number.POSITIVE_INFINITY
}
function findPromptPartIndex(content: string, text: string, used: Array<{ start: number; end: number }>, hint: number) {
let searchFrom = 0
let best = -1
let distance = Number.POSITIVE_INFINITY
const hinted = Number.isFinite(hint)
while (true) {
const start = content.indexOf(text, searchFrom)
if (start === -1) {
return best
}
const end = start + text.length
searchFrom = start + 1
if (used.some((range) => start < range.end && end > range.start)) {
continue
}
if (!hinted) {
return start
}
const nextDistance = Math.abs(start - hint)
if (nextDistance < distance) {
best = start
distance = nextDistance
}
}
}
function updatePromptPart(part: Mention, start: number, end: number, text: string): Mention {
if (part.type === "agent") {
return {
...part,
source: {
start,
end,
value: text,
},
}
}
if (!part.source?.text) {
return part
}
return {
...part,
source: {
...part.source,
text: {
...part.source.text,
start,
end,
value: text,
},
},
}
}

View file

@ -1,154 +0,0 @@
// Pure state machine for the prompt input.
//
// Handles history ring navigation and prompt text helpers. All functions are
// pure -- they take state in and return new state out, with no side effects.
//
// The history ring (PromptHistoryState) stores past prompts and tracks
// the current browse position. When the user arrows up at cursor offset 0,
// the current draft is saved and history begins. Arrowing past the end
// restores the draft.
export { displayCharAt, displaySlice, mentionTriggerIndex } from "@opencode-ai/tui/prompt/display"
import { stringWidth } from "@opencode-ai/tui/util/string-width"
import type { RunPrompt } from "./types"
const HISTORY_LIMIT = 200
export type PromptHistoryState = {
items: RunPrompt[]
index: number | null
draft: string
}
export type PromptMove = {
state: PromptHistoryState
text?: string
cursor?: number
apply: boolean
}
export function promptCopy(prompt: RunPrompt): RunPrompt {
return {
text: prompt.text,
parts: structuredClone(prompt.parts),
...(prompt.mode ? { mode: prompt.mode } : {}),
...(prompt.command ? { command: prompt.command } : {}),
}
}
export function promptSame(a: RunPrompt, b: RunPrompt): boolean {
return (
a.mode === b.mode &&
a.text === b.text &&
JSON.stringify(a.parts) === JSON.stringify(b.parts) &&
JSON.stringify(a.command) === JSON.stringify(b.command)
)
}
export function isExitCommand(input: string): boolean {
const text = input.trim().toLowerCase()
return text === "/exit" || text === "/quit" || text === ":q"
}
export function isNewCommand(input: string): boolean {
return input.trim().toLowerCase() === "/new"
}
export function createPromptHistory(items?: RunPrompt[]): PromptHistoryState {
const list = (items ?? []).filter((item) => item.text.trim().length > 0).map(promptCopy)
const next: RunPrompt[] = []
for (const item of list) {
if (next.length > 0 && promptSame(next[next.length - 1], item)) {
continue
}
next.push(item)
}
return {
items: next.slice(-HISTORY_LIMIT),
index: null,
draft: "",
}
}
export function pushPromptHistory(state: PromptHistoryState, prompt: RunPrompt): PromptHistoryState {
if (!prompt.text.trim()) {
return state
}
const next = promptCopy(prompt)
if (state.items[state.items.length - 1] && promptSame(state.items[state.items.length - 1], next)) {
return {
...state,
index: null,
draft: "",
}
}
const items = [...state.items, next].slice(-HISTORY_LIMIT)
return {
...state,
items,
index: null,
draft: "",
}
}
export function movePromptHistory(state: PromptHistoryState, dir: -1 | 1, text: string, cursor: number): PromptMove {
if (state.items.length === 0) {
return { state, apply: false }
}
if (dir === -1 && cursor !== 0) {
return { state, apply: false }
}
if (dir === 1 && cursor !== stringWidth(text)) {
return { state, apply: false }
}
if (state.index === null) {
if (dir === 1) {
return { state, apply: false }
}
const idx = state.items.length - 1
return {
state: {
...state,
index: idx,
draft: text,
},
text: state.items[idx].text,
cursor: 0,
apply: true,
}
}
const idx = state.index + dir
if (idx < 0) {
return { state, apply: false }
}
if (idx >= state.items.length) {
return {
state: {
...state,
index: null,
},
text: state.draft,
cursor: stringWidth(state.draft),
apply: true,
}
}
return {
state: {
...state,
index: idx,
},
text: state.items[idx].text,
cursor: dir === -1 ? 0 : stringWidth(state.items[idx].text),
apply: true,
}
}

View file

@ -1,340 +0,0 @@
// Pure state machine for the question UI.
//
// Supports both single-question and multi-question flows. Single questions
// submit immediately on selection. Multi-question flows use tabs and a
// final confirmation step.
//
// State transitions:
// questionSelect → picks an option (single: submits, multi: toggles/advances)
// questionSave → saves custom text input
// questionMove → arrow key navigation through options
// questionSetTab → tab navigation between questions
// questionSubmit → builds the final QuestionReply with all answers
//
// Custom answers: if a question has custom=true, an extra "Type your own
// answer" option appears. Selecting it enters editing mode with a text field.
import type { QuestionV2Info, QuestionV2Request } from "@opencode-ai/client/promise"
import type { QuestionReject, QuestionReply } from "./types"
export type QuestionBodyState = {
requestID: string
tab: number
answers: string[][]
custom: string[]
selected: number
editing: boolean
submitting: boolean
}
export type QuestionStep = {
state: QuestionBodyState
reply?: QuestionReply
}
export function createQuestionBodyState(requestID: string): QuestionBodyState {
return {
requestID,
tab: 0,
answers: [],
custom: [],
selected: 0,
editing: false,
submitting: false,
}
}
export function questionSync(state: QuestionBodyState, requestID: string): QuestionBodyState {
if (state.requestID === requestID) {
return state
}
return createQuestionBodyState(requestID)
}
export function questionSingle(request: QuestionV2Request): boolean {
return request.questions.length === 1 && request.questions[0]?.multiple !== true
}
export function questionTabs(request: QuestionV2Request): number {
return questionSingle(request) ? 1 : request.questions.length + 1
}
export function questionConfirm(request: QuestionV2Request, state: QuestionBodyState): boolean {
return !questionSingle(request) && state.tab === request.questions.length
}
export function questionInfo(request: QuestionV2Request, state: QuestionBodyState): QuestionV2Info | undefined {
return request.questions[state.tab]
}
export function questionCustom(request: QuestionV2Request, state: QuestionBodyState): boolean {
return questionInfo(request, state)?.custom !== false
}
export function questionInput(state: QuestionBodyState): string {
return state.custom[state.tab] ?? ""
}
export function questionPicked(state: QuestionBodyState): boolean {
const value = questionInput(state)
if (!value) {
return false
}
return state.answers[state.tab]?.includes(value) ?? false
}
export function questionOther(request: QuestionV2Request, state: QuestionBodyState): boolean {
const info = questionInfo(request, state)
if (!info || info.custom === false) {
return false
}
return state.selected === info.options.length
}
export function questionTotal(request: QuestionV2Request, state: QuestionBodyState): number {
const info = questionInfo(request, state)
if (!info) {
return 0
}
return info.options.length + (questionCustom(request, state) ? 1 : 0)
}
export function questionAnswers(state: QuestionBodyState, count: number): string[][] {
return Array.from({ length: count }, (_, idx) => state.answers[idx] ?? [])
}
export function questionSetTab(state: QuestionBodyState, tab: number): QuestionBodyState {
return {
...state,
tab,
selected: 0,
editing: false,
}
}
export function questionSetSelected(state: QuestionBodyState, selected: number): QuestionBodyState {
return {
...state,
selected,
}
}
export function questionSetEditing(state: QuestionBodyState, editing: boolean): QuestionBodyState {
return {
...state,
editing,
}
}
export function questionSetSubmitting(state: QuestionBodyState, submitting: boolean): QuestionBodyState {
return {
...state,
submitting,
}
}
function storeAnswers(state: QuestionBodyState, tab: number, list: string[]): QuestionBodyState {
const answers = [...state.answers]
answers[tab] = list
return {
...state,
answers,
}
}
export function questionStoreCustom(state: QuestionBodyState, tab: number, text: string): QuestionBodyState {
const custom = [...state.custom]
custom[tab] = text
return {
...state,
custom,
}
}
function questionPick(
state: QuestionBodyState,
request: QuestionV2Request,
answer: string,
custom = false,
): QuestionStep {
const answers = [...state.answers]
answers[state.tab] = [answer]
let next: QuestionBodyState = {
...state,
answers,
editing: false,
}
if (custom) {
const list = [...state.custom]
list[state.tab] = answer
next = {
...next,
custom: list,
}
}
if (questionSingle(request)) {
return {
state: next,
reply: {
requestID: request.id,
answers: [[answer]],
},
}
}
return {
state: questionSetTab(next, state.tab + 1),
}
}
function questionToggle(state: QuestionBodyState, answer: string): QuestionBodyState {
const list = [...(state.answers[state.tab] ?? [])]
const idx = list.indexOf(answer)
if (idx === -1) {
list.push(answer)
} else {
list.splice(idx, 1)
}
return storeAnswers(state, state.tab, list)
}
export function questionMove(state: QuestionBodyState, request: QuestionV2Request, dir: -1 | 1): QuestionBodyState {
const total = questionTotal(request, state)
if (total === 0) {
return state
}
return {
...state,
selected: (state.selected + dir + total) % total,
}
}
export function questionSelect(state: QuestionBodyState, request: QuestionV2Request): QuestionStep {
const info = questionInfo(request, state)
if (!info) {
return { state }
}
if (questionOther(request, state)) {
if (!info.multiple) {
return {
state: questionSetEditing(state, true),
}
}
const value = questionInput(state)
if (value && questionPicked(state)) {
return {
state: questionToggle(state, value),
}
}
return {
state: questionSetEditing(state, true),
}
}
const option = info.options[state.selected]
if (!option) {
return { state }
}
if (info.multiple) {
return {
state: questionToggle(state, option.label),
}
}
return questionPick(state, request, option.label)
}
export function questionSave(state: QuestionBodyState, request: QuestionV2Request): QuestionStep {
const info = questionInfo(request, state)
if (!info) {
return { state }
}
const value = questionInput(state).trim()
const prev = state.custom[state.tab]
if (!value) {
if (!prev) {
return {
state: questionSetEditing(state, false),
}
}
const next = questionStoreCustom(state, state.tab, "")
return {
state: questionSetEditing(
storeAnswers(
next,
state.tab,
(state.answers[state.tab] ?? []).filter((item) => item !== prev),
),
false,
),
}
}
if (info.multiple) {
const answers = [...(state.answers[state.tab] ?? [])]
if (prev) {
const idx = answers.indexOf(prev)
if (idx !== -1) {
answers.splice(idx, 1)
}
}
if (!answers.includes(value)) {
answers.push(value)
}
const next = questionStoreCustom(state, state.tab, value)
return {
state: questionSetEditing(storeAnswers(next, state.tab, answers), false),
}
}
return questionPick(state, request, value, true)
}
export function questionSubmit(request: QuestionV2Request, state: QuestionBodyState): QuestionReply {
return {
requestID: request.id,
answers: questionAnswers(state, request.questions.length),
}
}
export function questionReject(request: QuestionV2Request): QuestionReject {
return {
requestID: request.id,
}
}
export function questionHint(request: QuestionV2Request, state: QuestionBodyState): string {
if (state.submitting) {
return "Waiting for question event..."
}
if (questionConfirm(request, state)) {
return "enter submit esc dismiss"
}
if (state.editing) {
return "enter save esc cancel"
}
const info = questionInfo(request, state)
if (questionSingle(request)) {
return `↑↓ select enter ${info?.multiple ? "toggle" : "submit"} esc dismiss`
}
return `⇆ tab ↑↓ select enter ${info?.multiple ? "toggle" : "confirm"} esc dismiss`
}

View file

@ -1,166 +0,0 @@
// Boot-time resolution for direct interactive mode.
//
// These functions run concurrently at startup to gather everything the runtime
// needs before the first frame: TUI keymap config, diff display style,
// model variant list with context limits, and session history for the prompt
// history ring. All are async because they read config or hit the SDK, but
// none block each other.
import { Context, Effect, Layer } from "effect"
import { resolve } from "@opencode-ai/tui/config/v1"
import { makeGlobalNode } from "@opencode-ai/core/effect/app-node"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { makeRuntime } from "@opencode-ai/core/effect/runtime"
import { loadRunProviders } from "./catalog.shared"
import { resolveCurrentSession, sessionHistory } from "./session.shared"
import type { RunDiffStyle, RunInput, RunPrompt, RunProvider, RunTuiConfig } from "./types"
import { pickVariant } from "./variant.shared"
export type ModelInfo = {
providers: RunProvider[]
variants: string[]
limits: Record<string, number>
}
export type SessionInfo = {
first: boolean
history: RunPrompt[]
model?: NonNullable<RunInput["model"]>
variant: string | undefined
}
type BootService = {
readonly resolveModelInfo: (
sdk: RunInput["sdk"],
directory: string,
model: RunInput["model"],
) => Effect.Effect<ModelInfo>
readonly resolveSessionInfo: (
sdk: RunInput["sdk"],
sessionID: string,
model: RunInput["model"],
) => Effect.Effect<SessionInfo>
}
class Service extends Context.Service<Service, BootService>()("@opencode/RunBoot") {}
function emptyModelInfo(): ModelInfo {
return {
providers: [],
variants: [],
limits: {},
}
}
function emptySessionInfo(): SessionInfo {
return {
first: true,
history: [],
variant: undefined,
}
}
function defaultRunTuiConfig(): RunTuiConfig {
return {
...resolve({}, { terminalSuspend: process.platform !== "win32" }),
diff_style: "auto",
}
}
const layer = Layer.effect(
Service,
Effect.gen(function* () {
const resolveModelInfo = Effect.fn("RunBoot.resolveModelInfo")(function* (
sdk: RunInput["sdk"],
directory: string,
model: RunInput["model"],
) {
const providers = yield* Effect.promise(() => loadRunProviders(sdk, directory))
const limits = Object.fromEntries(
providers.flatMap((provider) =>
Object.entries(provider.models ?? {}).flatMap(([modelID, info]) => {
const limit = info?.limit?.context
if (typeof limit !== "number" || limit <= 0) {
return []
}
return [[`${provider.id}/${modelID}`, limit] as const]
}),
),
)
if (!model) {
return {
providers,
variants: [],
limits,
}
}
const info = providers.find((item) => item.id === model.providerID)?.models?.[model.modelID]
return {
providers,
variants: Object.keys(info?.variants ?? {}),
limits,
}
})
const resolveSessionInfo = Effect.fn("RunBoot.resolveSessionInfo")(function* (
sdk: RunInput["sdk"],
sessionID: string,
model: RunInput["model"],
) {
const session = yield* Effect.promise(() => resolveCurrentSession(sdk, sessionID).catch(() => undefined))
if (!session) {
return emptySessionInfo()
}
return {
first: session.first,
history: sessionHistory(session),
model: session.model,
variant: pickVariant(model ?? session.model, session),
}
})
return Service.of({
resolveModelInfo,
resolveSessionInfo,
})
}),
)
const node = makeGlobalNode({ service: Service, layer, deps: [] })
const runtime = makeRuntime(Service, LayerNode.compile(node))
// Fetches available variants and context limits for every provider/model pair.
export async function resolveModelInfo(
sdk: RunInput["sdk"],
directory: string,
model: RunInput["model"],
): Promise<ModelInfo> {
return runtime.runPromise((svc) => svc.resolveModelInfo(sdk, directory, model)).catch(() => emptyModelInfo())
}
export function resolveModelInfoStrict(sdk: RunInput["sdk"], directory: string, model: RunInput["model"]) {
return runtime.runPromise((svc) => svc.resolveModelInfo(sdk, directory, model))
}
// Fetches session messages to determine if this is the first turn and build prompt history.
export async function resolveSessionInfo(
sdk: RunInput["sdk"],
sessionID: string,
model: RunInput["model"],
): Promise<SessionInfo> {
return runtime.runPromise((svc) => svc.resolveSessionInfo(sdk, sessionID, model)).catch(() => emptySessionInfo())
}
// Reads TUI config once for direct mode keymap setup and display preferences.
export async function resolveRunTuiConfig(
config?: RunTuiConfig | Promise<RunTuiConfig>,
): Promise<RunTuiConfig> {
return Promise.resolve(config).then((value) => value ?? defaultRunTuiConfig()).catch(() => defaultRunTuiConfig())
}
export async function resolveDiffStyle(config?: RunTuiConfig | Promise<RunTuiConfig>): Promise<RunDiffStyle> {
return resolveRunTuiConfig(config).then((value) => value.diff_style ?? "auto")
}

View file

@ -1,389 +0,0 @@
// Lifecycle management for the split-footer renderer.
//
// Creates the OpenTUI CliRenderer in split-footer mode, resolves the theme
// from the terminal palette, writes the entry splash to scrollback, and
// constructs the RunFooter. Returns a Lifecycle handle whose close() writes
// the exit splash and tears everything down in the right order:
// footer.close → footer.destroy → renderer shutdown.
//
// Also wires SIGINT so Ctrl-c clears a live prompt draft first, then falls
// back to the usual two-press exit sequence through RunFooter.requestExit().
import path from "path"
import { CliRenderEvents, createCliRenderer, type CliRenderer, type ScrollbackWriter } from "@opentui/core"
import { Global } from "@opencode-ai/core/global"
import { isDefaultTitle } from "@opencode-ai/tui/util/session"
import { Locale } from "@opencode-ai/tui/util/locale"
import { resolveInteractiveStdin } from "./runtime.stdin"
import { entrySplash, exitSplash, splashMeta } from "./splash"
import { resolveRunTheme } from "./theme"
import type {
FooterApi,
PermissionReply,
QuestionReject,
QuestionReply,
RunAgent,
RunInput,
RunPrompt,
RunReference,
RunTuiConfig,
} from "./types"
import { formatModelLabel } from "./variant.shared"
const FOOTER_HEIGHT = 4
type SplashState = {
entry: boolean
exit: boolean
}
type CycleResult = {
modelLabel?: string
status?: string
variant?: string | undefined
variants?: string[]
}
type FooterLabels = {
agentLabel: string
modelLabel: string
}
export type LifecycleInput = {
directory: string
findFiles: (query: string) => Promise<string[]>
agents: RunAgent[]
references: RunReference[]
sessionID: string
sessionTitle?: string
getSessionID?: () => string | undefined
first: boolean
history: RunPrompt[]
agent: string | undefined
model: RunInput["model"]
variant: string | undefined
tuiConfig: RunTuiConfig | Promise<RunTuiConfig>
onPermissionReply: (input: PermissionReply) => void | Promise<void>
onQuestionReply: (input: QuestionReply) => void | Promise<void>
onQuestionReject: (input: QuestionReject) => void | Promise<void>
onCycleVariant?: () => CycleResult | void
onModelSelect?: (model: NonNullable<RunInput["model"]>) => CycleResult | void | Promise<CycleResult | void>
onVariantSelect?: (variant: string | undefined) => CycleResult | void | Promise<CycleResult | void>
onInterrupt?: () => void
onBackground?: () => void
onSubagentSelect?: (sessionID: string | undefined) => void
onSubagentInterrupt?: (sessionID: string) => void
}
export type Lifecycle = {
footer: FooterApi
onResize(fn: () => void): () => void
refreshTheme(): void
resetForReplay(input: { sessionTitle?: string; sessionID?: string; history: RunPrompt[] }): Promise<void>
close(input: { showExit: boolean; sessionTitle?: string; sessionID?: string; history?: RunPrompt[] }): Promise<void>
}
// Gracefully tears down the renderer. Order matters: switch external output
// back to passthrough before leaving split-footer mode, so pending stdout
// doesn't get captured into the now-dead scrollback pipeline.
function shutdown(renderer: CliRenderer): void {
if (renderer.isDestroyed) {
return
}
if (renderer.externalOutputMode === "capture-stdout") {
renderer.externalOutputMode = "passthrough"
}
if (renderer.screenMode === "split-footer") {
renderer.screenMode = "main-screen"
}
if (!renderer.isDestroyed) {
renderer.destroy()
}
}
function splashInfo(title: string | undefined, history: RunPrompt[]) {
if (title && !isDefaultTitle(title)) {
return {
title,
showSession: true,
}
}
const next = history.find((item) => item.text.trim().length > 0)
return {
title: next?.text ?? title,
showSession: !!next,
}
}
function footerLabels(input: Pick<RunInput, "agent" | "model" | "variant">): FooterLabels {
const agentLabel = Locale.titlecase(input.agent ?? "build")
return {
agentLabel,
modelLabel: input.model ? formatModelLabel(input.model, input.variant) : "",
}
}
function directoryLabel(directory: string) {
const resolved = path.resolve(directory)
const display =
resolved === Global.Path.home
? "~"
: resolved.startsWith(`${Global.Path.home}${path.sep}`)
? resolved.replace(Global.Path.home, "~")
: resolved
return display.replaceAll("\\", "/")
}
function queueSplash(
renderer: Pick<CliRenderer, "writeToScrollback" | "requestRender">,
state: SplashState,
phase: keyof SplashState,
write: ScrollbackWriter | undefined,
): boolean {
if (state[phase]) {
return false
}
if (!write) {
return false
}
state[phase] = true
renderer.writeToScrollback(write)
renderer.requestRender()
return true
}
// Boots the split-footer renderer and constructs the RunFooter.
//
// The renderer starts in split-footer mode with captured stdout so that
// scrollback commits and footer repaints happen in the same frame. After
// the entry splash, RunFooter takes over the footer region.
export async function createRuntimeLifecycle(input: LifecycleInput): Promise<Lifecycle> {
const source = resolveInteractiveStdin()
const footerTask = import("./footer")
try {
const renderer = await createCliRenderer({
stdin: source.stdin,
targetFps: 30,
maxFps: 60,
useMouse: false,
autoFocus: false,
openConsoleOnError: false,
exitOnCtrlC: false,
useKittyKeyboard: { events: process.platform === "win32" },
screenMode: "split-footer",
footerHeight: FOOTER_HEIGHT,
externalOutputMode: "capture-stdout",
consoleMode: "disabled",
clearOnShutdown: false,
})
const [theme, tuiConfig] = await Promise.all([resolveRunTheme(renderer), input.tuiConfig])
renderer.setBackgroundColor(theme.background)
const state: SplashState = {
entry: false,
exit: false,
}
const splash = splashInfo(input.sessionTitle, input.history)
const meta = splashMeta({
title: splash.title,
session_id: input.sessionID,
})
const labels = footerLabels({
agent: input.agent,
model: input.model,
variant: input.variant,
})
const wrote = queueSplash(
renderer,
state,
"entry",
entrySplash({
...meta,
theme: theme.splash,
showSession: splash.showSession,
detail: directoryLabel(input.directory),
}),
)
await renderer.idle().catch(() => {})
const { RunFooter } = await footerTask
let closed = false
let sigintRegistered = false
const footer = new RunFooter(renderer, {
directory: input.directory,
findFiles: input.findFiles,
agents: input.agents,
references: input.references,
sessionID: input.getSessionID ?? (() => input.sessionID),
...labels,
model: input.model,
variant: input.variant,
first: input.first,
history: input.history,
theme,
wrote,
tuiConfig,
diffStyle: tuiConfig.diff_style ?? "auto",
onPermissionReply: input.onPermissionReply,
onQuestionReply: input.onQuestionReply,
onQuestionReject: input.onQuestionReject,
onCycleVariant: input.onCycleVariant,
onModelSelect: input.onModelSelect,
onVariantSelect: input.onVariantSelect,
onInterrupt: input.onInterrupt,
onBackground: input.onBackground,
onEditorOpen: async ({ value }) => {
if (closed || renderer.isDestroyed) {
return
}
const { openEditor } = await import("@opencode-ai/tui/editor")
await renderer.idle().catch(() => {})
const ignore = () => {}
detachSigint()
process.on("SIGINT", ignore)
try {
return await openEditor({
value,
cwd: input.directory,
renderer,
stdin: source.stdin,
})
} finally {
process.off("SIGINT", ignore)
attachSigint()
}
},
onSubagentSelect: input.onSubagentSelect,
onSubagentInterrupt: input.onSubagentInterrupt,
})
const sigint = () => {
footer.requestExit()
}
const attachSigint = () => {
if (closed || sigintRegistered) {
return
}
process.on("SIGINT", sigint)
sigintRegistered = true
}
const detachSigint = () => {
if (!sigintRegistered) {
return
}
process.off("SIGINT", sigint)
sigintRegistered = false
}
attachSigint()
const close = async (next: {
showExit: boolean
sessionTitle?: string
sessionID?: string
history?: RunPrompt[]
}) => {
if (closed) {
return
}
closed = true
detachSigint()
let wroteExit = false
try {
await footer.idle().catch(() => {})
const show = renderer.isDestroyed ? false : next.showExit
if (!renderer.isDestroyed && show) {
const sessionID = next.sessionID || input.getSessionID?.() || input.sessionID
const splash = splashInfo(next.sessionTitle ?? input.sessionTitle, next.history ?? input.history)
wroteExit = queueSplash(
renderer,
state,
"exit",
exitSplash({
...splashMeta({
title: splash.title,
session_id: sessionID,
}),
theme: footer.currentTheme().splash,
}),
)
await renderer.idle().catch(() => {})
}
} finally {
footer.close()
await footer.idle().catch(() => {})
footer.destroy()
shutdown(renderer)
if (!wroteExit) {
process.stdout.write("\n")
}
source.cleanup?.()
}
}
return {
footer,
refreshTheme() {
footer.refreshTheme()
},
onResize(fn) {
let width = renderer.terminalWidth
let height = renderer.terminalHeight
const resize = () => {
if (width === renderer.terminalWidth && height === renderer.terminalHeight) {
return
}
width = renderer.terminalWidth
height = renderer.terminalHeight
fn()
}
renderer.on(CliRenderEvents.RESIZE, resize)
return () => renderer.off(CliRenderEvents.RESIZE, resize)
},
async resetForReplay(next) {
if (closed || renderer.isDestroyed || footer.isClosed) {
throw new Error("runtime closed")
}
await footer.idle()
if (closed || renderer.isDestroyed || footer.isClosed) {
throw new Error("runtime closed")
}
footer.resetForReplay(true)
renderer.resetSplitFooterForReplay({ clearSavedLines: true })
const splash = splashInfo(next.sessionTitle ?? input.sessionTitle, next.history)
renderer.writeToScrollback(
entrySplash({
...splashMeta({
title: splash.title,
session_id: next.sessionID ?? input.getSessionID?.() ?? input.sessionID,
}),
theme: footer.currentTheme().splash,
showSession: splash.showSession,
detail: directoryLabel(input.directory),
}),
)
renderer.requestRender()
},
close,
}
} catch (error) {
source.cleanup?.()
throw error
}
}

View file

@ -1,350 +0,0 @@
// Serial prompt queue for direct interactive mode.
//
// Prompts arrive from the footer (user types and hits enter) and queue up
// here. The queue drains one turn at a time; ordinary prompts waiting behind
// an active ordinary turn are exposed for edit/removal until they begin.
//
// The queue also handles /exit, /quit, and /new commands, empty-prompt rejection,
// and tracks per-turn wall-clock duration for the footer status line.
//
// Resolves when the footer closes and all in-flight work finishes.
import { ascending } from "@opencode-ai/schema/identifier"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { Locale } from "@opencode-ai/tui/util/locale"
import { isExitCommand, isNewCommand } from "./prompt.shared"
import type { FooterApi, FooterEvent, FooterQueuedPrompt, RunPrompt } from "./types"
type Trace = {
write(type: string, data?: unknown): void
}
type Deferred<T = void> = {
promise: Promise<T>
resolve: (value: T | PromiseLike<T>) => void
reject: (error?: unknown) => void
}
export type QueueInput = {
footer: FooterApi
initialInput?: string
trace?: Trace
onSend?: (prompt: RunPrompt) => void
onNewSession?: () => void | Promise<void>
run: (prompt: RunPrompt, signal: AbortSignal) => Promise<void>
}
type State = {
queue: RunPrompt[]
queued: FooterQueuedPrompt[]
active?: RunPrompt
ctrl?: AbortController
closed: boolean
}
function defer<T = void>(): Deferred<T> {
let resolve!: (value: T | PromiseLike<T>) => void
let reject!: (error?: unknown) => void
const promise = new Promise<T>((next, fail) => {
resolve = next
reject = fail
})
return { promise, resolve, reject }
}
// Runs the prompt queue until the footer closes.
//
// Subscribes to footer prompt events and drains operations through input.run().
// Ordinary prompts submitted during an ordinary active turn remain local and
// are exposed by the footer for edit/removal until their turn begins.
export async function runPromptQueue(input: QueueInput): Promise<void> {
const stop = defer<{ type: "closed" }>()
const done = defer()
const state: State = {
queue: [],
queued: [],
closed: input.footer.isClosed,
}
let draining: Promise<void> | undefined
const emit = (next: FooterEvent, row: Record<string, unknown>) => {
input.trace?.write("ui.patch", row)
input.footer.event(next)
}
const syncQueue = () => {
const queue = state.queue.length
emit({ type: "queue", queue }, { queue })
emit(
{
type: "queued.prompts",
prompts: [...state.queued],
},
{ queued: state.queued.length },
)
}
const removeLocalQueued = (queued: FooterQueuedPrompt) => {
if (!state.queued.includes(queued)) return
state.queued = state.queued.filter((item) => item !== queued)
syncQueue()
}
const finish = () => {
if (!state.closed || draining) {
return
}
done.resolve()
}
const close = () => {
if (state.closed) {
return
}
state.closed = true
state.queue.length = 0
state.queued.length = 0
state.ctrl?.abort()
stop.resolve({ type: "closed" })
finish()
}
const drain = () => {
if (draining || state.closed || state.queue.length === 0) {
return
}
draining = (async () => {
try {
while (!state.closed && state.queue.length > 0) {
const prompt = state.queue.shift()
if (!prompt) {
continue
}
const queued = state.queued.find((item) => item.prompt === prompt)
if (queued) removeLocalQueued(queued)
if (prompt.mode !== "shell" && isNewCommand(prompt.text)) {
syncQueue()
if (!input.onNewSession) {
emit(
{
type: "stream.patch",
patch: {
status: "new sessions unavailable",
},
},
{
status: "new sessions unavailable",
},
)
continue
}
emit(
{
type: "stream.patch",
patch: {
phase: "running",
status: "starting new session",
queue: state.queue.length,
},
},
{
phase: "running",
status: "starting new session",
queue: state.queue.length,
},
)
await input.onNewSession()
continue
}
const sent =
prompt.mode === "shell"
? prompt
: {
...prompt,
messageID: prompt.messageID ?? queued?.messageID ?? SessionMessage.ID.create(),
}
state.active = sent
emit(
{
type: "turn.send",
queue: state.queue.length,
},
{
phase: "running",
status: "sending prompt",
queue: state.queue.length,
},
)
const start = Date.now()
const ctrl = new AbortController()
state.ctrl = ctrl
try {
await input.footer.idle()
if (state.closed) {
break
}
if (sent.mode !== "shell") {
const commit = {
kind: "user",
text: sent.text,
phase: "start",
source: "system",
messageID: sent.messageID,
} as const
input.trace?.write("ui.commit", commit)
input.footer.append(commit)
}
input.onSend?.(sent)
if (state.closed) {
break
}
const task = input.run(sent, ctrl.signal).then(
() => ({ type: "done" as const }),
(error) => ({ type: "error" as const, error }),
)
const next = await Promise.race([task, stop.promise])
if (next.type === "closed") {
ctrl.abort()
break
}
if (next.type === "error") {
throw next.error
}
} finally {
if (state.ctrl === ctrl) {
state.ctrl = undefined
}
if (sent.mode !== "shell") {
const duration = Locale.duration(Math.max(0, Date.now() - start))
emit(
{
type: "turn.duration",
duration,
},
{
duration,
},
)
}
state.active = undefined
}
}
} catch (error) {
done.reject(error)
return
} finally {
draining = undefined
emit(
{
type: "turn.idle",
queue: state.queue.length,
},
{
phase: "idle",
status: "",
queue: state.queue.length,
},
)
}
finish()
})()
}
const submit = (prompt: RunPrompt) => {
if (!prompt.text.trim() || state.closed) {
return
}
if (prompt.mode !== "shell" && isExitCommand(prompt.text)) {
input.footer.close()
return
}
const active = state.active
if (
active &&
active.mode !== "shell" &&
!active.command &&
prompt.mode !== "shell" &&
!prompt.command &&
!isNewCommand(prompt.text)
) {
const queued: FooterQueuedPrompt = {
messageID: SessionMessage.ID.create(),
partID: "prt_" + ascending(),
prompt,
}
state.queued = [...state.queued, queued]
state.queue.push(prompt)
syncQueue()
return
}
state.queue.push(prompt)
syncQueue()
if (prompt.mode !== "shell" && isNewCommand(prompt.text)) {
drain()
return
}
emit(
{
type: "first",
first: false,
},
{
first: false,
},
)
drain()
}
const offPrompt = input.footer.onPrompt((prompt) => {
submit(prompt)
})
const offClose = input.footer.onClose(() => {
close()
})
const offRemoveQueued = input.footer.onQueuedRemove((messageID) => {
const queued = state.queued.find((item) => item.messageID === messageID)
if (!queued) return false
state.queue = state.queue.filter((prompt) => prompt !== queued.prompt)
removeLocalQueued(queued)
return true
})
try {
if (state.closed) {
return
}
submit({
text: input.initialInput ?? "",
parts: [],
})
finish()
await done.promise
} finally {
offPrompt()
offClose()
offRemoveQueued()
close()
await draining?.catch(() => {})
}
}

View file

@ -1,17 +0,0 @@
type PendingTask<T> = {
current?: Promise<T>
}
export function reusePendingTask<T>(slot: PendingTask<T>, run: () => Promise<T>) {
if (slot.current) {
return slot.current
}
const task = run().finally(() => {
if (slot.current === task) {
slot.current = undefined
}
})
slot.current = task
return task
}

View file

@ -1,37 +0,0 @@
import fs from "fs"
import * as tty from "node:tty"
export const INTERACTIVE_INPUT_ERROR = "opencode mini requires a controlling terminal for input"
type InteractiveStdin = {
stdin: NodeJS.ReadStream
cleanup?: () => void
}
function openTerminalStdin(path: string): NodeJS.ReadStream {
return new tty.ReadStream(fs.openSync(path, "r"))
}
export function resolveInteractiveStdin(
stdin: NodeJS.ReadStream = process.stdin,
open: (path: string) => NodeJS.ReadStream = openTerminalStdin,
platform = process.platform,
): InteractiveStdin {
if (stdin.isTTY) {
return { stdin }
}
const file = platform === "win32" ? "CONIN$" : "/dev/tty"
try {
const stream = open(file)
return {
stdin: stream,
cleanup: () => {
stream.destroy()
},
}
} catch (error) {
throw new Error(INTERACTIVE_INPUT_ERROR, { cause: error })
}
}

View file

@ -1,944 +0,0 @@
// Top-level orchestrator for `opencode mini`.
//
// Wires the boot sequence, lifecycle (renderer + footer), stream transport,
// and prompt queue together into a single session loop. Two entry points:
//
// runInteractiveMode -- used when an SDK client already exists (attach mode)
// runInteractiveDeferredMode -- paints before resolving its session
//
// Both delegate to runInteractiveRuntime, which:
// 1. resolves TUI config, model info, and session history,
// 2. creates the split-footer lifecycle (renderer + RunFooter),
// 3. starts the stream transport (SDK event subscription), lazily for fresh
// local sessions,
// 4. runs the prompt queue until the footer closes.
import { Flag } from "@opencode-ai/core/flag/flag"
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { loadRunAgents, loadRunCommands, loadRunReferences, waitForDefaultModel } from "./catalog.shared"
import { resolveModelInfo, resolveModelInfoStrict, resolveRunTuiConfig, resolveSessionInfo } from "./runtime.boot"
import { createRuntimeLifecycle } from "./runtime.lifecycle"
import { trace } from "./trace"
import { cycleVariant, formatModelLabel, resolveSavedVariant, resolveVariant, saveVariant } from "./variant.shared"
import type {
LocalReplayAnchor,
LocalReplayRow,
RunInput,
RunPrompt,
RunProvider,
RunTuiConfig,
StreamCommit,
} from "./types"
/** @internal Exported for testing */
export { pickVariant, resolveVariant } from "./variant.shared"
/** @internal Exported for testing */
export { runPromptQueue } from "./runtime.queue"
type BootContext = Pick<
RunInput,
"sdk" | "directory" | "sessionID" | "sessionTitle" | "resume" | "agent" | "model" | "variant"
>
type CreateSessionInput = {
agent: string | undefined
model: RunInput["model"]
variant: string | undefined
}
type CreateSession = (sdk: RunInput["sdk"], input: CreateSessionInput) => Promise<{ id: string; title?: string }>
type RunRuntimeInput = {
boot: () => Promise<BootContext>
afterPaint?: (ctx: BootContext) => Promise<void> | void
resolveSession?: (ctx: BootContext) => Promise<ResolvedSession>
createSession?: (ctx: BootContext, input: CreateSessionInput) => Promise<ResolvedSession>
files: RunInput["files"]
initialInput?: string
thinking: boolean
replay?: boolean
replayLimit?: number
demo?: RunInput["demo"]
tuiConfig?: RunTuiConfig | Promise<RunTuiConfig>
}
type RunDeferredInput = {
sdk: RunInput["sdk"]
directory: string
resolveAgent: () => Promise<string | undefined>
session: (sdk: RunInput["sdk"]) => Promise<{ id: string; title?: string; resume?: boolean } | undefined>
createSession?: CreateSession
agent: RunInput["agent"]
model: RunInput["model"]
variant: RunInput["variant"]
files: RunInput["files"]
initialInput?: string
thinking: boolean
replay?: boolean
replayLimit?: number
demo?: RunInput["demo"]
tuiConfig?: RunTuiConfig | Promise<RunTuiConfig>
}
type StreamTransportModule = Pick<
Awaited<typeof import("./stream-v2.transport")>,
"createSessionTransport" | "formatUnknownError"
>
export type RunRuntimeDeps = {
createRuntimeLifecycle?: typeof createRuntimeLifecycle
streamTransport?: Promise<StreamTransportModule>
}
type StreamState = {
mod: StreamTransportModule
handle: Awaited<ReturnType<StreamTransportModule["createSessionTransport"]>>
}
type RunDemo = ReturnType<(typeof import("./demo"))["createRunDemo"]>
type ResolvedSession = {
sessionID: string
sessionTitle?: string
agent?: string | undefined
resume?: boolean
}
function createSessionResolver(fn?: CreateSession) {
if (!fn) {
return undefined
}
return async (ctx: BootContext, input: CreateSessionInput): Promise<ResolvedSession> => {
const created = await fn(ctx.sdk, input)
if (!created.id) {
throw new Error("Failed to create session")
}
return {
sessionID: created.id,
sessionTitle: created.title,
agent: input.agent,
}
}
}
type RuntimeState = {
shown: boolean
aborting: boolean
model: RunInput["model"]
providers: RunProvider[]
variants: string[]
limits: Record<string, number>
activeVariant: string | undefined
sessionID: string
history: RunPrompt[]
localRows: LocalReplayRow[]
sessionTitle?: string
agent: string | undefined
switching?: Promise<void>
demo?: RunDemo
selectSubagent?: (sessionID: string | undefined) => void
session?: Promise<void>
stream?: Promise<StreamState>
}
function hasSession(input: RunRuntimeInput, state: RuntimeState) {
return !input.resolveSession || !!state.sessionID
}
function eagerStream(input: RunRuntimeInput, ctx: BootContext) {
return ctx.resume === true || !input.resolveSession || !!input.demo
}
function variantsFor(providers: RunProvider[], model: RunInput["model"]) {
if (!model) {
return []
}
return Object.keys(providers.find((item) => item.id === model.providerID)?.models?.[model.modelID]?.variants ?? {})
}
const RESIZE_DELAY = 250
const LOCAL_REPLAY_ROW_LIMIT = 100
async function resolveExitTitle(
ctx: BootContext,
input: RunRuntimeInput,
state: RuntimeState,
): Promise<string | undefined> {
if (!state.shown || !hasSession(input, state)) {
return undefined
}
return ctx.sdk.session
.get({ sessionID: state.sessionID })
.then((session) => session.title)
.catch(() => undefined)
}
// Core runtime loop. Boot resolves the SDK context, then we set up the
// lifecycle (renderer + footer), wire the stream transport for SDK events,
// and feed prompts through the queue until the user exits.
//
// Files only attach on the first prompt turn -- after that, includeFiles
// flips to false so subsequent turns don't re-send attachments.
async function runInteractiveRuntime(input: RunRuntimeInput, deps: RunRuntimeDeps = {}): Promise<void> {
const start = performance.now()
const log = trace()
const tuiConfigTask = resolveRunTuiConfig(input.tuiConfig)
const ctx = await input.boot()
const sessionTask =
ctx.resume === true
? resolveSessionInfo(ctx.sdk, ctx.sessionID, ctx.model)
: Promise.resolve({
first: true,
history: [],
model: undefined,
variant: undefined,
})
const savedTask = resolveSavedVariant(ctx.model)
const [session, savedVariant] = await Promise.all([sessionTask, savedTask])
const state: RuntimeState = {
shown: !session.first,
aborting: false,
model: ctx.model ?? session.model,
providers: [],
variants: [],
limits: {},
activeVariant: resolveVariant(ctx.variant, session.variant, savedVariant, []),
sessionID: ctx.sessionID,
history: [...session.history],
localRows: [],
sessionTitle: ctx.sessionTitle,
agent: ctx.agent,
}
const loadModel = async () => {
if (state.model) {
return {
model: state.model,
savedVariant,
boot: true,
info: await resolveModelInfo(ctx.sdk, ctx.directory, state.model),
}
}
const model = await waitForDefaultModel({
sdk: ctx.sdk,
directory: ctx.directory,
active: () => !footer.isClosed,
})
if (footer.isClosed) return
const [fallbackSavedVariant, info] = await Promise.all([
resolveSavedVariant(model),
resolveModelInfo(ctx.sdk, ctx.directory, model),
])
if (!model || state.model) {
return {
model: state.model,
savedVariant: undefined,
boot: false,
info,
}
}
state.model = model
return {
model,
savedVariant: fallbackSavedVariant,
boot: true,
info,
}
}
const shell = await (deps.createRuntimeLifecycle ?? createRuntimeLifecycle)({
directory: ctx.directory,
findFiles: (query) =>
ctx.sdk.file
.find({ query, type: "file", location: { directory: ctx.directory } })
.then((result) => result.data.map((file) => file.path))
.catch(() => []),
agents: [],
references: [],
sessionID: state.sessionID,
sessionTitle: state.sessionTitle,
getSessionID: () => state.sessionID,
first: session.first,
history: state.history,
agent: state.agent,
model: state.model,
variant: state.activeVariant,
tuiConfig: tuiConfigTask,
onPermissionReply: async (next) => {
if (state.demo?.permission(next)) {
return
}
log?.write("send.permission.reply", next)
await ctx.sdk.permission.reply({ sessionID: state.sessionID, ...next })
},
onQuestionReply: async (next) => {
if (state.demo?.questionReply(next)) {
return
}
await ctx.sdk.question.reply({
sessionID: state.sessionID,
requestID: next.requestID,
answers: next.answers ?? [],
})
},
onQuestionReject: async (next) => {
if (state.demo?.questionReject(next)) {
return
}
await ctx.sdk.question.reject({ sessionID: state.sessionID, ...next })
},
onCycleVariant: () => {
if (!state.model || state.variants.length === 0) {
return {
status: "no variants available",
}
}
state.activeVariant = cycleVariant(state.activeVariant, state.variants)
saveVariant(state.model, state.activeVariant)
return {
status: state.activeVariant ? `variant ${state.activeVariant}` : "variant default",
modelLabel: formatModelLabel(state.model, state.activeVariant, state.providers),
variant: state.activeVariant,
}
},
onModelSelect: async (model) => {
if (state.model?.providerID === model.providerID && state.model.modelID === model.modelID) {
return
}
state.model = model
state.activeVariant = undefined
state.variants = variantsFor(state.providers, model)
const switching = resolveSavedVariant(model).then((saved) => {
const current = state.model
if (!current || current.providerID !== model.providerID || current.modelID !== model.modelID) {
return
}
state.activeVariant = resolveVariant(ctx.variant, undefined, saved, state.variants)
})
state.switching = switching
await switching
if (state.switching === switching) {
state.switching = undefined
}
const current = state.model
if (!current || current.providerID !== model.providerID || current.modelID !== model.modelID) {
return
}
return {
modelLabel: formatModelLabel(model, state.activeVariant, state.providers),
status: `model ${model.modelID}`,
variant: state.activeVariant,
variants: state.variants,
}
},
onVariantSelect: async (variant) => {
if (!state.model || state.variants.length === 0) {
return {
status: "no variants available",
}
}
if (variant && !state.variants.includes(variant)) {
return {
status: `variant ${variant} unavailable`,
}
}
state.activeVariant = variant
saveVariant(state.model, state.activeVariant)
return {
status: state.activeVariant ? `variant ${state.activeVariant}` : "variant default",
modelLabel: formatModelLabel(state.model, state.activeVariant, state.providers),
variant: state.activeVariant,
variants: state.variants,
}
},
onInterrupt: () => {
if (!hasSession(input, state) || state.aborting) {
return false
}
state.aborting = true
void (
state.stream
? state.stream.then((item) => item.handle.interruptActiveTurn())
: ctx.sdk.session.interrupt({ sessionID: state.sessionID })
)
.catch(() => {})
.finally(() => {
state.aborting = false
})
return true
},
onBackground: () => {
if (!hasSession(input, state)) {
return
}
log?.write("send.background", { sessionID: state.sessionID })
void ctx.sdk.session.background({ sessionID: state.sessionID }).catch(() => {})
},
onSubagentInterrupt: (sessionID) => {
log?.write("send.subagent.interrupt", { sessionID })
void ctx.sdk.session.interrupt({ sessionID }).catch(() => {})
},
onSubagentSelect: (sessionID) => {
state.selectSubagent?.(sessionID)
log?.write("subagent.select", {
sessionID,
})
},
})
const footer = shell.footer
const firstPaint = footer.idle().catch(() => {})
const ensureSession = () => {
if (!input.resolveSession || state.sessionID) {
return Promise.resolve()
}
if (state.session) {
return state.session
}
state.session = input.resolveSession(ctx).then(async (next) => {
state.sessionID = next.sessionID
state.sessionTitle = next.sessionTitle ?? state.sessionTitle
state.agent = next.agent
if (!next.resume) return
const resumed = await resolveSessionInfo(ctx.sdk, next.sessionID, ctx.model)
session.first = resumed.first
session.history = resumed.history
session.model = resumed.model
session.variant = resumed.variant
state.shown = !resumed.first
state.history = [...resumed.history]
state.model = ctx.model ?? resumed.model
const resumedSavedVariant = state.model ? await resolveSavedVariant(state.model) : undefined
state.activeVariant = resolveVariant(ctx.variant, resumed.variant, resumedSavedVariant, [])
session.variant = state.activeVariant
footer.event({ type: "history", history: resumed.history })
footer.event({ type: "first", first: resumed.first })
})
return state.session
}
const modelTask = firstPaint.then(async () => {
if (footer.isClosed) return
await ensureSession()
if (footer.isClosed) return
return loadModel()
})
const rememberLocal = (commit: StreamCommit, after?: LocalReplayAnchor) => {
state.localRows = [...state.localRows, { commit, after }].slice(-LOCAL_REPLAY_ROW_LIMIT)
}
const applyCatalog = (catalog: {
agents: Awaited<ReturnType<typeof loadRunAgents>>
references: Awaited<ReturnType<typeof loadRunReferences>>
commands: Awaited<ReturnType<typeof loadRunCommands>>
}) => {
if (footer.isClosed) {
return
}
footer.event({
type: "catalog",
agents: catalog.agents,
references: catalog.references,
commands: catalog.commands,
})
}
const fetchCatalog = async () => {
const [agents, references, commands] = await Promise.all([
loadRunAgents(ctx.sdk, ctx.directory),
loadRunReferences(ctx.sdk, ctx.directory),
loadRunCommands(ctx.sdk, ctx.directory),
])
return { agents, references, commands }
}
const loadCatalog = async () => {
applyCatalog(
await Promise.all([
loadRunAgents(ctx.sdk, ctx.directory).catch(() => []),
loadRunReferences(ctx.sdk, ctx.directory).catch(() => []),
loadRunCommands(ctx.sdk, ctx.directory).catch(() => []),
]).then(([agents, references, commands]) => ({ agents, references, commands })),
)
}
const applyModelInfo = (
info: Awaited<ReturnType<typeof resolveModelInfo>>,
current: string | undefined,
boot = false,
saved = savedVariant,
) => {
state.providers = info.providers
state.variants = variantsFor(state.providers, state.model)
state.limits = info.limits
state.activeVariant = boot
? resolveVariant(ctx.variant, current, saved, state.variants)
: current && !state.variants.includes(current)
? undefined
: current
if (footer.isClosed) return
footer.event({ type: "models", providers: info.providers })
footer.event({ type: "variants", variants: state.variants, current: state.activeVariant })
if (state.model)
footer.event({
type: "model",
model: formatModelLabel(state.model, state.activeVariant, state.providers),
selection: state.model,
})
}
let catalogRefresh: Promise<void> | undefined
let catalogRefreshQueued = false
const requestCatalogRefresh = () => {
catalogRefreshQueued = true
if (catalogRefresh || footer.isClosed) return
catalogRefresh = (async () => {
await Promise.all([modelTask, initialCatalog])
while (catalogRefreshQueued && !footer.isClosed) {
catalogRefreshQueued = false
const [catalog, info] = await Promise.allSettled([
fetchCatalog(),
resolveModelInfoStrict(ctx.sdk, ctx.directory, state.model),
])
if (catalog.status === "fulfilled") applyCatalog(catalog.value)
if (info.status === "fulfilled") applyModelInfo(info.value, state.activeVariant)
}
})().finally(() => {
catalogRefresh = undefined
if (catalogRefreshQueued) requestCatalogRefresh()
})
void catalogRefresh.catch(() => {})
}
const initialCatalog = firstPaint.then(() => (footer.isClosed ? undefined : loadCatalog())).catch(() => {})
void initialCatalog
if (Flag.OPENCODE_SHOW_TTFD) {
void firstPaint.then(() => {
if (footer.isClosed) return
footer.append({
kind: "system",
text: `startup ${Math.max(0, Math.round(performance.now() - start))}ms`,
phase: "final",
source: "system",
})
})
}
const createDemo = async () => {
const { createRunDemo } = await import("./demo")
return createRunDemo({
footer,
sessionID: state.sessionID,
thinking: input.thinking,
})
}
if (input.demo) {
await firstPaint
if (!footer.isClosed) {
await ensureSession()
state.demo = await createDemo()
}
}
if (input.afterPaint) {
void firstPaint.then(() => (footer.isClosed ? undefined : input.afterPaint?.(ctx))).catch(() => {})
}
void modelTask.then((result) => {
if (!result) return
const current = state.model
const boot =
result.boot &&
!!current &&
current.providerID === result.model?.providerID &&
current.modelID === result.model.modelID
applyModelInfo(result.info, boot ? session.variant : state.activeVariant, boot, result.savedVariant)
})
let streamTask = deps.streamTransport
const loadStreamTransport = () => {
if (streamTask) return streamTask
streamTask = import("./stream-v2.transport")
return streamTask
}
const ensureStream = () => {
if (state.stream) {
return state.stream
}
// Share eager prewarm and first-turn boot through one in-flight promise,
// but clear it if transport creation fails so a later prompt can retry.
const next = (async () => {
await ensureSession()
if (footer.isClosed) {
throw new Error("runtime closed")
}
const mod = await loadStreamTransport()
if (footer.isClosed) {
throw new Error("runtime closed")
}
const handle = await mod.createSessionTransport({
sdk: ctx.sdk,
directory: ctx.directory,
sessionID: state.sessionID,
thinking: input.thinking,
replay: input.replay,
replayLimit: input.replayLimit,
limits: () => state.limits,
providers: () => state.providers,
footer,
trace: log,
onCatalogRefresh: requestCatalogRefresh,
})
if (footer.isClosed) {
await handle.close()
throw new Error("runtime closed")
}
state.selectSubagent = (sessionID) => handle.selectSubagent(sessionID)
return { mod, handle }
})()
state.stream = next
void next.catch(() => {
if (state.stream === next) {
state.stream = undefined
}
})
return next
}
let resizeTimer: ReturnType<typeof setTimeout> | undefined
const offResize = shell.onResize(() => {
if (resizeTimer) {
clearTimeout(resizeTimer)
}
resizeTimer = setTimeout(() => {
resizeTimer = undefined
if (footer.isClosed) {
return
}
shell.refreshTheme()
if (!input.replay || !state.stream) {
return
}
void state.stream
.then((item) =>
item.handle.replayOnResize({
localRows: () => state.localRows,
reset: () =>
shell.resetForReplay({
sessionTitle: state.sessionTitle,
sessionID: state.sessionID,
history: state.history,
}),
}),
)
.catch(() => {})
}, RESIZE_DELAY)
})
const runQueue = async () => {
await firstPaint
if (footer.isClosed) return
await ensureSession()
if (footer.isClosed) return
await modelTask
if (footer.isClosed) return
let includeFiles = true
if (state.demo) {
await state.demo.start()
}
const mod = await import("./runtime.queue")
const createSession = input.createSession
await mod.runPromptQueue({
footer,
initialInput: input.initialInput,
trace: log,
onSend: (prompt) => {
state.shown = true
state.history.push(prompt)
if (prompt.mode !== "shell") {
rememberLocal({
kind: "user",
text: prompt.text,
phase: "start",
source: "system",
messageID: prompt.messageID,
})
}
},
onNewSession: createSession
? async () => {
try {
await state.switching?.catch(() => {})
const created = await createSession(ctx, {
agent: state.agent,
model: state.model,
variant: state.activeVariant,
})
await footer.idle().catch(() => {})
await state.stream?.then((item) => item.handle.close()).catch(() => {})
state.stream = undefined
state.session = undefined
state.selectSubagent = undefined
state.shown = false
state.sessionID = created.sessionID
state.sessionTitle = created.sessionTitle
state.agent = created.agent ?? state.agent
state.history = []
state.localRows = []
includeFiles = true
state.demo = input.demo ? await createDemo() : undefined
log?.write("session.new", {
sessionID: state.sessionID,
})
footer.event({
type: "stream.subagent",
state: {
tabs: [],
details: {},
permissions: [],
questions: [],
},
})
footer.event({ type: "stream.view", view: { type: "prompt" } })
footer.event({
type: "stream.patch",
patch: {
phase: "idle",
duration: "",
usage: "",
first: true,
},
})
footer.append({
kind: "system",
text: `new session ${state.sessionID}`,
phase: "final",
source: "system",
})
await state.demo?.start()
} catch (error) {
footer.event({
type: "stream.patch",
patch: {
phase: "idle",
status: "failed to start new session",
},
})
const commit = {
kind: "error",
text: error instanceof Error ? error.message : String(error),
phase: "start",
source: "system",
messageID: SessionMessage.ID.create(),
} as const
rememberLocal(commit)
footer.append(commit)
}
}
: undefined,
run: async (prompt, signal) => {
if (state.demo && (await state.demo.prompt(prompt, signal))) {
return
}
await state.switching?.catch(() => {})
let outputAnchor: LocalReplayAnchor | undefined
try {
const next = await ensureStream()
await next.handle.runPromptTurn({
agent: state.agent,
model: state.model,
variant: state.activeVariant,
prompt,
files: input.files,
includeFiles,
onVisibleOutput: (anchor) => {
outputAnchor = anchor
},
signal,
})
if (prompt.messageID) {
state.localRows = state.localRows.filter(
(row) => row.commit.kind !== "user" || row.commit.messageID !== prompt.messageID,
)
}
// Shell and skill turns never send CLI file attachments; keep them
// pending for the next prompt-shaped turn.
if (prompt.mode !== "shell" && prompt.command?.source !== "skill") includeFiles = false
} catch (error) {
if (signal.aborted || footer.isClosed) {
return
}
const text =
(await state.stream?.then((item) => item.mod).catch(() => undefined))?.formatUnknownError(error) ??
(error instanceof Error ? error.message : String(error))
const commit = {
kind: "error",
text,
phase: "start",
source: "system",
messageID: prompt.messageID,
} as const
rememberLocal(commit, outputAnchor)
footer.append(commit)
}
},
})
}
try {
const eager = eagerStream(input, ctx)
if (eager) {
await firstPaint
if (footer.isClosed) return
if (input.replay && state.shown) {
// Replay commits immutable scrollback rows, so wait for provider names
// before bootstrapping existing session history.
await modelTask
}
await ensureStream()
}
if (!eager && input.resolveSession) {
void firstPaint
.then(() => {
if (footer.isClosed) {
return
}
return ensureStream()
})
.catch(() => {})
}
try {
await runQueue()
} finally {
if (resizeTimer) {
clearTimeout(resizeTimer)
}
offResize()
await state.stream?.then((item) => item.handle.close()).catch(() => {})
}
} finally {
const title = await resolveExitTitle(ctx, input, state)
await shell.close({
showExit: state.shown && hasSession(input, state),
sessionTitle: title,
sessionID: state.sessionID,
history: state.history,
})
}
}
// Deferred mode paints before session resolution. The caller may back the
// generated client with a transport that is still acquiring a daemon.
export async function runInteractiveDeferredMode(input: RunDeferredInput, deps?: RunRuntimeDeps): Promise<void> {
const sdk = input.sdk
let session: Promise<ResolvedSession> | undefined
return runInteractiveRuntime(
{
files: input.files,
initialInput: input.initialInput,
thinking: input.thinking,
replay: input.replay,
replayLimit: input.replayLimit,
demo: input.demo,
tuiConfig: input.tuiConfig,
resolveSession: () => {
if (session) {
return session
}
session = Promise.all([input.resolveAgent(), input.session(sdk)]).then(([agent, next]) => {
if (!next?.id) {
throw new Error("Session not found")
}
return {
sessionID: next.id,
sessionTitle: next.title,
agent,
resume: next.resume,
}
})
return session
},
createSession: createSessionResolver(input.createSession),
boot: async () => {
return {
sdk,
directory: input.directory,
sessionID: "",
sessionTitle: undefined,
resume: false,
agent: input.agent,
model: input.model,
variant: input.variant,
}
},
},
deps,
)
}
// Attach mode. Uses the caller-provided SDK client directly.
export async function runInteractiveMode(
input: RunInput & { createSession?: CreateSession; tuiConfig?: RunTuiConfig | Promise<RunTuiConfig> },
deps?: RunRuntimeDeps,
): Promise<void> {
return runInteractiveRuntime(
{
files: input.files,
initialInput: input.initialInput,
thinking: input.thinking,
replay: input.replay,
replayLimit: input.replayLimit,
demo: input.demo,
tuiConfig: input.tuiConfig,
boot: async () => ({
sdk: input.sdk,
directory: input.directory,
sessionID: input.sessionID,
sessionTitle: input.sessionTitle,
resume: input.resume,
agent: input.agent,
model: input.model,
variant: input.variant,
}),
createSession: createSessionResolver(input.createSession),
},
deps,
)
}

View file

@ -1,88 +0,0 @@
import { SyntaxStyle, TextAttributes, type ColorInput } from "@opentui/core"
import { type RunEntryTheme, type RunTheme } from "./theme"
import type { StreamCommit } from "./types"
function syntax(style?: SyntaxStyle): SyntaxStyle {
return style ?? SyntaxStyle.fromTheme([])
}
export function entrySyntax(theme: RunTheme): SyntaxStyle {
return syntax(theme.block.syntax)
}
export function entryFailed(commit: StreamCommit): boolean {
return commit.kind === "tool" && (commit.toolState === "error" || commit.part?.state.status === "error")
}
export function entryLook(commit: StreamCommit, theme: RunEntryTheme): { fg: ColorInput; attrs?: number } {
if (commit.kind === "user") {
return {
fg: theme.user.body,
//attrs: TextAttributes.BOLD,
}
}
if (entryFailed(commit)) {
return {
fg: theme.error.body,
attrs: TextAttributes.BOLD,
}
}
if (commit.phase === "final") {
return {
fg: theme.system.body,
attrs: TextAttributes.DIM,
}
}
if (commit.kind === "tool" && commit.phase === "start") {
return {
fg: theme.tool.start ?? theme.tool.body,
}
}
if (commit.kind === "assistant") {
return { fg: theme.assistant.body }
}
if (commit.kind === "reasoning") {
return {
fg: theme.reasoning.body,
attrs: TextAttributes.DIM,
}
}
if (commit.kind === "error") {
return {
fg: theme.error.body,
attrs: TextAttributes.BOLD,
}
}
if (commit.kind === "tool") {
return { fg: theme.tool.body }
}
return { fg: theme.system.body }
}
export function entryColor(commit: StreamCommit, theme: RunTheme): ColorInput {
if (commit.kind === "assistant") {
return theme.entry.assistant.body
}
if (commit.kind === "reasoning") {
return theme.entry.reasoning.body
}
if (entryFailed(commit)) {
return theme.entry.error.body
}
if (commit.kind === "tool") {
return theme.block.text
}
return entryLook(commit, theme.entry).fg
}

View file

@ -1,432 +0,0 @@
// Retained streaming append logic for direct-mode scrollback.
//
// Static entries are rendered through `scrollback.writer.tsx`. This file only
// keeps the retained-surface machinery needed for streaming assistant,
// reasoning, and tool progress entries that need stable markdown/code layout
// while content is still arriving.
import {
CodeRenderable,
MarkdownRenderable,
TextRenderable,
getTreeSitterClient,
type TreeSitterClient,
type CliRenderer,
type ScrollbackSurface,
} from "@opentui/core"
import { entryBody, entryCanStream, entryDone, entryFlags } from "./entry.body"
import { entryColor, entryLook, entrySyntax } from "./scrollback.shared"
import { turnSummaryCommit } from "./turn-summary"
import { entryWriter, sameEntryGroup, separatorRows, spacerWriter, turnSummaryWriter } from "./scrollback.writer"
import { type RunTheme } from "./theme"
import type { RunDiffStyle, RunEntryBody, StreamCommit } from "./types"
type ActiveBody = Exclude<RunEntryBody, { type: "none" | "structured" }>
type ActiveEntry = {
body: ActiveBody
commit: StreamCommit
surface: ScrollbackSurface
renderable: TextRenderable | CodeRenderable | MarkdownRenderable
content: string
committedRows: number
committedBlocks: number
pendingSpacerRows: number
rendered: boolean
}
function commitMarkdownBlocks(input: {
surface: ScrollbackSurface
renderable: MarkdownRenderable
startBlock: number
endBlockExclusive: number
trailingNewline: boolean
beforeCommit?: () => void
}) {
if (input.endBlockExclusive <= input.startBlock) {
return false
}
const first = input.renderable._blockStates[input.startBlock]
const last = input.renderable._blockStates[input.endBlockExclusive - 1]
if (!first || !last) {
return false
}
const next = input.renderable._blockStates[input.endBlockExclusive]
const start = first.renderable.y
const end = next ? next.renderable.y : last.renderable.y + last.renderable.height
input.beforeCommit?.()
input.surface.commitRows(start, end, {
trailingNewline: input.trailingNewline,
})
return true
}
function staticBody(commit: StreamCommit, body: RunEntryBody, spaced: number): RunEntryBody {
if (spaced === 0 || body.type !== "text") {
return body
}
if (commit.kind !== "tool" || commit.phase !== "progress" || commit.toolState !== "completed") {
return body
}
if (!body.content.startsWith("\n")) {
return body
}
return {
...body,
content: body.content.replace(/^\n/, ""),
}
}
export class RunScrollbackStream {
private tail: StreamCommit | undefined
private rendered: StreamCommit | undefined
private active: ActiveEntry | undefined
private diffStyle: RunDiffStyle | undefined
private sessionID?: () => string | undefined
private treeSitterClient: TreeSitterClient | undefined
private wrote: boolean
private pendingThemes: RunTheme[] = []
constructor(
private renderer: CliRenderer,
private theme: RunTheme,
options: {
wrote?: boolean
diffStyle?: RunDiffStyle
sessionID?: () => string | undefined
treeSitterClient?: TreeSitterClient
onThemeRelease?: (theme: RunTheme) => void
} = {},
) {
this.diffStyle = options.diffStyle
this.sessionID = options.sessionID
this.treeSitterClient = options.treeSitterClient
this.wrote = options.wrote ?? false
this.onThemeRelease = options.onThemeRelease
}
private onThemeRelease: ((theme: RunTheme) => void) | undefined
private releasePendingThemes(): void {
if (this.pendingThemes.length === 0) {
return
}
for (const theme of this.pendingThemes.splice(0)) this.onThemeRelease?.(theme)
}
public setTheme(theme: RunTheme): void {
if (this.theme === theme) {
return
}
const previous = this.theme
this.theme = theme
const active = this.active
if (!active) {
this.onThemeRelease?.(previous)
return
}
this.pendingThemes.push(previous)
const style = entryLook(active.commit, theme.entry)
if (active.renderable instanceof TextRenderable) {
active.renderable.fg = style.fg
active.renderable.attributes = style.attrs ?? 0
return
}
active.renderable.fg = entryColor(active.commit, theme)
active.renderable.syntaxStyle = entrySyntax(theme)
}
private createEntry(commit: StreamCommit, body: ActiveBody): ActiveEntry {
const surface = this.renderer.createScrollbackSurface({
startOnNewLine: entryFlags(commit).startOnNewLine,
})
const style = entryLook(commit, this.theme.entry)
const treeSitterClient = body.type === "text" ? undefined : (this.treeSitterClient ??= getTreeSitterClient())
const renderable =
body.type === "text"
? new TextRenderable(surface.renderContext, {
content: "",
width: "100%",
wrapMode: "word",
fg: style.fg,
attributes: style.attrs,
})
: body.type === "code"
? new CodeRenderable(surface.renderContext, {
content: "",
filetype: body.filetype,
syntaxStyle: entrySyntax(this.theme),
width: "100%",
wrapMode: "word",
drawUnstyledText: false,
streaming: true,
fg: entryColor(commit, this.theme),
treeSitterClient,
})
: new MarkdownRenderable(surface.renderContext, {
content: "",
syntaxStyle: entrySyntax(this.theme),
width: "100%",
streaming: true,
internalBlockMode: "top-level",
tableOptions: { widthMode: "content" },
fg: entryColor(commit, this.theme),
treeSitterClient,
})
surface.root.add(renderable)
const rows = separatorRows(this.rendered, commit, body)
return {
body,
commit,
surface,
renderable,
content: "",
committedRows: 0,
committedBlocks: 0,
pendingSpacerRows: rows || (!this.rendered && this.wrote ? 1 : 0),
rendered: false,
}
}
private markRendered(commit: StreamCommit | undefined): void {
if (!commit) {
return
}
this.rendered = commit
}
private writeSpacer(rows: number): void {
if (rows === 0) {
return
}
this.renderer.writeToScrollback(spacerWriter())
this.wrote = false
}
private flushPendingSpacer(active: ActiveEntry): void {
this.writeSpacer(active.pendingSpacerRows)
active.pendingSpacerRows = 0
}
private async flushActive(done: boolean, trailingNewline: boolean): Promise<boolean> {
const active = this.active
if (!active) {
return false
}
if (active.body.type === "text") {
if (!(active.renderable instanceof TextRenderable)) {
return false
}
const renderable = active.renderable
renderable.content = active.content
active.surface.render()
this.releasePendingThemes()
const targetRows = done ? active.surface.height : Math.max(active.committedRows, active.surface.height - 1)
if (targetRows <= active.committedRows) {
return false
}
this.flushPendingSpacer(active)
active.surface.commitRows(active.committedRows, targetRows, {
trailingNewline: done && targetRows === active.surface.height ? trailingNewline : false,
})
active.committedRows = targetRows
active.rendered = true
return true
}
if (active.body.type === "code") {
if (!(active.renderable instanceof CodeRenderable)) {
return false
}
const renderable = active.renderable
renderable.content = active.content
renderable.streaming = !done
await active.surface.settle()
this.releasePendingThemes()
const targetRows = done ? active.surface.height : Math.max(active.committedRows, active.surface.height - 1)
if (targetRows <= active.committedRows) {
return false
}
this.flushPendingSpacer(active)
active.surface.commitRows(active.committedRows, targetRows, {
trailingNewline: done && targetRows === active.surface.height ? trailingNewline : false,
})
active.committedRows = targetRows
active.rendered = true
return true
}
if (!(active.renderable instanceof MarkdownRenderable)) {
return false
}
const renderable = active.renderable
renderable.content = active.content
renderable.streaming = !done
await active.surface.settle()
this.releasePendingThemes()
const targetBlockCount = done ? renderable._blockStates.length : renderable._stableBlockCount
if (targetBlockCount <= active.committedBlocks) {
return false
}
if (
commitMarkdownBlocks({
surface: active.surface,
renderable,
startBlock: active.committedBlocks,
endBlockExclusive: targetBlockCount,
trailingNewline: done && targetBlockCount === renderable._blockStates.length ? trailingNewline : false,
beforeCommit: () => this.flushPendingSpacer(active),
})
) {
active.committedBlocks = targetBlockCount
active.rendered = true
return true
}
return false
}
private async finishActive(trailingNewline: boolean): Promise<StreamCommit | undefined> {
if (!this.active) {
return undefined
}
const active = this.active
try {
await this.flushActive(true, trailingNewline)
} finally {
if (this.active === active) {
this.active = undefined
}
if (!active.surface.isDestroyed) {
active.surface.destroy()
}
this.releasePendingThemes()
}
return active.rendered ? active.commit : undefined
}
private async writeStreaming(commit: StreamCommit, body: ActiveBody): Promise<void> {
if (!this.active || !sameEntryGroup(this.active.commit, commit) || this.active.body.type !== body.type) {
this.markRendered(await this.finishActive(false))
this.active = this.createEntry(commit, body)
}
this.active.body = body
this.active.commit = commit
this.active.content += body.content
await this.flushActive(false, false)
if (this.active.rendered) {
this.markRendered(this.active.commit)
}
}
public async append(commit: StreamCommit): Promise<void> {
const same = sameEntryGroup(this.tail, commit)
if (!same) {
this.markRendered(await this.finishActive(false))
}
if (commit.summary) {
this.writeSpacer(1)
this.renderer.writeToScrollback(turnSummaryWriter({ ...commit.summary, theme: this.theme }))
this.markRendered(commit)
this.tail = commit
return
}
const body = entryBody(commit)
if (body.type === "none") {
if (entryDone(commit)) {
this.markRendered(await this.finishActive(false))
}
this.tail = commit
return
}
if (
body.type !== "structured" &&
(entryCanStream(commit, body) || (commit.kind === "tool" && commit.phase === "final" && body.type === "markdown"))
) {
await this.writeStreaming(commit, body)
if (entryDone(commit)) {
this.markRendered(await this.finishActive(false))
}
this.tail = commit
return
}
if (same) {
this.markRendered(await this.finishActive(false))
}
const rows = separatorRows(this.rendered, commit, body)
const spaced = rows || (!this.rendered && this.wrote ? 1 : 0)
this.writeSpacer(spaced)
this.renderer.writeToScrollback(
entryWriter({
commit,
body: staticBody(commit, body, spaced),
theme: this.theme,
opts: {
diffStyle: this.diffStyle,
},
}),
)
this.markRendered(commit)
this.tail = commit
}
private resetActive(): void {
if (!this.active) {
return
}
if (!this.active.surface.isDestroyed) {
this.active.surface.destroy()
}
this.active = undefined
this.releasePendingThemes()
}
public async complete(trailingNewline = false): Promise<void> {
this.markRendered(await this.finishActive(trailingNewline))
}
public async writeTurnSummary(input: { agent: string; model: string; duration: string }): Promise<void> {
await this.append(turnSummaryCommit(input))
}
public destroy(): void {
this.resetActive()
this.releasePendingThemes()
}
}

View file

@ -1,308 +0,0 @@
import { createScrollbackWriter } from "@opentui/solid"
import { TextRenderable, type ColorInput, type ScrollbackRenderContext, type ScrollbackWriter } from "@opentui/core"
import { Match, Switch, createMemo } from "solid-js"
import { entryBody, entryFlags } from "./entry.body"
import { entryColor, entryLook, entrySyntax } from "./scrollback.shared"
import { toolFiletype, toolStructuredFinal } from "./tool"
import { RUN_THEME_FALLBACK, transparent, type RunTheme } from "./theme"
import type { EntryLayout, RunEntryBody, ScrollbackOptions, StreamCommit } from "./types"
export function entryGroupKey(commit: StreamCommit): string | undefined {
if (!commit.partID) {
return undefined
}
if (toolStructuredFinal(commit)) {
return `tool:${commit.partID}:final`
}
return `${commit.kind}:${commit.partID}`
}
export function sameEntryGroup(left: StreamCommit | undefined, right: StreamCommit): boolean {
if (!left) {
return false
}
const current = entryGroupKey(left)
const next = entryGroupKey(right)
return Boolean(current && next && current === next)
}
export function entryLayout(commit: StreamCommit, body: RunEntryBody = entryBody(commit)): EntryLayout {
if (commit.kind === "tool") {
if (body.type === "structured" || body.type === "markdown") {
return "block"
}
if (
commit.phase === "progress" &&
commit.toolState === "completed" &&
body.type === "text" &&
body.content.includes("\n")
) {
return "block"
}
return "inline"
}
if (commit.kind === "reasoning") {
return "block"
}
if (commit.kind === "error") {
return "block"
}
return "block"
}
export function separatorRows(
prev: StreamCommit | undefined,
next: StreamCommit,
body: RunEntryBody = entryBody(next),
): number {
if (!prev || sameEntryGroup(prev, next)) {
return 0
}
if (entryLayout(prev) === "inline" && entryLayout(next, body) === "inline") {
return 0
}
return 1
}
export function RunEntryContent(props: {
commit: StreamCommit
body?: RunEntryBody
theme?: RunTheme
opts?: ScrollbackOptions
width?: number
}) {
const theme = createMemo(() => props.theme ?? RUN_THEME_FALLBACK)
const body = createMemo(() => props.body ?? entryBody(props.commit))
const style = createMemo(() => entryLook(props.commit, theme().entry))
const syntax = createMemo(() => entrySyntax(theme()))
const color = createMemo(() => entryColor(props.commit, theme()))
const suppressBackgrounds = createMemo(() => props.opts?.suppressBackgrounds === true)
const diffBg = (color: ColorInput) => (suppressBackgrounds() ? transparent : color)
const streaming = createMemo(() => props.commit.phase === "progress")
const text = createMemo(() => {
const next = body()
return next.type === "text" ? next : undefined
})
const code = createMemo(() => {
const next = body()
return next.type === "code" ? next : undefined
})
const structured = createMemo(() => {
const next = body()
return next.type === "structured" ? next.snapshot : undefined
})
const markdown = createMemo(() => {
const next = body()
return next.type === "markdown" ? next : undefined
})
const code_snapshot = createMemo(() => {
const next = structured()
return next?.kind === "code" ? next : undefined
})
const diff_snapshot = createMemo(() => {
const next = structured()
return next?.kind === "diff" ? next : undefined
})
const task_snapshot = createMemo(() => {
const next = structured()
return next?.kind === "task" ? next : undefined
})
const question_snapshot = createMemo(() => {
const next = structured()
return next?.kind === "question" ? next : undefined
})
return (
<Switch fallback={null}>
<Match when={text()}>
<text width="100%" wrapMode="word" fg={style().fg} attributes={style().attrs}>
{text()!.content}
</text>
</Match>
<Match when={code()}>
<code
width="100%"
wrapMode="word"
filetype={code()!.filetype}
drawUnstyledText={false}
streaming={streaming()}
syntaxStyle={syntax()}
content={code()!.content}
fg={color()}
/>
</Match>
<Match when={code_snapshot()}>
<box width="100%" flexDirection="column" gap={1}>
<text width="100%" wrapMode="word" fg={theme().block.muted}>
{code_snapshot()!.title}
</text>
<box width="100%" paddingLeft={1}>
<line_number width="100%" fg={theme().block.muted} minWidth={3} paddingRight={1}>
<code
width="100%"
wrapMode="char"
filetype={toolFiletype(code_snapshot()!.file)}
streaming={false}
syntaxStyle={syntax()}
content={code_snapshot()!.content}
fg={theme().block.text}
/>
</line_number>
</box>
</box>
</Match>
<Match when={diff_snapshot()}>
<box width="100%" flexDirection="column" gap={1}>
{diff_snapshot()!.items.map((item) => (
<box width="100%" flexDirection="column" gap={1}>
<text width="100%" wrapMode="word" fg={theme().block.muted}>
{item.title}
</text>
{item.diff.trim() ? (
<box width="100%" paddingLeft={1}>
<diff
diff={item.diff}
view="unified"
filetype={toolFiletype(item.file)}
syntaxStyle={syntax()}
showLineNumbers={true}
width="100%"
wrapMode="word"
fg={theme().block.text}
addedBg={diffBg(theme().block.diffAddedBg)}
removedBg={diffBg(theme().block.diffRemovedBg)}
contextBg={diffBg(theme().block.diffContextBg)}
addedSignColor={theme().block.diffHighlightAdded}
removedSignColor={theme().block.diffHighlightRemoved}
lineNumberFg={theme().block.diffLineNumber}
lineNumberBg={diffBg(theme().block.diffContextBg)}
addedLineNumberBg={diffBg(theme().block.diffAddedLineNumberBg)}
removedLineNumberBg={diffBg(theme().block.diffRemovedLineNumberBg)}
/>
</box>
) : (
<text width="100%" wrapMode="word" fg={theme().block.diffRemoved}>
-{item.deletions ?? 0} line{item.deletions === 1 ? "" : "s"}
</text>
)}
</box>
))}
</box>
</Match>
<Match when={task_snapshot()}>
<box width="100%" flexDirection="column" gap={1}>
<text width="100%" wrapMode="word" fg={theme().block.muted}>
{task_snapshot()!.title}
</text>
<box width="100%" flexDirection="column" gap={0} paddingLeft={1}>
{task_snapshot()!.rows.map((row) => (
<text width="100%" wrapMode="word" fg={theme().block.text}>
{row}
</text>
))}
{task_snapshot()!.tail ? (
<text width="100%" wrapMode="word" fg={theme().block.muted}>
{task_snapshot()!.tail}
</text>
) : null}
</box>
</box>
</Match>
<Match when={question_snapshot()}>
<box width="100%" flexDirection="column" gap={1}>
<text width="100%" wrapMode="word" fg={theme().block.muted}>
# Questions
</text>
<box width="100%" flexDirection="column" gap={1}>
{question_snapshot()!.items.map((item) => (
<box width="100%" flexDirection="column" gap={0}>
<text width="100%" wrapMode="word" fg={theme().block.muted}>
{item.question}
</text>
<text width="100%" wrapMode="word" fg={theme().block.text}>
{item.answer}
</text>
</box>
))}
{question_snapshot()!.tail ? (
<text width="100%" wrapMode="word" fg={theme().block.muted}>
{question_snapshot()!.tail}
</text>
) : null}
</box>
</box>
</Match>
<Match when={markdown()}>
<markdown
width="100%"
syntaxStyle={syntax()}
streaming={streaming()}
content={markdown()!.content}
fg={color()}
tableOptions={{ widthMode: "content" }}
/>
</Match>
</Switch>
)
}
export function entryWriter(input: {
commit: StreamCommit
body?: RunEntryBody
theme?: RunTheme
opts?: ScrollbackOptions
}): ScrollbackWriter {
return createScrollbackWriter(
(ctx) => (
<RunEntryContent
commit={input.commit}
body={input.body}
theme={input.theme}
opts={{ ...input.opts, suppressBackgrounds: true }}
width={ctx.width}
/>
),
entryFlags(input.commit),
)
}
export function spacerWriter(): ScrollbackWriter {
return (ctx: ScrollbackRenderContext) => ({
root: new TextRenderable(ctx.renderContext, {
width: Math.max(1, Math.trunc(ctx.width)),
height: 1,
content: "",
}),
width: Math.max(1, Math.trunc(ctx.width)),
height: 1,
startOnNewLine: true,
trailingNewline: true,
})
}
export function turnSummaryWriter(input: { agent: string; model: string; duration: string; theme: RunTheme }) {
return createScrollbackWriter(
() => (
<box width="100%" height={1}>
<text wrapMode="none" truncate>
<span style={{ fg: input.theme.block.text }}>{input.agent}</span>
<span style={{ fg: input.theme.block.muted }}>
{" "}
· {input.model} · {input.duration}
</span>
</text>
</box>
),
{ startOnNewLine: true, trailingNewline: false },
)
}

View file

@ -1,17 +0,0 @@
import type { PermissionV2Request, QuestionV2Request } from "@opencode-ai/client/promise"
import type { FooterView } from "./types"
export function pickBlockerView(input: {
permission?: PermissionV2Request
question?: QuestionV2Request
}): FooterView {
if (input.permission) return { type: "permission", request: input.permission }
if (input.question) return { type: "question", request: input.question }
return { type: "prompt" }
}
export function blockerStatus(view: FooterView) {
if (view.type === "permission") return "awaiting permission"
if (view.type === "question") return "awaiting answer"
return ""
}

View file

@ -1,101 +0,0 @@
import type { SessionMessageInfo, SessionMessageUser } from "@opencode-ai/client/promise"
import { promptCopy, promptSame } from "./prompt.shared"
import type { RunInput, RunPrompt } from "./types"
const LIMIT = 200
export type SessionMessages = SessionMessageInfo[]
type Turn = {
prompt: RunPrompt
provider: string | undefined
model: string | undefined
variant: string | undefined
}
export type RunSession = {
first: boolean
turns: Turn[]
model?: NonNullable<RunInput["model"]>
variant?: string
}
function messagePrompt(message: SessionMessageUser): RunPrompt {
return {
text: message.text,
parts: [
...(message.files ?? []).map((file) => ({
type: "file" as const,
url: file.source.type === "uri" ? file.source.uri : `data:${file.mime};base64,${file.data}`,
mime: file.mime,
filename: file.name,
source: file.mention
? {
type: "file",
path: file.name ?? (file.source.type === "uri" ? file.source.uri : "inline attachment"),
text: { start: file.mention.start, end: file.mention.end, value: file.mention.text },
}
: undefined,
})),
...(message.agents ?? []).map((agent) => ({
type: "agent" as const,
name: agent.name,
source: agent.mention
? { start: agent.mention.start, end: agent.mention.end, value: agent.mention.text }
: undefined,
})),
],
}
}
export function createSession(messages: SessionMessages): RunSession {
return {
first: messages.length === 0,
turns: messages.flatMap((message) =>
message.type === "user"
? [{ prompt: messagePrompt(message), provider: undefined, model: undefined, variant: undefined }]
: [],
),
}
}
export async function resolveCurrentSession(
sdk: RunInput["sdk"],
sessionID: string,
limit = LIMIT,
): Promise<RunSession> {
const [response, session] = await Promise.all([
sdk.message.list({ sessionID, limit, order: "desc" }),
sdk.session.get({ sessionID }),
])
const current = createSession(response.data.toReversed())
return {
...current,
turns: current.turns.map((turn) => ({
...turn,
provider: session.model?.providerID,
model: session.model?.id,
variant: session.model?.variant,
})),
...(session.model && {
model: { providerID: session.model.providerID, modelID: session.model.id },
variant: session.model.variant,
}),
}
}
export function sessionHistory(session: RunSession, limit = LIMIT): RunPrompt[] {
return session.turns
.map((turn) => turn.prompt)
.filter((prompt) => prompt.text.trim())
.filter((prompt, index, prompts) => index === 0 || !promptSame(prompts[index - 1], prompt))
.map(promptCopy)
.slice(-limit)
}
export function sessionVariant(session: RunSession, model: RunInput["model"]): string | undefined {
if (!model) return
if (session.model?.providerID === model.providerID && session.model.modelID === model.modelID) return session.variant
return session.turns.findLast((turn) => turn.provider === model.providerID && turn.model === model.modelID)?.variant
}

View file

@ -1,280 +0,0 @@
// Entry and exit splash banners for direct interactive mode scrollback.
//
// Renders the full opencode entry logo and a compact [O] exit badge, plus
// session metadata and the resume command. These are scrollback snapshots, so
// they become immutable terminal history once committed.
//
// Both variants use a cell-based renderer. cells() classifies each character
// in the source template as text, full-block, half-block-mix, or
// half-block-top, and draw() renders it with foreground/background shadow
// colors from the theme.
import {
BoxRenderable,
type ColorInput,
TextAttributes,
TextRenderable,
type ScrollbackRenderContext,
type ScrollbackSnapshot,
type ScrollbackWriter,
} from "@opentui/core"
import { Locale } from "@opencode-ai/tui/util/locale"
import { go } from "@opencode-ai/tui/logo"
import type { RunSplashTheme } from "./theme"
export const SPLASH_TITLE_LIMIT = 50
export const SPLASH_TITLE_FALLBACK = "Untitled session"
type SplashInput = {
title: string | undefined
session_id: string
}
type SplashWriterInput = SplashInput & {
theme: RunSplashTheme
showSession?: boolean
detail?: string
}
export type SplashMeta = {
title: string
session_id: string
}
type Cell = {
char: string
mark: "text" | "full" | "mix" | "top"
}
function cells(line: string): Cell[] {
const list: Cell[] = []
for (const char of line) {
if (char === "_") {
list.push({ char: " ", mark: "full" })
continue
}
if (char === "^") {
list.push({ char: "▀", mark: "mix" })
continue
}
if (char === "~") {
list.push({ char: "▀", mark: "top" })
continue
}
list.push({ char, mark: "text" })
}
return list
}
function title(text: string | undefined): string {
if (!text) {
return SPLASH_TITLE_FALLBACK
}
let value = ""
let gap = false
for (const char of text.trim()) {
if (char === " " || char === "\n" || char === "\r" || char === "\t") {
gap = true
continue
}
if (gap && value.length > 0) {
value += " "
}
value += char
gap = false
}
if (!value) {
return SPLASH_TITLE_FALLBACK
}
return Locale.truncate(value, SPLASH_TITLE_LIMIT)
}
function write(
root: BoxRenderable,
ctx: ScrollbackRenderContext,
line: {
left: number
top: number
text: string
fg: ColorInput
bg?: ColorInput
attrs?: number
},
): void {
if (line.left >= ctx.width) {
return
}
root.add(
new TextRenderable(ctx.renderContext, {
position: "absolute",
left: line.left,
top: line.top,
width: Math.max(1, ctx.width - line.left),
height: 1,
wrapMode: "none",
content: line.text,
fg: line.fg,
bg: line.bg,
attributes: line.attrs,
}),
)
}
function push(
lines: Array<{ left: number; top: number; text: string; fg: ColorInput; bg?: ColorInput; attrs?: number }>,
left: number,
top: number,
text: string,
fg: ColorInput,
bg?: ColorInput,
attrs?: number,
): void {
lines.push({ left, top, text, fg, bg, attrs })
}
function draw(
lines: Array<{ left: number; top: number; text: string; fg: ColorInput; bg?: ColorInput; attrs?: number }>,
row: string,
input: {
left: number
top: number
fg: ColorInput
shadow: ColorInput
attrs?: number
},
) {
let x = input.left
for (const cell of cells(row)) {
if (cell.mark === "full" || cell.mark === "mix") {
push(lines, x, input.top, cell.char, input.fg, input.shadow, input.attrs)
x += 1
continue
}
if (cell.mark === "top") {
push(lines, x, input.top, cell.char, input.shadow, undefined, input.attrs)
x += 1
continue
}
push(lines, x, input.top, cell.char, input.fg, undefined, input.attrs)
x += 1
}
}
function build(input: SplashWriterInput, kind: "entry" | "exit", ctx: ScrollbackRenderContext): ScrollbackSnapshot {
const width = Math.max(1, ctx.width)
const meta = splashMeta(input)
const lines: Array<{ left: number; top: number; text: string; fg: ColorInput; bg?: ColorInput; attrs?: number }> = []
const left = input.theme.left
const right = input.theme.right
const leftShadow = input.theme.leftShadow
let height = 1
if (kind === "entry") {
const mark = go.right.slice(1)
const top = 1
const body_left = (mark[0]?.length ?? 0) + 2
for (let i = 0; i < mark.length; i += 1) {
draw(lines, mark[i] ?? "", {
left: 0,
top: top + i,
fg: left,
shadow: leftShadow,
})
}
push(lines, body_left, top, "OpenCode", right, undefined, TextAttributes.BOLD)
if (input.detail) {
push(
lines,
body_left,
top + 1,
Locale.truncateMiddle(input.detail, Math.max(1, width - body_left)),
left,
undefined,
)
}
height = top + mark.length
}
if (kind === "exit") {
const mark = go.right.slice(1)
const top = 1
const body_left = (mark[0]?.length ?? 0) + 2
const session = "Session "
const label = "Continue "
for (let i = 0; i < mark.length; i += 1) {
draw(lines, mark[i] ?? "", {
left: 0,
top: top + i,
fg: left,
shadow: leftShadow,
})
}
if (input.showSession !== false) {
push(lines, body_left, top, session, left, undefined, TextAttributes.DIM)
push(lines, body_left + session.length, top, meta.title, right, undefined, TextAttributes.BOLD)
}
push(lines, body_left, top + 1, label, left, undefined, TextAttributes.DIM)
push(
lines,
body_left + label.length,
top + 1,
`opencode mini -s ${meta.session_id}`,
right,
undefined,
TextAttributes.BOLD,
)
height = top + mark.length
}
const root = new BoxRenderable(ctx.renderContext, {
position: "absolute",
left: 0,
top: 0,
width,
height,
})
for (const line of lines) {
write(root, ctx, line)
}
return {
root,
width,
height,
rowColumns: width,
startOnNewLine: true,
trailingNewline: false,
}
}
export function splashMeta(input: SplashInput): SplashMeta {
return {
title: title(input.title),
session_id: input.session_id,
}
}
export function entrySplash(input: SplashWriterInput): ScrollbackWriter {
return (ctx) => build(input, "entry", ctx)
}
export function exitSplash(input: SplashWriterInput): ScrollbackWriter {
return (ctx) => build(input, "exit", ctx)
}

View file

@ -1,783 +0,0 @@
// Current-native subagent (child Session) tracking for the mini transport.
//
// Discovers child Sessions of the active parent from four current sources:
// 1. projected subagent tool output (`structured.sessionID`) during hydration
// 2. the current session list filtered by `parentID` during hydration
// 3. the process-local active-session map during hydration
// 4. live events from unknown sessions whose `parentID` matches the parent
//
// Tracks one footer tab per child and a detail transcript for the selected
// child, reduced from the same current live event stream the parent uses.
// Detail transcripts rebuild from projected messages on discovery, selection,
// and reconnect, then continue from live deltas using the same
// projected-prefix dedup the parent transport uses.
//
// Per-child interruption uses `v2.session.interrupt(childID)`. Per-child
// backgrounding is intentionally absent: subagent jobs block the parent
// session, so only whole-session `v2.session.background(parentID)` exists.
import type {
EventSubscribeOutput,
OpenCodeClient,
SessionMessageAssistantTool,
SessionMessageInfo,
} from "@opencode-ai/client/promise"
import { Locale } from "@opencode-ai/tui/util/locale"
import type { FooterSubagentDetail, FooterSubagentState, FooterSubagentTab, MiniToolPart, StreamCommit } from "./types"
import { toolOutputText } from "./tool"
const CHILD_MESSAGE_LIMIT = 80
const CHILD_FRAME_LIMIT = 80
const CHILD_EVENT_BUFFER_LIMIT = 64
const FAMILY_LIST_LIMIT = 100
const FALLBACK_LABEL = "Subagent"
type V2Event = EventSubscribeOutput
export function miniTool(input: {
sessionID: string
messageID: string
tool: SessionMessageAssistantTool
}): MiniToolPart {
const tool = input.tool
const providerCall =
tool.executed === undefined && tool.providerState === undefined
? undefined
: { executed: tool.executed, state: tool.providerState }
const providerResult =
tool.executed === undefined && tool.providerResultState === undefined
? undefined
: { executed: tool.executed, state: tool.providerResultState }
const base = {
id: `prt_${tool.id}`,
sessionID: input.sessionID,
messageID: input.messageID,
type: "tool" as const,
callID: tool.id,
tool: tool.name,
}
if (tool.state.status === "streaming") {
return {
...base,
state: { status: "pending", input: {}, raw: tool.state.input },
}
}
if (tool.state.status === "running") {
return {
...base,
state: {
status: "running",
input: tool.state.input,
title: tool.name,
metadata: { structured: tool.state.structured, content: tool.state.content, providerCall },
time: { start: tool.time.ran ?? tool.time.created },
},
}
}
if (tool.state.status === "completed") {
return {
...base,
state: {
status: "completed",
input: tool.state.input,
output: toolOutputText(tool.name, tool.state.content),
title: tool.name,
metadata: {
structured: tool.state.structured,
content: tool.state.content,
result: tool.state.result,
providerCall,
providerResult,
},
time: { start: tool.time.ran ?? tool.time.created, end: tool.time.completed ?? tool.time.created },
},
}
}
return {
...base,
state: {
status: "error",
input: tool.state.input,
error: tool.state.error.message,
metadata: {
structured: tool.state.structured,
content: tool.state.content,
result: tool.state.result,
providerCall,
providerResult,
},
time: { start: tool.time.ran ?? tool.time.created, end: tool.time.completed ?? tool.time.created },
},
}
}
export function toolCommit(part: MiniToolPart, phase: "start" | "progress" | "final"): StreamCommit {
const status = part.state.status
const text =
status === "running"
? part.tool === "task"
? "running task"
: `running ${part.tool}`
: status === "completed"
? part.state.output
: status === "error"
? part.state.error
: ""
return {
kind: "tool",
source: "tool",
text,
phase,
messageID: part.messageID,
partID: part.id,
tool: part.tool,
part,
toolState: status === "error" ? "error" : status === "completed" ? "completed" : "running",
toolError: status === "error" ? part.state.error : undefined,
}
}
type Frame = {
key: string
commit: StreamCommit
}
type ToolTrack = {
name: string
input: Record<string, unknown>
started: number
providerState?: Record<string, unknown>
}
type ChildState = {
sessionID: string
label: string
description: string
status: FooterSubagentTab["status"]
background: boolean
title?: string
callIDs: Set<string>
lastUpdatedAt: number
frames: Frame[]
text: Map<string, string>
projectedText: Map<string, string>
reasoning: Map<string, string>
projectedReasoning: Map<string, string>
tools: Map<string, ToolTrack>
finishedTools: Set<string>
messageIDs: Set<string>
prompts: Map<string, string>
hydrated: boolean
}
export type SubagentTrackerInput = {
sdk: OpenCodeClient
sessionID: string
thinking: boolean
emit: () => void
}
export type SubagentTracker = {
main(event: V2Event): void
foreign(sessionID: string, event: V2Event): void
hydrate(next: { messages: SessionMessageInfo[]; active: Record<string, unknown> }): Promise<void>
select(sessionID: string | undefined): void
snapshot(): FooterSubagentState
}
function record(value: unknown): Record<string, unknown> | undefined {
if (typeof value === "object" && value !== null && !Array.isArray(value)) return value as Record<string, unknown>
return undefined
}
function text(value: unknown): string | undefined {
if (typeof value !== "string") return undefined
const next = value.trim()
return next || undefined
}
function childSessionID(structured: Record<string, unknown> | undefined) {
const sessionID = text(structured?.sessionID)
if (!sessionID || !sessionID.startsWith("ses")) return undefined
const status = structured?.status
if (status !== "running" && status !== "completed") return undefined
return { sessionID, running: status === "running" }
}
function tab(child: ChildState): FooterSubagentTab {
return {
sessionID: child.sessionID,
partID: `subagent:${child.sessionID}`,
callID: `subagent:${child.sessionID}`,
label: child.label,
description: child.description || child.title || "",
status: child.status,
background: child.background ? true : undefined,
title: child.title,
toolCalls: child.callIDs.size > 0 ? child.callIDs.size : undefined,
lastUpdatedAt: child.lastUpdatedAt,
}
}
export function createSubagentTracker(input: SubagentTrackerInput): SubagentTracker {
const children = new Map<string, ChildState>()
// Live subagent tool calls in the parent, so tool.success structured output
// can be joined with the call's input metadata.
const pendingCalls = new Map<string, Record<string, unknown>>()
// Foreign sessions already resolved through session.get. Non-children stay
// cached so unrelated concurrent sessions are checked at most once.
const checked = new Set<string>()
// Foreign events buffered while a session.get discovery is in flight, so a
// fast child (including its settled event) is not lost mid-discovery.
const pendingEvents = new Map<string, V2Event[]>()
const hydrationEvents = new Map<string, V2Event[]>()
const hydrationOverflow = new Set<string>()
const hydrations = new Map<string, Promise<void>>()
let selected: string | undefined
const fragmentKey = (messageID: string, partID: string) => `${messageID}\u0000${partID}`
const ensureChild = (sessionID: string): ChildState => {
const existing = children.get(sessionID)
const child: ChildState = existing ?? {
sessionID,
label: FALLBACK_LABEL,
description: "",
status: "running",
background: false,
callIDs: new Set(),
lastUpdatedAt: Date.now(),
frames: [],
text: new Map(),
projectedText: new Map(),
reasoning: new Map(),
projectedReasoning: new Map(),
tools: new Map(),
finishedTools: new Set(),
messageIDs: new Set(),
prompts: new Map(),
hydrated: false,
}
if (!existing) children.set(sessionID, child)
// Adopting a child while its session.get discovery is still in flight:
// drain the buffered events now. They arrived before whatever the caller
// applies next, so replaying them first preserves bus order, and the
// resolved discovery can no longer replay stale events (e.g. step.started)
// after a terminal settled event was applied directly.
const buffered = pendingEvents.get(sessionID)
if (buffered) {
pendingEvents.delete(sessionID)
for (const event of buffered) reduce(child, event)
}
return child
}
const touch = (child: ChildState, timestamp?: number) => {
child.lastUpdatedAt = Math.max(child.lastUpdatedAt, timestamp ?? Date.now())
}
const notifyDetail = (child: ChildState) => {
if (child.sessionID === selected) input.emit()
}
const setFrame = (child: ChildState, key: string, commit: StreamCommit) => {
const index = child.frames.findIndex((item) => item.key === key)
if (index === -1) {
child.frames.push({ key, commit })
if (child.frames.length > CHILD_FRAME_LIMIT) child.frames.splice(0, child.frames.length - CHILD_FRAME_LIMIT)
return
}
child.frames[index] = { key, commit }
}
const applyMeta = (child: ChildState, meta: Record<string, unknown> | undefined) => {
if (!meta) return
const agent = text(meta.agent)
if (agent) child.label = Locale.titlecase(agent)
const description = text(meta.description)
if (description) child.description = description
if (meta.background === true) child.background = true
}
const userFrame = (child: ChildState, messageID: string, value: string) => {
if (child.messageIDs.has(messageID)) return false
child.messageIDs.add(messageID)
setFrame(child, `user:${messageID}`, {
kind: "user",
source: "system",
text: value,
phase: "start",
messageID,
})
return true
}
const childTool = (child: ChildState, item: SessionMessageAssistantTool, messageID: string) => {
const part = miniTool({
sessionID: child.sessionID,
messageID,
tool: item,
})
if (item.state.status === "streaming") return
child.callIDs.add(item.id)
if (item.state.status === "running") {
setFrame(child, `tool:${item.id}`, toolCommit(part, "start"))
return
}
child.finishedTools.add(item.id)
child.tools.delete(item.id)
setFrame(child, `tool:${item.id}`, toolCommit(part, "final"))
}
const rebuild = (child: ChildState, messages: SessionMessageInfo[]) => {
child.frames = []
child.text.clear()
child.projectedText.clear()
child.reasoning.clear()
child.projectedReasoning.clear()
child.finishedTools.clear()
child.messageIDs.clear()
child.callIDs.clear()
for (const message of messages) {
if (message.type === "user") {
child.prompts.delete(message.id)
userFrame(child, message.id, message.text)
continue
}
if (message.type !== "assistant") continue
child.messageIDs.add(message.id)
let textOrdinal = 0
let reasoningOrdinal = 0
for (const item of message.content) {
if (item.type === "text") {
const id = `text:${textOrdinal++}`
const key = fragmentKey(message.id, id)
child.text.set(key, item.text)
child.projectedText.set(key, item.text)
setFrame(child, key, {
kind: "assistant",
source: "assistant",
text: item.text,
phase: "progress",
messageID: message.id,
partID: id,
})
continue
}
if (item.type === "reasoning") {
const id = `reasoning:${reasoningOrdinal++}`
const key = fragmentKey(message.id, id)
child.reasoning.set(key, item.text)
child.projectedReasoning.set(key, item.text)
if (input.thinking)
setFrame(child, key, {
kind: "reasoning",
source: "reasoning",
text: `Thinking: ${item.text}`,
phase: "progress",
messageID: message.id,
partID: id,
})
continue
}
childTool(child, item, message.id)
}
if (message.error) {
setFrame(child, `error:${message.id}`, {
kind: "error",
source: "system",
text: message.error.message,
phase: "start",
messageID: message.id,
})
}
}
}
const hydrateChild = (child: ChildState): Promise<void> => {
const existing = hydrations.get(child.sessionID)
if (existing) return existing
const pendingPrompts = new Map(child.prompts)
const pendingTools = new Map(child.tools)
let retry = false
const task = input.sdk.message
.list({ sessionID: child.sessionID, limit: CHILD_MESSAGE_LIMIT, order: "desc" })
.then((response) => {
const buffered = hydrationEvents.get(child.sessionID) ?? []
hydrationEvents.delete(child.sessionID)
if (hydrationOverflow.delete(child.sessionID)) {
child.hydrated = false
retry = true
notifyDetail(child)
return
}
for (const [id, prompt] of pendingPrompts) {
if (!child.prompts.has(id)) child.prompts.set(id, prompt)
}
rebuild(child, structuredClone(response.data).toReversed() as SessionMessageInfo[])
for (const [id, tool] of pendingTools) {
if (!child.finishedTools.has(id) && !child.tools.has(id)) child.tools.set(id, tool)
}
for (const event of buffered) reduce(child, event)
child.hydrated = true
notifyDetail(child)
})
.catch(() => {
hydrationEvents.delete(child.sessionID)
hydrationOverflow.delete(child.sessionID)
})
.finally(() => {
hydrations.delete(child.sessionID)
if (retry) queueMicrotask(() => void hydrateChild(child))
})
hydrations.set(child.sessionID, task)
return task
}
const discover = (sessionID: string) => {
if (checked.has(sessionID) || children.has(sessionID) || sessionID === input.sessionID) return
checked.add(sessionID)
if (!pendingEvents.has(sessionID)) pendingEvents.set(sessionID, [])
void input.sdk.session
.get({ sessionID })
.then((session) => {
const buffered = pendingEvents.get(sessionID) ?? []
pendingEvents.delete(sessionID)
if (session.parentID !== input.sessionID) return
const child = ensureChild(sessionID)
if (session.agent) child.label = Locale.titlecase(session.agent)
child.title = session.title
for (const event of buffered) reduce(child, event)
touch(child)
input.emit()
void hydrateChild(child)
})
.catch(() => {
// Allow a later event to retry discovery after transient failures.
pendingEvents.delete(sessionID)
checked.delete(sessionID)
})
}
const reduce = (child: ChildState, event: V2Event) => {
if (event.type === "session.input.admitted") {
if (event.data.input.type === "user") child.prompts.set(event.data.inputID, event.data.input.data.text)
return
}
if (event.type === "session.input.promoted") {
const prompt = child.prompts.get(event.data.inputID)
if (prompt === undefined) return
child.prompts.delete(event.data.inputID)
if (userFrame(child, event.data.inputID, prompt)) {
touch(child, event.created)
notifyDetail(child)
}
return
}
if (event.type === "session.step.started") {
touch(child, event.created)
if (child.label === FALLBACK_LABEL && event.data.agent) child.label = Locale.titlecase(event.data.agent)
if (child.status !== "running") child.status = "running"
input.emit()
return
}
if (event.type === "session.text.started") {
return
}
if (event.type === "session.text.delta") {
const id = `text:${event.data.ordinal}`
const key = fragmentKey(event.data.assistantMessageID, id)
const projected = child.projectedText.get(key)
const covered = projected?.indexOf(event.data.delta) ?? -1
if (projected && covered >= 0) {
child.projectedText.set(key, projected.slice(covered + event.data.delta.length))
return
}
const next = (child.text.get(key) ?? "") + event.data.delta
child.text.set(key, next)
setFrame(child, key, {
kind: "assistant",
source: "assistant",
text: next,
phase: "progress",
messageID: event.data.assistantMessageID,
partID: id,
})
touch(child, event.created)
notifyDetail(child)
return
}
if (event.type === "session.text.ended") {
const id = `text:${event.data.ordinal}`
const key = fragmentKey(event.data.assistantMessageID, id)
child.text.set(key, event.data.text)
child.projectedText.delete(key)
setFrame(child, key, {
kind: "assistant",
source: "assistant",
text: event.data.text,
phase: "progress",
messageID: event.data.assistantMessageID,
partID: id,
})
touch(child, event.created)
notifyDetail(child)
return
}
if (event.type === "session.reasoning.started") {
return
}
if (event.type === "session.reasoning.delta") {
const id = `reasoning:${event.data.ordinal}`
const key = fragmentKey(event.data.assistantMessageID, id)
const projected = child.projectedReasoning.get(key)
const covered = projected?.indexOf(event.data.delta) ?? -1
if (projected && covered >= 0) {
child.projectedReasoning.set(key, projected.slice(covered + event.data.delta.length))
return
}
const next = (child.reasoning.get(key) ?? "") + event.data.delta
child.reasoning.set(key, next)
if (!input.thinking) return
setFrame(child, key, {
kind: "reasoning",
source: "reasoning",
text: `Thinking: ${next}`,
phase: "progress",
messageID: event.data.assistantMessageID,
partID: id,
})
notifyDetail(child)
return
}
if (event.type === "session.reasoning.ended") {
const id = `reasoning:${event.data.ordinal}`
const key = fragmentKey(event.data.assistantMessageID, id)
child.reasoning.set(key, event.data.text)
child.projectedReasoning.delete(key)
if (!input.thinking) return
setFrame(child, key, {
kind: "reasoning",
source: "reasoning",
text: `Thinking: ${event.data.text}`,
phase: "progress",
messageID: event.data.assistantMessageID,
partID: id,
})
notifyDetail(child)
return
}
if (event.type === "session.tool.input.started") {
if (child.finishedTools.has(event.data.callID)) return
child.tools.set(event.data.callID, { name: event.data.name, input: {}, started: event.created })
return
}
if (event.type === "session.tool.called") {
if (child.finishedTools.has(event.data.callID)) return
const current = child.tools.get(event.data.callID)
child.tools.set(event.data.callID, {
name: current?.name ?? "tool",
input: event.data.input,
started: current?.started ?? event.created,
providerState: event.data.state,
})
childTool(
child,
structuredClone({
type: "tool",
id: event.data.callID,
name: current?.name ?? "tool",
executed: event.data.executed,
providerState: event.data.state,
state: { status: "running", input: event.data.input, structured: {}, content: [] },
time: { created: current?.started ?? event.created, ran: event.created },
}) as SessionMessageAssistantTool,
event.data.assistantMessageID,
)
touch(child, event.created)
notifyDetail(child)
return
}
if (event.type === "session.tool.success" || event.type === "session.tool.failed") {
if (child.finishedTools.has(event.data.callID)) return
const current = child.tools.get(event.data.callID)
const failed = event.type === "session.tool.failed"
childTool(
child,
structuredClone({
type: "tool",
id: event.data.callID,
name: current?.name ?? "tool",
executed: event.data.executed,
providerState: current?.providerState,
providerResultState: event.data.resultState,
state: failed
? {
status: "error",
input: current?.input ?? {},
structured: {},
content: [],
error: event.data.error,
result: event.data.result,
}
: {
status: "completed",
input: current?.input ?? {},
structured: event.data.structured,
content: event.data.content,
result: event.data.result,
},
time: {
created: current?.started ?? event.created,
ran: current?.started,
completed: event.created,
},
}) as SessionMessageAssistantTool,
event.data.assistantMessageID,
)
touch(child, event.created)
notifyDetail(child)
return
}
if (event.type === "session.step.ended") return
if (event.type === "session.step.failed") {
setFrame(child, `error:step:${event.data.assistantMessageID}`, {
kind: "error",
source: "system",
text: event.data.error.message,
phase: "start",
messageID: event.data.assistantMessageID,
})
touch(child, event.created)
notifyDetail(child)
return
}
if (event.type === "session.execution.started") {
child.status = "running"
touch(child, event.created)
input.emit()
return
}
if (
event.type === "session.execution.succeeded" ||
event.type === "session.execution.failed" ||
event.type === "session.execution.interrupted"
) {
child.status =
event.type === "session.execution.succeeded"
? "completed"
: event.type === "session.execution.interrupted"
? "cancelled"
: "error"
touch(child, event.created)
input.emit()
}
}
const mainTool = (item: SessionMessageAssistantTool, active?: Record<string, unknown>) => {
if (item.name !== "subagent" || item.state.status !== "completed") return
const found = childSessionID(record(item.state.structured))
if (!found) return
const child = ensureChild(found.sessionID)
applyMeta(child, record(item.state.input))
if (found.running) child.background = true
if (child.status === "running") {
const running = found.running && (!active || found.sessionID in active)
child.status = running ? "running" : "completed"
}
touch(child, item.time.completed ?? item.time.created)
}
return {
main(event) {
if (event.type === "session.tool.input.started") {
if (event.data.name === "subagent") pendingCalls.set(event.data.callID, {})
return
}
if (event.type === "session.tool.called") {
if (pendingCalls.has(event.data.callID)) pendingCalls.set(event.data.callID, event.data.input)
return
}
if (event.type === "session.tool.failed") {
pendingCalls.delete(event.data.callID)
return
}
if (event.type !== "session.tool.success") return
const pending = pendingCalls.get(event.data.callID)
pendingCalls.delete(event.data.callID)
const found = childSessionID(record(event.data.structured))
if (!found) return
const child = ensureChild(found.sessionID)
applyMeta(child, pending)
if (found.running) {
child.background = true
child.status = "running"
}
if (!found.running && child.status === "running") child.status = "completed"
touch(child, event.created)
input.emit()
if (!child.hydrated) void hydrateChild(child)
},
foreign(sessionID, event) {
const child = children.get(sessionID)
if (child) {
if (hydrations.has(sessionID)) {
const buffered = hydrationEvents.get(sessionID) ?? []
if (buffered.length < CHILD_EVENT_BUFFER_LIMIT) buffered.push(event)
else hydrationOverflow.add(sessionID)
hydrationEvents.set(sessionID, buffered)
}
reduce(child, event)
return
}
discover(sessionID)
const buffered = pendingEvents.get(sessionID)
if (buffered && buffered.length < CHILD_EVENT_BUFFER_LIMIT) buffered.push(event)
},
async hydrate(next) {
for (const message of next.messages) {
if (message.type !== "assistant") continue
for (const item of message.content) {
if (item.type === "tool") mainTool(item, next.active)
}
}
// Family index: adopt children directly from the current session list so
// historical subagents beyond the projected message window still get tabs.
const family = await input.sdk.session
.list({ parentID: input.sessionID, limit: FAMILY_LIST_LIMIT, order: "desc" })
.then((response) => response.data)
.catch(() => [])
for (const session of family) {
const child = ensureChild(session.id)
if (session.agent && child.label === FALLBACK_LABEL) child.label = Locale.titlecase(session.agent)
if (!child.title) child.title = session.title
touch(child, session.time.updated)
}
for (const sessionID of Object.keys(next.active)) discover(sessionID)
for (const child of children.values()) {
// Reconnect can miss a child's settled event; the active map is the
// authoritative live signal for still-running children.
if (child.status === "running" && !(child.sessionID in next.active)) child.status = "completed"
}
const current = selected ? children.get(selected) : undefined
if (current) await hydrateChild(current)
if (children.size > 0) input.emit()
},
select(sessionID) {
selected = sessionID
const child = sessionID ? children.get(sessionID) : undefined
if (child && !child.hydrated) void hydrateChild(child)
input.emit()
},
snapshot() {
const tabs = [...children.values()].map(tab).toSorted((a, b) => {
const active = Number(b.status === "running") - Number(a.status === "running")
if (active !== 0) return active
return b.lastUpdatedAt - a.lastUpdatedAt
})
const child = selected ? children.get(selected) : undefined
const details: Record<string, FooterSubagentDetail> = child
? { [child.sessionID]: { sessionID: child.sessionID, commits: child.frames.map((item) => item.commit) } }
: {}
return { tabs, details, permissions: [], questions: [] }
},
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,175 +0,0 @@
// Thin bridge between transport output and the footer API.
//
// Transports produce StreamCommit[] and an optional FooterOutput (patch +
// view + subagent state). This module forwards them to footer.append() and
// footer.event() respectively, adding trace writes along the way. It also
// defaults status updates to phase "running" if the caller didn't set a
// phase -- a convenience so transport code doesn't have to repeat that.
import type { FooterApi, FooterOutput, FooterPatch, FooterSubagentState, StreamCommit } from "./types"
type Trace = {
write(type: string, data?: unknown): void
}
type OutputInput = {
footer: FooterApi
trace?: Trace
}
type StreamOutput = {
commits: StreamCommit[]
footer?: FooterOutput
}
// Default to "running" phase when a status string arrives without an explicit phase.
function patch(next: FooterPatch): FooterPatch {
if (typeof next.status === "string" && next.phase === undefined) {
return {
phase: "running",
...next,
}
}
return next
}
function summarize(value: unknown): unknown {
if (typeof value === "string") {
if (value.length <= 160) {
return value
}
return {
type: "string",
length: value.length,
preview: `${value.slice(0, 160)}...`,
}
}
if (Array.isArray(value)) {
return {
type: "array",
length: value.length,
}
}
if (!value || typeof value !== "object") {
return value
}
return {
type: "object",
keys: Object.keys(value),
}
}
function traceCommit(commit: StreamCommit) {
return {
...commit,
text: summarize(commit.text),
textLength: commit.text.length,
part: commit.part
? {
id: commit.part.id,
sessionID: commit.part.sessionID,
messageID: commit.part.messageID,
callID: commit.part.callID,
tool: commit.part.tool,
state: {
status: commit.part.state.status,
title: "title" in commit.part.state ? summarize(commit.part.state.title) : undefined,
error: "error" in commit.part.state ? summarize(commit.part.state.error) : undefined,
time: "time" in commit.part.state ? summarize(commit.part.state.time) : undefined,
input: summarize(commit.part.state.input),
metadata: "metadata" in commit.part.state ? summarize(commit.part.state.metadata) : undefined,
},
}
: undefined,
}
}
export function traceSubagentState(state: FooterSubagentState) {
return {
tabs: state.tabs,
details: Object.fromEntries(
Object.entries(state.details).map(([sessionID, detail]) => [
sessionID,
{
sessionID,
commits: detail.commits.map(traceCommit),
},
]),
),
permissions: state.permissions.map((item) => ({
id: item.id,
sessionID: item.sessionID,
action: item.action,
resources: item.resources,
source: item.source,
metadata: item.metadata
? {
keys: Object.keys(item.metadata),
input: summarize(item.metadata.input),
}
: undefined,
})),
questions: state.questions.map((item) => ({
id: item.id,
sessionID: item.sessionID,
questions: item.questions.map((question) => ({
header: question.header,
question: question.question,
options: question.options.length,
multiple: question.multiple,
})),
})),
}
}
export function traceFooterOutput(footer?: FooterOutput) {
if (!footer?.subagent) {
return footer
}
return {
...footer,
subagent: traceSubagentState(footer.subagent),
}
}
// Forwards transport output to the footer: commits go to scrollback, patches update the status bar.
export function writeSessionOutput(input: OutputInput, out: StreamOutput): void {
for (const commit of out.commits) {
input.trace?.write("ui.commit", commit)
input.footer.append(commit)
}
if (out.footer?.patch) {
const next = patch(out.footer.patch)
input.trace?.write("ui.patch", next)
input.footer.event({
type: "stream.patch",
patch: next,
})
}
if (out.footer?.subagent) {
input.trace?.write("ui.subagent", traceSubagentState(out.footer.subagent))
input.footer.event({
type: "stream.subagent",
state: out.footer.subagent,
})
}
if (!out.footer?.view) {
return
}
input.trace?.write("ui.patch", {
view: out.footer.view,
})
input.footer.event({
type: "stream.view",
view: out.footer.view,
})
}

View file

@ -1,647 +0,0 @@
// Theme resolution for direct interactive mode.
//
// Derives scrollback and footer colors from the terminal's actual palette.
// resolveRunTheme() queries the renderer for the terminal's palette,
// detects dark/light mode, builds a small system theme locally, and maps it to
// the run footer + scrollback color model. Falls back to a hardcoded dark-mode
// palette if detection fails.
import { RGBA, SyntaxStyle, type CliRenderer, type ColorInput, type TerminalColors } from "@opentui/core"
import type { TuiThemeCurrent } from "@opencode-ai/plugin/tui"
import type { EntryKind } from "./types"
type Tone = {
body: ColorInput
start?: ColorInput
}
export type RunEntryTheme = Record<EntryKind, Tone>
export type RunSplashTheme = {
left: ColorInput
right: ColorInput
leftShadow: ColorInput
rightShadow: ColorInput
}
export type RunFooterTheme = {
highlight: ColorInput
selected: ColorInput
selectedText: ColorInput
warning: ColorInput
success: ColorInput
error: ColorInput
muted: ColorInput
text: ColorInput
status: ColorInput
statusAccent: ColorInput
shade: ColorInput
surface: ColorInput
pane: ColorInput
border: ColorInput
line: ColorInput
}
export type RunBlockTheme = {
highlight: ColorInput
warning: ColorInput
text: ColorInput
muted: ColorInput
syntax?: SyntaxStyle
diffAdded: ColorInput
diffRemoved: ColorInput
diffAddedBg: ColorInput
diffRemovedBg: ColorInput
diffContextBg: ColorInput
diffHighlightAdded: ColorInput
diffHighlightRemoved: ColorInput
diffLineNumber: ColorInput
diffAddedLineNumberBg: ColorInput
diffRemovedLineNumberBg: ColorInput
}
export type RunTheme = {
background: ColorInput
footer: RunFooterTheme
entry: RunEntryTheme
splash: RunSplashTheme
block: RunBlockTheme
}
type ThemeColor = Exclude<keyof TuiThemeCurrent, "thinkingOpacity">
type HexColor = `#${string}`
type RefName = string
type Variant = {
dark: HexColor | RefName
light: HexColor | RefName
}
type ColorValue = HexColor | RefName | Variant | RGBA | number
type ThemeJson = {
defs?: Record<string, HexColor | RefName>
theme: Omit<Record<ThemeColor, ColorValue>, "selectedListItemText" | "backgroundMenu"> & {
selectedListItemText?: ColorValue
backgroundMenu?: ColorValue
thinkingOpacity?: number
}
}
type SharedSyntaxTheme = TuiThemeCurrent & {
_hasSelectedListItemText: boolean
}
export const transparent = RGBA.fromValues(0, 0, 0, 0)
function alpha(color: RGBA, value: number): RGBA {
return RGBA.fromValues(color.r, color.g, color.b, Math.max(0, Math.min(1, value)))
}
function rgba(hex: string, value?: number): RGBA {
const color = RGBA.fromHex(hex)
return value === undefined ? color : alpha(color, value)
}
function mode(bg: RGBA): "dark" | "light" {
return luminance(bg) > 0.5 ? "light" : "dark"
}
function luminance(color: RGBA): number {
return 0.299 * color.r + 0.587 * color.g + 0.114 * color.b
}
function fade(color: RGBA, base: RGBA, fallback: number, scale: number, limit: number): RGBA {
if (color.a === 0) {
return RGBA.fromValues(color.r, color.g, color.b, Math.max(0, Math.min(1, fallback)))
}
const target = Math.min(limit, color.a * scale)
const mix = Math.min(1, target / color.a)
return RGBA.fromValues(
base.r + (color.r - base.r) * mix,
base.g + (color.g - base.g) * mix,
base.b + (color.b - base.b) * mix,
color.a,
)
}
function ansiToRgba(code: number): RGBA {
if (code < 16) {
const ansi = [
"#000000",
"#800000",
"#008000",
"#808000",
"#000080",
"#800080",
"#008080",
"#c0c0c0",
"#808080",
"#ff0000",
"#00ff00",
"#ffff00",
"#0000ff",
"#ff00ff",
"#00ffff",
"#ffffff",
]
return RGBA.fromHex(ansi[code] ?? "#000000")
}
if (code < 232) {
const index = code - 16
const b = index % 6
const g = Math.floor(index / 6) % 6
const r = Math.floor(index / 36)
const value = (x: number) => (x === 0 ? 0 : x * 40 + 55)
return RGBA.fromInts(value(r), value(g), value(b))
}
if (code < 256) {
const gray = (code - 232) * 10 + 8
return RGBA.fromInts(gray, gray, gray)
}
return RGBA.fromInts(0, 0, 0)
}
function tint(base: RGBA, overlay: RGBA, value: number): RGBA {
return RGBA.fromInts(
Math.round((base.r + (overlay.r - base.r) * value) * 255),
Math.round((base.g + (overlay.g - base.g) * value) * 255),
Math.round((base.b + (overlay.b - base.b) * value) * 255),
)
}
function chroma(color: RGBA) {
return Math.max(color.r, color.g, color.b) - Math.min(color.r, color.g, color.b)
}
function indexedPalette(colors: TerminalColors, size: number = Math.max(colors.palette.length, 16)): RGBA[] {
return Array.from({ length: size }, (_, index) => {
const value = colors.palette[index]
return RGBA.fromIndex(index, value ? RGBA.fromHex(value) : ansiToRgba(index))
})
}
function srgbToLinear(value: number): number {
if (value <= 0.04045) {
return value / 12.92
}
return ((value + 0.055) / 1.055) ** 2.4
}
function oklab(color: RGBA) {
const r = srgbToLinear(color.r)
const g = srgbToLinear(color.g)
const b = srgbToLinear(color.b)
const l = Math.cbrt(0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b)
const m = Math.cbrt(0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b)
const s = Math.cbrt(0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b)
return {
l: 0.2104542553 * l + 0.793617785 * m - 0.0040720468 * s,
a: 1.9779984951 * l - 2.428592205 * m + 0.4505937099 * s,
b: 0.0259040371 * l + 0.7827717662 * m - 0.808675766 * s,
}
}
function nearestIndexed(indexed: RGBA[], rgba: RGBA): RGBA {
const target = oklab(rgba)
const hit = indexed.reduce(
(best, item) => {
const sample = oklab(item)
const dl = sample.l - target.l
const da = sample.a - target.a
const db = sample.b - target.b
const dist = dl * dl * 2 + da * da + db * db
if (dist >= best.dist) return best
return {
dist,
item,
}
},
{
dist: Number.POSITIVE_INFINITY,
item: indexed[0]!,
},
)
return RGBA.clone(hit.item)
}
function paletteColor(colors: TerminalColors, index: number): RGBA {
const value = colors.palette[index]
return value ? RGBA.fromHex(value) : ansiToRgba(index)
}
function splashShadow(indexed: RGBA[], base: RGBA, overlay: RGBA, value: number): RGBA {
const mixed = tint(base, overlay, value)
return nearestIndexed(indexed, mixed)
}
export function resolveTheme(theme: ThemeJson, pick: "dark" | "light"): TuiThemeCurrent {
const defs = theme.defs ?? {}
const resolveColor = (value: ColorValue, chain: string[] = []): RGBA => {
if (value instanceof RGBA) return value
if (typeof value === "number") {
return RGBA.fromIndex(value, ansiToRgba(value))
}
if (typeof value !== "string") {
return resolveColor(value[pick], chain)
}
if (value === "transparent" || value === "none") {
return RGBA.fromInts(0, 0, 0, 0)
}
if (value.startsWith("#")) {
return RGBA.fromHex(value)
}
if (chain.includes(value)) {
throw new Error(`Circular color reference: ${[...chain, value].join(" -> ")}`)
}
const next = defs[value] ?? theme.theme[value as ThemeColor]
if (next === undefined) {
throw new Error(`Color reference "${value}" not found in defs or theme`)
}
return resolveColor(next, [...chain, value])
}
const resolved = Object.fromEntries(
Object.entries(theme.theme)
.filter(([key]) => key !== "selectedListItemText" && key !== "backgroundMenu" && key !== "thinkingOpacity")
.map(([key, value]) => [key, resolveColor(value as ColorValue)]),
) as Partial<Record<ThemeColor, RGBA>>
return {
...(resolved as Record<ThemeColor, RGBA>),
selectedListItemText:
theme.theme.selectedListItemText === undefined
? resolved.background!
: resolveColor(theme.theme.selectedListItemText),
backgroundMenu:
theme.theme.backgroundMenu === undefined ? resolved.backgroundElement! : resolveColor(theme.theme.backgroundMenu),
thinkingOpacity: theme.theme.thinkingOpacity ?? 0.6,
}
}
function generateGrayScale(bg: RGBA, isDark: boolean, map: (rgba: RGBA) => RGBA): Record<number, RGBA> {
const r = bg.r * 255
const g = bg.g * 255
const b = bg.b * 255
const lum = 0.299 * r + 0.587 * g + 0.114 * b
const cast = 0.25 * (1 - chroma(bg)) ** 2
const gray = (level: number) => {
const factor = level / 12
if (isDark && lum < 10) {
const value = Math.floor(factor * 0.4 * 255)
return map(RGBA.fromInts(value, value, value))
}
if (!isDark && lum > 245) {
const value = Math.floor(255 - factor * 0.4 * 255)
return map(RGBA.fromInts(value, value, value))
}
const value = isDark ? lum + (255 - lum) * factor * 0.4 : lum * (1 - factor * 0.4)
const tone = RGBA.fromInts(Math.floor(value), Math.floor(value), Math.floor(value))
if (cast === 0) return map(tone)
const ratio = lum === 0 ? 0 : value / lum
return map(
tint(
tone,
RGBA.fromInts(
Math.floor(Math.max(0, Math.min(r * ratio, 255))),
Math.floor(Math.max(0, Math.min(g * ratio, 255))),
Math.floor(Math.max(0, Math.min(b * ratio, 255))),
),
cast,
),
)
}
return Object.fromEntries(Array.from({ length: 12 }, (_, index) => [index + 1, gray(index + 1)]))
}
function generateMutedTextColor(bg: RGBA, isDark: boolean, map: (rgba: RGBA) => RGBA): RGBA {
const lum = 0.299 * bg.r * 255 + 0.587 * bg.g * 255 + 0.114 * bg.b * 255
const gray = isDark
? lum < 10
? 180
: Math.min(Math.floor(160 + lum * 0.3), 200)
: lum > 245
? 75
: Math.max(Math.floor(100 - (255 - lum) * 0.2), 60)
return map(RGBA.fromInts(gray, gray, gray))
}
export function generateSystem(colors: TerminalColors, pick: "dark" | "light"): ThemeJson {
const bg_snapshot = RGBA.fromHex(colors.defaultBackground ?? colors.palette[0]!)
const fg_snapshot = RGBA.fromHex(colors.defaultForeground ?? colors.palette[7]!)
const bg = RGBA.defaultBackground(bg_snapshot)
const fg = RGBA.defaultForeground(fg_snapshot)
const isDark = pick === "dark"
const color = (index: number) => paletteColor(colors, index)
const grays = generateGrayScale(bg_snapshot, isDark, (rgba) => rgba)
const textMuted = generateMutedTextColor(bg_snapshot, isDark, (rgba) => rgba)
const ansi = {
red: color(1),
green: color(2),
yellow: color(3),
blue: color(4),
magenta: color(5),
cyan: color(6),
red_bright: color(9),
green_bright: color(10),
}
const diff_alpha = isDark ? 0.22 : 0.14
const diff_context_bg = grays[2]
const primary = ansi.cyan
const secondary = ansi.magenta
return {
theme: {
primary,
secondary,
accent: primary,
error: ansi.red,
warning: ansi.yellow,
success: ansi.green,
info: ansi.cyan,
text: fg,
textMuted,
selectedListItemText: bg,
background: alpha(bg, 0),
backgroundPanel: grays[2],
backgroundElement: grays[3],
backgroundMenu: grays[3],
borderSubtle: grays[6],
border: grays[7],
borderActive: grays[8],
diffAdded: ansi.green,
diffRemoved: ansi.red,
diffContext: grays[7],
diffHunkHeader: grays[7],
diffHighlightAdded: ansi.green_bright,
diffHighlightRemoved: ansi.red_bright,
diffAddedBg: tint(bg_snapshot, ansi.green, diff_alpha),
diffRemovedBg: tint(bg_snapshot, ansi.red, diff_alpha),
diffContextBg: diff_context_bg,
diffLineNumber: textMuted,
diffAddedLineNumberBg: tint(diff_context_bg, ansi.green, diff_alpha),
diffRemovedLineNumberBg: tint(diff_context_bg, ansi.red, diff_alpha),
markdownText: fg,
markdownHeading: fg,
markdownLink: ansi.blue,
markdownLinkText: ansi.cyan,
markdownCode: ansi.green,
markdownBlockQuote: ansi.yellow,
markdownEmph: ansi.yellow,
markdownStrong: fg,
markdownHorizontalRule: grays[7],
markdownListItem: ansi.blue,
markdownListEnumeration: ansi.cyan,
markdownImage: ansi.blue,
markdownImageText: ansi.cyan,
markdownCodeBlock: fg,
syntaxComment: textMuted,
syntaxKeyword: ansi.magenta,
syntaxFunction: ansi.blue,
syntaxVariable: fg,
syntaxString: ansi.green,
syntaxNumber: ansi.yellow,
syntaxType: ansi.cyan,
syntaxOperator: ansi.cyan,
syntaxPunctuation: fg,
},
}
}
function quantizeColor(indexed: RGBA[], rgba: RGBA): RGBA {
if (rgba.a === 0 || rgba.intent === "default" || rgba.intent === "indexed") {
return RGBA.clone(rgba)
}
return nearestIndexed(indexed, rgba)
}
function quantizeTheme(theme: TuiThemeCurrent, indexed: RGBA[]): TuiThemeCurrent {
const resolved = Object.fromEntries(
Object.entries(theme)
.filter(([key]) => key !== "thinkingOpacity")
.map(([key, value]) => [key, quantizeColor(indexed, value as RGBA)]),
) as Partial<Record<ThemeColor, RGBA>>
return {
...(resolved as Record<ThemeColor, RGBA>),
thinkingOpacity: theme.thinkingOpacity,
}
}
function splashTheme(theme: TuiThemeCurrent, indexed: RGBA[]): RunSplashTheme {
const left = nearestIndexed(indexed, theme.textMuted)
const right = nearestIndexed(indexed, theme.text)
return {
left,
right,
leftShadow: splashShadow(indexed, theme.background, left, 0.14),
rightShadow: splashShadow(indexed, theme.background, right, 0.14),
}
}
function map(
footerTheme: TuiThemeCurrent,
scrollbackTheme: TuiThemeCurrent,
splash: RunSplashTheme,
syntax?: SyntaxStyle,
): RunTheme {
const footerBackground = alpha(footerTheme.background, 1)
const footerMode = mode(footerBackground)
const shade = fade(footerTheme.backgroundMenu, footerTheme.background, 0.12, 0.56, 0.72)
const surface = fade(footerTheme.backgroundMenu, footerTheme.background, 0.18, 0.76, 0.9)
const line = fade(footerTheme.backgroundMenu, footerTheme.background, 0.24, 0.9, 0.98)
const statusBase = tint(footerBackground, rgba("#000000"), footerMode === "dark" ? 0.12 : 0.06)
const statusAccentBase =
footerMode === "dark" ? tint(footerBackground, rgba("#ffffff"), 0.06) : tint(statusBase, rgba("#000000"), 0.04)
const collapsedStatus = footerMode === "dark" && luminance(statusBase) <= 0.04
// Pure-black backgrounds need a slight lift or the row disappears into the terminal background.
const status = collapsedStatus ? tint(statusBase, statusAccentBase, 0.7) : statusBase
const statusAccent = collapsedStatus ? tint(status, rgba("#ffffff"), 0.06) : statusAccentBase
return {
background: footerTheme.background,
footer: {
highlight: footerTheme.primary,
selected: footerTheme.backgroundElement,
selectedText: footerTheme.selectedListItemText,
warning: footerTheme.warning,
success: footerTheme.success,
error: footerTheme.error,
muted: footerTheme.textMuted,
text: footerTheme.text,
status,
statusAccent,
shade,
surface,
pane: footerTheme.backgroundMenu,
border: footerTheme.border,
line,
},
entry: {
system: {
body: scrollbackTheme.textMuted,
},
user: {
body: scrollbackTheme.primary,
},
assistant: {
body: scrollbackTheme.text,
},
reasoning: {
body: scrollbackTheme.textMuted,
},
tool: {
body: scrollbackTheme.text,
start: scrollbackTheme.textMuted,
},
error: {
body: scrollbackTheme.error,
},
},
splash,
block: {
highlight: scrollbackTheme.primary,
warning: scrollbackTheme.warning,
text: scrollbackTheme.text,
muted: scrollbackTheme.textMuted,
syntax,
diffAdded: scrollbackTheme.diffAdded,
diffRemoved: scrollbackTheme.diffRemoved,
diffAddedBg: transparent,
diffRemovedBg: transparent,
diffContextBg: transparent,
diffHighlightAdded: scrollbackTheme.diffHighlightAdded,
diffHighlightRemoved: scrollbackTheme.diffHighlightRemoved,
diffLineNumber: scrollbackTheme.diffLineNumber,
diffAddedLineNumberBg: scrollbackTheme.diffAddedLineNumberBg,
diffRemovedLineNumberBg: scrollbackTheme.diffRemovedLineNumberBg,
},
}
}
const seed = {
highlight: RGBA.fromIndex(6, rgba("#38bdf8")),
muted: RGBA.fromIndex(8, rgba("#64748b")),
text: RGBA.defaultForeground(rgba("#f8fafc")),
panel: rgba("#0f172a"),
success: RGBA.fromIndex(2, rgba("#22c55e")),
warning: RGBA.fromIndex(3, rgba("#f59e0b")),
error: RGBA.fromIndex(1, rgba("#ef4444")),
}
function tone(body: ColorInput, start?: ColorInput): Tone {
return {
body,
start,
}
}
const fallbackSplashIndexed = Array.from({ length: 256 }, (_, index) => RGBA.fromIndex(index))
const fallbackSplashLeft = RGBA.fromIndex(67)
const fallbackSplashRight = RGBA.fromIndex(110)
export const RUN_THEME_FALLBACK: RunTheme = {
background: RGBA.fromValues(0, 0, 0, 0),
footer: {
highlight: seed.highlight,
selected: seed.text,
selectedText: seed.panel,
warning: seed.warning,
success: seed.success,
error: seed.error,
muted: seed.muted,
text: seed.text,
status: tint(seed.panel, rgba("#000000"), 0.12),
statusAccent: tint(seed.panel, rgba("#ffffff"), 0.06),
shade: alpha(seed.panel, 0.68),
surface: alpha(seed.panel, 0.86),
pane: seed.panel,
border: seed.muted,
line: alpha(seed.panel, 0.96),
},
entry: {
system: tone(seed.muted),
user: tone(seed.highlight),
assistant: tone(seed.text),
reasoning: tone(seed.muted),
tool: tone(seed.text, seed.muted),
error: tone(seed.error),
},
splash: {
left: fallbackSplashLeft,
right: fallbackSplashRight,
leftShadow: splashShadow(fallbackSplashIndexed, RGBA.fromValues(0, 0, 0, 0), fallbackSplashLeft, 0.14),
rightShadow: splashShadow(fallbackSplashIndexed, RGBA.fromValues(0, 0, 0, 0), fallbackSplashRight, 0.14),
},
block: {
highlight: seed.highlight,
warning: seed.warning,
text: seed.text,
muted: seed.muted,
diffAdded: seed.success,
diffRemoved: seed.error,
diffAddedBg: alpha(seed.success, 0.18),
diffRemovedBg: alpha(seed.error, 0.18),
diffContextBg: alpha(seed.panel, 0.72),
diffHighlightAdded: seed.success,
diffHighlightRemoved: seed.error,
diffLineNumber: seed.muted,
diffAddedLineNumberBg: alpha(seed.success, 0.12),
diffRemovedLineNumberBg: alpha(seed.error, 0.12),
},
}
export async function resolveRunTheme(renderer: CliRenderer): Promise<RunTheme> {
try {
const colors = await renderer.getPalette({
size: 256,
})
const bg = colors.defaultBackground ?? colors.palette[0]
if (!bg) {
return RUN_THEME_FALLBACK
}
// Palette-only terminal reloads can leave renderer.themeMode stale, but
// ANSI slot zero is not the terminal background when OSC 11 is absent.
const pick = colors.defaultBackground
? mode(RGBA.fromHex(colors.defaultBackground))
: (renderer.themeMode ?? mode(RGBA.fromHex(bg)))
const footerTheme = resolveTheme(generateSystem(colors, pick), pick)
const indexed = indexedPalette(colors, 256)
const scrollbackTheme = quantizeTheme(footerTheme, indexed)
const shared = await import("@opencode-ai/tui/context/theme")
const syntaxTheme: SharedSyntaxTheme = {
...scrollbackTheme,
_hasSelectedListItemText: true,
}
const syntax = shared.generateSyntax(syntaxTheme)
return map(footerTheme, scrollbackTheme, splashTheme(scrollbackTheme, indexed), syntax)
} catch {
return RUN_THEME_FALLBACK
}
}

File diff suppressed because it is too large Load diff

View file

@ -1,94 +0,0 @@
// Dev-only JSONL event trace for direct interactive mode.
//
// Enable with OPENCODE_DIRECT_TRACE=1. Writes one JSON line per event to
// ~/.local/share/opencode/log/direct/<timestamp>-<pid>.jsonl. Also writes
// a latest.json pointer so you can quickly find the most recent trace.
//
// The trace captures the full closed loop: outbound prompts, inbound SDK
// events, reducer output, footer commits, and turn lifecycle markers.
// Useful for debugging stream ordering, permission behavior, and
// footer/transcript mismatches.
//
// Lazy-initialized: the first call to trace() decides whether tracing is
// active based on the env var, and subsequent calls return the cached result.
import fs from "fs"
import path from "path"
import { Global } from "@opencode-ai/core/global"
export type Trace = {
write(type: string, data?: unknown): void
}
let state: Trace | false | undefined
function stamp() {
return new Date()
.toISOString()
.replace(/[-:]/g, "")
.replace(/\.\d+Z$/, "Z")
}
function file() {
return path.join(Global.Path.log, "direct", `${stamp()}-${process.pid}.jsonl`)
}
function latest() {
return path.join(Global.Path.log, "direct", "latest.json")
}
function text(data: unknown) {
return JSON.stringify(
data,
(_key, value) => {
if (typeof value === "bigint") {
return String(value)
}
return value
},
0,
)
}
export function trace(): Trace | undefined {
if (state !== undefined) {
return state || undefined
}
if (!process.env.OPENCODE_DIRECT_TRACE) {
state = false
return undefined
}
const target = file()
fs.mkdirSync(path.dirname(target), { recursive: true })
fs.writeFileSync(
latest(),
text({
time: new Date().toISOString(),
pid: process.pid,
cwd: process.cwd(),
argv: process.argv.slice(2),
path: target,
}) + "\n",
)
state = {
write(type: string, data?: unknown) {
fs.appendFileSync(
target,
text({
time: new Date().toISOString(),
pid: process.pid,
type,
data,
}) + "\n",
)
},
}
state.write("trace.start", {
argv: process.argv.slice(2),
cwd: process.cwd(),
path: target,
})
return state
}

View file

@ -1,21 +0,0 @@
import type { StreamCommit } from "./types"
export function turnSummaryCommit(input: {
agent: string
model: string
duration: string
messageID?: string
}): StreamCommit {
return {
kind: "system",
text: `${input.agent} · ${input.model} · ${input.duration}`,
phase: "final",
source: "system",
summary: {
agent: input.agent,
model: input.model,
duration: input.duration,
},
messageID: input.messageID,
}
}

View file

@ -1,454 +0,0 @@
// Shared type vocabulary for the direct interactive mode (`opencode mini`).
//
// Direct mode uses a split-footer terminal layout: immutable scrollback for the
// session transcript, and a mutable footer for prompt input, status, and
// permission/question UI. Every module in run/* shares these types to stay
// aligned on that two-lane model.
//
// Data flow through the system:
//
// V2 events / demo actions → StreamCommit[] + FooterOutput
// → stream.ts bridges to footer API
// → footer.ts queues commits and patches the footer view
// → OpenTUI split-footer renderer writes to terminal
import type {
OpenCodeClient,
PermissionV2Request,
QuestionV2Request,
ReferenceListOutput,
} from "@opencode-ai/client/promise"
import type { TuiConfig } from "@opencode-ai/tui/config/v1"
export type RunFilePart = {
type: "file"
url: string
filename: string
mime: string
}
type PromptModel = { providerID: string; modelID: string }
export type RunPromptPart =
| {
type: "file"
url: string
filename?: string
mime?: string
source?: {
type: string
text: { start: number; end: number; value: string }
[key: string]: unknown
}
}
| { type: "agent"; name: string; source?: { start: number; end: number; value: string } }
export type RunCommand = {
name: string
description?: string
source?: string
template?: string
hints?: unknown[]
agent?: string
model?: {
[key: string]: unknown
}
subtask?: boolean
}
export type RunProviderModel = {
id: string
providerID: string
api?: {
[key: string]: unknown
}
name?: string
capabilities?: {
[key: string]: unknown
}
cost?: {
input: number
output?: number
cache?: {
read: number
write: number
}
}
limit?: {
context: number
input?: number
output?: number
}
status?: string
options?: {
[key: string]: unknown
}
headers?: {
[key: string]: string
}
release_date?: string
variants?: Record<string, unknown>
}
export type RunProvider = {
id: string
name: string
source?: string
env?: string[]
options?: {
[key: string]: unknown
}
models: Record<string, RunProviderModel>
}
export type RunPrompt = {
messageID?: string
partID?: string
text: string
parts: RunPromptPart[]
mode?: "shell"
command?: {
name: string
arguments: string
// Catalog source of the matched slash entry ("skill" routes to session.skill).
source?: string
}
}
export type FooterQueuedPrompt = {
messageID: string
partID: string
prompt: RunPrompt
}
export type RunAgent = {
id: string
name: string
description?: string
mode: "subagent" | "primary" | "all"
hidden: boolean
}
export type RunReference = ReferenceListOutput["data"][number]
export type RunInput = {
sdk: OpenCodeClient
directory: string
sessionID: string
sessionTitle?: string
resume?: boolean
replay?: boolean
replayLimit?: number
agent: string | undefined
model: PromptModel | undefined
variant: string | undefined
files: RunFilePart[]
initialInput?: string
thinking: boolean
demo?: boolean
}
// The semantic role of a scrollback entry. Maps 1:1 to theme colors.
export type EntryKind = "system" | "user" | "assistant" | "reasoning" | "tool" | "error"
// Whether the assistant is actively processing a turn.
export type FooterPhase = "idle" | "running"
// Full snapshot of footer status bar state. Every update replaces the whole
// object in the SolidJS signal so the view re-renders atomically.
export type FooterState = {
phase: FooterPhase
status: string
queue: number
model: string
duration: string
usage: string
first: boolean
interrupt: number
exit: number
}
// A partial update to FooterState. The footer merges this onto the current state.
export type FooterPatch = Partial<FooterState>
export type RunDiffStyle = "auto" | "stacked"
export type TurnSummary = {
agent: string
model: string
duration: string
}
export type ScrollbackOptions = {
diffStyle?: RunDiffStyle
suppressBackgrounds?: boolean
}
export type ToolCodeSnapshot = {
kind: "code"
title: string
content: string
file?: string
}
export type ToolDiffSnapshot = {
kind: "diff"
items: Array<{
title: string
diff: string
file?: string
deletions?: number
}>
}
export type ToolTaskSnapshot = {
kind: "task"
title: string
rows: string[]
tail: string
}
export type ToolQuestionSnapshot = {
kind: "question"
items: Array<{
question: string
answer: string
}>
tail: string
}
export type ToolSnapshot = ToolCodeSnapshot | ToolDiffSnapshot | ToolTaskSnapshot | ToolQuestionSnapshot
export type MiniToolState =
| { status: "pending"; input: Record<string, unknown>; raw?: string }
| {
status: "running"
input: Record<string, unknown>
title?: string
metadata?: Record<string, unknown>
time: { start: number }
}
| {
status: "completed"
input: Record<string, unknown>
output: string
title?: string
metadata?: Record<string, unknown>
time: { start: number; end: number }
}
| {
status: "error"
input: Record<string, unknown>
error: string
metadata?: Record<string, unknown>
time: { start: number; end: number }
}
export type MiniToolPart = {
id: string
sessionID: string
messageID: string
type?: "tool"
callID: string
tool: string
state: MiniToolState
}
export type EntryLayout = "inline" | "block"
export type RunEntryBody =
| { type: "none" }
| { type: "text"; content: string }
| { type: "code"; content: string; filetype?: string }
| { type: "markdown"; content: string }
| { type: "structured"; snapshot: ToolSnapshot }
// Which interactive surface the footer is showing. Only one view is active at
// a time. The transport drives transitions: when a permission arrives the view
// switches to "permission", and when the permission resolves it falls back to
// "prompt".
export type FooterView =
| { type: "prompt" }
| { type: "permission"; request: PermissionV2Request }
| { type: "question"; request: QuestionV2Request }
export type FooterPromptRoute =
| { type: "composer" }
| { type: "queued-menu" }
| { type: "subagent-menu" }
| { type: "subagent"; sessionID: string }
| { type: "command" }
| { type: "skill" }
| { type: "model" }
| { type: "variant" }
export type FooterSubagentTab = {
sessionID: string
partID: string
callID: string
label: string
description: string
status: "running" | "completed" | "cancelled" | "error"
background?: boolean
title?: string
toolCalls?: number
lastUpdatedAt: number
}
export type FooterSubagentDetail = {
sessionID: string
commits: StreamCommit[]
}
export type FooterSubagentState = {
tabs: FooterSubagentTab[]
details: Record<string, FooterSubagentDetail>
permissions: PermissionV2Request[]
questions: QuestionV2Request[]
}
// The transport emits this alongside scrollback commits so the footer can update in the same frame.
export type FooterOutput = {
patch?: FooterPatch
view?: FooterView
subagent?: FooterSubagentState
}
// Typed messages sent to RunFooter.event(). The prompt queue and stream
// transport both emit these to update footer state without reaching into
// internal signals directly.
export type FooterEvent =
| {
type: "history"
history: RunPrompt[]
}
| {
type: "catalog"
agents: RunAgent[]
references: RunReference[]
commands?: RunCommand[]
}
| {
type: "models"
providers: RunProvider[]
}
| {
type: "variants"
variants: string[]
current: string | undefined
}
| {
type: "queue"
queue: number
}
| {
type: "queued.prompts"
prompts: FooterQueuedPrompt[]
}
| {
type: "first"
first: boolean
}
| {
type: "model"
model: string
selection: NonNullable<RunInput["model"]>
}
| {
type: "turn.send"
queue: number
}
| {
type: "turn.wait"
}
| {
type: "turn.idle"
queue: number
}
| {
type: "turn.duration"
duration: string
}
| {
type: "stream.patch"
patch: FooterPatch
}
| {
type: "stream.view"
view: FooterView
}
| {
type: "stream.subagent"
state: FooterSubagentState
}
export type PermissionReply = Omit<Parameters<OpenCodeClient["permission"]["reply"]>[0], "sessionID">
export type QuestionReply = {
requestID: string
answers: string[][]
}
export type QuestionReject = Omit<Parameters<OpenCodeClient["question"]["reject"]>[0], "sessionID">
export type RunTuiConfig = Pick<TuiConfig.Resolved, "keybinds" | "leader_timeout" | "diff_style">
// Lifecycle phase of a scrollback entry. "start" opens the entry, "progress"
// appends content (coalesced in the footer queue), "final" closes it.
export type StreamPhase = "start" | "progress" | "final"
export type StreamSource = "assistant" | "reasoning" | "tool" | "system"
export type StreamToolState = "running" | "completed" | "error"
// A single append-only commit to scrollback. The transport produces these from
// V2 events, and RunFooter.append() queues them for the next
// microtask flush. Once flushed, they become immutable terminal scrollback
// rows -- they cannot be rewritten.
export type StreamCommit = {
kind: EntryKind
text: string
phase: StreamPhase
source: StreamSource
summary?: TurnSummary
messageID?: string
partID?: string
tool?: string
part?: MiniToolPart
interrupted?: boolean
toolState?: StreamToolState
toolError?: string
shell?: {
callID: string
command: string
}
}
export type LocalReplayAnchor = {
kind: EntryKind
text: string
phase: StreamPhase
messageID?: string
partID?: string
toolState?: StreamToolState
visible?: string
}
export type LocalReplayRow = {
commit: StreamCommit
after?: LocalReplayAnchor
}
// The public contract between the stream transport / prompt queue and
// the footer. RunFooter implements this. The transport and queue never
// touch the renderer directly -- they go through this interface.
export type FooterApi = {
readonly isClosed: boolean
onPrompt(fn: (input: RunPrompt) => void): () => void
onQueuedRemove(fn: (messageID: string) => boolean | Promise<boolean>): () => void
onClose(fn: () => void): () => void
event(next: FooterEvent): void
append(commit: StreamCommit): void
idle(): Promise<void>
close(): void
destroy(): void
}

View file

@ -1,220 +0,0 @@
// Model variant resolution and persistence.
//
// Variants are provider-specific reasoning effort levels (e.g., "high", "max").
// Resolution priority: CLI --variant flag > saved preference > session history.
//
// The saved variant persists across sessions in ~/.local/state/opencode/model.json
// so your last-used variant sticks. Cycling (ctrl+t) updates both the active
// variant and the persisted file.
import path from "path"
import { FSUtil } from "@opencode-ai/core/fs-util"
import { Context, Effect, Layer } from "effect"
import { LayerNode } from "@opencode-ai/core/effect/layer-node"
import { makeGlobalNode } from "@opencode-ai/core/effect/app-node"
import { makeRuntime } from "@opencode-ai/core/effect/runtime"
import { Global } from "@opencode-ai/core/global"
import { createSession, sessionVariant, type RunSession, type SessionMessages } from "./session.shared"
import type { RunInput, RunProvider } from "./types"
const MODEL_FILE = path.join(Global.Path.state, "model.json")
type ModelState = Record<string, unknown> & {
variant?: Record<string, string | undefined>
}
type VariantService = {
readonly resolveSavedVariant: (model: RunInput["model"]) => Effect.Effect<string | undefined>
readonly saveVariant: (model: RunInput["model"], variant: string | undefined) => Effect.Effect<void>
}
type VariantRuntime = {
resolveSavedVariant(model: RunInput["model"]): Promise<string | undefined>
saveVariant(model: RunInput["model"], variant: string | undefined): Promise<void>
}
function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value)
}
class Service extends Context.Service<Service, VariantService>()("@opencode/RunVariant") {}
function modelKey(provider: string, model: string): string {
return `${provider}/${model}`
}
function variantKey(model: NonNullable<RunInput["model"]>): string {
return modelKey(model.providerID, model.modelID)
}
export function modelInfo(providers: RunProvider[] | undefined, model: NonNullable<RunInput["model"]>) {
const provider = providers?.find((item) => item.id === model.providerID)
return {
provider: provider?.name ?? model.providerID,
model: provider?.models[model.modelID]?.name ?? model.modelID,
}
}
export function formatModelLabel(
model: NonNullable<RunInput["model"]>,
variant: string | undefined,
providers?: RunProvider[],
): string {
const names = modelInfo(providers, model)
const label = variant ? ` · ${variant}` : ""
return `${names.model} · ${names.provider}${label}`
}
export function cycleVariant(current: string | undefined, variants: string[]): string | undefined {
if (variants.length === 0) {
return undefined
}
if (!current) {
return variants[0]
}
const idx = variants.indexOf(current)
if (idx === -1 || idx === variants.length - 1) {
return undefined
}
return variants[idx + 1]
}
export function pickVariant(model: RunInput["model"], input: RunSession | SessionMessages): string | undefined {
return sessionVariant(Array.isArray(input) ? createSession(input) : input, model)
}
function fitVariant(value: string | undefined, variants: string[]): string | undefined {
if (!value) {
return undefined
}
if (variants.length === 0 || variants.includes(value)) {
return value
}
return undefined
}
// Picks the active variant. CLI flag wins, then saved preference, then session
// history. fitVariant() checks saved and session values against the available
// variants list -- if the provider doesn't offer a variant, it drops.
export function resolveVariant(
input: string | undefined,
session: string | undefined,
saved: string | undefined,
variants: string[],
): string | undefined {
if (input !== undefined) {
return input
}
const fallback = fitVariant(saved, variants)
const current = fitVariant(session, variants)
if (current !== undefined) {
return current
}
return fallback
}
function state(value: unknown): ModelState {
if (!isRecord(value)) {
return {}
}
const variant = isRecord(value.variant)
? Object.fromEntries(
Object.entries(value.variant).flatMap(([key, item]) => {
if (typeof item !== "string") {
return []
}
return [[key, item] as const]
}),
)
: undefined
return {
...value,
variant,
}
}
const layer = Layer.fresh(
Layer.effect(
Service,
Effect.gen(function* () {
const file = yield* FSUtil.Service
const read = Effect.fn("RunVariant.read")(function* () {
return yield* file.readJson(MODEL_FILE).pipe(
Effect.map(state),
Effect.catchCause(() => Effect.succeed(state(undefined))),
)
})
const resolveSavedVariant = Effect.fn("RunVariant.resolveSavedVariant")(function* (model: RunInput["model"]) {
if (!model) {
return undefined
}
return (yield* read()).variant?.[variantKey(model)]
})
const saveVariant = Effect.fn("RunVariant.saveVariant")(function* (
model: RunInput["model"],
variant: string | undefined,
) {
if (!model) {
return
}
const current = yield* read()
const next = {
...current.variant,
}
const key = variantKey(model)
if (variant) {
next[key] = variant
}
if (!variant) {
delete next[key]
}
yield* file
.writeJson(MODEL_FILE, {
...current,
variant: next,
})
.pipe(Effect.orElseSucceed(() => undefined))
})
return Service.of({
resolveSavedVariant,
saveVariant,
})
}),
),
)
const node = makeGlobalNode({ service: Service, layer, deps: [FSUtil.node] })
/** @internal Exported for testing. */
export function createVariantRuntime(replacements?: readonly LayerNode.Replacement[]): VariantRuntime {
const runtime = makeRuntime(Service, LayerNode.compile(node, replacements))
return {
resolveSavedVariant: (model) => runtime.runPromise((svc) => svc.resolveSavedVariant(model)).catch(() => undefined),
saveVariant: (model, variant) => runtime.runPromise((svc) => svc.saveVariant(model, variant)).catch(() => {}),
}
}
const runtime = createVariantRuntime()
export async function resolveSavedVariant(model: RunInput["model"]): Promise<string | undefined> {
return runtime.resolveSavedVariant(model)
}
export function saveVariant(model: RunInput["model"], variant: string | undefined): void {
void runtime.saveVariant(model, variant)
}

View file

@ -2,8 +2,7 @@ import type { EventSubscribeOutput, OpenCodeClient } from "@opencode-ai/client/p
import { SessionMessage } from "@opencode-ai/schema/session-message"
import { EOL } from "node:os"
import { readFile } from "node:fs/promises"
import { toolOutputText } from "../mini/tool"
import type { MiniToolPart } from "../mini/types"
import { toolOutputText, type MiniToolPart } from "@opencode-ai/tui/mini/tool"
import { UI } from "./ui"
type Model = {

View file

@ -6,9 +6,8 @@ import { open } from "node:fs/promises"
import path from "node:path"
import { readStdin } from "../util/io"
import { ServerConnection } from "../services/server-connection"
import { loadRunAgents, waitForCatalogReady } from "../mini/catalog.shared"
import { toolInlineInfo } from "../mini/tool"
import type { MiniToolPart } from "../mini/types"
import { waitForCatalogReady } from "../services/catalog"
import { toolInlineInfo, type MiniToolPart } from "@opencode-ai/tui/mini/tool"
import { runNonInteractivePrompt } from "./noninteractive"
import { UI } from "./ui"
@ -171,7 +170,10 @@ export function parseRunModel(value?: string) {
async function validateAgent(client: OpenCodeClient, directory: string, name?: string) {
if (!name) return
const agents = await loadRunAgents(client, directory).catch(() => undefined)
const agents = await client.agent
.list({ location: { directory } })
.then((result) => result.data)
.catch(() => undefined)
if (!agents) {
warning("failed to list agents. Falling back to default agent")
return

View file

@ -0,0 +1,22 @@
import type { OpenCodeClient } from "@opencode-ai/client/promise"
// Location plugins initialize asynchronously, so explicit model selection must
// wait for that exact model before prompt admission. The execution path owns
// the authoritative error if readiness times out.
export async function waitForCatalogReady(input: {
sdk: OpenCodeClient
directory: string
workspace?: string
model: { providerID: string; modelID: string }
timeoutMs?: number
}) {
const deadline = Date.now() + (input.timeoutMs ?? 5_000)
while (Date.now() < deadline) {
const models = await input.sdk.model
.list({ location: { directory: input.directory, workspace: input.workspace } })
.then((result) => result.data)
.catch(() => undefined)
if (models?.some((model) => model.providerID === input.model.providerID && model.id === input.model.modelID)) return
await new Promise((resolve) => setTimeout(resolve, 25))
}
}