Files
LLeMbas-CLI/tests/terminal-contract3.test.ts
T
HomerandClaude Opus 5.5 026e4f3219 A shell line that looks as if it holds a secret is not sent: one table (terminal point a)
loop.json terminal.secrets (spec 3.15.0) replaces
terminal.complete.history_secret: named patterns (assignments and set/setenv
of key/token/secret/password/credential/auth names, client password options,
-u user:pass, Authorization/Bearer/Basic, user:pass@ in an address, key
prefixes, a long high-entropy word), one entry for history lines alone.

- lembas complete --shell: a matching typed line makes no request — status 0,
  empty output, texts.secret on stderr, the rule's name in --debug.
- History lines are filtered by the same table.
- A terminal context's block with such a command: placeholder, no output.

Conformance: terminal.json kind secret (40 ordinary commands that must not
match, 26 that must), a context case.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 08:32:44 +00:00

534 lines
33 KiB
TypeScript

// Terminal contract 3 (harness/acp.md, *A command placed at the prompt*, *The terminal's
// settings*): a command placed in the display's manual mode against a stand-in pane whose
// "person" presses Enter, edits and presses Enter, presses Ctrl+C, or does nothing; and the
// settings store on a real disk — migration, the lock, symlinks, the commands and what uses them.
// The rules themselves are the conformance cases (harness/conformance/terminal.json).
import { afterEach, beforeEach, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, statSync, 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 { Store } from "../src/session/store.ts"
import { settingsCommand, modelsObject } from "../src/terminal/cli.ts"
import { completeCommand } from "../src/terminal/complete.ts"
import { terminalEnv } from "../src/terminal/env.ts"
import { terminalModels } from "../src/terminal/models.ts"
import { awaitPlaced, inputFile, readInputMark } from "../src/terminal/place.ts"
import { applyChanges, effective, parsePair, readStore, realDir, settingsFile, settingsFor, updateStore } from "../src/terminal/settings.ts"
import { parseStatus, type StatusRecord } from "../src/terminal/status.ts"
import { createSurface } from "../src/terminal/surface.ts"
import { createView } from "../src/tui/state.ts"
import { openSurface } from "../src/tui/terminal_surface.tsx"
import { fakePane, statusText } from "./fake-pane.ts"
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
import { TN } from "./terminal-names.ts"
const P = LOOP.terminal.place
const PX = P.texts
let fake: Fake | undefined
const dirs: string[] = []
const waits = { place: P.wait_seconds, run: LOOP.terminal.run.wait_seconds }
const tmp = (name: string) => {
const d = realpathSync(mkdtempSync(join(tmpdir(), name)))
dirs.push(d)
return d
}
const clean = () => {
rmSync(settingsFile(), { force: true })
rmSync(join(paths.config, LOOP.terminal.settings.lock), { force: true })
}
beforeEach(clean)
afterEach(() => {
fake?.stop()
fake = undefined
delete process.env[TN.status_dir]
P.wait_seconds = waits.place
LOOP.terminal.run.wait_seconds = waits.run
clean()
for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true })
})
function setup(script: Parameters<typeof fakeProvider>[0]) {
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")
return tmp("lembas-c3-")
}
function pane(o: Parameters<typeof fakePane>[1] = {}) {
const p = fakePane(tmp("lembas-tty-pane-"), o)
process.env[TN.status_dir] = p.statusDir
return p
}
const env = (exe: string) => terminalEnv({ [TN.version]: "2.0.0", [TN.pane]: "1", [TN.executable]: exe })!
const run = (id: string, command: string, more: object = {}) => toolCall(0, id, "terminal_run", JSON.stringify({ command, why: "because you asked", ...more }))
const toolResult = (req: any, id: string): string => req.messages.find((m: any) => m.role === "tool" && m.tool_call_id === id).content
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")
}
/** A display's session in manual mode: nobody is ever asked on a card for a command. */
function manual(dir: string, p: ReturnType<typeof pane>, o: { mode?: "manual" | "auto"; store?: Store } = {}) {
let cards = 0
const asker: Asker = { ask: async (): Promise<AskReply> => (cards++, { kind: "deny" }) }
const bus = new Bus()
const notices: string[] = []
bus.on((e) => e.type === "notice" && notices.push(e.message))
const app = createApp({ cwd: dir, asker, bus, store: o.store ?? false, terminal: env(p.exe), surface: { pane: 7 }, kind: "display", snapshots: false, ...(o.mode ? { mode: o.mode } : {}) })
/** What the "person" does a moment after the n-th command was placed. */
const person = (act: (n: number) => void, after = 600) => {
let n = 0
bus.on((e) => e.type === "tool_start" && e.name === "terminal_run" && setTimeout(() => act(++n), after))
}
return { app, bus, notices, person, cards: () => cards }
}
// ── a command placed at the prompt ──────────────────────────────────────────────────────────
test("placed, and the person presses Enter: no card, no Enter of ours, the exit status and the pane's end", async () => {
const dir = setup([{ chunks: [run("c1", "make test")] }, { chunks: [delta({ content: "done" }, "stop")] }])
const p = pane()
const t = manual(dir, p)
t.person(() => p.enter({ exit: 2 }))
await t.app.turns.prompt("run the tests")
expect(t.cards()).toBe(0)
expect(p.placed()).toBe("make test\n")
expect(p.typed()).toBe("")
const r = toolResult(fake!.requests[1], "c1")
expect(r).toContain("Placed at the prompt of pane 7 of the person's terminal, not entered: make test\nThe person pressed Enter: it ran as placed.\nIt ended with exit status 2.")
expect(r).toContain("~ $ make test\noutput of the command")
// Settled: nothing stands at the prompt any more.
expect(t.app.terminal!.placed).toBeUndefined()
})
test("placed, and the person edits the line before Enter: the model is told what actually ran", async () => {
const dir = setup([{ chunks: [run("c1", "rm -r build")] }, { chunks: [delta({ content: "done" }, "stop")] }])
const p = pane({ screen: "~ $ ls\nbuild src\n~ $ " })
const t = manual(dir, p)
t.person(() => p.enter({ line: "rm -r build/cache", exit: 0 }))
await t.app.turns.prompt("clean up")
const r = toolResult(fake!.requests[1], "c1")
expect(r).toContain("not entered: rm -r build\nThe person changed the line before running it. What ran, read from their screen: rm -r build/cache\nIt ended with exit status 0.")
expect(r).toContain("~ $ rm -r build/cache\noutput of the command")
})
test("placed, and the person presses Ctrl+C: declined — and the same command is not to be placed again", async () => {
const dir = setup([{ chunks: [run("c1", "systemctl restart web")] }, { chunks: [delta({ content: "left it" }, "stop")] }])
const p = pane()
const t = manual(dir, p)
t.person(() => p.dismiss())
await t.app.turns.prompt("restart it")
const r = toolResult(fake!.requests[1], "c1")
expect(r).toContain("The person did not run it")
expect(r).toContain("do not place the same command again unless they ask for it")
expect(p.typed()).toBe("")
expect(t.app.terminal!.placed).toBeUndefined()
})
test("placed, and the person does nothing: the call ends as left, the line stays, a second command is refused, the next question says what became of it", async () => {
P.wait_seconds = 1
const dir = setup([
{ chunks: [run("c1", "make deploy")] },
{ chunks: [run("c2", "make clean")] },
{ chunks: [delta({ content: "waiting for you" }, "stop")] },
{ chunks: [delta({ content: "it ran" }, "stop")] },
])
const p = pane()
const t = manual(dir, p)
await t.app.turns.prompt("deploy")
const left = toolResult(fake!.requests[1], "c1")
expect(left).toContain("It is still at their prompt after 1 seconds, not run. This call ends here and the line stays where it is")
// One at a time: the second is refused in words and nothing more is typed.
expect(toolResult(fake!.requests[2], "c2")).toContain("Not placed: the command you placed before is still at the person's prompt, neither run nor dismissed: make deploy")
expect(p.placed()).toBe("make deploy\n")
// The display says the line is still there, and keeps saying what stands at the prompt.
expect(t.notices).toContain("Still at your prompt, not run: make deploy")
expect(t.app.terminal!.placed).toMatchObject({ command: "make deploy", pane: 7, waiting: false })
// Later the person runs it; with their next question the model is told.
p.enter({ exit: 0 })
await t.app.turns.prompt("and now?")
expect(lastUser(fake!.requests.at(-1))).toContain("[The command you placed at the person's prompt — make deploy — has since been run by them, exit status 0.")
expect(t.app.terminal!.placed).toBeUndefined()
})
test("terminal_read with wait waits for the person to run a command left at their prompt, and says what became of it", async () => {
P.wait_seconds = 1
const read = toolCall(0, "c2", "terminal_read", JSON.stringify({ wait: 20, lines: 10 }))
const dir = setup([{ chunks: [run("c1", "make deploy")] }, { chunks: [read] }, { chunks: [delta({ content: "deployed" }, "stop")] }])
const p = pane()
const t = manual(dir, p)
// The person takes their time: Enter only after the call that placed it gave up waiting.
t.bus.on((e) => e.type === "tool_start" && e.name === "terminal_read" && setTimeout(() => p.enter({ exit: 0 }), 500))
await t.app.turns.prompt("deploy")
expect(toolResult(fake!.requests[1], "c1")).toContain("It is still at their prompt after 1 seconds, not run.")
const r = toolResult(fake!.requests[2], "c2")
expect(r).toContain("[The command placed at the prompt of pane 7 has been run by the person, exit status 0.]")
expect(r).toContain("~ $ make deploy\noutput of the command")
expect(t.app.terminal!.placed).toBeUndefined()
})
test("placed and cleared without Enter: found gone when the wait is up — dismissed", async () => {
P.wait_seconds = 1
const dir = setup([{ chunks: [run("c1", "make deploy")] }, { chunks: [delta({ content: "ok" }, "stop")] }])
const p = pane()
const t = manual(dir, p)
t.person(() => p.clear(), 400)
await t.app.turns.prompt("deploy")
expect(toolResult(fake!.requests[1], "c1")).toContain("The person did not run it")
})
test("only at an empty prompt: nothing is added to what the person typed, in words", async () => {
const dir = setup([{ chunks: [run("c1", "make test")] }, { chunks: [delta({ content: "run it yourself: make test" }, "stop")] }])
const p = pane({ screen: "~ $ git commit -m 'half a mess" })
const t = manual(dir, p)
await t.app.turns.prompt("run the tests")
expect(toolResult(fake!.requests[1], "c1")).toContain("Not placed: the prompt in pane 7 is not empty — the person has something typed there, and nothing is ever added to what they typed.")
expect(p.placed()).toBe("")
expect(p.typed()).toBe("")
})
test("the terminal's input mark decides before the line does — and stops auto mode too", async () => {
const dir = setup([{ chunks: [run("c1", "make test")] }, { chunks: [delta({ content: "ok" }, "stop")] }])
const p = pane()
// The prompt looks empty, but the terminal says something is typed at this very prompt.
writeFileSync(inputFile(p.statusDir, 7), `${TN.inputMagic}=1\nid=sh.1\nseq=1\ntyped=1\n`, { mode: 0o600 })
expect(readInputMark(inputFile(p.statusDir, 7))).toEqual({ id: "sh.1", seq: 1, typed: true })
const t = manual(dir, p, { mode: "auto" })
await t.app.turns.prompt("run the tests")
expect(toolResult(fake!.requests[1], "c1")).toContain("Not placed: the prompt in pane 7 is not empty")
expect(p.typed()).toBe("")
// A mark others may write is no mark.
writeFileSync(inputFile(p.statusDir, 7), `${TN.inputMagic}=1\nid=sh.1\nseq=1\ntyped=1\n`, { mode: 0o666 })
Bun.spawnSync(["chmod", "666", inputFile(p.statusDir, 7)])
expect(readInputMark(inputFile(p.statusDir, 7))).toBeUndefined()
})
test("auto mode is as before: typed with its Enter; a hardline command is refused before anything is typed in either mode", async () => {
const dir = setup([{ chunks: [run("c1", "uptime")] }, { chunks: [delta({ content: "up" }, "stop")] }])
const p = pane()
const t = manual(dir, p, { mode: "auto" })
await t.app.turns.prompt("uptime?")
expect(p.typed()).toBe("uptime\n")
expect(p.placed()).toBe("")
expect(toolResult(fake!.requests[1], "c1")).toContain("Typed into pane 7 of the person's terminal and entered: uptime")
fake!.stop()
for (const mode of ["manual", "auto"] as const) {
const dir2 = setup([{ chunks: [run("c1", "rm -rf /")] }, { chunks: [delta({ content: "no" }, "stop")] }])
const p2 = pane()
const t2 = manual(dir2, p2, { mode })
const denied: string[] = []
t2.bus.on((e) => e.type === "tool_denied" && denied.push(e.reason))
await t2.app.turns.prompt("wipe it")
expect(denied).toHaveLength(1)
expect(p2.placed()).toBe("")
expect(p2.typed()).toBe("")
expect(p2.calls()).not.toContain("send-text")
fake!.stop()
}
})
test("without a status record: placed, and whether it ran is not known — answered at once", async () => {
const dir = setup([{ chunks: [run("c1", "ls")] }, { chunks: [delta({ content: "ok" }, "stop")] }])
const p = pane({ record: false })
const t = manual(dir, p)
const started = Date.now()
await t.app.turns.prompt("list")
expect(Date.now() - started).toBeLessThan(5000)
expect(p.placed()).toBe("ls\n")
expect(toolResult(fake!.requests[1], "c1")).toContain("whether the person ran it is not known here")
expect(t.app.terminal!.placed).toBeUndefined()
})
test("a stop while a command stands placed does not touch the person's prompt, and the display says it is still there", async () => {
const dir = setup([{ chunks: [run("c1", "make all")] }, { chunks: [delta({ content: "ok" }, "stop")] }, { chunks: [delta({ content: "I see." }, "stop")] }])
const p = pane()
const store = new Store()
const bus = new Bus()
const view = createView(bus)
const notices: string[] = []
bus.on((e) => e.type === "notice" && notices.push(e.message))
const { app } = openSurface({ cwd: dir, window: "win-p", pane: 7, terminal: env(p.exe), store, modelTitles: false }, view, bus)
const s = createSurface(app, view, { window: "win-p", quit: () => {} })
let asked = ""
bus.on((e) => e.type === "tool_start" && setTimeout(() => ((asked = s.ask()), s.feed("/stop\r")), 600))
await app.turns.prompt("build it").catch(() => {})
expect(asked).toBe("placed make all")
expect(p.placed()).toBe("make all\n")
// Nothing was sent to the pane after the placing: no Ctrl+C, no clearing.
expect(p.calls().split("\n").filter((l) => l.includes("send-text"))).toHaveLength(1)
expect(notices).toContain("Still at your prompt, not run: make all")
expect(s.ask()).toBe("placed make all")
expect(s.placedWaiting()).toBeUndefined()
// /approve from a terminal that knows the card: decides nothing, in words.
s.feed("/approve\r")
expect(view.state.items.filter((i) => i.kind === "notice").map((i) => (i as { text: string }).text)).toContain(PX.no_card)
await app.close()
// The display is closed and opened again: the session still knows what stands at the prompt…
const bus2 = new Bus()
const view2 = createView(bus2)
const again = openSurface({ cwd: dir, window: "win-p", pane: 7, terminal: env(p.exe), store, modelTitles: false }, view2, bus2)
const s2 = createSurface(again.app, view2, { window: "win-p", quit: () => {} })
expect(s2.ask()).toBe("placed make all")
// …and sees, once a second, what became of it: the person dismissed it.
p.dismiss()
s2.tick()
expect(view2.state.items.filter((i) => i.kind === "notice").map((i) => (i as { text: string }).text)).toContain("The command at your prompt was dismissed: make all")
expect(s2.ask()).toBe("")
await again.app.turns.prompt("what now?")
expect(lastUser(fake!.requests.at(-1))).toContain("was given up by them, not run. Do not place it again unless they ask.]")
await again.app.close()
})
test("the person presses Enter and the command runs long, or stops to ask: still running, waiting for them", async () => {
const rec = (text: string) => parseStatus(text) as StatusRecord
const before = rec(statusText({ id: "a", seq: 4 }))
const world = (at: (ms: number) => { rec?: StatusRecord; text?: string }) => {
let t = 0
return { read: () => at(t).rec, look: async () => at(t).text ?? "", now: () => t, sleep: async (ms: number) => void (t += ms) }
}
const running = rec(statusText({ id: "a", seq: 4, state: "running" }))
// Entered after 5 s, still running 30 s later — and the display is told the moment Enter is seen.
let entered = 0
expect(await awaitPlaced({ before, ...world((ms) => ({ rec: ms < 5000 ? before : running, text: "Compiling…" })), entered: () => entered++ })).toMatchObject({ kind: "running" })
expect(entered).toBe(1)
// Entered, and it asks for a password: the answer is the person's.
expect(await awaitPlaced({ before, ...world((ms) => ({ rec: ms < 1000 ? before : running, text: "[sudo] password for user: " })) })).toMatchObject({ kind: "waiting", what: "password" })
// Nobody touches it for the whole wait.
const left = world(() => ({ rec: before }))
expect(await awaitPlaced({ before, ...left, free: async () => false })).toEqual({ kind: "left", ms: P.wait_seconds * 1000 })
// A stop: left, and said to be stopped.
const stopped = new AbortController()
stopped.abort()
expect(await awaitPlaced({ before, ...world(() => ({ rec: before })), signal: stopped.signal })).toMatchObject({ kind: "left", stopped: true })
})
// ── the settings store ──────────────────────────────────────────────────────────────────────
const settings = async (args: string[]) => {
const out: string[] = []
const err: string[] = []
const status = await settingsCommand(args, { out: (l) => void out.push(l), err: (l) => void err.push(l) })
return { status, out, err, json: () => JSON.parse(out[0]!) }
}
test("contract 2's file is read as the global level and written back in the new shape, losing nothing", () => {
mkdirSync(paths.config, { recursive: true })
writeFileSync(settingsFile(), JSON.stringify({ main_model: "fake/other", autocomplete_model: "open/tiny" }))
expect(terminalModels()).toEqual({ main_model: "fake/other", autocomplete_model: "open/tiny" })
// Reading alone changes nothing on disk.
expect(JSON.parse(readFileSync(settingsFile(), "utf8"))).toEqual({ main_model: "fake/other", autocomplete_model: "open/tiny" })
updateStore((s) => applyChanges(s, { global: true }, [parsePair("mode=auto")]))
expect(JSON.parse(readFileSync(settingsFile(), "utf8"))).toEqual({ version: 2, global: { main_model: "fake/other", autocomplete_model: "open/tiny", mode: "auto" }, directories: {} })
expect(statSync(settingsFile()).mode & 0o777).toBe(0o600)
// Nothing is left beside it: no temporary file, no lock.
expect(existsSync(join(paths.config, LOOP.terminal.settings.lock))).toBe(false)
// A file of a newer version is not written to.
writeFileSync(settingsFile(), JSON.stringify({ version: 3, global: { mode: "auto" }, directories: {}, more: 1 }))
expect(() => updateStore((s) => applyChanges(s, { global: true }, [parsePair("mode=manual")]))).toThrow("the settings file is version 3")
expect(JSON.parse(readFileSync(settingsFile(), "utf8")).more).toBe(1)
})
test("paths are compared with their links resolved; the nearest entry holds in subdirectories; a directory that is gone keeps its entry", async () => {
const root = tmp("lembas-settings-")
mkdirSync(join(root, "project", "src"), { recursive: true })
symlinkSync(join(root, "project"), join(root, "link"))
expect(realDir(join(root, "link", "src"))).toBe(join(root, "project", "src"))
// Set through the link: the entry is the real directory's.
expect((await settings(["set", "--cwd", join(root, "link"), "--json", "mode=auto", "highlight=off"])).status).toBe(0)
expect(Object.keys(readStore().directories)).toEqual([join(root, "project")])
const got = (await settings(["--cwd", join(root, "link", "src"), "--json"])).json()
expect(got.cwd).toBe(join(root, "project", "src"))
expect(got.directory).toEqual({ path: join(root, "project"), mode: "auto", highlight: false })
expect(got.effective.mode).toBe("auto")
expect(got.from.mode).toBe(join(root, "project"))
expect(got.from.ai).toBe("default")
// A directory that does not exist is compared as written, under what of it does exist.
expect(realDir(join(root, "link", "not", "there"))).toBe(join(root, "project", "not", "there"))
expect(settingsFor(join(root, "link", "not", "there")).effective.mode).toBe("auto")
// Removed from the disk: its entry stays until it is forgotten.
rmSync(join(root, "project"), { recursive: true })
expect(settingsFor(join(root, "project", "src")).effective.mode).toBe("auto")
const forgot = await settings(["forget", "--cwd", join(root, "project"), "--json"])
expect(forgot.status).toBe(0)
expect(forgot.json().directory).toBeNull()
// Forgetting what is not there: status 0, a line, nothing changed.
const again = await settings(["forget", "--cwd", join(root, "project"), "--json"])
expect(again.status).toBe(0)
expect(again.err[0]).toContain("nothing to forget")
})
test("lembas terminal settings: the JSON of the read, set and forget; errors are a sentence and a status", async () => {
setup([])
const read = await settings(["--cwd", "/srv/app", "--json"])
expect(read.status).toBe(0)
expect(read.out).toHaveLength(1)
expect(read.json()).toEqual({
cwd: "/srv/app",
effective: { main_model: null, autocomplete_model: null, mode: "manual", ai: true, autocomplete: false, suggestions: true, highlight: true, display_width: 0.33 },
from: { main_model: "default", autocomplete_model: "default", mode: "default", ai: "default", autocomplete: "default", suggestions: "default", highlight: "default", display_width: "default" },
global: {},
directory: null,
})
// Global, answered for a directory; a model is stored as its ref.
const g = await settings(["set", "--global", "--cwd", "/srv/app", "--json", "main_model=fake/other", "autocomplete=true", "display_width=0.4"])
expect(g.status).toBe(0)
expect(g.json()).toMatchObject({ cwd: "/srv/app", effective: { main_model: "fake/other", autocomplete: true, display_width: 0.4 }, from: { main_model: "global" }, global: { main_model: "fake/other", autocomplete: true, display_width: 0.4 }, directory: null })
// For a directory; `default` removes a key.
const d = await settings(["set", "--cwd", "/srv/app", "--json", "main_model=fake/m", "mode=auto"])
expect(d.json()).toMatchObject({ effective: { main_model: "fake/m", mode: "auto", autocomplete: true }, from: { main_model: "/srv/app", mode: "/srv/app", autocomplete: "global" }, directory: { path: "/srv/app", main_model: "fake/m", mode: "auto" } })
expect((await settings(["set", "--cwd", "/srv/app", "--json", "main_model=default"])).json()).toMatchObject({ effective: { main_model: "fake/other" }, from: { main_model: "global" }, directory: { path: "/srv/app", mode: "auto" } })
// A model the login does not serve is refused, and nothing of the call is written — unless forced.
const bad = await settings(["set", "--global", "--json", "suggestions=off", "main_model=open/gone"])
expect(bad.status).toBe(2)
expect(bad.out).toEqual([])
expect(bad.err[0]).toContain("no model open/gone for main_model")
expect(readStore().global.suggestions).toBeUndefined()
expect((await settings(["set", "--global", "--force", "--json", "autocomplete_model=open/tiny"])).json().global.autocomplete_model).toBe("open/tiny")
// What cannot be read: status 2, the sentence, the usage.
for (const args of [["set", "--json", "mode=auto"], ["set", "--global"], ["set", "--global", "mode=plan"], ["set", "--cwd", "relative", "mode=auto"], ["forget"], ["--cwd", "relative"], ["frobnicate"]]) {
const r = await settings(args)
expect({ args, status: r.status, out: r.out }).toEqual({ args, status: 2, out: [] })
expect(r.err.length).toBeGreaterThan(0)
}
// Without --json: a small table — the key, the value, where it comes from.
const table = await settings(["--cwd", "/srv/app/deep"])
expect(table.out[0]).toBe("settings kept for /srv/app")
expect(table.out[1]).toMatch(/^setting +value +from$/)
expect(table.out.find((l) => l.startsWith("mode "))).toMatch(/^mode +auto +\/srv\/app$/)
expect(table.out.find((l) => l.startsWith("autocomplete_model "))).toMatch(/^autocomplete_model +open\/tiny +global$/)
// Every row starts its columns at the same place.
const at = table.out.slice(1).map((l) => l.indexOf(l.trimStart().split(/ {2,}/)[1]!))
expect(new Set(at).size).toBe(1)
// models --json is the store's global level, with the answer for a directory when one is given.
const m = await modelsObject({ timeoutMs: 50, cwd: "/srv/app/deep" })
expect(m.main.model).toBe("fake/other")
expect(m.autocomplete.model).toBe("open/tiny")
expect(m.effective).toEqual({ cwd: "/srv/app/deep", main_model: "fake/other", autocomplete_model: "open/tiny", from: { main_model: "global", autocomplete_model: "global" } })
expect((await modelsObject({ timeoutMs: 50 })).effective).toBeUndefined()
})
test("two terminals writing at once both keep their change; the oldest directory goes first when there are too many", async () => {
setup([])
const cli = join(import.meta.dir, "..", "src", "cli.ts")
const one = (i: number) => Bun.spawn(["bun", cli, "terminal", "settings", "set", "--cwd", `/srv/app-${i}`, "--json", "mode=auto", `note_${i}=x`], { env: process.env as Record<string, string>, stdout: "pipe", stderr: "pipe" })
const procs = Array.from({ length: 6 }, (_, i) => one(i))
const codes = await Promise.all(procs.map((p) => p.exited))
expect(codes).toEqual([0, 0, 0, 0, 0, 0])
const store = readStore()
expect(Object.keys(store.directories).sort()).toEqual([0, 1, 2, 3, 4, 5].map((i) => `/srv/app-${i}`))
for (let i = 0; i < 6; i++) expect(store.directories[`/srv/app-${i}`]).toEqual({ mode: "auto", [`note_${i}`]: "x" })
// A lock left by a process that is gone is taken over.
writeFileSync(join(paths.config, LOOP.terminal.settings.lock), "999999999")
updateStore((s) => applyChanges(s, { global: true }, [parsePair("mode=auto")]))
expect(readStore().global.mode).toBe("auto")
// The cap: the directory written longest ago is dropped.
const max = LOOP.terminal.settings.directories_max
let s = readStore()
s = { ...s, directories: {} }
for (let i = 0; i < max; i++) s = applyChanges(s, { dir: `/d/${i}` }, [parsePair("mode=auto")])
s = applyChanges(s, { dir: "/d/0" }, [parsePair("ai=false")])
s = applyChanges(s, { dir: "/d/new" }, [parsePair("mode=auto")])
expect(Object.keys(s.directories)).toHaveLength(max)
expect(s.directories["/d/1"]).toBeUndefined()
expect(s.directories["/d/0"]).toEqual({ mode: "auto", ai: false })
expect(effective(s, "/d/new/x").effective.mode).toBe("auto")
}, 60_000)
test("the display starts with what holds in its directory; -m and --mode win for that start; /model and /mode say they are for the session only", async () => {
const dir = setup([])
const p = pane()
updateStore((s) => applyChanges(applyChanges(s, { global: true }, [parsePair("main_model=fake/m")]), { dir }, [parsePair("main_model=fake/other"), parsePair("mode=auto")]))
mkdirSync(join(dir, "sub"))
const open = (cwd: string, more: object = {}) => {
const bus = new Bus()
const view = createView(bus)
const o = openSurface({ cwd, window: `w-${Math.random().toString(36).slice(2)}`, terminal: env(p.exe), store: false, ...more }, view, bus)
return { ...o, view, bus }
}
// In the directory and under it: the directory's model. Elsewhere: the global one.
expect(open(dir).app.engine.model.ref).toBe("fake/other")
expect(open(join(dir, "sub")).app.engine.model.ref).toBe("fake/other")
expect(open(tmp("lembas-else-")).app.engine.model.ref).toBe("fake/m")
expect(open(dir, { model: "fake/m" }).app.engine.model.ref).toBe("fake/m")
// The mode is resolved by the command (`lembas terminal`), which hands it to the display.
expect(settingsFor(join(dir, "sub")).effective.mode).toBe("auto")
// /model and /mode change the running session and say so; the store is not written.
const before = readFileSync(settingsFile(), "utf8")
const d = open(dir)
const s = createSurface(d.app, d.view, { window: "w", quit: () => {} })
const said = () => d.view.state.items.filter((i) => i.kind === "notice").map((i) => (i as { text: string }).text)
s.feed("/mode auto\r")
expect(said().at(-1)).toBe("mode: auto — for this display only. The terminal's settings keep what a display starts with.")
s.feed("/model fake/m\r")
expect(said().at(-1)).toBe("model: fake/m — for this conversation only. The terminal's settings keep what a display starts with.")
expect(readFileSync(settingsFile(), "utf8")).toBe(before)
})
test("lembas complete --shell uses the directory's autocomplete model, and answers nothing where autocomplete or ai was set to false", async () => {
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 = async (args: string[]) => {
const out: string[] = []
const err: string[] = []
const status = await completeCommand(["--shell", "bash", ...args], { stdin: "git che", out: (t) => void out.push(t), err: (l) => void err.push(l), login, env: {} })
return { status, out: out.join(""), err }
}
try {
updateStore((s) => applyChanges(applyChanges(applyChanges(s, { global: true }, [parsePair("autocomplete_model=open/tiny"), parsePair("autocomplete=true")]), { dir: "/srv/app" }, [parsePair("autocomplete_model=open/code")]), { dir: "/srv/private" }, [parsePair("ai=false")]))
expect(await go(["--cwd", "/srv/app/src"])).toEqual({ status: 0, out: "ckout main", err: [] })
expect(await go(["--cwd", "/home/user"])).toEqual({ status: 0, out: "ckout main", err: [] })
// No directory given: still completed, with the global settings.
expect(await go([])).toEqual({ status: 0, out: "ckout main", err: [] })
expect(bodies.map((b) => b.model)).toEqual(["open/code", "open/tiny", "open/tiny"])
expect(bodies[2].prefix).toContain("# Working directory: not known")
// Turned off for a directory: no request, status 0, one line on standard error.
expect(await go(["--cwd", "/srv/private/notes"])).toEqual({ status: 0, out: "", err: ["lembas complete: autocomplete is turned off in the terminal's settings (ai: false, from /srv/private)"] })
updateStore((s) => applyChanges(s, { global: true }, [parsePair("autocomplete=false")]))
expect(await go(["--cwd", "/home/user"])).toEqual({ status: 0, out: "", err: ["lembas complete: autocomplete is turned off in the terminal's settings (autocomplete: false, from global)"] })
expect(bodies).toHaveLength(3)
// --debug: a line per decision on standard error, and the same answer on standard output.
updateStore((s) => applyChanges(s, { global: true }, [parsePair("autocomplete=default")]))
const dbg = await go(["--cwd", "/srv/app", "--debug"])
expect(dbg.out).toBe("ckout main")
expect(dbg.err.every((l) => l.startsWith("lembas complete: debug: "))).toBe(true)
const all = dbg.err.join("\n")
expect(all).toContain("shell bash, cwd /srv/app, timeout 2500 ms, standard input 7 bytes")
expect(all).toContain("autocomplete=false (default)")
expect(all).toContain("autocomplete_model=open/code (/srv/app)")
expect(all).toContain("model: open/code (terminal)")
expect(all).toContain("request: POST /v1/lembas/complete, line of 7 bytes")
expect(all).toMatch(/answered in \d+ ms by x: 10 characters, 10 printed/)
// Nothing of the line or the suggestion is in it.
expect(all).not.toContain("git che")
expect(all).not.toContain("ckout")
} finally {
server.stop(true)
}
})
test("lembas complete --shell sends no line that looks as if it holds a secret (spec 3.15.0)", async () => {
const bodies: any[] = []
const server = Bun.serve({ port: 0, fetch: async (req) => (bodies.push(await req.json()), Response.json({ text: "x", model: "x", finish: "stop" })) })
const login = { instance: { base_url: `http://127.0.0.1:${server.port}` }, token: "lmb_test" } as never
try {
for (const stdin of ["export OPENAI_API_KEY=abc", "mysql -u root -phunter2 sh", "curl -u alice:pw https://example.org"]) {
const out: string[] = []
const err: string[] = []
const status = await completeCommand(["--shell", "bash", "--debug"], { stdin, out: (t) => void out.push(t), err: (l) => void err.push(l), login, env: {}, settings: undefined })
expect(status).toBe(0)
expect(out.join("")).toBe("")
expect(err).toContain(LOOP.terminal.complete.texts.secret)
expect(err.some((l) => /debug: the line looks as if it holds a secret \(rule \w+\) — no request/.test(l))).toBe(true)
// Never the line itself.
expect(err.join("\n")).not.toContain(stdin)
}
expect(bodies).toHaveLength(0)
} finally {
server.stop(true)
}
})