Files
LLeMbas-CLI/tests/review-limits.test.ts
T
HomerandClaude Fable 5.2 83e51137c8 The remote limits are judged on every request of an open session (L-M1, L-S1, L-C1)
The limits are read live, but only load() and session/new asked them: a
session already in memory (the hub's, across links), a terminal's shared
session and an open web terminal were never judged again. lembas remote
disable, a removed root, a lowered mode or terminal off changed nothing for
them.

- get() and terminalFor() judge the session by the rule a new one in its
  directory is judged by; one that no longer fits is refused and halted (turn,
  queue, subagents, jobs); one that fits is lowered to max_mode. cancel,
  status and delete are always answered; a session shared by name stays.
- The link applies a change at once (enforce) instead of waiting for a
  request, then redials as before.
- terminal input is judged like terminal/open; a refused terminal is closed
  with a reason.
- sessions/list needs a cwd on the link; status and title of a session out
  of reach answer as for one that does not exist.
- One within(path, dir) replaces the containment copies; the two written
  with relative() called a child named ..cache outside.

Spec: acp.md. Conformance: limits.json (new, 24 cases), paths.json op
within. Link tests against a stand-in server for each of the four changes.

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

231 lines
12 KiB
TypeScript

// The device's limits apply to every request as they are at that moment (harness acp.md): a
// session, or a terminal, that was opened while they allowed it is judged again when they change.
// Against a stand-in LLeMbas server on the link, for each change: remote work turned off, a
// directory taken out of the roots, the mode lowered, terminals switched off.
import { afterAll, afterEach, expect, test } from "bun:test"
import { existsSync, mkdirSync, mkdtempSync, realpathSync, rmSync, writeFileSync } from "node:fs"
import { tmpdir } from "node:os"
import { join } from "node:path"
import { Hub } from "../src/acp/hub.ts"
import { limitsFromConfig, runLink } from "../src/acp/link.ts"
import { Peer } from "../src/acp/rpc.ts"
import { paths } from "../src/config/paths.ts"
import { setTrust } from "../src/project/root.ts"
import { delta, fakeProvider, toolCall, type Fake } from "./fake-provider.ts"
afterAll(() => {
rmSync(join(paths.config, "lembas.json"), { force: true })
rmSync(join(paths.config, "lembas"), { recursive: true, force: true })
})
let fake: Fake | undefined
const stops: (() => void)[] = []
afterEach(() => {
fake?.stop()
for (const s of stops.splice(0)) s()
})
function project(): string {
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-lim-")))
setTrust(dir, "trusted")
return dir
}
let n = 0
/** The device's config.yaml as it is now; the link reads it again within `pollMs`. */
function remote(url: string, block: string) {
mkdirSync(paths.config, { recursive: true })
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n f:\n type: webui\n url: ${url}\n models: { f/m: {} }\n`, { mode: 0o600 })
// A comment of a new length each time: the file's stamp changes whatever the clock's grain.
writeFileSync(join(paths.config, "config.yaml"), `model: f/m\n#${"x".repeat(++n)}\nremote:\n${block}`)
}
/** The web UI's side of the link, across the device's redials: a request goes over the link as
* it is now. */
interface Web {
request<T = any>(method: string, params?: unknown): Promise<T>
notify(method: string, params?: unknown): void
/** The device dialled again after a change of its limits, and said its new ones. */
redialled(): Promise<any>
exits: any[]
events: any[]
}
/** A stand-in server, and the service's side as `lembas service run` sets it up: a hub that holds
* the sessions across links. The device dials; `drive` is the web UI. The test fails unless
* `drive` ran to its end. */
async function linked(drive: (web: Web) => Promise<void>): Promise<void> {
let failure: unknown
let finished = false
let peer: Peer | undefined
let dials = 0
let seen = 0
let init: any
const stop = new AbortController()
const exits: any[] = []
const events: any[] = []
const ready = async (n: number) => {
for (let i = 0; i < 400 && dials < n; i++) await Bun.sleep(10)
if (dials < n) throw new Error(`the device did not dial (${n})`)
}
const web: Web = {
request: (m, p) => peer!.request(m, p, 20_000),
notify: (m, p) => peer!.notify(m, p),
redialled: async () => {
await ready(++seen)
return init
},
exits,
events,
}
const server = Bun.serve({
port: 0,
fetch(req, srv) {
const base = `http://${new URL(req.url).host}`
if (new URL(req.url).pathname === "/.well-known/lembas.json")
return Response.json({ service: "lembas", version: "2.0.0", protocol: 3, protocols: [3], harness_spec: "3.0.0", base_url: base, api: { openai: `${base}/v1` }, login: { device: { code: `${base}/c`, token: `${base}/t`, verify: `${base}/d` } } })
if (new URL(req.url).pathname === "/api/devices/link" && srv.upgrade(req)) return
return new Response("no", { status: 404 })
},
websocket: {
async open(ws) {
const p = new Peer({ send: (t) => ws.send(t), onMessage: (fn) => ((ws as any).recv = fn), onClose: () => {}, close: () => ws.close() })
p.on("_lembas/terminal/exit", (x) => void exits.push(x))
p.on("_lembas/event", (x) => void events.push(x.event))
p.handle("session/request_permission", () => ({ outcome: { outcome: "selected", optionId: "once" } }))
init = await p.request("initialize", { protocolVersion: 1, clientCapabilities: { _meta: { lembas: true } } })
peer = p
dials++
},
message(ws, msg) {
;(ws as any).recv?.(typeof msg === "string" ? msg : new TextDecoder().decode(msg))
},
},
})
stops.push(() => server.stop(true))
const base = `http://127.0.0.1:${server.port}`
writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { fake: { base_url: base, connection: "fake", logged_in_at: "" } } }))
mkdirSync(join(paths.config, "lembas"), { recursive: true })
writeFileSync(join(paths.config, "lembas", "fake.key"), "lmb_device\n", { mode: 0o600 })
const hub = new Hub({ service: true, limits: limitsFromConfig() })
const link = runLink({ backoffMs: [10, 20], pollMs: 40, hub, signal: stop.signal })
try {
await ready(++seen)
await drive(web)
finished = true
} catch (e) {
failure = e
}
stop.abort()
await link.catch(() => {})
for (const s of hub.held.values()) await s.app.close().catch(() => {})
if (failure) throw failure
expect(finished).toBe(true)
}
const text = (t: string) => [{ type: "text", text: t }]
test("remote disable is a stop: the open session is refused from then on, and its running turn ends", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "first" })] }, { chunks: [toolCall(0, "t1", "bash", JSON.stringify({ command: "sleep 30", description: "wait" }))] }, { chunks: [delta({ content: "never" })] }])
const root = project()
const on = ` enabled: true\n roots: [${root}]\n max_mode: auto\n`
remote(fake.url, on)
await linked(async (web) => {
const s: any = await web.request("session/new", { cwd: root, _meta: { mode: "auto" } })
expect((await web.request<any>("session/prompt", { sessionId: s.sessionId, prompt: text("one") })).stopReason).toBe("end_turn")
// A turn that is working — a command that would run for half a minute.
const started = Date.now()
const running = web.request<any>("session/prompt", { sessionId: s.sessionId, prompt: text("two") })
await Bun.sleep(400)
remote(fake!.url, on.replace("enabled: true", "enabled: false"))
expect((await running).stopReason).toBe("cancelled")
expect(Date.now() - started).toBeLessThan(10_000)
// Nothing works any more, so the device dials again and says what it accepts now: nothing.
expect((await web.redialled())._meta.lembas.limits.roots).toEqual([])
await expect(web.request("session/prompt", { sessionId: s.sessionId, prompt: text("three") })).rejects.toThrow("remote work is off")
await expect(web.request("_lembas/steer", { sessionId: s.sessionId, text: "more" })).rejects.toThrow("remote work is off")
await expect(web.request("_lembas/session/compact", { sessionId: s.sessionId })).rejects.toThrow("remote work is off")
await expect(web.request("session/set_mode", { sessionId: s.sessionId, modeId: "auto" })).rejects.toThrow("remote work is off")
// Stopping and asking are never refused.
expect(await web.request<any>("session/cancel", { sessionId: s.sessionId })).toEqual({ cancelled: "none" })
expect((await web.request<any>("_lembas/session/status", { sessionId: s.sessionId })).exists).toBe(true)
})
expect(fake.requests.length).toBe(2)
})
test("a directory taken out of the roots: its open session is refused in the words a new one is", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "first" })] }])
const root = project()
const other = project()
remote(fake.url, ` enabled: true\n roots: [${root}]\n`)
await linked(async (web) => {
const s: any = await web.request("session/new", { cwd: root })
await web.request("session/prompt", { sessionId: s.sessionId, prompt: text("one") })
remote(fake!.url, ` enabled: true\n roots: [${other}]\n`)
expect((await web.redialled())._meta.lembas.limits.roots).toEqual([other])
await expect(web.request("session/prompt", { sessionId: s.sessionId, prompt: text("two") })).rejects.toThrow("outside the directories this device accepts")
await expect(web.request("_lembas/configure", { sessionId: s.sessionId, model: "f/m" })).rejects.toThrow("outside the directories")
// A session in the directory now allowed opens as ever.
expect(typeof ((await web.request("session/new", { cwd: other })) as any).sessionId).toBe("string")
})
expect(fake.requests.length).toBe(1)
})
test("the mode lowered: an open session in auto runs its next prompt no looser than the new limit", async () => {
const root = project()
const marker = join(root, "written")
fake = fakeProvider([{ chunks: [toolCall(0, "t1", "bash", JSON.stringify({ command: `touch ${marker}`, description: "write" }))] }, { chunks: [delta({ content: "done" })] }])
remote(fake.url, ` enabled: true\n roots: [${root}]\n max_mode: auto\n`)
await linked(async (web) => {
const s: any = await web.request("session/new", { cwd: root, _meta: { mode: "auto" } })
expect(s.modes.currentModeId).toBe("auto")
remote(fake!.url, ` enabled: true\n roots: [${root}]\n max_mode: plan\n`)
expect((await web.redialled())._meta.lembas.limits.max_mode).toBe("plan")
const r = await web.request<any>("session/prompt", { sessionId: s.sessionId, prompt: text("write it") })
expect(r.stopReason).toBe("end_turn")
})
// Plan mode refused the command the session's old mode would have run.
expect(existsSync(marker)).toBe(false)
expect(JSON.stringify(fake.requests[1].messages.at(-1))).toContain("lan mode")
})
test("remote terminal off: an open terminal is closed, with or without anything typed", async () => {
fake = fakeProvider([])
const root = project()
const on = ` enabled: true\n roots: [${root}]\n terminal: true\n`
remote(fake.url, on)
await linked(async (web) => {
const a: any = await web.request("_lembas/terminal/open", { cwd: root })
remote(fake!.url, on.replace("terminal: true", "terminal: false"))
// Typed at once, before the link has looked at the file again: judged by the request itself.
web.notify("_lembas/terminal/input", { terminalId: a.terminalId, data: Buffer.from("echo hi\n").toString("base64") })
for (let i = 0; i < 100 && !web.exits.length; i++) await Bun.sleep(20)
expect(web.exits[0].terminalId).toBe(a.terminalId)
expect(web.exits[0].reason).toContain("switched off")
await expect(web.request("_lembas/terminal/open", { cwd: root })).rejects.toThrow("lembas remote terminal on")
})
})
test("sessions the client was never shown are out of its reach: no list of the machine, no status, no rename", async () => {
fake = fakeProvider([{ chunks: [delta({ content: "first" })] }])
const root = project()
const elsewhere = project()
remote(fake.url, ` enabled: true\n roots: [${root}]\n`)
const { Store } = await import("../src/session/store.ts")
const store = new Store()
const hidden = store.createSession(elsewhere, "f/m").id
store.setTitle(hidden, "private notes")
await linked(async (web) => {
await expect(web.request("_lembas/sessions/list", {})).rejects.toThrow("a directory is required")
await expect(web.request("_lembas/sessions/list", { cwd: elsewhere })).rejects.toThrow("outside")
const st: any = await web.request("_lembas/session/status", { sessionId: hidden })
expect(st.exists).toBe(false)
expect(st.title).toBe("")
await expect(web.request("_lembas/session/title", { sessionId: hidden, title: "renamed" })).rejects.toThrow("no such session")
const s: any = await web.request("session/new", { cwd: root })
await web.request("session/prompt", { sessionId: s.sessionId, prompt: text("one") })
expect(((await web.request("_lembas/sessions/list", { cwd: root })) as any).sessions.map((x: any) => x.id)).toContain(s.sessionId)
})
expect(store.session(hidden)?.title).toBe("private notes")
})