Files
LLeMbas-CLI/scripts/smoke.ts
T
HomerandClaude Fable 5.2 99081c4ed4 The terminal is LLeMbas TERM: terminal contract 4, harness spec 3.15.0
LLEMBAS_TERM, LLEMBAS_TERM_PANE, LLEMBAS_TERM_EXECUTABLE, LLEMBAS_TERM_STATUS_DIR,
llembas-term-status=1, llembas-term-input=1, the llembas-term directory and the
llembas_term_status user var are the names. The ones from before the rename are
also read — a whole family at a time, the new one first — so the terminal's
releases before it work unchanged. One place decides: src/terminal/env.ts
(terminalNames, namesOf, isMagic). lembas --version --json: terminal_contract 4,
capability terminal_names_2. connection.json: product term.

The terminal's tests run in both spellings (scripts/test-terminal-names.sh, in
scripts/ci.sh).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-12-02 20:15:36 +00:00

543 lines
33 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env bun
// Smoke test of the COMPILED binary — what `bun test` cannot see: that the bundle, OpenTUI's
// native library and bun:sqlite FTS5 all survive `bun build --compile`.
// bun run scripts/smoke.ts [path/to/binary]
import { existsSync, mkdirSync, mkdtempSync, readdirSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join, resolve } from "node:path"
import { fakePane } from "../tests/fake-pane.ts"
import { delta, fakeProvider, toolCall, usage } from "../tests/fake-provider.ts"
import { placeDisplay } from "../src/tui/layout.ts"
import { png } from "../tests/png.ts"
import { drive, fakeHome, type Driver } from "./drive.ts"
const bin = resolve(process.argv[2] ?? "dist/lembas")
const home = mkdtempSync(join(tmpdir(), "lembas-smoke-"))
const env = { ...process.env, LEMBAS_HOME: home }
let failed = 0
const check = (name: string, ok: boolean, detail = "") => {
console.log(`${ok ? "✓" : "✗"} ${name}${ok ? "" : " " + detail}`)
if (!ok) failed++
}
const run = (args: string[], cwd = home) => {
const r = Bun.spawnSync([bin, ...args], { cwd, env, stdout: "pipe", stderr: "pipe" })
return { code: r.exitCode, out: r.stdout.toString(), err: r.stderr.toString() }
}
/** Whether the display pane's border is in column `x` on every row of the terminal. */
const borderOnEveryRow = (d: Driver, x: number, rows: number) => Array.from({ length: rows }, (_, y) => d.cell(x, y)).every((c) => c === "│")
const BLOCKS = /[▀▄█▌▐▖▗▘▙▚▛▜▝▞▟]/
// 1. --version
const v = run(["--version"])
check("--version", v.code === 0 && /^\d+\.\d+\.\d+/.test(v.out), v.err)
// 2. a headless run against a fake endpoint, with the session store on (FTS5 inside the binary)
const fake = fakeProvider([{ chunks: [delta({ content: "smoke ok" }), usage(5, 2)] }], { served: [{ id: "fake/m" }] })
mkdirSync(join(home, ".config/lembas"), { recursive: true })
writeFileSync(
join(home, ".config/lembas/connections.yaml"),
`connections:\n fake:\n type: webui\n url: ${fake.url}\n api_key: smoke\n models:\n fake/m: {}\n`,
{ mode: 0o600 },
)
writeFileSync(join(home, ".config/lembas/config.yaml"), "model: fake/m\nupdate: { auto: off }\n")
const r = await new Promise<{ code: number; out: string; err: string }>((res) => {
const p = Bun.spawn([bin, "run", "say hi"], { cwd: home, env, stdout: "pipe", stderr: "pipe" })
Promise.all([new Response(p.stdout).text(), new Response(p.stderr).text(), p.exited]).then(([out, err, code]) => res({ code, out, err }))
})
fake.stop()
check("run → streamed answer", r.code === 0 && r.out === "smoke ok\n", JSON.stringify(r))
const s = run(["sessions"])
check("sessions → recorded (sqlite + FTS5 in the binary)", s.code === 0 && s.out.includes("fake/m"), s.err || s.out)
// 2b. serve --stdio: the ACP agent inside the binary answers initialize, opens a session and
// streams a reply — the code the LLeMbas link runs too.
{
const f = fakeProvider([{ chunks: [delta({ content: "acp ok" })] }], { served: [{ id: "fake/m" }] })
writeFileSync(
join(home, ".config/lembas/connections.yaml"),
`connections:\n fake:\n type: webui\n url: ${f.url}\n api_key: smoke\n models:\n fake/m: {}\n`,
{ mode: 0o600 },
)
const p = Bun.spawn([bin, "serve", "--stdio"], { cwd: home, env, stdin: "pipe", stdout: "pipe", stderr: "pipe" })
const lines: any[] = []
const reader = (async () => {
let buf = ""
for await (const chunk of p.stdout as unknown as AsyncIterable<Uint8Array>) {
buf += new TextDecoder().decode(chunk)
let nl: number
while ((nl = buf.indexOf("\n")) >= 0) {
const line = buf.slice(0, nl).trim()
buf = buf.slice(nl + 1)
if (line) lines.push(JSON.parse(line))
}
}
})()
const send = (m: unknown) => p.stdin.write(JSON.stringify(m) + "\n")
const answer = async (id: number) => {
for (let i = 0; i < 300; i++) {
const hit = lines.find((l) => l.id === id)
if (hit) return hit
await Bun.sleep(20)
}
return undefined
}
send({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: 1, clientCapabilities: {} } })
const init = await answer(1)
send({ jsonrpc: "2.0", id: 2, method: "session/new", params: { cwd: home, mcpServers: [] } })
const session = await answer(2)
send({ jsonrpc: "2.0", id: 3, method: "session/prompt", params: { sessionId: session?.result?.sessionId, prompt: [{ type: "text", text: "hi" }] } })
const done = await answer(3)
const text = lines.filter((l) => l.method === "session/update" && l.params.update.sessionUpdate === "agent_message_chunk").map((l) => l.params.update.content.text).join("")
p.stdin.end()
await Promise.race([p.exited, Bun.sleep(3000)])
p.kill()
await reader.catch(() => {})
f.stop()
check("serve --stdio → ACP session streams a reply", init?.result?.protocolVersion === 1 && done?.result?.stopReason === "end_turn" && text === "acp ok", JSON.stringify({ init, session, done, text }))
}
// 3. the real TUI in a real PTY, read back through a headless xterm, at two sizes
for (const [cols, rows] of [
[120, 40],
[80, 24],
] as const) {
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [delta({ content: "Let me check." }), toolCall(0, "c1", "bash", '{"command":"echo smoke > out.txt","description":"Write out.txt"}'), usage(9000, 40)] },
{ chunks: [delta({ content: "## Done\n\nWrote **out.txt**." }), usage(12000, 60)] },
])
const d = await drive({ cols, rows, bin, home: h, cwd })
// A fresh directory opens with the first-run question; trust it (the default), then work.
const firstRun = await d.waitFor("Trust this directory?")
await d.key("\r")
const drawn = await d.waitFor("shift+tab mode")
await d.type("make a file")
await d.key("\r")
const asked = await d.waitFor("Allow once")
await d.key("y")
const answered = await d.waitFor("Wrote out.txt.")
await Bun.sleep(200)
const screen = d.screen()
const wrapped = d.wrapped()
// The display pane: a column at the right over every row — beside the prompt and the status bar.
const place = placeDisplay({ width: cols, enabled: true, zoomed: false })
const fullHeight = place.mode === "side" && borderOnEveryRow(d, place.left, rows)
const keyLine = Array.from({ length: cols - place.left }, (_, i) => d.cell(place.left + i, rows - 1) || " ").join("")
const promptRow = Array.from({ length: place.left }, (_, i) => d.cell(i, rows - 2) || " ").join("")
await d.key("\x03")
await d.key("\x03")
const code = await d.close()
f.stop()
const file = await Bun.file(join(cwd, "out.txt")).text().catch(() => "")
check(
`TUI ${cols}x${rows}: the display pane stands beside the conversation, the prompt and the status bar, over the full height`,
fullHeight && keyLine.includes("hide") && promptRow.includes("❯") && screen.some((l) => l.includes("Recent activity")),
`placement=${JSON.stringify(place)} fullHeight=${fullHeight} keyLine=${JSON.stringify(keyLine)} promptRow=${JSON.stringify(promptRow)}\n${screen.join("\n")}`,
)
check(
`TUI ${cols}x${rows}: first run → prompt → approval → answer → quit`,
firstRun && drawn && asked && answered && file === "smoke\n" && code === 0,
`firstRun=${firstRun} drawn=${drawn} asked=${asked} answered=${answered} file=${JSON.stringify(file)} exit=${code}\n${screen.join("\n")}`,
)
check(`TUI ${cols}x${rows}: nothing wider than the terminal`, wrapped.length === 0, `wrapped rows: ${wrapped.join(", ")}`)
check(`TUI ${cols}x${rows}: status bar on the last row`, (screen[rows - 1] ?? "").includes("manual · fake/coder"), screen[rows - 1] ?? "")
}
// 3a. too narrow for two columns (70×24): the display is not silently absent — the status bar
// names the key, alt+d puts it in the transcript's place (the prompt and the status bar stay) and
// alt+d again brings the transcript back.
{
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [delta({ content: "Reading it." }), toolCall(0, "c1", "read", '{"path":"hello.txt"}'), usage(900, 40)] },
{ chunks: [delta({ content: "It says hello." }), usage(1200, 20)] },
])
const d = await drive({ cols: 70, rows: 24, bin, home: h, cwd })
await d.waitFor("Trust this directory?")
await d.key("\r")
await d.waitFor("shift+tab mode")
await d.type("read it")
await d.key("\r")
const answered = await d.waitFor("It says hello.")
const named = await d.waitFor("alt+d display")
const tucked = !d.screen().some((l) => l.includes("Recent activity"))
await d.key("\x1bd")
const opened = (await d.waitFor("Recent activity")) && (await d.waitFor("alt+d transcript"))
await Bun.sleep(200)
const zoom = d.screen()
const inPlace = !zoom.some((l) => l.includes("It says hello.")) && (zoom[22] ?? "").includes("❯") && (zoom[23] ?? "").includes("manual · fake/coder") && d.cell(0, 0) !== "│"
const wrapped = d.wrapped()
await d.key("\x1bd")
const back = (await d.waitFor("It says hello.")) && !d.screen().some((l) => l.includes("Recent activity"))
await d.key("\x03")
await d.key("\x03")
const code = await d.close()
f.stop()
check(
"TUI 70x24: no room beside the conversation — the status bar names the display, alt+d opens it in the transcript's place and back",
answered && named && tucked && opened && inPlace && back && code === 0,
`answered=${answered} named=${named} tucked=${tucked} opened=${opened} inPlace=${inPlace} back=${back} exit=${code}\n${zoom.join("\n")}`,
)
check("TUI 70x24: the display in the transcript's place is no wider than the terminal", wrapped.length === 0, `wrapped rows: ${wrapped.join(", ")}`)
}
// 3c. compact and full, and a picture, at 120×40: beside the display a round of calls is one line;
// alt+t shows every call on its own line and back; a picture attached with @ is drawn in the
// images tab — OpenTUI's native image decoder inside the compiled binary (blocks: this terminal
// has no graphics protocol).
{
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [delta({ content: "Looking." }), toolCall(0, "c1", "read", '{"path":"hello.txt"}'), toolCall(1, "c2", "grep", '{"pattern":"hello","path":"."}'), usage(900, 40)] },
{ chunks: [delta({ content: "Both say hello." }), usage(1200, 20)] },
// Twice: the session's title is asked of the model too.
{ chunks: [delta({ content: "A picture, noted." }), usage(1300, 20)] },
{ chunks: [delta({ content: "A picture, noted." }), usage(1300, 20)] },
])
writeFileSync(join(cwd, "shot.png"), png(64, 32))
const d = await drive({ cols: 120, rows: 40, bin, home: h, cwd })
await d.waitFor("Trust this directory?")
await d.key("\r")
await d.waitFor("shift+tab mode")
await d.type("look")
await d.key("\r")
const answered = await d.waitFor("Both say hello.")
const left = () => d.screen().map((l) => l.slice(0, 68))
const compact = (await d.waitFor("▸ 2 tools · read · grep")) && !left().some((l) => /read +hello\.txt/.test(l))
await d.key("\x1bt")
await d.waitFor("transcript: full")
await Bun.sleep(300)
const full = left().some((l) => /read +hello\.txt/.test(l)) && left().some((l) => /grep +hello/.test(l)) && !left().some((l) => l.includes("2 tools"))
const fullScreen = d.screen()
await d.key("\x1bt")
const again = await d.waitFor("▸ 2 tools · read · grep")
await d.type("@shot.png what is this ")
await d.key("\r")
const noted = await d.waitFor("A picture, noted.")
await d.type("/display images")
await d.key("\r")
const listed = await d.waitFor("shot.png · attached")
await Bun.sleep(500)
const picture = d.screen()
const drawn = picture.some((l) => BLOCKS.test(l.slice(68))) && picture.some((l) => l.includes("64×32"))
const wrapped = d.wrapped()
await d.key("\x03")
await d.key("\x03")
const code = await d.close()
const modes = d.modes()
f.stop()
check(
"TUI 120x40: beside the display a tool round is one line; alt+t shows every call and back",
answered && compact && full && again,
`answered=${answered} compact=${compact} full=${full} again=${again}\n${fullScreen.join("\n")}`,
)
check(
"TUI 120x40: an attached picture is drawn in the images tab (the native decoder inside the binary)",
noted && listed && drawn && wrapped.length === 0 && code === 0 && modes.mouse === "none" && !modes.altScreen,
`noted=${noted} listed=${listed} drawn=${drawn} wrapped=${wrapped.join(",")} exit=${code} modes=${JSON.stringify(modes)}\n${picture.join("\n")}`,
)
}
// 3b. jobs, at 80×24: a command the model starts in the background is counted in the status bar;
// /jobs opens the list (the row fits the terminal) and esc closes it; quitting with it running asks
// first, and y stops it and leaves.
{
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [delta({ content: "Starting it." }), toolCall(0, "c1", "bash", '{"command":"sleep 60","background":true,"description":"A long server that keeps running"}'), usage(900, 40)] },
{ chunks: [delta({ content: "Started it in the background." }), usage(1200, 20)] },
])
const d = await drive({ cols: 80, rows: 24, bin, home: h, cwd })
await d.waitFor("Trust this directory?")
await d.key("\r")
await d.waitFor("shift+tab mode")
await d.type("start a server")
await d.key("\r")
const asked = await d.waitFor("Allow once")
await d.key("y")
const started = await d.waitFor("Started it in the background.")
const counted = await d.waitFor("1 job ·")
await d.type("/jobs")
await d.key("\r")
const opened = await d.waitFor("enter open · k stop")
// The row: id, the description, the state, the time, and the box's border after them.
const row = d.screen().find((l) => l.includes("job1")) ?? ""
const listed = /job1 .*A long server.*running +\d+s +│/.test(row)
const wrapped = d.wrapped()
const screen = d.screen()
await d.key("\x1b")
await Bun.sleep(400)
const closed = !d.screen().some((l) => l.includes("enter open · k stop"))
await d.key("\x03")
await d.key("\x03")
const confirm = await d.waitFor("1 job running — stop it and quit?")
await d.key("y")
const code = await d.close()
f.stop()
check(
"TUI 80x24: a background job is counted; /jobs opens and closes; quitting with it running asks, y stops it and quits",
asked && started && counted && opened && listed && closed && confirm && code === 0,
`asked=${asked} started=${started} counted=${counted} opened=${opened} listed=${listed} closed=${closed} confirm=${confirm} exit=${code}\n${screen.join("\n")}`,
)
check("TUI 80x24: the jobs list is no wider than the terminal", wrapped.length === 0, `wrapped rows: ${wrapped.join(", ")}`)
}
// 4. a fresh install: no model yet. A screen that says what to add (not an exception with the
// terminal left in mouse-reporting mode); r once it is added opens the session; the terminal is
// given back as it was found.
{
const { fake: f, home: h, cwd } = fakeHome([{ chunks: [delta({ content: "hello after setup" }), usage(5, 2)] }])
const cfgDir = join(h, ".config/lembas")
const connections = await Bun.file(join(cfgDir, "connections.yaml")).text()
await Bun.write(join(cfgDir, "connections.yaml"), "connections: {}\n")
await Bun.write(join(cfgDir, "config.yaml"), "mode: manual\nupdate: { auto: off }\n")
const d = await drive({ cols: 100, rows: 30, bin, home: h, cwd })
await d.waitFor("Trust this directory?")
await d.key("\r")
const setup = await d.waitFor("not logged in to a LLeMbas server")
await Bun.write(join(cfgDir, "connections.yaml"), connections)
await Bun.write(join(cfgDir, "config.yaml"), "model: fake/coder\nupdate: { auto: off }\n")
// The screen opens on the sign-in, its address focused: ctrl+r tries again from there.
const focused = await d.waitFor("Log in to a LLeMbas instance")
await d.key("\x12")
const opened = await d.waitFor("fake/coder")
await d.type("hi")
await d.key("\r")
const answered = await d.waitFor("hello after setup")
await d.key("\x03")
await d.key("\x03")
const code = await d.close()
const modes = d.modes()
f.stop()
check("fresh install: no model → setup screen on the sign-in; ctrl+r after adding one → a session", setup && focused && opened && answered && code === 0, `setup=${setup} focused=${focused} opened=${opened} answered=${answered} exit=${code}\n${d.screen().join("\n")}`)
check("fresh install: the terminal is given back (mouse reporting off, normal screen)", modes.mouse === "none" && !modes.altScreen, JSON.stringify(modes))
}
// 5. /reload: the same process starts again (execv) on the same session — the conversation is
// there, the terminal is the TUI's again, and quitting leaves it as it was found.
{
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [delta({ content: "first answer" }), usage(5, 2)] },
{ chunks: [delta({ content: "second answer" }), usage(9, 2)] },
])
const d = await drive({ cols: 100, rows: 30, bin, home: h, cwd })
await d.waitFor("Trust this directory?")
await d.key("\r")
await d.waitFor("fake/coder")
await d.type("hello")
await d.key("\r")
const answered = await d.waitFor("first answer")
await d.type("/reload")
await d.key("\r")
// The new program draws its welcome box again, with the conversation loaded under it.
await Bun.sleep(300)
const back = await d.waitFor("shift+tab mode")
// The new program's next request carries the conversation from before the reload.
await d.type("again")
await d.key("\r")
await d.waitFor("second answer")
const history = JSON.stringify(f.requests[1]?.messages ?? [])
const kept = history.includes("hello") && history.includes("first answer")
const screen = d.screen()
await d.key("\x03")
await d.key("\x03")
const code = await d.close()
const modes = d.modes()
f.stop()
check("/reload: started again, back on the same session", answered && back && kept && code === 0, `answered=${answered} back=${back} kept=${kept} exit=${code}\n${screen.join("\n")}`)
check("/reload: the terminal is given back on quit", modes.mouse === "none" && !modes.altScreen, JSON.stringify(modes))
}
// 6. local mode (-l): everything in the project, nothing written anywhere else — the user's
// directories, HOME and TMPDIR are checked file by file before and after a whole session.
{
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [delta({ content: "Writing it." }), toolCall(0, "c1", "bash", '{"command":"echo local > out.txt","description":"Write out.txt"}'), usage(900, 40)] },
{ chunks: [delta({ content: "local done" }), usage(1200, 20)] },
])
const tmp = mkdtempSync(join(tmpdir(), "lembas-smoke-tmp-"))
const listing = (dir: string): string[] => {
const out: string[] = []
for (const e of readdirSync(dir, { withFileTypes: true, recursive: true })) out.push(join(e.parentPath, e.name))
return out.sort()
}
const before = { home: listing(h), tmp: listing(tmp) }
const d = await drive({ cols: 100, rows: 30, bin, home: h, cwd, args: ["-l"], env: { HOME: h, TMPDIR: tmp, XDG_CONFIG_HOME: join(h, ".config"), XDG_DATA_HOME: join(h, ".local/share"), XDG_STATE_HOME: join(h, ".local/state") } })
const firstRun = await d.waitFor("Trust this directory?")
await d.key("\r")
const drawn = await d.waitFor("shift+tab mode", 15000)
await d.type("make a file")
await d.key("\r")
const asked = await d.waitFor("Allow once")
await d.key("y")
const answered = await d.waitFor("local done")
await d.type("/remote")
await d.key("\r")
const refused = await d.waitFor("off in local mode")
const screen = d.screen()
await d.key("\x03")
await d.key("\x03")
const code = await d.close()
f.stop()
const after = { home: listing(h), tmp: listing(tmp) }
const grew = [...after.home.filter((p) => !before.home.includes(p)), ...after.tmp.filter((p) => !before.tmp.includes(p))]
const kept = ["data/sessions.db", "state/trust.json"].every((p) => existsSync(join(cwd, ".agent/local/lembas", p)))
check(
"local mode: a whole session works from the project",
firstRun && drawn && asked && answered && refused && kept && code === 0 && (screen[29] ?? "").includes("local"),
`firstRun=${firstRun} drawn=${drawn} asked=${asked} answered=${answered} refused=${refused} kept=${kept} exit=${code}\n${screen.join("\n")}`,
)
check("local mode: nothing written outside the project (home, XDG dirs, TMPDIR)", grew.length === 0, grew.join(", "))
}
// 7. the terminal's display (harness acp.md, *The terminal's display*, contract 3): `lembas
// terminal` in a real PTY at a third of a terminal's width, driven with the exact bytes a
// LLeMbas terminal writes to its pane, against a stand-in for the terminal's own program that
// records what is typed and plays a pane (tests/fake-pane.ts). Manual mode places a command at
// the prompt without Enter; the stand-in "person" presses Enter, edits it and presses Enter,
// presses Ctrl+C, and does nothing.
{
const { fake: f, home: h, cwd } = fakeHome([
{ chunks: [toolCall(0, "c1", "terminal_run", '{"command":"make test","why":"to see the failure again"}'), usage(900, 40)] },
{ chunks: [delta({ content: "The **oven** test fails: 220 expected." }), usage(1200, 20)] },
// The conversation's title, asked of the model once the first reply is in.
{ chunks: [delta({ content: "Oven test" }), usage(100, 3)] },
{ chunks: [toolCall(0, "c2", "terminal_run", '{"command":"make test","why":"to run it once more"}'), usage(1300, 40)] },
{ chunks: [delta({ content: "With one job it passes." }), usage(1400, 20)] },
{ chunks: [toolCall(0, "c3", "terminal_run", '{"command":"systemctl restart web","why":"to pick up the change"}'), usage(1500, 40)] },
{ chunks: [delta({ content: "Left it alone." }), usage(1600, 20)] },
{ chunks: [toolCall(0, "c4", "terminal_run", '{"command":"make clean","why":"to start fresh"}'), usage(1700, 40)] },
{ chunks: [delta({ content: "still the oven" }), usage(1800, 20)] },
])
const tty = mkdtempSync(join(tmpdir(), "lembas-smoke-tty-"))
const pane = fakePane(tty, { output: "SMOKE-PANE-OUTPUT 1 failed" })
const ttyEnv = { LLEMBAS_TERM: "2.0.0", LLEMBAS_TERM_PANE: "3", LLEMBAS_TERM_EXECUTABLE: pane.exe, LLEMBAS_TERM_STATUS_DIR: pane.statusDir }
const context = join(tty, "context-1.json")
writeFileSync(context, JSON.stringify({ version: 2, pane: 7, cwd, shell: "zsh", blocks: [{ seq: 1, command: "make test", exit: 2, output: "FAIL src/oven.test.ts\n1 failed" }] }), { mode: 0o600 })
const args = ["terminal", "--window", "smoke-1", "--pane", "7"]
const d = await drive({ cols: 45, rows: 30, bin, home: h, cwd, args, env: ttyEnv })
const up = await d.waitFor("idle")
const noBox = !d.screen().some((l) => l.includes("shift+tab") || l.includes("ctrl+"))
// Keys typed into the pane, one by one: no message, no command.
await d.type("ls /new\r")
await Bun.sleep(300)
const ignored = f.requests.length === 0
const sends = () => pane.calls().split("\n").filter((l) => l.includes("send-text")).length
const toolResult = (id: string) => String(f.requests.flatMap((r) => r.messages).find((m: { role: string; tool_call_id?: string }) => m.role === "tool" && m.tool_call_id === id)?.content ?? "")
// What the terminal sends, in ONE write: the context line, then the question as a paste.
await d.key(`/terminal-context ${context}\r\x1b[200~why did it fail?\x1b[201~\r`)
// (a) Manual mode: no approval card — the command stands at the person's prompt, not entered.
const placed = await d.waitFor("at your prompt: make test")
await Bun.sleep(400)
const waiting = d.screen()
const noCard = !waiting.join("\n").includes("allow terminal_run?")
const notEntered = pane.placed() === "make test\n" && pane.typed() === ""
const sent = JSON.stringify(f.requests[0]?.messages ?? [])
check(
"display 45x30: up without a box, typed keys ignored, one write is a question with its context",
up && noBox && ignored && placed && sent.includes("why did it fail?") && sent.includes("<terminal>") && sent.includes("1 failed") && !existsSync(context),
`up=${up} noBox=${noBox} ignored=${ignored} placed=${placed} contextGone=${!existsSync(context)}\n${waiting.join("\n")}`,
)
check(
"display, manual: the command is placed at the person's prompt without Enter, with no approval card — the display says where it is and what they can do",
placed && noCard && notEntered && pane.calls().includes("cli send-text --pane-id 7 --no-paste") && waiting.join(" ").replace(/[│┃]/g, "").replace(/\s+/g, " ").includes("Enter runs it · Ctrl+C dismisses") && waiting[0]!.includes("asking") && waiting.some((l) => l.startsWith("$ make test") && l.includes("at your prompt")),
`noCard=${noCard} placed=${JSON.stringify(pane.placed())} typed=${JSON.stringify(pane.typed())}\n${waiting.join("\n")}`,
)
// A terminal written for the card sends /approve: it decides nothing, and nothing is typed.
await d.key("/approve\r")
const told = await d.waitFor("Nothing to approve here")
check("display: /approve from a terminal that knows the card decides nothing, in words", told && pane.typed() === "" && sends() === 1, d.screen().join("\n"))
// The person presses Enter in their own pane.
pane.enter({ exit: 2 })
const ran = await d.waitFor("ran, exit 2")
const answered = await d.waitFor("220 expected")
await Bun.sleep(200)
const screen = d.screen()
check(
"display, placed and Enter: the exit status and the end of the pane come back; the row says ran, never the output",
ran && answered && toolResult("c1").includes("The person pressed Enter: it ran as placed.\nIt ended with exit status 2.") && toolResult("c1").includes("SMOKE-PANE-OUTPUT") && screen.some((l) => l.startsWith("$ make test") && l.includes("ran, exit 2")) && !screen.join("\n").includes("SMOKE-PANE-OUTPUT"),
`ran=${ran} answered=${answered}\n${toolResult("c1")}\n${screen.join("\n")}`,
)
check("display 45x30: nothing wider than the pane", d.wrapped().length === 0 && screen.every((l) => l.length <= 45), `wrapped rows: ${d.wrapped().join(", ")}`)
check("display: no tool that edits files or runs a shell of its own is offered", (() => { const names: string[] = (f.requests[0]?.tools ?? []).map((t: { function: { name: string } }) => t.function.name); return names.includes("terminal_run") && !["bash", "edit", "write", "multiedit", "apply_patch", "read", "task"].some((n) => names.includes(n)) })(), JSON.stringify((f.requests[0]?.tools ?? []).map((t: { function: { name: string } }) => t.function.name)))
// (b) The person edits the line, then presses Enter: the model is told what actually ran.
await d.waitFor("idle")
await d.key("\x1b[200~once more\x1b[201~\r")
await d.waitFor("at your prompt: make test")
await Bun.sleep(500)
pane.enter({ line: "make test -j1", exit: 0 })
const edited = (await d.waitFor("ran, edited")) && (await d.waitFor("one job it passes"))
check("display, placed and edited before Enter: the model is told the line was changed, and what ran", edited && toolResult("c2").includes("The person changed the line before running it. What ran, read from their screen: make test -j1\nIt ended with exit status 0."), `${toolResult("c2")}\n${d.screen().join("\n")}`)
// (c) Ctrl+C on the line: declined.
await d.waitFor("idle")
await d.key("\x1b[200~restart the web service\x1b[201~\r")
await d.waitFor("at your prompt: systemctl")
await Bun.sleep(500)
pane.dismiss()
const dismissed = (await d.waitFor("dismissed")) && (await d.waitFor("Left it alone."))
check("display, placed and Ctrl+C: the model is told the person declined and not to place it again", dismissed && toolResult("c3").includes("The person did not run it") && toolResult("c3").includes("do not place the same command again") && !pane.typed().includes("systemctl"), `${toolResult("c3")}\n${d.screen().join("\n")}`)
// (d) The person does nothing, and the turn is stopped: their prompt line is not touched.
await d.waitFor("idle")
await d.key("\x1b[200~clean up\x1b[201~\r")
await d.waitFor("at your prompt: make clean")
await Bun.sleep(500)
const before = sends()
await d.key("/stop\r")
const still = await d.waitFor("Still at your prompt, not run: make")
await Bun.sleep(300)
check("display, placed and left: /stop gives up the wait, sends nothing more to the pane, and says the command is still at the prompt", still && sends() === before && pane.placed().endsWith("make clean\n") && pane.typed() === "", `still=${still} sends=${sends()}/${before}\n${d.screen().join("\n")}`)
// A second display for the same window, while this one runs: refused in words.
const d2 = await drive({ cols: 160, rows: 10, bin, home: h, cwd, args, env: ttyEnv })
const refused = await d2.waitFor("already running")
await d2.close()
check("display: a second display for the same window is refused in words", refused, d2.screen().join("\n"))
await d.key("/quit\r")
const code = await d.close()
const modes = d.modes()
check("display: /quit ends it and the pane is given back", code === 0 && modes.mouse === "none" && !modes.altScreen, `exit=${code} ${JSON.stringify(modes)}`)
// Started again for the same window: the conversation is carried on, what the model was given
// of the terminal is not given again — and it still knows what stands at the person's prompt.
writeFileSync(context, JSON.stringify({ version: 2, pane: 7, cwd, shell: "zsh", blocks: [{ seq: 1, command: "make test", exit: 2, output: "FAIL src/oven.test.ts\n1 failed" }] }), { mode: 0o600 })
const d3 = await drive({ cols: 45, rows: 30, bin, home: h, cwd, args, env: ttyEnv })
const again = (await d3.waitFor("why did it fail?")) && (await d3.waitFor("idle"))
await d3.key(`/terminal-context ${context}\r\x1b[200~and now?\x1b[201~\r`)
const second = await d3.waitFor("still the oven")
const last = JSON.stringify(f.requests.at(-1)?.messages.at(-1) ?? {})
const history = JSON.stringify(f.requests.at(-1)?.messages ?? [])
await d3.key("/quit\r")
await d3.close()
f.stop()
check("display: the same window carries its conversation on, and a context already given is not given again", again && second && history.includes("why did it fail?") && last.includes("and now?") && !last.includes("<terminal>") && !last.includes("agents"), `again=${again} second=${second}\n${last}`)
check("display: opened again, the model is told the command it placed is still at the prompt", last.includes("make clean") && last.includes("is still there, not run"), last)
// Outside a LLeMbas terminal there is no display; the version says the contract.
const outside = run(["terminal", "--window", "x"])
check("lembas terminal outside a LLeMbas terminal: status 2, in words", outside.code === 2 && outside.err.includes("LLEMBAS_TERM is not set"), JSON.stringify(outside))
const v = JSON.parse(run(["--version", "--json"]).out || "{}")
check("--version --json: terminal contract 4 with the display's, the settings', the placing's and the renamed names' capabilities", v.terminal_contract === 4 && ["terminal_surface", "terminal_await", "terminal_context_2", "terminal_models", "terminal_settings", "terminal_placed", "terminal_names_2"].every((c) => (v.capabilities ?? []).includes(c)), JSON.stringify(v))
// The terminal's settings and its two models, from the compiled binary, with a GUI's bare environment.
// In the names of a terminal released before the rename (LLEMBAS_TTY): read as before.
const bare = (a: string[], stdin = "") => {
const p = Bun.spawnSync([bin, ...a], { cwd: "/", env: { LEMBAS_HOME: h, PATH: "/usr/bin:/bin", HOME: h, LLEMBAS_TTY: "2.0.0" }, stdin: Buffer.from(stdin), stdout: "pipe", stderr: "pipe" })
return { code: p.exitCode, out: p.stdout.toString(), err: p.stderr.toString() }
}
const m = bare(["terminal", "models", "--json"])
const models = JSON.parse(m.out || "{}")
check("lembas terminal models --json: the models and the terminal's two settings", m.code === 0 && Array.isArray(models.models) && models.models.some((x: { ref: string }) => x.ref === "fake/coder") && models.main?.model === null && "autocomplete" in models, m.out + m.err)
const set = bare(["terminal", "settings", "set", "--cwd", cwd, "--json", "main_model=fake/coder", "mode=auto", "autocomplete=off"])
const got = JSON.parse(bare(["terminal", "settings", "--cwd", join(cwd, "deeper"), "--json"]).out || "{}")
check(
"lembas terminal settings: set for a directory, read from under it — one JSON line, the nearest entry, where each value comes from",
set.code === 0 && set.out.trimEnd().split("\n").length === 1 && got.effective?.mode === "auto" && got.effective?.main_model === "fake/coder" && got.from?.mode === got.directory?.path && got.from?.ai === "default" && got.effective?.display_width === 0.33,
set.out + set.err + JSON.stringify(got),
)
const off = bare(["complete", "--shell", "bash", "--cwd", cwd, "--timeout-ms", "2500"], "git che")
check("lembas complete --shell where autocomplete was set to false: status 0, nothing printed, one line why", off.code === 0 && off.out === "" && off.err.includes("autocomplete is turned off in the terminal's settings"), JSON.stringify(off))
const bad = bare(["terminal", "settings", "set", "--global", "mode=plan"])
check("lembas terminal settings set: a value it cannot take is a sentence and status 2", bad.code === 2 && bad.out === "" && bad.err.includes("mode takes one of manual, auto"), JSON.stringify(bad))
// A display started in that directory starts in the directory's mode.
const d4 = await drive({ cols: 45, rows: 12, bin, home: h, cwd, args: ["terminal", "--window", "smoke-2", "--pane", "7"], env: ttyEnv })
const auto = await d4.waitFor("auto · idle")
await d4.key("/quit\r")
await d4.close()
check("display: starts in the mode kept for its directory", auto, d4.screen().join("\n"))
}
process.exit(failed ? 1 : 0)