The terminal's round shipped `<kind>#<id> <keys> <text>` with a numeric id (1-9 digits) and sends /approve <id>, /always <id>, /deny <id> when an id was shown, /answer <n> without one. lembas_ask now says approval#12 yn …; ids are a counter per display; /answer with one word is the option, with two the id and the option. A lembas_ask value cut to state.max_bytes ends in U+2026 (ask_id.ellipsis), the placed kind too. Conformance: terminal.json ask_id cases redone (+7). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
447 lines
28 KiB
TypeScript
447 lines
28 KiB
TypeScript
// The terminal's display, contract 2 (harness acp.md, *The terminal's display*): the parts that
|
|
// need no screen — the status record on disk and its races, a typed command waited for, the tool
|
|
// profile as a model is really sent it, the two modes, context that continues, one conversation
|
|
// per window, the terminal's two models.
|
|
import { afterEach, expect, test } from "bun:test"
|
|
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { createApp } from "../src/app.ts"
|
|
import { Bus, type AskReply, type Asker } from "../src/bus/index.ts"
|
|
import { paths } from "../src/config/paths.ts"
|
|
import { LOOP } from "../src/harness.ts"
|
|
import { completeCommand } from "../src/terminal/complete.ts"
|
|
import { terminalEnv } from "../src/terminal/env.ts"
|
|
import { Reader, SurfaceInput } from "../src/terminal/input.ts"
|
|
import { saveTerminalModels, terminalModels } from "../src/terminal/models.ts"
|
|
import { awaitCommand, parseStatus, readStatus, statusFile, type StatusRecord } from "../src/terminal/status.ts"
|
|
import { createSurface } from "../src/terminal/surface.ts"
|
|
import { holdWindow, setWindowSession, windowId, windowSession } from "../src/terminal/windows.ts"
|
|
import { Store } from "../src/session/store.ts"
|
|
import { createView } from "../src/tui/state.ts"
|
|
import { openSurface } from "../src/tui/terminal_surface.tsx"
|
|
import { fakePane } from "./fake-pane.ts"
|
|
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
|
|
import { TN } from "./terminal-names.ts"
|
|
|
|
let fake: Fake | undefined
|
|
const dirs: string[] = []
|
|
const tmp = (name: string) => {
|
|
const d = realpathSync(mkdtempSync(join(tmpdir(), name)))
|
|
dirs.push(d)
|
|
return d
|
|
}
|
|
afterEach(() => {
|
|
fake?.stop()
|
|
fake = undefined
|
|
delete process.env[TN.status_dir]
|
|
rmSync(join(paths.config, LOOP.terminal.models.file), { force: true })
|
|
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
|
|
})
|
|
|
|
const record = (o: Record<string, string | number>) => `${TN.statusMagic}=1\n${Object.entries(o).map(([k, v]) => `${k}=${v}\n`).join("")}`
|
|
|
|
// ── the status record on disk ───────────────────────────────────────────────────────────────
|
|
|
|
test("a status record is read only from the person's own regular file that nobody else may write", () => {
|
|
const dir = tmp("lembas-status-")
|
|
const f = statusFile(dir, 7)
|
|
expect(readStatus(f)).toBeUndefined()
|
|
writeFileSync(f, record({ id: "a.1", seq: 3, state: "prompt", exit: 0 }), { mode: 0o600 })
|
|
expect(readStatus(f)).toEqual({ id: "a.1", seq: 3, state: "prompt", exit: 0 })
|
|
// Writable by others: not believed.
|
|
chmodSync(f, 0o622)
|
|
expect(readStatus(f)).toBeUndefined()
|
|
chmodSync(f, 0o600)
|
|
// Somebody else's.
|
|
expect(readStatus(f, { uid: 4242 })).toBeUndefined()
|
|
// A link is not followed.
|
|
const link = statusFile(dir, 8)
|
|
symlinkSync(f, link)
|
|
expect(readStatus(link)).toBeUndefined()
|
|
// Too large, half written, empty: no record — never an exception.
|
|
writeFileSync(f, record({ id: "a.1", seq: 3 }) + "x".repeat(LOOP.terminal.status.max_bytes))
|
|
expect(readStatus(f)).toBeUndefined()
|
|
writeFileSync(f, `${TN.statusMagic}=1\nid=a.1\nse`)
|
|
expect(readStatus(f)).toBeUndefined()
|
|
writeFileSync(f, "")
|
|
expect(readStatus(f)).toBeUndefined()
|
|
// A record of a shell of this machine that is gone is stale; one that came by user var is not judged so.
|
|
writeFileSync(f, record({ id: "a.1", seq: 3, state: "running", pid: 99 }))
|
|
expect(readStatus(f, { alive: () => false })).toBeUndefined()
|
|
expect(readStatus(f, { alive: () => true })?.state).toBe("running")
|
|
writeFileSync(f, record({ id: "a.1", seq: 3, state: "running", pid: 99, via: "uservar" }))
|
|
expect(readStatus(f, { alive: () => false })).toEqual({ id: "a.1", seq: 3, state: "running", uservar: true })
|
|
})
|
|
|
|
/** A clock and a script of what the record and the pane say at each moment. */
|
|
function world(at: (ms: number) => { rec?: StatusRecord; pane?: string }) {
|
|
let t = 0
|
|
return { now: () => t, sleep: async (ms: number) => void (t += ms), read: () => at(t).rec, look: async () => at(t).pane ?? "" }
|
|
}
|
|
const rec = (o: Record<string, string | number>) => parseStatus(record(o))!
|
|
|
|
test("a typed command is waited for: ended, another shell, still running, waiting for the person, no record", async () => {
|
|
const before = rec({ id: "a", seq: 4, state: "prompt", exit: 0 })
|
|
// Ended: the count went up — even when the reads never saw it running.
|
|
let w = world((ms) => ({ rec: ms < 450 ? before : rec({ id: "a", seq: 5, state: "prompt", exit: 2 }) }))
|
|
expect(await awaitCommand({ before, ...w })).toEqual({ kind: "ended", exit: 2, ms: 450 })
|
|
// A prompt of the same shell with the same count is not an end, however long it stands.
|
|
w = world(() => ({ rec: before, pane: "$ " }))
|
|
expect(await awaitCommand({ before, ...w, waitMs: 3000 })).toMatchObject({ kind: "running" })
|
|
// Running, then the pane asks for a password: waiting for the person, soon — not at the timeout.
|
|
w = world(() => ({ rec: rec({ id: "a", seq: 4, state: "running" }), pane: "[sudo] password for user: " }))
|
|
const waiting = await awaitCommand({ before, ...w })
|
|
expect(waiting).toMatchObject({ kind: "waiting", what: "password" })
|
|
expect((waiting as { ms: number }).ms).toBeLessThan(2000)
|
|
// The race: the pane still shows the question, but the record already says the command ended.
|
|
let reads = 0
|
|
const racing = { now: w.now, sleep: w.sleep, look: async () => "Continue? [y/N] ", read: () => (++reads > 7 ? rec({ id: "a", seq: 5, state: "prompt", exit: 1 }) : rec({ id: "a", seq: 4, state: "running" })) }
|
|
expect(await awaitCommand({ before, ...racing })).toMatchObject({ kind: "ended", exit: 1 })
|
|
// Another shell's prompt (ssh typed, the other machine's record came by user var).
|
|
w = world((ms) => ({ rec: ms < 300 ? rec({ id: "a", seq: 4, state: "running" }) : rec({ id: "r", seq: 1, state: "prompt", host: "workstation", via: "uservar" }) }))
|
|
expect(await awaitCommand({ before, ...w })).toEqual({ kind: "ended", other: true, host: "workstation", ms: 300, reported: true })
|
|
// No record before and none after (a shell without the integration): typed, after a moment.
|
|
w = world(() => ({}))
|
|
expect(await awaitCommand({ before: undefined, ...w })).toEqual({ kind: "typed" })
|
|
expect(w.now()).toBeLessThan(1500)
|
|
// The call said the pane takes commands although a program runs: nothing is waited for.
|
|
expect(await awaitCommand({ before: rec({ id: "a", seq: 4, state: "running" }), ...world(() => ({})), atPrompt: true })).toEqual({ kind: "typed" })
|
|
// A stop gives up the wait, never the command.
|
|
const stopped = new AbortController()
|
|
stopped.abort()
|
|
expect(await awaitCommand({ before, ...world(() => ({ rec: before })), signal: stopped.signal })).toMatchObject({ kind: "running" })
|
|
})
|
|
|
|
// ── input: bytes as they arrive ─────────────────────────────────────────────────────────────
|
|
|
|
test("the exact bytes a terminal sends are one question with its context; typed keys are nothing", () => {
|
|
const input = new SurfaceInput()
|
|
const sent = "/terminal-context /run/user/1000/llembas-term/context-1.json\r\x1b[200~why did it fail?\x1b[201~\r"
|
|
expect(input.feed(sent)).toEqual([
|
|
{ a: "command", name: "terminal-context", arg: "/run/user/1000/llembas-term/context-1.json" },
|
|
{ a: "say", text: "why did it fail?" },
|
|
])
|
|
// The same bytes one at a time — as typing arrives — make neither.
|
|
const typed = new SurfaceInput()
|
|
expect([..."/new\rrm -rf /\ry"].flatMap((ch) => typed.feed(ch))).toEqual([])
|
|
// A large paste arrives in many reads, cut anywhere.
|
|
const big = "x".repeat(9000)
|
|
const bytes = `\x1b[200~${big}\x1b[201~\r`
|
|
const cut = new SurfaceInput()
|
|
const out = []
|
|
for (let i = 0; i < bytes.length; i += 4095) out.push(...cut.feed(bytes.slice(i, i + 4095)))
|
|
expect(out).toEqual([{ a: "say", text: big }])
|
|
// A paste is plain text: control characters in it are taken out, and it is cut to the most.
|
|
expect(new SurfaceInput().feed("\x1b[200~a\x00b\x07c\x1b[201~\r")).toEqual([{ a: "say", text: "abc" }])
|
|
const huge = new SurfaceInput().feed(`\x1b[200~${"y".repeat(LOOP.terminal.surface.paste_max_bytes + 10)}\x1b[201~\r`)
|
|
expect((huge[0] as { text: string }).text.length).toBe(LOOP.terminal.surface.paste_max_bytes)
|
|
// An escape sequence cut by a read is still one sequence.
|
|
const r = new Reader()
|
|
expect([...r.push("\x1b["), ...r.push("6~")]).toEqual([{ t: "scroll", how: "page_down" }])
|
|
})
|
|
|
|
// ── the session of a display ────────────────────────────────────────────────────────────────
|
|
|
|
function setup(script: Parameters<typeof fakeProvider>[0], config = "") {
|
|
fake = fakeProvider(script)
|
|
mkdirSync(paths.config, { recursive: true })
|
|
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n fake:\n type: webui\n url: ${fake.url}\n models:\n fake/m: { context: 32768 }\n fake/other: { context: 8192 }\n`, { mode: 0o600 })
|
|
writeFileSync(join(paths.config, "config.yaml"), `model: fake/m\n${config}`)
|
|
const dir = tmp("lembas-display-")
|
|
// A project that would be read by the TUI: its instruction file, its edit mode.
|
|
Bun.spawnSync(["git", "init", "-q", dir])
|
|
writeFileSync(join(dir, "AGENTS.md"), "PROJECT-INSTRUCTIONS-MARK\n")
|
|
return dir
|
|
}
|
|
|
|
/** A stand-in for the terminal's program that plays a pane (tests/fake-pane.ts): what is typed
|
|
* with its Enter lands in `typed` and a "shell" writes the pane's status record — one prompt
|
|
* later, with `exit`; what is placed without Enter lands in `placed` and waits for the person. */
|
|
function pane(o: { exit?: number; screen?: string; record?: boolean; pane?: number } = {}) {
|
|
const p = fakePane(tmp("lembas-tty-pane-"), o)
|
|
process.env[TN.status_dir] = p.statusDir
|
|
return p
|
|
}
|
|
|
|
const yes: Asker = { ask: async (): Promise<AskReply> => ({ kind: "once" }) }
|
|
const toolResult = (req: any, id: string): string => req.messages.find((m: any) => m.role === "tool" && m.tool_call_id === id).content
|
|
const names = (req: any): string[] => req.tools.map((t: any) => t.function.name)
|
|
const run = (id: string, command: string, more: object = {}) => toolCall(0, id, "terminal_run", JSON.stringify({ command, why: "because you asked", ...more }))
|
|
const lastUser = (req: any): string => {
|
|
const m = [...req.messages].reverse().find((x: any) => x.role === "user")
|
|
return typeof m.content === "string" ? m.content : m.content.map((p: any) => p.text ?? "").join("\n")
|
|
}
|
|
const env = (exe: string) => terminalEnv({ [TN.version]: "2.0.0", [TN.pane]: "1", [TN.executable]: exe })!
|
|
|
|
test("the terminal profile: exactly its tools, its own prompt, no project — and a pane from the start", async () => {
|
|
const dir = setup([{ chunks: [run("c1", "uptime")] }, { chunks: [delta({ content: "up." }, "stop")] }], "mode: edit\n")
|
|
const p = pane({ exit: 0 })
|
|
// Manual mode in the display asks nothing for a command: it is placed, and the person runs it.
|
|
let cards = 0
|
|
const nobody: Asker = { ask: async (): Promise<AskReply> => (cards++, { kind: "deny" }) }
|
|
const app = createApp({ cwd: dir, asker: nobody, store: false, terminal: env(p.exe), surface: { pane: 7 }, kind: "display", snapshots: false })
|
|
expect(app.engine.mode).toBe("manual")
|
|
app.bus.on((e) => e.type === "tool_start" && setTimeout(() => p.enter(), 700))
|
|
await app.turns.prompt("how long has this machine been up?")
|
|
expect(cards).toBe(0)
|
|
const offered = names(fake!.requests[0])
|
|
// Nothing outside the profile — no bash, no file tool, no subagent — and the profile's own.
|
|
expect(offered.filter((n) => !LOOP.terminal.profile.tools.includes(n))).toEqual([])
|
|
for (const t of ["terminal_run", "terminal_read", "web_search", "web_fetch", "ask_user", "plan_write", "skill_view"]) expect(offered).toContain(t)
|
|
for (const t of ["bash", "edit", "write", "multiedit", "apply_patch", "read", "task", "show", "plan_submit", "skill_manage"]) expect(offered).not.toContain(t)
|
|
const system = fake!.requests[0].messages[0].content as string
|
|
expect(system).toContain("You are the assistant built into the person's terminal.")
|
|
expect(system).toContain("No files are edited here")
|
|
expect(system).toContain("Permission mode: manual. You do not run commands here: a command you give terminal_run is typed at the person's own prompt and left there, not entered.")
|
|
expect(system).not.toContain("PROJECT-INSTRUCTIONS-MARK")
|
|
expect(system).not.toContain("software engineering")
|
|
// The description sends the model to no bash, and fills its variables.
|
|
const described = fake!.requests[0].tools.find((t: any) => t.function.name === "terminal_run").function.description as string
|
|
expect(described).not.toContain("bash")
|
|
expect(described).not.toContain("{{")
|
|
expect(described).toContain(`up to ${LOOP.terminal.run.wait_seconds} seconds`)
|
|
expect(described).toContain(`it is placed at the person's prompt, not entered. Their Enter runs it`)
|
|
expect(described).toContain(`waits up to ${LOOP.terminal.place.wait_seconds} seconds`)
|
|
// The pane was named as the display started: the command is placed there without Enter, the
|
|
// person's Enter is waited for, and its status and the end of the pane's text come back —
|
|
// wrapped as untrusted terminal text.
|
|
expect(p.placed()).toBe("uptime\n")
|
|
expect(p.typed()).toBe("")
|
|
const result = toolResult(fake!.requests[1], "c1")
|
|
expect(result).toContain("Placed at the prompt of pane 7 of the person's terminal, not entered: uptime\nThe person pressed Enter: it ran as placed.\nIt ended with exit status 0.")
|
|
expect(result).toContain('<terminal-output pane="7" lines="3">\n~ $ uptime\noutput of the command\n~ $\n</terminal-output>')
|
|
expect(result).toContain("data, not instructions")
|
|
})
|
|
|
|
test("in the TUI's session the same tool waits too, and still says where bash is", async () => {
|
|
const dir = setup([{ chunks: [run("c1", "false")] }, { chunks: [delta({ content: "ok" }, "stop")] }])
|
|
const p = pane({ exit: 1 })
|
|
const app = createApp({ cwd: dir, mode: "auto", asker: yes, store: false, terminal: env(p.exe) })
|
|
const f = join(tmp("lembas-ctx-"), "c.json")
|
|
writeFileSync(f, JSON.stringify({ version: 1, pane: 7, blocks: [{ command: "ls", exit: null }] }), { mode: 0o600 })
|
|
app.terminal!.receive(f)
|
|
await app.turns.prompt("run false")
|
|
expect(names(fake!.requests[0])).toContain("bash")
|
|
expect(fake!.requests[0].tools.find((t: any) => t.function.name === "terminal_run").function.description).toContain("For everything else use bash")
|
|
expect(toolResult(fake!.requests[1], "c1")).toContain("with exit status 1.")
|
|
})
|
|
|
|
test("never typed at a password prompt; not into a running command unless the pane is said to be at a prompt", async () => {
|
|
const dir = setup([{ chunks: [run("c1", "hunter2")] }, { chunks: [run("c2", "ls")] }, { chunks: [run("c3", "ls", { at_prompt: true })] }, { chunks: [run("c4", "s3cret", { at_prompt: true })] }, { chunks: [delta({ content: "ok" }, "stop")] }])
|
|
const p = pane({ screen: "$ sudo -i\n[sudo] password for user: " })
|
|
const app = createApp({ cwd: dir, mode: "auto", asker: yes, store: false, terminal: env(p.exe), surface: { pane: 7 }, kind: "display", snapshots: false })
|
|
let step = 0
|
|
app.bus.on((e) => {
|
|
if (e.type !== "tool_end") return
|
|
step++
|
|
// After the first refusal the pane is in a remote shell: the local record says "running".
|
|
if (step === 1) (p.screen("user@server:~$ "), writeFileSync(statusFile(process.env[TN.status_dir]!, 7), record({ id: "sh.1", seq: 1, state: "running" }), { mode: 0o600 }))
|
|
if (step === 3) p.screen("user@server:~$ su\nPassword: ")
|
|
})
|
|
await app.turns.prompt("go")
|
|
expect(toolResult(fake!.requests[1], "c1")).toContain("is asking for a password or a code. That is the person's to type, never yours.")
|
|
expect(toolResult(fake!.requests[2], "c2")).toContain("Not typed: a command is running in pane 7")
|
|
// at_prompt: typed, and nothing is waited for — the record cannot tell the remote command's end.
|
|
expect(toolResult(fake!.requests[3], "c3")).toContain("Its result is not known here")
|
|
// …but never at a password prompt, whatever the call says.
|
|
expect(toolResult(fake!.requests[4], "c4")).toContain("is asking for a password or a code")
|
|
expect(p.typed()).toBe("ls\n")
|
|
})
|
|
|
|
test("two modes: edit and plan are refused in words and the mode stays", async () => {
|
|
const dir = setup([])
|
|
const p = pane()
|
|
const bus = new Bus()
|
|
const view = createView(bus)
|
|
const app = createApp({ cwd: dir, asker: view.asker, bus, store: false, terminal: env(p.exe), surface: { pane: 7 }, kind: "display", snapshots: false })
|
|
const s = createSurface(app, view, { window: "w1", quit: () => {} })
|
|
const said = () => view.state.items.filter((i) => i.kind === "notice").map((i) => (i as { text: string }).text)
|
|
s.feed("/mode edit\r")
|
|
expect(app.engine.mode).toBe("manual")
|
|
expect(said().at(-1)).toBe(LOOP.terminal.surface.texts.no_edit)
|
|
s.feed("/mode plan\r")
|
|
expect(app.engine.mode).toBe("manual")
|
|
expect(said().at(-1)).toBe(LOOP.terminal.surface.texts.no_plan)
|
|
s.feed("/mode auto\r")
|
|
expect(app.engine.mode).toBe("auto")
|
|
s.feed("/model fake/other\r")
|
|
expect(app.engine.model.ref).toBe("fake/other")
|
|
s.feed("/model nope\r")
|
|
expect(said().at(-1)).toBe("No such model: nope. lembas terminal models lists them.")
|
|
expect(app.engine.model.ref).toBe("fake/other")
|
|
})
|
|
|
|
test("context that continues: each question brings only what is new, and what the agent ran is not repeated", async () => {
|
|
const dir = setup([
|
|
{ chunks: [delta({ content: "the test failed." }, "stop")] },
|
|
{ chunks: [run("c1", "make test")] },
|
|
{ chunks: [delta({ content: "it passes now." }, "stop")] },
|
|
{ chunks: [delta({ content: "nothing new." }, "stop")] },
|
|
])
|
|
const p = pane({ exit: 0 })
|
|
const bus = new Bus()
|
|
const view = createView(bus)
|
|
const store = new Store()
|
|
const { app } = openSurface({ cwd: dir, window: "win-a", pane: 7, terminal: env(p.exe), store, mode: "auto", modelTitles: false }, view, bus)
|
|
const send = (file: object) => {
|
|
const f = join(tmp("lembas-ctx-"), "c.json")
|
|
writeFileSync(f, JSON.stringify(file), { mode: 0o600 })
|
|
return app.terminal!.receive(f, { next: true })
|
|
}
|
|
const b1 = { seq: 1, command: "make test", exit: 2, output: "1 failed" }
|
|
expect(send({ version: 2, pane: 7, cwd: "/srv/app", shell: "zsh", blocks: [b1] })).toBe("terminal context: 1 command from pane 7 — it goes with your next message")
|
|
await app.turns.prompt("why?")
|
|
expect(lastUser(fake!.requests[0])).toContain("What the person's terminal showed when they sent this (pane 7).")
|
|
expect(lastUser(fake!.requests[0])).toContain("$ make test\n1 failed")
|
|
// The second question: the terminal sends the same block again, plus nothing else.
|
|
send({ version: 2, pane: 7, cwd: "/srv/app", shell: "zsh", blocks: [b1] })
|
|
await app.turns.prompt("run it again")
|
|
expect(lastUser(fake!.requests[1])).not.toContain("<terminal>")
|
|
expect(toolResult(fake!.requests[2], "c1")).toContain("with exit status 0.")
|
|
// The third: what the agent typed comes back from the terminal — named, without its output.
|
|
const b2 = { seq: 2, command: "make test", exit: 0, output: "output of the command" }
|
|
const b3 = { seq: 3, command: "git status", exit: 0, output: "clean" }
|
|
expect(send({ version: 2, pane: 7, cwd: "/srv/app/web", shell: "zsh", blocks: [b1, b2, b3] })).toBe("terminal context: 2 commands from pane 7, new since the last question — it goes with your next message")
|
|
await app.turns.prompt("and now?")
|
|
const third = lastUser(fake!.requests[3])
|
|
expect(third).toContain("What is new in the person's terminal since you last saw it (pane 7).")
|
|
expect(third).toContain("(1 command you have already seen left out)")
|
|
expect(third).toContain(`<command exit="0">\n$ make test\n${LOOP.terminal.context.texts.yours}\n</command>`)
|
|
expect(third).toContain("$ git status\nclean")
|
|
expect(third).toContain("Working directory: /srv/app/web")
|
|
expect(third).not.toContain("Shell:")
|
|
expect(third).not.toContain("1 failed")
|
|
// What was given is kept with the session: a display closed and opened again goes on from there.
|
|
await app.close()
|
|
const view2 = createView(new Bus())
|
|
const again = openSurface({ cwd: dir, window: "win-a", pane: 7, terminal: env(p.exe), store, mode: "auto", modelTitles: false }, view2, new Bus())
|
|
expect(again.resumed).toBe(true)
|
|
expect(again.app.engine.sessionId).toBe(app.engine.sessionId)
|
|
expect(view2.state.items.filter((i) => i.kind === "user").map((i) => (i as { text: string }).text)).toEqual(["why?", "run it again", "and now?"])
|
|
const f = join(tmp("lembas-ctx-"), "c.json")
|
|
writeFileSync(f, JSON.stringify({ version: 2, pane: 7, cwd: "/srv/app/web", shell: "zsh", blocks: [b1, b2, b3] }), { mode: 0o600 })
|
|
expect(again.app.terminal!.receive(f, { next: true })).toBe(LOOP.terminal.context.texts.chip_nothing)
|
|
// --new: another conversation for the same window.
|
|
const fresh = openSurface({ cwd: dir, window: "win-a", pane: 7, terminal: env(p.exe), store, fresh: true, modelTitles: false }, createView(new Bus()), new Bus())
|
|
expect(fresh.resumed).toBe(false)
|
|
expect(windowSession("win-a")).toBe(fresh.app.engine.sessionId)
|
|
// Another window has its own.
|
|
const other = openSurface({ cwd: dir, window: "win-b", terminal: env(p.exe), store, modelTitles: false }, createView(new Bus()), new Bus())
|
|
expect(other.app.engine.sessionId).not.toBe(fresh.app.engine.sessionId)
|
|
})
|
|
|
|
test("a display closed while a typed command had not ended says so when it is opened again", async () => {
|
|
const dir = setup([{ chunks: [run("c1", "make all")] }, { chunks: [delta({ content: "ok" }, "stop")] }, { chunks: [delta({ content: "I will look." }, "stop")] }])
|
|
// The pane's shell never comes back to its prompt: the record stays as it was.
|
|
const p = pane({ record: false })
|
|
writeFileSync(statusFile(process.env[TN.status_dir]!, 7), record({ id: "sh.1", seq: 1, state: "prompt" }), { mode: 0o600 })
|
|
const store = new Store()
|
|
const bus = new Bus()
|
|
const view = createView(bus)
|
|
const { app } = openSurface({ cwd: dir, window: "win-c", pane: 7, terminal: env(p.exe), store, mode: "auto", modelTitles: false }, view, bus)
|
|
// The pane is closed a moment after the command was typed.
|
|
bus.on((e) => e.type === "tool_start" && setTimeout(() => app.engine.cancel(), 400))
|
|
await app.turns.prompt("build it")
|
|
expect(p.typed()).toBe("make all\n")
|
|
await app.close()
|
|
const bus2 = new Bus()
|
|
const view2 = createView(bus2)
|
|
const notices: string[] = []
|
|
bus2.on((e) => e.type === "notice" && notices.push(e.message))
|
|
const again = openSurface({ cwd: dir, window: "win-c", pane: 7, terminal: env(p.exe), store, mode: "auto", modelTitles: false }, view2, bus2)
|
|
expect(notices).toContain("When this display was closed, a command typed into pane 7 had not been seen to end: make all")
|
|
await again.app.turns.prompt("did it finish?")
|
|
expect(lastUser(fake!.requests.at(-1))).toContain("its result is not known. Read the pane with terminal_read before relying on it.]")
|
|
})
|
|
|
|
test("one display per window: the second is refused while the first runs; a dead one's mark is taken over", () => {
|
|
expect(windowId("tab-3.a_b")).toBe("tab-3.a_b")
|
|
for (const bad of ["", "a b", "../x", "x".repeat(65), "a/b", undefined]) expect(windowId(bad)).toBeUndefined()
|
|
const first = holdWindow("win-lock", { pid: 1001, alive: () => true })
|
|
expect("release" in first).toBe(true)
|
|
expect(holdWindow("win-lock", { pid: 1002, alive: () => true })).toEqual({ taken: 1001 })
|
|
// The first is gone without giving it back: the next takes it.
|
|
const second = holdWindow("win-lock", { pid: 1002, alive: () => false })
|
|
expect("release" in second).toBe(true)
|
|
// The first's late release does not take the second's mark away.
|
|
;(first as { release(): void }).release()
|
|
expect(holdWindow("win-lock", { pid: 1003, alive: () => true })).toEqual({ taken: 1002 })
|
|
;(second as { release(): void }).release()
|
|
expect("release" in holdWindow("win-lock", { pid: 1003, alive: () => true })).toBe(true)
|
|
setWindowSession("win-map", "ses_1")
|
|
setWindowSession("win-map", "ses_2")
|
|
expect(windowSession("win-map")).toBe("ses_2")
|
|
expect(windowSession("win-none")).toBeUndefined()
|
|
})
|
|
|
|
test("the terminal's two models are its own: a file on this machine, and complete --shell asks for its model", async () => {
|
|
expect(terminalModels()).toEqual({ main_model: null, autocomplete_model: null })
|
|
saveTerminalModels({ autocomplete_model: "open/flash" })
|
|
saveTerminalModels({ main_model: "fake/other" })
|
|
expect(terminalModels()).toEqual({ main_model: "fake/other", autocomplete_model: "open/flash" })
|
|
expect(JSON.parse(readFileSync(join(paths.config, LOOP.terminal.models.file), "utf8"))).toEqual({ version: 2, global: { autocomplete_model: "open/flash", main_model: "fake/other" }, directories: {} })
|
|
// A display starts on the terminal's chat model, not on the TUI's.
|
|
const dir = setup([])
|
|
const p = pane()
|
|
const opened = openSurface({ cwd: dir, window: "win-m", terminal: env(p.exe), store: false }, createView(new Bus()), new Bus())
|
|
expect(opened.app.engine.model.ref).toBe("fake/other")
|
|
// A quick switch wins for that start.
|
|
expect(openSurface({ cwd: dir, window: "win-m2", terminal: env(p.exe), store: false, model: "fake/m" }, createView(new Bus()), new Bus()).app.engine.model.ref).toBe("fake/m")
|
|
// complete --shell: the terminal's autocomplete model, a quick switch before it, none: the server's.
|
|
const bodies: any[] = []
|
|
const server = Bun.serve({ port: 0, fetch: async (req) => (bodies.push(await req.json()), Response.json({ text: "ckout main", model: "x", finish: "stop" })) })
|
|
const login = { instance: { base_url: `http://127.0.0.1:${server.port}` }, token: "lmb_test" } as never
|
|
const go = (args: string[], choice?: string | null) => completeCommand(["--shell", "zsh", "--cwd", "/home/user", ...args], { stdin: "git che", out: () => {}, err: () => {}, login, ...(choice !== undefined ? { choice } : {}) })
|
|
try {
|
|
await go([])
|
|
await go(["--model", "open/pro"])
|
|
await go([], null)
|
|
} finally {
|
|
server.stop(true)
|
|
}
|
|
expect(bodies.map((b) => b.model)).toEqual(["open/flash", "open/pro", undefined])
|
|
})
|
|
|
|
test("an approval's answer is bound to what was shown: lembas_ask carries its id, and another id decides nothing (spec 3.15.0)", async () => {
|
|
const dir = setup([])
|
|
const p = pane()
|
|
const bus = new Bus()
|
|
const view = createView(bus)
|
|
const app = createApp({ cwd: dir, asker: view.asker, bus, store: false, terminal: env(p.exe), surface: { pane: 7 }, kind: "display", snapshots: false })
|
|
const s = createSurface(app, view, { window: "w1", quit: () => {} })
|
|
const said = () => view.state.items.filter((i) => i.kind === "notice").map((i) => (i as { text: string }).text)
|
|
const card = (command: string) =>
|
|
view.asker.ask({ tool: "terminal_run", args: { command }, request: { permission: "terminal_run", class: "execute", patterns: [command], command }, decision: { action: "ask", reason: "x", always: [] } } as never) as Promise<AskReply>
|
|
const first = card("make test")
|
|
await Bun.sleep(10)
|
|
const m = /^approval#(\d{1,9}) yn terminal_run: make test$/.exec(s.ask())
|
|
expect(m).not.toBeNull()
|
|
const id = m![1]!
|
|
// The id of another card: refused in words, the card stays.
|
|
const other = String(Number(id) + 100)
|
|
s.feed(`/approve ${other}\r`)
|
|
expect(said().at(-1)).toBe(`${other} is not what is asked now (${id}) — nothing decided. Answer what the display shows.`)
|
|
expect(view.state.pending).toBeDefined()
|
|
// Its own id: decided.
|
|
s.feed(`/deny ${id}\r`)
|
|
expect((await first).kind).toBe("deny")
|
|
// A new card has a new id; no id answers what is asked now, as before.
|
|
const second = card("make all")
|
|
await Bun.sleep(10)
|
|
expect(s.ask()).not.toStartWith(`approval#${id} `)
|
|
s.feed("/approve\r")
|
|
expect((await second).kind).toBe("once")
|
|
// Nothing asked: an id is refused as not what is asked.
|
|
s.feed(`/approve ${id}\r`)
|
|
expect(said().at(-1)).toBe(`${id} is not what is asked now — nothing decided. Answer what the display shows.`)
|
|
// A line too long for the ask line is cut and ends in an ellipsis.
|
|
const long = card("echo " + "x".repeat(400))
|
|
await Bun.sleep(10)
|
|
const line = s.ask()
|
|
expect(Buffer.byteLength(line, "utf8")).toBeLessThanOrEqual(LOOP.terminal.state.max_bytes)
|
|
expect(line.endsWith("\u2026")).toBe(true)
|
|
s.feed("/deny\r")
|
|
await long
|
|
})
|