refactor(tui): extract standalone package (#31193)

This commit is contained in:
Dax 2026-06-07 01:24:27 -04:00 committed by GitHub
commit 106f8e94d6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
84 changed files with 1147 additions and 1918 deletions

View file

@ -90,7 +90,6 @@
"@opencode-ai/sdk": "workspace:*",
"@opencode-ai/server": "workspace:*",
"@opencode-ai/tui": "workspace:*",
"@opencode-ai/ui": "workspace:*",
"@openrouter/ai-sdk-provider": "2.9.0",
"@opentelemetry/api": "1.9.0",
"@opentelemetry/context-async-hooks": "2.6.1",
@ -112,7 +111,6 @@
"ai-gateway-provider": "3.1.2",
"bonjour-service": "1.3.0",
"chokidar": "4.0.3",
"clipboardy": "4.0.0",
"cross-spawn": "catalog:",
"decimal.js": "10.5.0",
"diff": "catalog:",

View file

@ -1,10 +1,8 @@
import { cmd } from "./cmd"
import { UI } from "@/cli/ui"
import { win32DisableProcessedInput, win32InstallCtrlCGuard } from "../tui/win32"
import { errorMessage } from "@opencode-ai/tui/util/error"
import { validateSession } from "../tui/validate-session"
import { ServerAuth } from "@/server/auth"
import { resolveTuiRuntime } from "../tui/runtime"
export const AttachCommand = cmd({
command: "attach <url>",
@ -46,54 +44,46 @@ export const AttachCommand = cmd({
}),
handler: async (args) => {
const { TuiConfig } = await import("@/config/tui")
const unguard = win32InstallCtrlCGuard()
try {
win32DisableProcessedInput()
if (args.fork && !args.continue && !args.session) {
UI.error("--fork requires --continue or --session")
process.exitCode = 1
return
}
const directory = (() => {
if (!args.dir) return undefined
try {
process.chdir(args.dir)
return process.cwd()
} catch {
// If the directory doesn't exist locally (remote attach), pass it through.
return args.dir
}
})()
const headers = ServerAuth.headers({ password: args.password, username: args.username })
const config = await TuiConfig.get()
const runtime = resolveTuiRuntime(config)
if (args.fork && !args.continue && !args.session) {
UI.error("--fork requires --continue or --session")
process.exitCode = 1
return
}
const directory = (() => {
if (!args.dir) return undefined
try {
await validateSession({
url: args.url,
sessionID: args.session,
directory,
headers,
})
} catch (error) {
UI.error(errorMessage(error))
process.exitCode = 1
return
process.chdir(args.dir)
return process.cwd()
} catch {
// If the directory doesn't exist locally (remote attach), pass it through.
return args.dir
}
})()
const headers = ServerAuth.headers({ password: args.password, username: args.username })
const config = await TuiConfig.get()
const { createTuiRenderer, tui } = await import("@opencode-ai/tui")
const { createLegacyTuiHost } = await import("../tui/host")
const { createLegacyTuiPluginHost } = await import("@/plugin/tui/runtime")
const renderer = await createTuiRenderer(config, runtime)
const handle = tui({
...runtime,
try {
await validateSession({
url: args.url,
sessionID: args.session,
directory,
headers,
})
} catch (error) {
UI.error(errorMessage(error))
process.exitCode = 1
return
}
const { Effect } = await import("effect")
const { run } = await import("../tui/layer")
const { createLegacyTuiPluginHost } = await import("@/plugin/tui/runtime")
await Effect.runPromise(
run({
url: args.url,
config,
host: createLegacyTuiHost(renderer),
pluginHost: createLegacyTuiPluginHost(),
renderer,
args: {
continue: args.continue,
sessionID: args.session,
@ -101,10 +91,7 @@ export const AttachCommand = cmd({
},
directory,
headers,
})
await handle.done
} finally {
unguard?.()
}
}),
)
},
})

View file

@ -11,7 +11,6 @@ import { withNetworkOptions, resolveNetworkOptionsNoConfig } from "@/cli/network
import { Filesystem } from "@/util/filesystem"
import type { GlobalEvent } from "@opencode-ai/sdk/v2"
import type { EventSource } from "@opencode-ai/tui/context/sdk"
import { win32DisableProcessedInput, win32InstallCtrlCGuard } from "../tui/win32"
import { writeHeapSnapshot } from "v8"
import {
OPENCODE_PROCESS_ROLE,
@ -20,7 +19,7 @@ import {
sanitizedProcessEnv,
} from "@opencode-ai/core/util/opencode-process"
import { validateSession } from "../tui/validate-session"
import { resolveTuiRuntime } from "../tui/runtime"
import { win32InstallCtrlCGuard } from "@opencode-ai/tui/terminal-win32"
declare global {
const OPENCODE_WORKER_PATH: string
@ -113,15 +112,9 @@ export const TuiThreadCommand = cmd({
describe: "agent to use",
}),
handler: async (args) => {
const { TuiConfig } = await import("@/config/tui")
// Keep ENABLE_PROCESSED_INPUT cleared even if other code flips it.
// (Important when running under `bun run` wrappers on Windows.)
const unguard = win32InstallCtrlCGuard()
try {
// Must be the very first thing — disables CTRL_C_EVENT before any Worker
// spawn or async work so the OS cannot kill the process group.
win32DisableProcessedInput()
const { TuiConfig } = await import("@/config/tui")
if (args.fork && !args.continue && !args.session) {
UI.error("--fork requires --continue or --session")
process.exitCode = 1
@ -189,7 +182,6 @@ export const TuiThreadCommand = cmd({
const prompt = await input(args.prompt)
const config = await TuiConfig.get()
const runtime = resolveTuiRuntime(config)
const network = resolveNetworkOptionsNoConfig(args)
const external =
@ -230,42 +222,43 @@ export const TuiThreadCommand = cmd({
}, 1000).unref?.()
try {
const { createTuiRenderer, tui } = await import("@opencode-ai/tui")
const { createLegacyTuiHost } = await import("../tui/host")
const { Effect } = await import("effect")
const { run } = await import("../tui/layer")
const { createLegacyTuiPluginHost } = await import("@/plugin/tui/runtime")
const renderer = await createTuiRenderer(config, runtime)
const handle = tui({
...runtime,
url: transport.url,
renderer,
async onSnapshot() {
const tui = writeHeapSnapshot("tui.heapsnapshot")
const server = await client.call("snapshot", undefined)
return [tui, server]
},
config,
host: createLegacyTuiHost(renderer),
pluginHost: createLegacyTuiPluginHost(),
directory: cwd,
fetch: transport.fetch,
events: transport.events,
args: {
continue: args.continue,
sessionID: args.session,
agent: args.agent,
model: args.model,
prompt,
fork: args.fork,
},
})
await handle.done
await Effect.runPromise(
run({
url: transport.url,
async onSnapshot() {
const tui = writeHeapSnapshot("tui.heapsnapshot")
const server = await client.call("snapshot", undefined)
return [tui, server]
},
config,
pluginHost: createLegacyTuiPluginHost(),
directory: cwd,
fetch: transport.fetch,
events: transport.events,
args: {
continue: args.continue,
sessionID: args.session,
agent: args.agent,
model: args.model,
prompt,
fork: args.fork,
},
}),
)
} finally {
await stop()
}
process.exit(0)
} finally {
unguard?.()
try {
unguard?.()
} catch (error) {
Log.Default.warn("failed to restore terminal guard", { error: errorMessage(error) })
}
}
process.exit(0)
},
})
// scratch

View file

@ -1,262 +0,0 @@
import type {
TuiAttention,
TuiAttentionNotifyInput,
TuiAttentionNotifyResult,
TuiAttentionNotifySkipReason,
TuiAttentionWhen,
TuiKV,
TuiAttentionSoundName,
TuiAttentionSoundPack,
TuiAttentionSoundPackInfo,
} from "@opencode-ai/plugin/tui"
import { AttentionSoundName, type TuiConfig } from "@opencode-ai/tui/config"
import { Schema } from "effect"
import stripAnsi from "strip-ansi"
import * as TuiAudio from "./audio"
import defaultSoundPath from "@opencode-ai/ui/audio/bip-bop-01.mp3" with { type: "file" }
import questionSoundPath from "@opencode-ai/ui/audio/bip-bop-03.mp3" with { type: "file" }
import permissionSoundPath from "@opencode-ai/ui/audio/staplebops-06.mp3" with { type: "file" }
import errorSoundPath from "@opencode-ai/ui/audio/nope-03.mp3" with { type: "file" }
import doneSoundPath from "@opencode-ai/ui/audio/bip-bop-01.mp3" with { type: "file" }
import subagentDoneSoundPath from "@opencode-ai/ui/audio/yup-01.mp3" with { type: "file" }
import * as Log from "@opencode-ai/core/util/log"
type FocusState = "unknown" | "focused" | "blurred"
type AttentionRenderer = {
readonly isDestroyed: boolean
on(event: "focus" | "blur", listener: () => void): unknown
off(event: "focus" | "blur", listener: () => void): unknown
triggerNotification(message: string, title?: string): boolean
}
type RegisteredSoundPack = TuiAttentionSoundPack & {
builtin: boolean
}
type TuiAttentionHost = TuiAttention & {
dispose(): void
}
const log = Log.create({ service: "tui.attention" })
const DEFAULT_TITLE = "opencode"
const DEFAULT_PACK_ID = "opencode.default"
const KV_SOUND_PACK = "attention_sound_pack"
const TITLE_LIMIT = 80
const MESSAGE_LIMIT = 240
const BUILTIN_PACK: RegisteredSoundPack = {
id: DEFAULT_PACK_ID,
name: "OpenCode Default",
builtin: true,
sounds: {
default: defaultSoundPath,
question: questionSoundPath,
permission: permissionSoundPath,
error: errorSoundPath,
done: doneSoundPath,
subagent_done: subagentDoneSoundPath,
},
}
function skipped(reason: TuiAttentionNotifySkipReason): TuiAttentionNotifyResult {
return {
ok: false,
notification: false,
sound: false,
skipped: reason,
}
}
function normalizeText(input: string | undefined, fallback: string, limit: number) {
const text = stripAnsi(input ?? "")
.replace(/[ \t]*[\r\n]+[ \t]*/g, " ")
.replace(/[\u0000-\u0009\u000B\u000C\u000E-\u001F\u007F-\u009F]/g, "")
.trim()
const normalized = text.length ? text : fallback
return Array.from(normalized).slice(0, limit).join("")
}
function clampVolume(volume: number) {
if (!Number.isFinite(volume)) return 0
return Math.min(1, Math.max(0, volume))
}
function soundVolume(input: TuiAttentionNotifyInput, config: Pick<TuiConfig.Resolved, "attention">) {
if (!config.attention.sound) return
if (input.sound === false) return
if (input.sound === undefined) return clampVolume(config.attention.volume)
if (input.sound === true) return clampVolume(config.attention.volume)
return clampVolume(input.sound.volume ?? config.attention.volume)
}
function normalizePack(pack: TuiAttentionSoundPack): RegisteredSoundPack | undefined {
const id = pack.id.trim()
if (!id) return
return {
id,
name: pack.name?.trim() || undefined,
builtin: false,
sounds: Object.fromEntries(
Object.entries(pack.sounds).filter(
(item): item is [TuiAttentionSoundName, string] =>
Schema.is(AttentionSoundName)(item[0]) && typeof item[1] === "string" && item[1].trim().length > 0,
),
),
}
}
function focusSkip(when: TuiAttentionWhen, focus: FocusState) {
if (when === "always") return
if (focus === "unknown") return "focus_unknown"
if (when === "blurred" && focus === "focused") return "focused"
if (when === "focused" && focus === "blurred") return "blurred"
}
export function createTuiAttention(input: {
renderer: AttentionRenderer
config: Pick<TuiConfig.Resolved, "attention">
kv?: TuiKV
audio?: Pick<typeof TuiAudio, "loadSoundFile" | "play">
}): TuiAttentionHost {
let focus: FocusState = "unknown"
let disposed = false
let activePackID: string | undefined
const packs = new Map<string, RegisteredSoundPack>([[BUILTIN_PACK.id, BUILTIN_PACK]])
const audio = input.audio ?? TuiAudio
const onFocus = () => {
focus = "focused"
}
const onBlur = () => {
focus = "blurred"
}
input.renderer.on("focus", onFocus)
input.renderer.on("blur", onBlur)
function configuredPackID() {
const stored = input.kv?.get<string | undefined>(KV_SOUND_PACK, undefined)
return activePackID ?? stored ?? input.config.attention.sound_pack
}
function currentPack() {
return packs.get(configuredPackID()) ?? BUILTIN_PACK
}
function soundCandidates(name: TuiAttentionSoundName) {
return [input.config.attention.sounds[name], currentPack().sounds[name], BUILTIN_PACK.sounds[name]].filter(
(item, index, list): item is string => typeof item === "string" && list.indexOf(item) === index,
)
}
async function playSound(name: TuiAttentionSoundName, volume: number) {
try {
for (const file of soundCandidates(name)) {
const current = await audio.loadSoundFile(file).catch((error) => {
log.debug("failed to load attention sound", { file, error })
return null
})
if (disposed) return false
if (current == null) continue
if (audio.play(current, { volume }) != null) return true
}
return false
} catch (error) {
log.debug("failed to play attention sound", { error })
return false
}
}
return {
async notify(request) {
try {
if (!input.config.attention.enabled) return skipped("attention_disabled")
if (disposed || input.renderer.isDestroyed) return skipped("renderer_destroyed")
const message = normalizeText(request.message, "", MESSAGE_LIMIT)
if (!message) return skipped("empty_message")
const requestedNotification = typeof request.notification === "object" ? request.notification : undefined
const notificationSkip = focusSkip(requestedNotification?.when ?? "blurred", focus)
const notificationRequested = input.config.attention.notifications && request.notification !== false
const shouldNotify = notificationRequested && !notificationSkip
const notification = shouldNotify
? (() => {
try {
return input.renderer.triggerNotification(
message,
normalizeText(request.title, DEFAULT_TITLE, TITLE_LIMIT),
)
} catch (error) {
log.debug("failed to trigger attention notification", { error })
return false
}
})()
: false
const volume = soundVolume(request, input.config)
const requestedSound = typeof request.sound === "object" ? request.sound : undefined
const soundSkip = volume === undefined ? undefined : focusSkip(requestedSound?.when ?? "always", focus)
const soundName =
requestedSound?.name && Schema.is(AttentionSoundName)(requestedSound.name) ? requestedSound.name : "default"
const sound = volume === undefined || soundSkip ? false : await playSound(soundName, volume)
if (!notification && !sound) {
if (notificationRequested && notificationSkip) return skipped(notificationSkip)
if (soundSkip) return skipped(soundSkip)
}
return {
ok: notification || sound,
notification,
sound,
}
} catch (error) {
log.debug("failed to handle attention notification", { error })
return {
ok: false,
notification: false,
sound: false,
}
}
},
soundboard: {
registerPack(pack) {
const next = normalizePack(pack)
if (!next) return () => {}
packs.set(next.id, next)
let disposed = false
return () => {
if (disposed) return
disposed = true
if (packs.get(next.id) === next) packs.delete(next.id)
}
},
activate(id, options) {
const pack = packs.get(id)
if (!pack) return false
activePackID = pack.id
if (options?.persist) input.kv?.set(KV_SOUND_PACK, pack.id)
return true
},
current() {
return currentPack().id
},
list(): TuiAttentionSoundPackInfo[] {
const current = currentPack().id
return Array.from(packs.values()).map((pack) => ({
id: pack.id,
name: pack.name,
active: pack.id === current,
builtin: pack.builtin,
}))
},
},
dispose() {
if (disposed) return
disposed = true
input.renderer.off("focus", onFocus)
input.renderer.off("blur", onBlur)
},
}
}

View file

@ -1,58 +0,0 @@
import { Audio, type AudioErrorContext, type AudioPlayOptions, type AudioSound, type AudioVoice } from "@opentui/core"
import * as Log from "@opencode-ai/core/util/log"
const log = Log.create({ service: "tui.audio" })
let audio: Audio | null | undefined
const sounds = new Map<string, Promise<AudioSound | null>>()
function getAudio() {
if (audio !== undefined) return audio
try {
const next = Audio.create({ autoStart: false })
next.on("error", (error: Error, context: AudioErrorContext) => {
log.debug("tui audio error", { error, context })
})
audio = next
return next
} catch (error) {
log.debug("failed to create tui audio", { error })
audio = null
return null
}
}
export function loadSoundFile(file: string) {
const current = getAudio()
if (!current) return Promise.resolve(null)
const cached = sounds.get(file)
if (cached) return cached
const task = Bun.file(file)
.bytes()
.then((bytes) => current.loadSound(bytes))
.catch((error) => {
log.debug("failed to load tui sound", { file, error })
return null
})
sounds.set(file, task)
return task
}
export function play(sound: AudioSound, options?: AudioPlayOptions) {
const current = getAudio()
if (!current) return null
if (!current.isStarted() && !current.start()) return null
return current.play(sound, options)
}
export function stopVoice(voice: AudioVoice) {
return audio?.stopVoice(voice) ?? false
}
export function dispose() {
audio?.dispose()
audio = undefined
sounds.clear()
}
export * as TuiAudio from "./audio"

View file

@ -1,181 +0,0 @@
import { platform, release } from "os"
import { lazy } from "../../util/lazy.js"
import { tmpdir } from "os"
import path from "path"
import fs from "fs/promises"
import { Effect } from "effect"
import { ChildProcess } from "effect/unstable/process"
import { AppProcess } from "@opencode-ai/core/process"
import * as Filesystem from "../../util/filesystem"
import * as Process from "../../util/process"
const writeWithStdin = (cmd: string[], text: string): Promise<void> =>
Effect.runPromise(
AppProcess.Service.use((svc) => svc.run(ChildProcess.make(cmd[0]!, cmd.slice(1)), { stdin: text })).pipe(
Effect.provide(AppProcess.defaultLayer),
Effect.catch(() => Effect.void),
Effect.asVoid,
),
).catch(() => undefined)
// Lazy load which and clipboardy to avoid expensive execa/which/isexe chain at startup
const getWhich = lazy(async () => {
const { which } = await import("@opencode-ai/core/util/which")
return which
})
const getClipboardy = lazy(async () => {
const { default: clipboardy } = await import("clipboardy")
return clipboardy
})
/**
* Writes text to clipboard via OSC 52 escape sequence.
* This allows clipboard operations to work over SSH by having
* the terminal emulator handle the clipboard locally.
*/
function writeOsc52(text: string): void {
if (!process.stdout.isTTY) return
const base64 = Buffer.from(text).toString("base64")
const osc52 = `\x1b]52;c;${base64}\x07`
const passthrough = process.env["TMUX"] || process.env["STY"]
const sequence = passthrough ? `\x1bPtmux;\x1b${osc52}\x1b\\` : osc52
process.stdout.write(sequence)
}
export interface Content {
data: string
mime: string
}
// Checks clipboard for images first, then falls back to text.
//
// On Windows prompt/ can call this from multiple paste signals because
// terminals surface image paste differently:
// 1. A forwarded Ctrl+V keypress
// 2. An empty bracketed-paste hint for image-only clipboard in Windows
// Terminal <1.25
// 3. A kitty Ctrl+V key-release fallback for Windows Terminal 1.25+
export async function read(): Promise<Content | undefined> {
const os = platform()
if (os === "darwin") {
const tmpfile = path.join(tmpdir(), "opencode-clipboard.png")
try {
await Process.run(
[
"osascript",
"-e",
'set imageData to the clipboard as "PNGf"',
"-e",
`set fileRef to open for access POSIX file "${tmpfile}" with write permission`,
"-e",
"set eof fileRef to 0",
"-e",
"write imageData to fileRef",
"-e",
"close access fileRef",
],
{ nothrow: true },
)
const buffer = await Filesystem.readBytes(tmpfile)
return { data: buffer.toString("base64"), mime: "image/png" }
} catch {
} finally {
await fs.rm(tmpfile, { force: true }).catch(() => {})
}
}
// Windows/WSL: probe clipboard for images via PowerShell.
// Bracketed paste can't carry image data so we read it directly.
if (os === "win32" || release().includes("WSL")) {
const script =
"Add-Type -AssemblyName System.Windows.Forms; $img = [System.Windows.Forms.Clipboard]::GetImage(); if ($img) { $ms = New-Object System.IO.MemoryStream; $img.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png); [System.Convert]::ToBase64String($ms.ToArray()) }"
const base64 = await Process.text(["powershell.exe", "-NonInteractive", "-NoProfile", "-command", script], {
nothrow: true,
})
if (base64.text) {
const imageBuffer = Buffer.from(base64.text.trim(), "base64")
if (imageBuffer.length > 0) {
return { data: imageBuffer.toString("base64"), mime: "image/png" }
}
}
}
if (os === "linux") {
const wayland = await Process.run(["wl-paste", "-t", "image/png"], { nothrow: true })
if (wayland.stdout.byteLength > 0) {
return { data: Buffer.from(wayland.stdout).toString("base64"), mime: "image/png" }
}
const x11 = await Process.run(["xclip", "-selection", "clipboard", "-t", "image/png", "-o"], {
nothrow: true,
})
if (x11.stdout.byteLength > 0) {
return { data: Buffer.from(x11.stdout).toString("base64"), mime: "image/png" }
}
}
const clipboardy = await getClipboardy()
const text = await clipboardy.read().catch(() => {})
if (text) {
return { data: text, mime: "text/plain" }
}
}
const getCopyMethod = lazy(async () => {
const os = platform()
const which = await getWhich()
if (os === "darwin" && which("osascript")) {
console.log("clipboard: using osascript")
return async (text: string) => {
const escaped = text.replace(/\\/g, "\\\\").replace(/"/g, '\\"')
await Process.run(["osascript", "-e", `set the clipboard to "${escaped}"`], { nothrow: true })
}
}
if (os === "linux") {
if (process.env["WAYLAND_DISPLAY"] && which("wl-copy")) {
console.log("clipboard: using wl-copy")
return (text: string) => writeWithStdin(["wl-copy"], text)
}
if (which("xclip")) {
console.log("clipboard: using xclip")
return (text: string) => writeWithStdin(["xclip", "-selection", "clipboard"], text)
}
if (which("xsel")) {
console.log("clipboard: using xsel")
return (text: string) => writeWithStdin(["xsel", "--clipboard", "--input"], text)
}
}
if (os === "win32") {
console.log("clipboard: using powershell")
return (text: string) =>
// Pipe via stdin to avoid PowerShell string interpolation ($env:FOO, $(), etc.)
writeWithStdin(
[
"powershell.exe",
"-NonInteractive",
"-NoProfile",
"-Command",
"[Console]::InputEncoding = [System.Text.Encoding]::UTF8; Set-Clipboard -Value ([Console]::In.ReadToEnd())",
],
text,
)
}
console.log("clipboard: no native support")
return async (text: string) => {
const clipboardy = await getClipboardy()
await clipboardy.write(text).catch(() => {})
}
})
export async function copy(text: string): Promise<void> {
writeOsc52(text)
const method = await getCopyMethod()
await method(text)
}
export * as Clipboard from "./clipboard"

View file

@ -1,287 +0,0 @@
import { Database } from "bun:sqlite"
import { statSync } from "node:fs"
import os from "node:os"
import path from "node:path"
import { Option, Schema } from "effect"
import type { EditorSelection } from "@opencode-ai/tui/context/editor"
const ZedEditorRowSchema = Schema.Struct({
item_kind: Schema.String,
editor_id: Schema.NullOr(Schema.Number),
workspace_id: Schema.Number,
workspace_paths: Schema.NullOr(Schema.String),
timestamp: Schema.String,
buffer_path: Schema.NullOr(Schema.String),
})
const ZedSelectionRowSchema = Schema.Struct({
selection_start: Schema.NullOr(Schema.Number),
selection_end: Schema.NullOr(Schema.Number),
})
const ZedEditorContentsSchema = Schema.Struct({
contents: Schema.NullOr(Schema.String),
})
const decodeZedEditorRow = Schema.decodeUnknownOption(ZedEditorRowSchema)
const decodeZedSelectionRow = Schema.decodeUnknownOption(ZedSelectionRowSchema)
const decodeZedEditorContents = Schema.decodeUnknownOption(ZedEditorContentsSchema)
const utf8 = new TextEncoder()
type ZedEditorRow = Schema.Schema.Type<typeof ZedEditorRowSchema>
type ZedActiveEditorRow = ZedEditorRow & { item_kind: "Editor"; editor_id: number }
export type ZedSelectionResult =
| { type: "selection"; selection: EditorSelection }
| { type: "empty" }
| { type: "unavailable" }
export async function resolveZedSelection(dbPath: string, cwd = process.cwd()): Promise<ZedSelectionResult> {
const active = queryZedActiveEditor(dbPath, cwd)
if (active.type !== "row") return active
const row = active.row
if (!row.buffer_path) return { type: "empty" }
const selections = queryZedEditorSelections(dbPath, row)
if (selections.type !== "selections") return selections
const byteRanges = selections.selections
.flatMap((selection) => {
if (selection.selection_start == null || selection.selection_end == null) return []
return [
{
start: Math.min(selection.selection_start, selection.selection_end),
end: Math.max(selection.selection_start, selection.selection_end),
},
]
})
.sort((left, right) => left.start - right.start || left.end - right.end)
if (byteRanges.length === 0) return { type: "unavailable" }
const contents = queryZedEditorContents(dbPath, row)
const text =
contents.type === "contents" && contents.contents != null
? contents.contents
: await Bun.file(row.buffer_path)
.text()
.catch(() => undefined)
if (text == null) return { type: "unavailable" }
const ranges = byteRanges.map((range) => {
const startOffset = utf8ByteOffsetToStringIndex(text, range.start)
const endOffset = utf8ByteOffsetToStringIndex(text, range.end)
return {
text: text.slice(startOffset, endOffset),
selection: offsetsToSelection(text, startOffset, endOffset),
}
})
return {
type: "selection",
selection: {
filePath: row.buffer_path,
source: "zed",
ranges,
},
}
}
function queryZedActiveEditor(dbPath: string, cwd: string) {
let db: Database | undefined
try {
db = new Database(dbPath, { readonly: true })
const raw = db
.query(
`select
i.kind as item_kind,
e.item_id as editor_id,
i.workspace_id as workspace_id,
w.paths as workspace_paths,
w.timestamp as timestamp,
e.buffer_path as buffer_path
from items i
join panes p on p.pane_id = i.pane_id and p.workspace_id = i.workspace_id
join workspaces w on w.workspace_id = i.workspace_id
left join editors e on e.item_id = i.item_id and e.workspace_id = i.workspace_id
where i.active = 1 and p.active = 1
order by w.timestamp desc`,
)
.all()
const rows = raw.flatMap((row) => {
const parsed = decodeZedEditorRow(row)
return Option.isSome(parsed) ? [parsed.value] : []
})
if (raw.length > 0 && rows.length === 0) return { type: "unavailable" as const }
const row = rows
.map((row) => ({ row, score: scoreZedWorkspace(row.workspace_paths, cwd) }))
.filter((entry) => entry.score > 0)
.sort((left, right) => right.score - left.score || right.row.timestamp.localeCompare(left.row.timestamp))[0]?.row
if (!row) return { type: "empty" as const }
if (row.item_kind !== "Editor") return { type: "unavailable" as const }
if (!isZedActiveEditorRow(row)) return { type: "empty" as const }
return { type: "row" as const, row }
} catch {
return { type: "unavailable" as const }
} finally {
db?.close()
}
}
function queryZedEditorSelections(dbPath: string, row: ZedActiveEditorRow) {
let db: Database | undefined
try {
db = new Database(dbPath, { readonly: true })
const raw = db
.query(
`select
start as selection_start,
end as selection_end
from editor_selections
where editor_id = $editorID and workspace_id = $workspaceID`,
)
.all({ $editorID: row.editor_id, $workspaceID: row.workspace_id })
const selections = raw.flatMap((selection) => {
const parsed = decodeZedSelectionRow(selection)
return Option.isSome(parsed) ? [parsed.value] : []
})
if (raw.length > 0 && selections.length === 0) return { type: "unavailable" as const }
return { type: "selections" as const, selections }
} catch {
return { type: "unavailable" as const }
} finally {
db?.close()
}
}
function queryZedEditorContents(dbPath: string, row: ZedActiveEditorRow) {
let db: Database | undefined
try {
db = new Database(dbPath, { readonly: true })
const parsed = decodeZedEditorContents(
db
.query(
`select contents
from editors
where item_id = $editorID and workspace_id = $workspaceID`,
)
.get({ $editorID: row.editor_id, $workspaceID: row.workspace_id }),
)
if (Option.isNone(parsed)) return { type: "unavailable" as const }
return { type: "contents" as const, contents: parsed.value.contents }
} catch {
return { type: "unavailable" as const }
} finally {
db?.close()
}
}
function isZedActiveEditorRow(row: ZedEditorRow): row is ZedActiveEditorRow {
return row.item_kind === "Editor" && row.editor_id != null
}
export function resolveZedDbPath() {
const candidates = [
process.env.OPENCODE_ZED_DB,
path.join(os.homedir(), "Library", "Application Support", "Zed", "db", "0-stable", "db.sqlite"),
path.join(os.homedir(), ".local", "share", "zed", "db", "0-stable", "db.sqlite"),
].filter((item): item is string => Boolean(item))
return candidates.find((item) => isFile(item))
}
export function isZedTerminal() {
return process.env.ZED_TERM === "true" || process.env.TERM_PROGRAM?.toLowerCase() === "zed"
}
function isFile(item: string) {
try {
return statSync(item).isFile()
} catch {
return false
}
}
function scoreZedWorkspace(workspacePaths: string | null, cwd: string) {
return zedWorkspacePaths(workspacePaths).reduce((score, item) => {
if (pathContains(item, cwd)) return Math.max(score, path.resolve(item).length)
return score
}, 0)
}
function zedWorkspacePaths(value: string | null) {
if (!value) return []
const parsed = parseJson(value)
if (Array.isArray(parsed)) return parsed.filter((item): item is string => typeof item === "string")
return value.split(/\r?\n/).filter(Boolean)
}
export function offsetToPosition(text: string, offset: number) {
const stringOffset = utf8ByteOffsetToStringIndex(text, offset)
return offsetsToSelection(text, stringOffset, stringOffset).start
}
function utf8ByteOffsetToStringIndex(text: string, byteOffset: number) {
if (byteOffset <= 0) return 0
let bytes = 0
for (let index = 0; index < text.length; ) {
const codePoint = text.codePointAt(index)
if (codePoint === undefined) return text.length
const nextIndex = index + (codePoint > 0xffff ? 2 : 1)
bytes += utf8.encode(text.slice(index, nextIndex)).length
if (bytes >= byteOffset) return nextIndex
index = nextIndex
}
return text.length
}
function offsetsToSelection(text: string, startOffset: number, endOffset: number) {
const start = Math.max(0, Math.min(startOffset, text.length))
const end = Math.max(0, Math.min(endOffset, text.length))
let line = 1
let lineStart = 0
let startPosition = position(line, lineStart, start)
let endPosition = position(line, lineStart, end)
for (let index = 0; index <= end; index++) {
if (index === start) startPosition = position(line, lineStart, index)
if (index === end) {
endPosition = position(line, lineStart, index)
break
}
if (text[index] === "\n") {
line += 1
lineStart = index + 1
}
}
return { start: startPosition, end: endPosition }
}
function position(line: number, lineStart: number, offset: number) {
return {
line,
character: offset - lineStart + 1,
}
}
function pathContains(parent: string, child: string) {
const relative = path.relative(path.resolve(parent), path.resolve(child))
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative))
}
function parseJson(value: string) {
try {
return JSON.parse(value) as unknown
} catch {
return
}
}

View file

@ -1,43 +0,0 @@
import { defer } from "@/util/defer"
import { existsSync } from "node:fs"
import { rm } from "node:fs/promises"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { CliRenderer } from "@opentui/core"
import { Filesystem } from "@/util/filesystem"
import { Process } from "@/util/process"
export async function open(opts: { value: string; renderer: CliRenderer; cwd?: string }): Promise<string | undefined> {
const editor = process.env["VISUAL"] || process.env["EDITOR"]
if (!editor) return
const filepath = join(tmpdir(), `${Date.now()}.md`)
await using _ = defer(async () => rm(filepath, { force: true }))
// In attach mode the server's project directory may not exist locally.
// Fall back to the local process cwd so the editor can still spawn.
const cwd = opts.cwd && existsSync(opts.cwd) ? opts.cwd : process.cwd()
await Filesystem.write(filepath, opts.value)
opts.renderer.suspend()
opts.renderer.currentRenderBuffer.clear()
try {
const parts = editor.split(" ")
const proc = Process.spawn([...parts, filepath], {
cwd,
stdin: "inherit",
stdout: "inherit",
stderr: "inherit",
shell: process.platform === "win32",
})
await proc.exited
const content = await Filesystem.readText(filepath)
return content || undefined
} finally {
opts.renderer.currentRenderBuffer.clear()
opts.renderer.resume()
opts.renderer.requestRender()
}
}
export * as Editor from "./editor"

View file

@ -1,36 +0,0 @@
import type { TuiHost, TuiInput } from "@opencode-ai/tui"
import { Log } from "@opencode-ai/core/util/log"
import { FormatError, FormatUnknownError } from "@/cli/error"
import { createTuiAttention } from "./attention"
import { createLegacyTuiPlatform } from "./platform"
import * as TuiAudio from "./audio"
import { win32DisableProcessedInput, win32FlushInputBuffer, win32InstallCtrlCGuard } from "./win32"
export function createLegacyTuiHost(renderer: TuiInput["renderer"]): TuiHost {
return {
platform: createLegacyTuiPlatform(renderer),
attention: createTuiAttention,
logger: Log.Default,
disposeAudio: TuiAudio.dispose,
formatError: FormatError,
formatUnknownError: FormatUnknownError,
lifecycle: {
prepare() {
const unguard = win32InstallCtrlCGuard()
win32DisableProcessedInput()
return unguard
},
flushInput: win32FlushInputBuffer,
onSighup(handler) {
process.on("SIGHUP", handler)
return () => process.off("SIGHUP", handler)
},
writeStdout: (text) => process.stdout.write(text),
writeStderr: (text) => process.stderr.write(text),
suspend(resume) {
process.once("SIGCONT", resume)
process.kill(0, "SIGTSTP")
},
},
}
}

View file

@ -0,0 +1,7 @@
import { run as runTui, type TuiInput } from "@opencode-ai/tui"
import { Global } from "@opencode-ai/core/global"
import { Effect } from "effect"
export function run(input: TuiInput) {
return runTui(input).pipe(Effect.provide(Global.defaultLayer))
}

View file

@ -1,124 +0,0 @@
import type { CliRenderer } from "@opentui/core"
import type { TuiPlatform } from "@opencode-ai/tui/platform"
import { Filesystem } from "@/util/filesystem"
import { Clipboard } from "./clipboard"
import { Editor } from "./editor"
import { Flock } from "@opencode-ai/core/util/flock"
import { Glob } from "@opencode-ai/core/util/glob"
import { Global } from "@opencode-ai/core/global"
import { readJson, writeJsonAtomic } from "@opencode-ai/tui/util/persistence"
import path from "path"
import os from "node:os"
import { readdirSync, readFileSync, statSync } from "node:fs"
import { resolveZedSelection } from "./editor-zed"
export function createLegacyTuiPlatform(renderer: CliRenderer): TuiPlatform {
const statePath = path.join(Global.Path.state, "kv.json")
const stateLock = `tui-kv:${statePath}`
return {
files: {
readText: Filesystem.readText,
readBytes: Filesystem.readBytes,
mime: Filesystem.mimeType,
},
state: {
read: () => Flock.withLock(stateLock, () => readJson<Record<string, unknown>>(statePath)),
write: (value) => Flock.withLock(stateLock, () => writeJsonAtomic(statePath, value)),
},
themes: {
async discover() {
const directories = [
Global.Path.config,
...(await Array.fromAsync(Filesystem.up({ targets: [".opencode"], start: process.cwd() }))),
]
const result: Record<string, unknown> = {}
for (const dir of directories) {
for (const item of await Glob.scan("themes/*.json", {
cwd: dir,
absolute: true,
dot: true,
symlink: true,
})) {
result[path.basename(item, ".json")] = await Filesystem.readJson(item)
}
}
return result
},
subscribeRefresh(refresh) {
process.on("SIGUSR2", refresh)
return () => process.off("SIGUSR2", refresh)
},
},
clipboard: {
read: Clipboard.read,
write: Clipboard.copy,
},
editor: {
open: (input) => Editor.open({ ...input, renderer }),
connection: discoverEditorConnection,
selection: (directory) => resolveZedSelection(resolveZedDbPath(), directory),
},
export: {
write: Filesystem.write,
},
}
}
export function discoverEditorConnection(directory: string) {
const root = path.join(os.homedir(), ".claude", "ide")
const contains = (parent: string) => {
const resolved = path.resolve(parent)
const relative = path.relative(resolved, path.resolve(directory))
return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative)) ? resolved.length : 0
}
try {
return readdirSync(root)
.filter((entry) => entry.endsWith(".lock"))
.flatMap((entry) => {
const file = path.join(root, entry)
const port = Number.parseInt(path.basename(file, ".lock"), 10)
if (!Number.isInteger(port) || port <= 0 || port > 65535) return []
try {
const value = JSON.parse(readFileSync(file, "utf-8")) as Record<string, unknown>
if (value.transport !== undefined && value.transport !== "ws") return []
const folders = Array.isArray(value.workspaceFolders)
? value.workspaceFolders.filter((item): item is string => typeof item === "string")
: []
const score = Math.max(0, ...folders.map(contains))
if (!score) return []
return [
{
url: `ws://127.0.0.1:${port}`,
authToken: typeof value.authToken === "string" ? value.authToken : undefined,
source: `lock:${port}`,
score,
mtime: statSync(file).mtimeMs,
},
]
} catch {
return []
}
})
.sort((left, right) => right.score - left.score || right.mtime - left.mtime)
.map(({ url, authToken, source }) => ({ url, authToken, source }))[0]
} catch {
return undefined
}
}
function resolveZedDbPath() {
const candidates = [
process.env.OPENCODE_ZED_DB,
path.join(os.homedir(), "Library", "Application Support", "Zed", "db", "0-stable", "db.sqlite"),
path.join(os.homedir(), ".local", "share", "zed", "db", "0-stable", "db.sqlite"),
].filter((item): item is string => Boolean(item))
return (
candidates.find((item) => {
try {
return statSync(item).isFile()
} catch {
return false
}
}) ?? ""
)
}

View file

@ -1,57 +0,0 @@
import { Flag } from "@opencode-ai/core/flag/flag"
import { Global } from "@opencode-ai/core/global"
import { InstallationChannel, InstallationVersion } from "@opencode-ai/core/installation/version"
import type { TuiConfig } from "@opencode-ai/tui/config"
import { createTuiBuildInfo, createTuiEnvironment } from "@opencode-ai/tui/runtime"
import path from "path"
import { isZedTerminal, resolveZedDbPath } from "./editor-zed"
export function resolveTuiRuntime(config: TuiConfig.Resolved) {
return {
environment: createTuiEnvironment({
cwd: process.cwd(),
platform: process.platform,
initialRoute: parseInitialRoute(process.env.OPENCODE_ROUTE),
paths: {
home: Global.Path.home,
state: Global.Path.state,
worktree: path.join(Global.Path.data, "worktree"),
},
capabilities: {
mouse: !Flag.OPENCODE_DISABLE_MOUSE && (config.mouse ?? true),
copyOnSelect: !Flag.OPENCODE_EXPERIMENTAL_DISABLE_COPY_ON_SELECT,
terminalTitle: !Flag.OPENCODE_DISABLE_TERMINAL_TITLE,
terminalSuspend: process.platform !== "win32",
workspaces: Flag.OPENCODE_EXPERIMENTAL_WORKSPACES,
showTimeToFirstDraw: Flag.OPENCODE_SHOW_TTFD,
},
terminal: {
multiplexer: process.env.TMUX ? "tmux" : process.env.STY ? "screen" : undefined,
displayServer: process.env.WAYLAND_DISPLAY ? "wayland" : process.env.DISPLAY ? "x11" : undefined,
},
editor: {
command: process.env.VISUAL || process.env.EDITOR,
port: parsePort(process.env.CLAUDE_CODE_SSE_PORT || process.env.OPENCODE_EDITOR_SSE_PORT),
zedTerminal: isZedTerminal(),
zedDatabase: resolveZedDbPath(),
},
skipInitialLoading: Boolean(process.env.OPENCODE_FAST_BOOT),
}),
build: createTuiBuildInfo({
version: InstallationVersion,
channel: InstallationChannel,
}),
}
}
function parsePort(value: string | undefined) {
if (!value) return
const port = Number.parseInt(value, 10)
if (!Number.isInteger(port) || port <= 0 || port > 65535) return
return port
}
function parseInitialRoute(value: string | undefined) {
if (!value) return
return JSON.parse(value) as unknown
}

View file

@ -1,130 +0,0 @@
import { dlopen, ptr } from "bun:ffi"
import type { ReadStream } from "node:tty"
const STD_INPUT_HANDLE = -10
const ENABLE_PROCESSED_INPUT = 0x0001
const kernel = () =>
dlopen("kernel32.dll", {
GetStdHandle: { args: ["i32"], returns: "ptr" },
GetConsoleMode: { args: ["ptr", "ptr"], returns: "i32" },
SetConsoleMode: { args: ["ptr", "u32"], returns: "i32" },
FlushConsoleInputBuffer: { args: ["ptr"], returns: "i32" },
})
let k32: ReturnType<typeof kernel> | undefined
function load() {
if (process.platform !== "win32") return false
try {
k32 ??= kernel()
return true
} catch {
return false
}
}
/**
* Clear ENABLE_PROCESSED_INPUT on the console stdin handle.
*/
export function win32DisableProcessedInput() {
if (process.platform !== "win32") return
if (!process.stdin.isTTY) return
if (!load()) return
const handle = k32!.symbols.GetStdHandle(STD_INPUT_HANDLE)
const buf = new Uint32Array(1)
if (k32!.symbols.GetConsoleMode(handle, ptr(buf)) === 0) return
const mode = buf[0]!
if ((mode & ENABLE_PROCESSED_INPUT) === 0) return
k32!.symbols.SetConsoleMode(handle, mode & ~ENABLE_PROCESSED_INPUT)
}
/**
* Discard any queued console input (mouse events, key presses, etc.).
*/
export function win32FlushInputBuffer() {
if (process.platform !== "win32") return
if (!process.stdin.isTTY) return
if (!load()) return
const handle = k32!.symbols.GetStdHandle(STD_INPUT_HANDLE)
k32!.symbols.FlushConsoleInputBuffer(handle)
}
let unhook: (() => void) | undefined
/**
* Keep ENABLE_PROCESSED_INPUT disabled.
*
* On Windows, Ctrl+C becomes a CTRL_C_EVENT (instead of stdin input) when
* ENABLE_PROCESSED_INPUT is set. Various runtimes can re-apply console modes
* (sometimes on a later tick), and the flag is console-global, not per-process.
*
* We combine:
* - A `setRawMode(...)` hook to re-clear after known raw-mode toggles.
* - A low-frequency poll as a backstop for native/external mode changes.
*/
export function win32InstallCtrlCGuard() {
if (process.platform !== "win32") return
if (!process.stdin.isTTY) return
if (!load()) return
if (unhook) return unhook
const stdin = process.stdin as ReadStream
const original = stdin.setRawMode
const handle = k32!.symbols.GetStdHandle(STD_INPUT_HANDLE)
const buf = new Uint32Array(1)
if (k32!.symbols.GetConsoleMode(handle, ptr(buf)) === 0) return
const initial = buf[0]!
const enforce = () => {
if (k32!.symbols.GetConsoleMode(handle, ptr(buf)) === 0) return
const mode = buf[0]!
if ((mode & ENABLE_PROCESSED_INPUT) === 0) return
k32!.symbols.SetConsoleMode(handle, mode & ~ENABLE_PROCESSED_INPUT)
}
// Some runtimes can re-apply console modes on the next tick; enforce twice.
const later = () => {
enforce()
setImmediate(enforce)
}
let wrapped: ReadStream["setRawMode"] | undefined
if (typeof original === "function") {
wrapped = (mode: boolean) => {
const result = original.call(stdin, mode)
later()
return result
}
stdin.setRawMode = wrapped
}
// Ensure it's cleared immediately too (covers any earlier mode changes).
later()
const interval = setInterval(enforce, 100)
interval.unref()
let done = false
unhook = () => {
if (done) return
done = true
clearInterval(interval)
if (wrapped && stdin.setRawMode === wrapped) {
stdin.setRawMode = original
}
k32!.symbols.SetConsoleMode(handle, initial)
unhook = undefined
}
return unhook
}

View file

@ -1,6 +1,6 @@
import { describe, expect, test } from "bun:test"
import type { AudioPlayOptions, AudioSound } from "@opentui/core"
import { createTuiAttention } from "@/cli/tui/attention"
import { createTuiAttention } from "@opencode-ai/tui/attention"
import type { TuiConfig } from "@opencode-ai/tui/config"
type FocusEvent = "focus" | "blur"

View file

@ -1,330 +0,0 @@
import { afterEach, expect, spyOn, test } from "bun:test"
import { createTestRenderer } from "@opentui/core/testing"
import { mkdir } from "node:fs/promises"
import path from "node:path"
import { tmpdir } from "../../fixture/fixture"
import { createTuiResolvedConfig } from "../../fixture/tui-runtime"
import { tui, type TuiHandle } from "@opencode-ai/tui"
import { createLegacyTuiHost } from "../../../src/cli/tui/host"
import { Global } from "@opencode-ai/core/global"
import { createEventSource, createFetch, directory } from "../../fixture/tui-sdk"
import * as TuiAudio from "../../../src/cli/tui/audio"
import * as TuiKeymap from "@opencode-ai/tui/keymap"
import { createTuiBuildInfo, createTuiEnvironment } from "@opencode-ai/tui/runtime"
type TestRendererSetup = Awaited<ReturnType<typeof createTestRenderer>>
type TmpDir = Awaited<ReturnType<typeof tmpdir>>
const disabledInternalPlugins = {
"internal:home-footer": false,
"internal:home-tips": false,
"internal:sidebar-context": false,
"internal:sidebar-mcp": false,
"internal:sidebar-lsp": false,
"internal:sidebar-todo": false,
"internal:sidebar-files": false,
"internal:sidebar-footer": false,
"internal:plugin-manager": false,
"internal:session-v2-debug": false,
"which-key": false,
}
let active: { handle?: TuiHandle; setup?: TestRendererSetup; restore?: () => void; tmp?: TmpDir } | undefined
afterEach(async () => {
const current = active
active = undefined
await current?.handle?.exit().catch(() => {})
await current?.handle?.done.catch(() => {})
await current?.handle?.ready.catch(() => {})
if (current?.setup && !current.setup.renderer.isDestroyed) current.setup.renderer.destroy()
current?.restore?.()
await Bun.sleep(20)
await current?.tmp?.[Symbol.asyncDispose]()
})
test("returns a handle immediately and resolves ready after async mount setup", async () => {
const app = await startTui()
expect(await promiseState(app.handle.ready)).toBe("pending")
app.theme.resolve("dark")
await app.handle.ready
expect(app.setup.renderer.isDestroyed).toBe(false)
expect(await promiseState(app.handle.done)).toBe("pending")
})
test("production can await done only and still receives mount failures", async () => {
const app = await startTui({ rejectTheme: new Error("theme failed") })
await expect(app.handle.done).rejects.toThrow("theme failed")
expect(app.setup.renderer.isDestroyed).toBe(true)
})
test("plugin startup failure does not fail the app", async () => {
const error = spyOn(console, "error").mockImplementation(() => {})
try {
const app = await startTui({ rejectPlugins: new Error("plugins failed") })
app.theme.resolve("dark")
await expect(app.handle.ready).resolves.toBeUndefined()
await app.pluginHost.started
expect(app.setup.renderer.isDestroyed).toBe(false)
expect(app.pluginHost.starts).toBe(1)
await app.handle.exit()
await app.handle.done
} finally {
error.mockRestore()
}
})
test("exit destroys the renderer, resolves done, and runs cleanup once", async () => {
const beforeSighup = process.listenerCount("SIGHUP")
const app = await startTui()
app.theme.resolve("dark")
await app.handle.ready
expect(process.listenerCount("SIGHUP")).toBeGreaterThan(beforeSighup)
await Promise.all([app.handle.exit(), app.handle.exit()])
await app.handle.done
expect(app.setup.renderer.isDestroyed).toBe(true)
expect(process.listenerCount("SIGHUP")).toBeLessThanOrEqual(beforeSighup)
})
test("exit preserves reason formatting and exit messages", async () => {
const stdout: string[] = []
const stderr: string[] = []
const stdoutWrite = spyOn(process.stdout, "write").mockImplementation((chunk: string | Uint8Array) => {
stdout.push(String(chunk))
return true
})
const stderrWrite = spyOn(process.stderr, "write").mockImplementation((chunk: string | Uint8Array) => {
stderr.push(String(chunk))
return true
})
try {
const app = await startTui()
app.theme.resolve("dark")
await app.handle.ready
app.handle.exit.message.set("goodbye")
await app.handle.exit(new Error("boom"))
await app.handle.done
expect(stderr.join("")).toContain("boom")
expect(stdout.join("")).toBe("goodbye\n")
} finally {
stdoutWrite.mockRestore()
stderrWrite.mockRestore()
}
})
test("exit before ready cancels mount and resolves done", async () => {
const app = await startTui()
await app.handle.exit()
await app.handle.done
expect(app.setup.renderer.isDestroyed).toBe(true)
await expect(app.handle.ready).resolves.toBeUndefined()
})
test("direct renderer destruction still cleans up and resolves done", async () => {
const beforeSighup = process.listenerCount("SIGHUP")
const app = await startTui()
app.theme.resolve("dark")
await app.handle.ready
app.setup.renderer.destroy()
await app.handle.done
expect(process.listenerCount("SIGHUP")).toBeLessThanOrEqual(beforeSighup)
})
test("SIGHUP exits before ready and removes its listener", async () => {
const beforeSighup = process.listenerCount("SIGHUP")
const app = await startTui()
process.emit("SIGHUP")
await app.handle.done
expect(app.setup.renderer.isDestroyed).toBe(true)
expect(process.listenerCount("SIGHUP")).toBeLessThanOrEqual(beforeSighup)
})
test("SIGHUP exits after ready and removes its listener", async () => {
const beforeSighup = process.listenerCount("SIGHUP")
const app = await startTui()
app.theme.resolve("dark")
await app.handle.ready
process.emit("SIGHUP")
await app.handle.done
expect(app.setup.renderer.isDestroyed).toBe(true)
expect(process.listenerCount("SIGHUP")).toBe(beforeSighup)
})
test("plugin, audio, and keymap cleanup run exactly once", async () => {
const originalRegister = TuiKeymap.registerOpencodeKeymap
let unregisterKeymapCalls = 0
const registerKeymap = spyOn(TuiKeymap, "registerOpencodeKeymap").mockImplementation((...args) => {
const unregister = originalRegister(...args)
return () => {
unregisterKeymapCalls++
unregister()
}
})
const disposeAudio = spyOn(TuiAudio, "dispose")
try {
const app = await startTui()
app.theme.resolve("dark")
await app.handle.ready
app.setup.renderer.destroy()
await Promise.all([app.handle.exit(), app.handle.exit()])
await app.handle.done
expect(registerKeymap).toHaveBeenCalledTimes(1)
expect(unregisterKeymapCalls).toBe(1)
expect(app.pluginHost.disposes).toBe(1)
expect(disposeAudio).toHaveBeenCalledTimes(1)
} finally {
registerKeymap.mockRestore()
disposeAudio.mockRestore()
}
})
test("plugin disposal failure does not stop remaining cleanup", async () => {
const error = spyOn(console, "error").mockImplementation(() => {})
const disposeAudio = spyOn(TuiAudio, "dispose")
try {
const app = await startTui({ rejectPluginDispose: new Error("dispose failed") })
app.theme.resolve("dark")
await app.handle.ready
await app.handle.exit()
await app.handle.done
expect(app.pluginHost.disposes).toBe(1)
expect(disposeAudio).toHaveBeenCalledTimes(1)
expect(app.setup.renderer.isDestroyed).toBe(true)
} finally {
error.mockRestore()
disposeAudio.mockRestore()
}
})
async function startTui(options: { rejectTheme?: Error; rejectPlugins?: Error; rejectPluginDispose?: Error } = {}) {
const tmp = await tmpdir()
const isolated = await isolateGlobalPaths(tmp.path)
const setup = await createTestRenderer({ width: 80, height: 24, useThread: false, maxFps: Number.POSITIVE_INFINITY })
const theme = deferred<"dark" | "light" | null>()
const waitForThemeMode = spyOn(setup.renderer, "waitForThemeMode").mockImplementation(() => {
if (options.rejectTheme) return Promise.reject(options.rejectTheme)
return theme.promise
})
setup.renderer.once("destroy", () => theme.resolve(null))
const calls = createFetch()
const events = createEventSource()
const pluginStarted = deferred<void>()
const pluginHost = {
starts: 0,
disposes: 0,
started: pluginStarted.promise,
async start() {
pluginHost.starts++
pluginStarted.resolve()
if (options.rejectPlugins) throw options.rejectPlugins
},
async dispose() {
pluginHost.disposes++
if (options.rejectPluginDispose) throw options.rejectPluginDispose
},
}
const environment = createTuiEnvironment({
cwd: tmp.path,
platform: "linux",
paths: { home: tmp.path, state: isolated.state, worktree: path.join(tmp.path, "worktree") },
capabilities: {
mouse: true,
copyOnSelect: true,
terminalTitle: false,
terminalSuspend: false,
workspaces: false,
showTimeToFirstDraw: false,
},
terminal: {},
editor: { zedTerminal: false },
skipInitialLoading: false,
})
const handle = tui({
environment,
build: createTuiBuildInfo({ version: "test", channel: "test" }),
url: "http://test",
renderer: setup.renderer,
host: createLegacyTuiHost(setup.renderer),
config: createTuiResolvedConfig({ plugin_enabled: disabledInternalPlugins }),
directory,
fetch: calls.fetch,
events: events.source,
pluginHost,
args: {},
})
active = {
handle,
setup,
tmp,
restore: () => {
waitForThemeMode.mockRestore()
isolated.restore()
},
}
return { handle, setup, theme, pluginHost }
}
async function isolateGlobalPaths(root: string) {
const previous = Global.Path.config
Global.Path.config = path.join(root, "config")
const state = path.join(root, "state")
await mkdir(Global.Path.config, { recursive: true })
await mkdir(state, { recursive: true })
await Bun.write(path.join(state, "kv.json"), JSON.stringify({ animations_enabled: false }))
return {
state,
restore() {
Global.Path.config = previous
},
}
}
async function promiseState(promise: Promise<unknown>) {
let state: "pending" | "resolved" | "rejected" = "pending"
promise.then(
() => {
state = "resolved"
},
() => {
state = "rejected"
},
)
await Promise.resolve()
return state
}
function deferred<T>() {
let resolve!: (value: T | PromiseLike<T>) => void
let reject!: (error: unknown) => void
const promise = new Promise<T>((done, fail) => {
resolve = done
reject = fail
})
return { promise, resolve, reject }
}

View file

@ -1,11 +1,10 @@
import { describe, expect, test } from "bun:test"
describe("tui attach", () => {
test("loads the public TUI API and legacy hosts lazily", async () => {
test("loads the TUI integration lazily", async () => {
const source = await Bun.file(new URL("../../../src/cli/cmd/attach.ts", import.meta.url)).text()
expect(source).toMatch(/await import\(["']@opencode-ai\/tui["']\)/)
expect(source).toContain('await import("../tui/host")')
expect(source).toContain('await import("../tui/layer")')
expect(source).toMatch(/await import\(["']@\/plugin\/tui\/runtime["']\)/)
expect(source).not.toContain('import("./app")')
})

View file

@ -3,7 +3,12 @@ import { mkdir, symlink } from "node:fs/promises"
import os from "node:os"
import path from "node:path"
import { afterEach, expect, spyOn, test } from "bun:test"
import { isZedTerminal, offsetToPosition, resolveZedDbPath, resolveZedSelection } from "../../../src/cli/tui/editor-zed"
import {
isZedTerminal,
offsetToPosition,
resolveZedDbPath,
resolveZedSelection,
} from "@opencode-ai/tui/editor-zed"
import { tmpdir } from "../../fixture/fixture"
const originalZedTerm = process.env.ZED_TERM

View file

@ -3,12 +3,11 @@ import os from "node:os"
import path from "node:path"
import { afterEach, expect, spyOn, test } from "bun:test"
import { createRoot } from "solid-js"
import { EditorContextProvider, useEditorContext } from "@opencode-ai/tui/context/editor"
import { EditorContextProvider, useEditorContext, type EditorIntegration } from "@opencode-ai/tui/context/editor"
import { tmpdir } from "../../fixture/fixture"
import { FakeWebSocket } from "../../lib/websocket"
import { TestTuiEnvironmentProvider } from "../../fixture/tui-environment"
import { TuiPlatformProvider, type TuiPlatform } from "@opencode-ai/tui/platform"
import { discoverEditorConnection } from "../../../src/cli/tui/platform"
import { TestTuiContexts } from "../../fixture/tui-environment"
import { discoverEditorConnection } from "@opencode-ai/tui/editor"
const originalClaudePort = process.env.CLAUDE_CODE_SSE_PORT
const originalOpencodePort = process.env.OPENCODE_EDITOR_SSE_PORT
@ -36,17 +35,14 @@ function mountEditorContext(WebSocketImpl?: typeof WebSocket) {
const value = process.env.CLAUDE_CODE_SSE_PORT || process.env.OPENCODE_EDITOR_SSE_PORT
return (
<TestTuiEnvironmentProvider
<TestTuiContexts
cwd={process.cwd()}
paths={{ home: os.homedir() }}
editor={{ port: value ? Number.parseInt(value, 10) : undefined }}
>
<TuiPlatformProvider value={platform}>
<EditorContextProvider WebSocketImpl={WebSocketImpl}>
<EditorContextProvider integration={editorService} WebSocketImpl={WebSocketImpl}>
<Consumer />
</EditorContextProvider>
</TuiPlatformProvider>
</TestTuiEnvironmentProvider>
</TestTuiContexts>
)
})
@ -56,16 +52,8 @@ function mountEditorContext(WebSocketImpl?: typeof WebSocket) {
}
}
const platform: TuiPlatform = {
files: {
readText: (file) => Bun.file(file).text(),
readBytes: (file) => Bun.file(file).bytes(),
mime: () => Promise.resolve("application/octet-stream"),
},
editor: {
open: () => Promise.resolve(undefined),
connection: discoverEditorConnection,
},
const editorService: EditorIntegration = {
connection: discoverEditorConnection,
}
function createWebSocketImpl(...sockets: FakeWebSocket[]) {

View file

@ -5,11 +5,10 @@ import { tmpdir } from "../../fixture/fixture"
import { resolveThreadDirectory } from "../../../src/cli/cmd/tui"
describe("tui thread", () => {
test("loads the public TUI API and legacy hosts lazily", async () => {
test("loads the TUI integration lazily", async () => {
const source = await Bun.file(new URL("../../../src/cli/cmd/tui.ts", import.meta.url)).text()
expect(source).toMatch(/await import\(["']@opencode-ai\/tui["']\)/)
expect(source).toContain('await import("../tui/host")')
expect(source).toContain('await import("../tui/layer")')
expect(source).toMatch(/await import\(["']@\/plugin\/tui\/runtime["']\)/)
expect(source).not.toContain('import("./app")')
})

View file

@ -1,42 +1,32 @@
/** @jsxImportSource @opentui/solid */
import { createTuiEnvironment, TuiEnvironmentProvider, type TuiEnvironment } from "@opencode-ai/tui/runtime"
import {
TuiPathsProvider,
TuiStartupProvider,
TuiTerminalEnvironmentProvider,
type TuiPaths,
} from "@opencode-ai/tui/context/runtime"
import type { ParentProps } from "solid-js"
export function TestTuiEnvironmentProvider(
export function TestTuiContexts(
props: ParentProps<{
cwd?: string
directory?: string
paths?: Partial<TuiEnvironment["paths"]>
capabilities?: Partial<TuiEnvironment["capabilities"]>
editor?: Partial<TuiEnvironment["editor"]>
paths?: Partial<TuiPaths>
}>,
) {
return (
<TuiEnvironmentProvider
value={createTuiEnvironment({
<TuiPathsProvider
value={{
cwd: props.cwd ?? props.directory ?? "/tmp/opencode/packages/opencode",
platform: "linux",
paths: {
home: "/tmp/opencode/home",
state: "/tmp/opencode/state",
worktree: "/tmp/opencode",
...props.paths,
},
capabilities: {
mouse: true,
copyOnSelect: true,
terminalTitle: false,
terminalSuspend: false,
workspaces: false,
showTimeToFirstDraw: false,
...props.capabilities,
},
terminal: {},
editor: { zedTerminal: false, ...props.editor },
skipInitialLoading: false,
})}
home: "/tmp/opencode/home",
state: "/tmp/opencode/state",
worktree: "/tmp/opencode",
...props.paths,
}}
>
{props.children}
</TuiEnvironmentProvider>
<TuiTerminalEnvironmentProvider value={{ platform: "linux" }}>
<TuiStartupProvider value={{ skipInitialLoading: false }}>{props.children}</TuiStartupProvider>
</TuiTerminalEnvironmentProvider>
</TuiPathsProvider>
)
}