893 lines
45 KiB
TypeScript
893 lines
45 KiB
TypeScript
// LLeMbas connection 1 (harness/connection.md) as the CLI does it: the link against a stand-in
|
|
// server — replaced by a newer link (4409), a token refused and then signed in again, a handshake
|
|
// that never finishes, a server that accepts and drops, a link that goes silent — and the smaller
|
|
// rules: who the CLI says it is, a failed turn in the prompt's answer, the stdio client's name and
|
|
// protocol, the lock, a line with no end, Retry-After.
|
|
import { afterAll, afterEach, expect, test } from "bun:test"
|
|
import { createHash } from "node:crypto"
|
|
import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from "node:fs"
|
|
import { tmpdir } from "node:os"
|
|
import { join } from "node:path"
|
|
import { PassThrough } from "node:stream"
|
|
import { AcpAgent, clientName, minClientFor, turnError } from "../src/acp/agent.ts"
|
|
import { heldLogin, LinkError, runLink, type LinkOptions, type LinkStatus } from "../src/acp/link.ts"
|
|
import { Peer, stdioTransport, type Transport } from "../src/acp/rpc.ts"
|
|
import { paths } from "../src/config/paths.ts"
|
|
import { apiCall, discover, LembasError, models, SignInRejected } from "../src/lembas/client.ts"
|
|
import { CONNECTION, reconnectWait, USER_AGENT } from "../src/lembas/connection.ts"
|
|
import { instances, login, loginWithToken, refreshDiscovery, sync } from "../src/lembas/login.ts"
|
|
import { setTrust } from "../src/project/root.ts"
|
|
import { retrying } from "../src/provider/common.ts"
|
|
import { failureCode, request } from "../src/provider/http.ts"
|
|
import { ProviderError, type StreamEvent } from "../src/provider/types.ts"
|
|
import { holdsLock, takeLock } from "../src/service.ts"
|
|
import { VERSION } from "../src/version.ts"
|
|
import { delta, 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()
|
|
fake = undefined
|
|
for (const s of stops.splice(0)) s()
|
|
rmSync(join(paths.config, "lembas.json"), { force: true })
|
|
rmSync(join(paths.config, "lembas"), { recursive: true, force: true })
|
|
})
|
|
|
|
const keyPath = () => join(paths.config, "lembas", "fake.key")
|
|
|
|
/** A login as `lembas login` leaves it: the index, and the key in its own file. */
|
|
function kept(base: string, token: string | null = "lmb_first") {
|
|
mkdirSync(join(paths.config, "lembas"), { recursive: true })
|
|
writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { fake: { base_url: base, connection: "fake", logged_in_at: "" } } }))
|
|
if (token === null) rmSync(keyPath(), { force: true })
|
|
else writeFileSync(keyPath(), `${token}\n`, { mode: 0o600 })
|
|
}
|
|
|
|
interface Dial {
|
|
n: number
|
|
token: string
|
|
agent: string
|
|
ws: any
|
|
/** What the device sent on this socket, as JSON-RPC messages. */
|
|
got: any[]
|
|
/** Ask the device something, as the server does after the hello. */
|
|
ask: (method: string, params?: unknown) => Promise<any>
|
|
}
|
|
|
|
/** A stand-in LLeMbas server: discovery, and the link's socket handed to `onDial` each time the
|
|
* device dials. It does nothing by itself — not even `initialize` — so each test says exactly
|
|
* what the server does. */
|
|
function standIn(onDial: (d: Dial) => void | Promise<void>, o: { discovery?: () => Response | undefined } = {}) {
|
|
const dials: Dial[] = []
|
|
const agents: string[] = []
|
|
const server = Bun.serve({
|
|
port: 0,
|
|
fetch(req, srv) {
|
|
const u = new URL(req.url)
|
|
const base = `http://${u.host}`
|
|
if (u.pathname === "/.well-known/lembas.json") {
|
|
agents.push(req.headers.get("user-agent") ?? "")
|
|
return (
|
|
o.discovery?.() ??
|
|
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 (u.pathname === "/api/devices/link" && srv.upgrade(req, { data: { token: (req.headers.get("authorization") ?? "").replace(/^Bearer /, ""), agent: req.headers.get("user-agent") ?? "" } } as never)) return
|
|
return new Response("no", { status: 404 })
|
|
},
|
|
websocket: {
|
|
open(ws) {
|
|
const data = ws.data as unknown as { token: string; agent: string; dial?: Dial; waiting?: Map<number, (m: any) => void> }
|
|
const waiting = (data.waiting = new Map())
|
|
let id = 1000
|
|
const d: Dial = {
|
|
n: dials.length + 1,
|
|
token: data.token,
|
|
agent: data.agent,
|
|
ws,
|
|
got: [],
|
|
ask: (method, params) =>
|
|
new Promise((resolve) => {
|
|
const mine = id++
|
|
waiting.set(mine, resolve)
|
|
ws.send(JSON.stringify({ jsonrpc: "2.0", id: mine, method, params }))
|
|
}),
|
|
}
|
|
data.dial = d
|
|
dials.push(d)
|
|
void onDial(d)
|
|
},
|
|
message(ws, msg) {
|
|
const data = ws.data as unknown as { dial?: Dial; waiting?: Map<number, (m: any) => void> }
|
|
const m = JSON.parse(String(msg))
|
|
data.dial?.got.push(m)
|
|
if (m.method === undefined && data.waiting?.has(m.id)) data.waiting.get(m.id)!(m)
|
|
},
|
|
},
|
|
})
|
|
stops.push(() => server.stop(true))
|
|
return { base: `http://127.0.0.1:${server.port}`, dials, agents }
|
|
}
|
|
|
|
const initialize = (d: Dial) => d.ask("initialize", { protocolVersion: 1, clientInfo: { name: "llembas-server", version: "2.0.0" }, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
|
|
|
|
/** Run the link with test-sized timers, collecting what it says. */
|
|
function link(o: LinkOptions = {}) {
|
|
const stop = new AbortController()
|
|
stops.push(() => stop.abort())
|
|
const said: LinkStatus[] = []
|
|
const done = runLink({ backoffMs: [10, 80], signal: stop.signal, ...o, timers: { random: () => 0.5, login: 10, ...o.timers }, onStatus: (s) => void said.push(s) })
|
|
const until = async (ok: () => boolean, what: string) => {
|
|
for (let i = 0; i < 400 && !ok(); i++) await Bun.sleep(10)
|
|
if (!ok()) throw new Error(`timed out waiting for ${what}: ${JSON.stringify(said.map((s) => [s.state, s.code, s.detail]))}`)
|
|
}
|
|
return { stop, said, done, until, codes: () => said.map((s) => `${s.state}:${s.code}`) }
|
|
}
|
|
|
|
test("who the CLI says it is: llembas-cli/<version>, on discovery and on the link's upgrade request", async () => {
|
|
expect(USER_AGENT).toBe(`llembas-cli/${VERSION}`)
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
d.ws.close(4403, "revoked")
|
|
})
|
|
kept(srv.base)
|
|
const l = link()
|
|
expect((await l.done).code).toBe("signed_out")
|
|
expect(srv.agents).toEqual([USER_AGENT])
|
|
expect(srv.dials[0]!.agent).toBe(USER_AGENT)
|
|
})
|
|
|
|
test("linked is said only after initialize was answered, never at the open socket", async () => {
|
|
let let_in!: () => void
|
|
const gate = new Promise<void>((r) => (let_in = r))
|
|
const srv = standIn(async (d) => {
|
|
await gate
|
|
await initialize(d)
|
|
})
|
|
kept(srv.base)
|
|
const l = link()
|
|
// The socket is open and the hello was sent: still connecting.
|
|
await l.until(() => srv.dials[0]?.got.some((m) => m.method === "_lembas/hello") === true, "the hello")
|
|
await Bun.sleep(50)
|
|
expect(l.codes()).toEqual(["connecting:connecting"])
|
|
let_in()
|
|
await l.until(() => l.said.some((s) => s.state === "linked"), "linked")
|
|
expect(l.said.at(-1)).toMatchObject({ state: "linked", code: "linked", instance: srv.base })
|
|
l.stop.abort()
|
|
expect(await l.done).toMatchObject({ state: "stopped", code: "stopped", detail: "stopped" })
|
|
})
|
|
|
|
test("a token refused before initialize never says linked (the server accepts the socket first)", async () => {
|
|
const srv = standIn((d) => d.ws.close(4403, "not allowed to link"))
|
|
kept(srv.base)
|
|
const l = link()
|
|
const end = await l.done
|
|
expect(end).toMatchObject({ state: "stopped", code: "signed_out" })
|
|
expect(end.detail).toContain("no longer accepts this sign-in — sign in again. Run lembas login. (not allowed to link)")
|
|
expect(l.codes()).toEqual(["connecting:connecting", "stopped:signed_out"])
|
|
expect(srv.dials.length).toBe(1)
|
|
})
|
|
|
|
test("4409, replaced by a newer link of the same device: stopped with its own code, and no dial again", async () => {
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
d.ws.close(4409, "replaced by a newer link")
|
|
})
|
|
kept(srv.base)
|
|
const l = link()
|
|
const end = await l.done
|
|
expect(end).toMatchObject({ state: "stopped", code: "replaced" })
|
|
expect(end.detail).toContain("A newer link of this device took its place")
|
|
await Bun.sleep(150)
|
|
expect(srv.dials.length).toBe(1)
|
|
})
|
|
|
|
test("a plain 1000 is a link that dropped, and is dialled again — only 4409 means replaced", async () => {
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
d.ws.close(d.n === 1 ? 1000 : 4409, "bye")
|
|
})
|
|
kept(srv.base)
|
|
const l = link()
|
|
expect((await l.done).code).toBe("replaced")
|
|
expect(srv.dials.length).toBe(2)
|
|
expect(l.said.find((s) => s.state === "waiting")).toMatchObject({ code: "unreachable" })
|
|
})
|
|
|
|
test("4403 after the key changed: the sign-in was made again, so the link dials at once with the new key", async () => {
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
if (d.token !== "lmb_first") return
|
|
// `lembas login` again: the new key is written, then the old token is signed out — which is
|
|
// what closes this link.
|
|
writeFileSync(keyPath(), "lmb_second\n", { mode: 0o600 })
|
|
d.ws.close(4403, "revoked")
|
|
})
|
|
kept(srv.base)
|
|
const l = link()
|
|
await l.until(() => srv.dials.length === 2 && l.said.at(-1)?.state === "linked", "the second link")
|
|
expect(srv.dials.map((d) => d.token)).toEqual(["lmb_first", "lmb_second"])
|
|
expect(l.said.some((s) => s.state === "stopped")).toBe(false)
|
|
expect(l.said.some((s) => s.detail === "the sign-in kept here changed; linking again with it")).toBe(true)
|
|
l.stop.abort()
|
|
await l.done
|
|
})
|
|
|
|
test("the service stays when its token is refused, and links again by itself once lembas login has run", async () => {
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
if (d.token === "lmb_first") d.ws.close(4403, "revoked")
|
|
})
|
|
kept(srv.base)
|
|
const l = link({ stay: true })
|
|
await l.until(() => l.said.at(-1)?.code === "signed_out", "the refusal")
|
|
// It does not come back by itself: nothing dials while the same key is there.
|
|
await Bun.sleep(120)
|
|
expect(srv.dials.length).toBe(1)
|
|
expect(l.said.at(-1)).toMatchObject({ state: "stopped", code: "signed_out" })
|
|
writeFileSync(keyPath(), "lmb_second\n", { mode: 0o600 })
|
|
await l.until(() => l.said.at(-1)?.state === "linked", "the link with the new key")
|
|
expect(srv.dials.map((d) => d.token)).toEqual(["lmb_first", "lmb_second"])
|
|
l.stop.abort()
|
|
expect((await l.done).code).toBe("stopped")
|
|
})
|
|
|
|
test("no key file: not a crash and not a restart loop — stopped as not_logged_in, and healed by a login", async () => {
|
|
const srv = standIn((d) => void initialize(d))
|
|
kept(srv.base, null)
|
|
// A terminal's /remote is told at once, with the code.
|
|
expect(() => heldLogin()).toThrow(LinkError)
|
|
const refused = await runLink({ backoffMs: [10, 20] }).catch((e) => e)
|
|
expect(refused).toBeInstanceOf(LinkError)
|
|
expect(refused.code).toBe("not_logged_in")
|
|
expect(refused.message).toContain("not logged in")
|
|
// The service says so and waits.
|
|
const l = link({ stay: true })
|
|
await l.until(() => l.said.length > 0, "a status")
|
|
await Bun.sleep(80)
|
|
expect(l.codes()).toEqual(["stopped:not_logged_in"])
|
|
expect(srv.dials.length).toBe(0)
|
|
writeFileSync(keyPath(), "lmb_new\n", { mode: 0o600 })
|
|
await l.until(() => l.said.at(-1)?.state === "linked", "the link after the login")
|
|
expect(srv.dials[0]!.token).toBe("lmb_new")
|
|
l.stop.abort()
|
|
await l.done
|
|
})
|
|
|
|
test("not logged in at all: the service waits in not_logged_in until there is a login", async () => {
|
|
const srv = standIn((d) => void initialize(d))
|
|
const l = link({ stay: true })
|
|
await l.until(() => l.said.length > 0, "a status")
|
|
expect(l.said[0]).toMatchObject({ state: "stopped", code: "not_logged_in", instance: "" })
|
|
kept(srv.base, "lmb_new")
|
|
await l.until(() => l.said.at(-1)?.state === "linked", "the link after the login")
|
|
l.stop.abort()
|
|
await l.done
|
|
})
|
|
|
|
test("a handshake that never finishes is given up on, and counts as a failure", async () => {
|
|
// The server accepts the socket, reads the hello, and never sends initialize.
|
|
const srv = standIn(() => {})
|
|
kept(srv.base)
|
|
const l = link({ timers: { handshake: 60 } })
|
|
await l.until(() => srv.dials.length >= 3, "three dials")
|
|
l.stop.abort()
|
|
await l.done
|
|
expect(l.said.some((s) => s.state === "linked")).toBe(false)
|
|
const waits = l.said.filter((s) => s.state === "waiting")
|
|
expect(waits[0]).toMatchObject({ code: "timeout" })
|
|
expect(waits[0]!.detail).toContain("did not finish linking")
|
|
// The wait grows: 10 ms, then 20 ms — an open socket did not set it back.
|
|
expect(waits.slice(0, 2).map((s) => s.detail!.match(/trying again in (\d+) ms/)?.[1])).toEqual(["10", "20"])
|
|
})
|
|
|
|
test("flapping: a server that accepts and drops at once is dialled ever more slowly, up to the ceiling", async () => {
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
await Bun.sleep(5)
|
|
d.ws.close(1011, "internal error")
|
|
})
|
|
kept(srv.base)
|
|
const l = link()
|
|
await l.until(() => l.said.filter((s) => s.state === "waiting").length >= 5, "five waits")
|
|
l.stop.abort()
|
|
await l.done
|
|
const waits = l.said.filter((s) => s.state === "waiting").map((s) => Number(s.detail!.match(/trying again in (\d+) ms/)?.[1]))
|
|
// It was linked each time — for a moment, which is not health: the wait is not set back.
|
|
expect(waits.slice(0, 5)).toEqual([10, 20, 40, 80, 80])
|
|
expect(l.said.filter((s) => s.state === "linked").length).toBeGreaterThanOrEqual(5)
|
|
})
|
|
|
|
test("the wait starts over only after a link that stayed healthy", async () => {
|
|
const srv = standIn(async (d) => {
|
|
await initialize(d)
|
|
// The third link lives long enough to count as healthy; the others drop at once.
|
|
if (d.n === 3) await Bun.sleep(120)
|
|
d.ws.close(1011, "internal error")
|
|
})
|
|
kept(srv.base)
|
|
const l = link({ timers: { healthy: 60 } })
|
|
await l.until(() => l.said.filter((s) => s.state === "waiting").length >= 4, "four waits")
|
|
l.stop.abort()
|
|
await l.done
|
|
const waits = l.said.filter((s) => s.state === "waiting").map((s) => Number(s.detail!.match(/trying again in (\d+) ms/)?.[1]))
|
|
expect(waits.slice(0, 4)).toEqual([10, 20, 10, 20])
|
|
})
|
|
|
|
test("the reconnect schedule: 1 s doubling to 60 s, within ±20 %", () => {
|
|
expect([1, 2, 3, 4, 5, 6, 7, 8, 20].map((n) => reconnectWait(n, 0.5))).toEqual([1000, 2000, 4000, 8000, 16000, 32000, 60000, 60000, 60000])
|
|
expect(reconnectWait(0, 0.5)).toBe(1000)
|
|
expect(reconnectWait(1, 0)).toBe(800)
|
|
expect(reconnectWait(1, 0.999999)).toBe(1200)
|
|
expect(reconnectWait(7, 0)).toBe(48000)
|
|
for (let i = 0; i < 200; i++) {
|
|
const w = reconnectWait(3)
|
|
expect(w).toBeGreaterThanOrEqual(3200)
|
|
expect(w).toBeLessThanOrEqual(4800)
|
|
}
|
|
expect(CONNECTION.reconnect).toEqual({ first_s: 1, ceiling_s: 60, jitter: 0.2, healthy_s: 30 })
|
|
expect(CONNECTION.link.close.replaced).toBe(4409)
|
|
})
|
|
|
|
test("liveness: pings keep a quiet link, and a link nothing is heard on is closed and dialled again", async () => {
|
|
// A healthy server says nothing for a while, but answers pings: the link stays.
|
|
const quiet = standIn((d) => void initialize(d))
|
|
kept(quiet.base)
|
|
const a = link({ timers: { ping: 20, silence: 70 } })
|
|
await a.until(() => a.said.at(-1)?.state === "linked", "linked")
|
|
await Bun.sleep(250)
|
|
expect(a.said.at(-1)?.state).toBe("linked")
|
|
expect(quiet.dials.length).toBe(1)
|
|
a.stop.abort()
|
|
await a.done
|
|
|
|
// A server that finishes the upgrade, answers initialize by hand, and then goes silent — no
|
|
// pong, no close: what a dead connection looks like from here.
|
|
let sockets = 0
|
|
const dead = Bun.listen({
|
|
hostname: "127.0.0.1",
|
|
port: 0,
|
|
socket: {
|
|
data(sock, chunk) {
|
|
const text = chunk.toString("latin1")
|
|
const head = text.split("\r\n\r\n")[0] ?? ""
|
|
if (/^GET \/\.well-known\/lembas\.json/.test(head)) {
|
|
const base = `http://127.0.0.1:${dead.port}`
|
|
const body = JSON.stringify({ 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` } } })
|
|
sock.write(`HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: ${body.length}\r\nconnection: close\r\n\r\n${body}`)
|
|
sock.end()
|
|
return
|
|
}
|
|
const key = /sec-websocket-key: *(\S+)/i.exec(head)?.[1]
|
|
if (!key) return
|
|
sockets++
|
|
const accept = createHash("sha1").update(`${key}258EAFA5-E914-47DA-95CA-C5AB0DC85B11`).digest("base64")
|
|
sock.write(`HTTP/1.1 101 Switching Protocols\r\nupgrade: websocket\r\nconnection: Upgrade\r\nsec-websocket-accept: ${accept}\r\n\r\n`)
|
|
// initialize, as one unmasked text frame; whatever comes back is never read.
|
|
const msg = Buffer.from(JSON.stringify({ jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: 1, clientCapabilities: { _meta: { lembas: { protocol: 3 } } } } }))
|
|
sock.write(Buffer.concat([Buffer.from([0x81, 126, msg.length >> 8, msg.length & 0xff]), msg]))
|
|
},
|
|
},
|
|
})
|
|
stops.push(() => dead.stop(true))
|
|
kept(`http://127.0.0.1:${dead.port}`)
|
|
const b = link({ timers: { ping: 20, silence: 70 } })
|
|
await b.until(() => b.said.some((s) => s.state === "waiting"), "the silence being noticed")
|
|
expect(b.said.some((s) => s.state === "linked")).toBe(true)
|
|
const gone = b.said.find((s) => s.state === "waiting")!
|
|
expect(gone.code).toBe("timeout")
|
|
expect(gone.detail).toContain("nothing was heard from")
|
|
await b.until(() => sockets >= 2, "a second dial")
|
|
b.stop.abort()
|
|
await b.done
|
|
})
|
|
|
|
test("why a dial failed is a code: not LLeMbas, a server that fails, one that is too old, one that is not there", async () => {
|
|
let answer: () => Response = () => new Response("no", { status: 404 })
|
|
const srv = standIn(() => {}, { discovery: () => answer() })
|
|
const code = async (address: string) => {
|
|
const e = await discover(address).catch((x) => x)
|
|
expect(e).toBeInstanceOf(LembasError)
|
|
return [e.code, e.message]
|
|
}
|
|
expect((await code(srv.base))[0]).toBe("not_lembas")
|
|
answer = () => new Response("<html>bad gateway</html>", { status: 502 })
|
|
const failing = await code(srv.base)
|
|
expect(failing[0]).toBe("server_error")
|
|
expect(failing[1]).toContain("answered 502")
|
|
expect(failing[1]).not.toContain("not a LLeMbas")
|
|
answer = () => Response.json({ service: "something-else" })
|
|
expect((await code(srv.base))[0]).toBe("not_lembas")
|
|
answer = () => new Response("not json")
|
|
expect((await code(srv.base))[0]).toBe("not_lembas")
|
|
answer = () => Response.json({ service: "lembas", version: "1.7.3", protocol: 1, protocols: [1, 2] })
|
|
expect((await code(srv.base))[0]).toBe("server_too_old")
|
|
answer = () => Response.json({ service: "lembas", version: "3.0.0", protocol: 4, protocols: [4] })
|
|
expect((await code(srv.base))[0]).toBe("client_too_old")
|
|
answer = () => new Response("slow down", { status: 429, headers: { "retry-after": "7" } })
|
|
const busy = await discover(srv.base).catch((x) => x)
|
|
expect([busy.code, busy.retryAfter]).toEqual(["busy", 7])
|
|
expect((await code("ftp://example.org"))[0]).toBe("invalid_address")
|
|
const closed = Bun.serve({ port: 0, fetch: () => new Response("no") })
|
|
const port = closed.port
|
|
closed.stop(true)
|
|
expect((await code(`http://127.0.0.1:${port}`))[0]).toBe("unreachable")
|
|
// The link says the same code while it waits to try again, and does not open a socket for it.
|
|
answer = () => new Response("<html>bad gateway</html>", { status: 502 })
|
|
kept(srv.base)
|
|
const l = link()
|
|
await l.until(() => l.said.some((s) => s.state === "waiting"), "a wait")
|
|
l.stop.abort()
|
|
await l.done
|
|
expect(l.said.find((s) => s.state === "waiting")).toMatchObject({ code: "server_error" })
|
|
expect(srv.dials.length).toBe(0)
|
|
})
|
|
|
|
// ---- the prompt's answer, and the stdio client --------------------------------------------
|
|
|
|
function pair(): [Transport, Transport] {
|
|
const make = () => ({ msg: (_: string) => {}, end: () => {} })
|
|
const a = make()
|
|
const b = make()
|
|
const side = (me: typeof a, other: typeof a): Transport => ({
|
|
send: (t) => queueMicrotask(() => other.msg(t)),
|
|
onMessage: (fn) => (me.msg = fn),
|
|
onClose: (fn) => (me.end = fn),
|
|
close: () => (me.end(), other.end()),
|
|
})
|
|
return [side(a, b), side(b, a)]
|
|
}
|
|
|
|
function config(url: 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 })
|
|
writeFileSync(join(paths.config, "config.yaml"), "model: f/m\n")
|
|
}
|
|
|
|
function project(): string {
|
|
const dir = realpathSync(mkdtempSync(join(tmpdir(), "ph-conn-")))
|
|
setTrust(dir, "trusted")
|
|
return dir
|
|
}
|
|
|
|
function stdioClient(init: Record<string, unknown>) {
|
|
const [ta, tb] = pair()
|
|
const agent = new AcpAgent(new Peer(ta))
|
|
const c = new Peer(tb)
|
|
const events: any[] = []
|
|
c.on("_lembas/event", (p) => void events.push(p.event))
|
|
return { c, agent, events, init: c.request<any>("initialize", { protocolVersion: 1, ...init }) }
|
|
}
|
|
|
|
/** A model endpoint that answers each chat request with the next of `answers`, then with a reply. */
|
|
function chat(answers: Response[]) {
|
|
const srv = Bun.serve({
|
|
port: 0,
|
|
fetch(req) {
|
|
if (req.method !== "POST") return new Response("not found", { status: 404 })
|
|
return answers.shift() ?? new Response(`data: ${JSON.stringify(delta({ content: "fine now" }))}\n\ndata: ${JSON.stringify(delta({}, "stop"))}\n\ndata: [DONE]\n\n`, { headers: { "content-type": "text/event-stream" } })
|
|
},
|
|
})
|
|
stops.push(() => srv.stop(true))
|
|
return `http://127.0.0.1:${srv.port}`
|
|
}
|
|
|
|
test("a turn that fails says so in the prompt's answer: _meta.lembas.error, a code and one line", async () => {
|
|
// The server's own refusal of the token: a 401 with its challenge.
|
|
config(chat([new Response(JSON.stringify({ error: { message: "That token is not valid, has expired or was revoked." } }), { status: 401, headers: { "www-authenticate": 'Bearer realm="lembas"' } })]))
|
|
const { c, events, init } = stdioClient({ clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
|
|
await init
|
|
const s: any = await c.request("session/new", { cwd: project(), mcpServers: [] })
|
|
const failed: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] })
|
|
// The stop reason is as before: ACP has none for a failure.
|
|
expect(failed.stopReason).toBe("end_turn")
|
|
expect(failed._meta.lembas.error.code).toBe("signed_out")
|
|
expect(failed._meta.lembas.error.message).toContain("That token is not valid")
|
|
expect(failed._meta.lembas.error.message).not.toContain("\n")
|
|
// The event is still there, for a client that reads events, and carries the same code.
|
|
expect(events.find((e) => e.type === "error")).toMatchObject({ code: "signed_out" })
|
|
// A turn that works has no error.
|
|
const fine: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "again" }] })
|
|
expect(fine._meta.lembas.error).toBeUndefined()
|
|
})
|
|
|
|
test("a 401 without the server's challenge is a model provider's, passed through: failed, in its words, and no sign-out", async () => {
|
|
config(chat([new Response(JSON.stringify({ error: { message: "Incorrect API key provided to the provider." } }), { status: 401 })]))
|
|
const { c, init } = stdioClient({ clientCapabilities: { _meta: { lembas: { protocol: 3 } } } })
|
|
await init
|
|
const s: any = await c.request("session/new", { cwd: project(), mcpServers: [] })
|
|
const r: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] })
|
|
expect(r._meta.lembas.error.code).toBe("failed")
|
|
expect(r._meta.lembas.error.message).toContain("Incorrect API key provided to the provider.")
|
|
// The same holds for every request with the device's token.
|
|
const bare = Bun.serve({ port: 0, fetch: () => Response.json({ detail: "upstream said no" }, { status: 401 }) })
|
|
const own = Bun.serve({ port: 0, fetch: () => Response.json({ detail: "That token is not valid, has expired or was revoked." }, { status: 401, headers: { "WWW-Authenticate": 'Bearer realm="lembas"' } }) })
|
|
stops.push(() => (bare.stop(true), own.stop(true)))
|
|
const passed = await models({ api: { openai: `http://127.0.0.1:${bare.port}/v1` } }, "lmb_x", undefined).catch((e) => e)
|
|
expect(passed).toBeInstanceOf(LembasError)
|
|
expect(passed).not.toBeInstanceOf(SignInRejected)
|
|
expect([passed.code, passed.message]).toEqual(["failed", "listing the models: upstream said no"])
|
|
const refused = await models({ api: { openai: `http://127.0.0.1:${own.port}/v1` } }, "lmb_x", undefined).catch((e) => e)
|
|
expect(refused).toBeInstanceOf(SignInRejected)
|
|
expect(refused.code).toBe("signed_out")
|
|
expect((await apiCall(`http://127.0.0.1:${bare.port}`, "lmb_x", undefined, "GET", "/v1/x")).signedOut).toBe(false)
|
|
expect((await apiCall(`http://127.0.0.1:${own.port}`, "lmb_x", undefined, "GET", "/v1/x")).signedOut).toBe(true)
|
|
})
|
|
|
|
test("a server that cannot be reached is `unreachable` in the answer, and plain ACP clients get it too", async () => {
|
|
const closed = Bun.serve({ port: 0, fetch: () => new Response("no") })
|
|
const port = closed.port
|
|
closed.stop(true)
|
|
config(`http://127.0.0.1:${port}`)
|
|
// No `_meta.lembas` at all: this client gets no events — only the answer can tell it.
|
|
const { c, init } = stdioClient({ clientCapabilities: {} })
|
|
await init
|
|
const s: any = await c.request("session/new", { cwd: project(), mcpServers: [] })
|
|
const r: any = await c.request("session/prompt", { sessionId: s.sessionId, prompt: [{ type: "text", text: "hi" }] })
|
|
expect(r._meta.lembas.error.code).toBe("unreachable")
|
|
expect(r._meta.lembas.error.message).toContain("cannot reach")
|
|
})
|
|
|
|
test("a failure's code: from why no answer came, else from its status, else failed", () => {
|
|
// A bare 401 is not the server's refusal of the token: only one with its challenge is.
|
|
expect(failureCode(new ProviderError("x", 401))).toBe("failed")
|
|
expect(failureCode(Object.assign(new ProviderError("x", 401), { code: "signed_out" }))).toBe("signed_out")
|
|
expect(failureCode(new ProviderError("x", 403))).toBe("not_allowed")
|
|
expect(failureCode(new ProviderError("x", 429))).toBe("busy")
|
|
expect(failureCode(new ProviderError("x", 503))).toBe("server_error")
|
|
expect(failureCode(new ProviderError("x", 400))).toBe("failed")
|
|
expect(failureCode(new ProviderError("x"))).toBe("failed")
|
|
expect(failureCode(new Error("x"))).toBe("failed")
|
|
expect(turnError({ message: "\n first line \nsecond" })).toEqual({ code: "failed", message: "first line" })
|
|
})
|
|
|
|
test("the stdio agent reads and logs clientInfo, and answers its own protocol to a client that says a higher one", async () => {
|
|
const logged: string[] = []
|
|
const error = console.error
|
|
console.error = (...a: unknown[]) => void logged.push(a.join(" "))
|
|
stops.push(() => (console.error = error))
|
|
// An editor that says protocol 2: both use 2, nothing to tell.
|
|
const two = stdioClient({ clientInfo: { name: "llembas-nvim", version: "1.0.0" }, clientCapabilities: { _meta: { lembas: { protocol: 2, editor: true } } } })
|
|
const a = await two.init
|
|
expect(a._meta.lembas.protocol).toBe(3)
|
|
expect(a._meta.lembas.notice).toBeUndefined()
|
|
expect(two.agent.client).toBe("llembas-nvim/1.0.0")
|
|
expect(logged.at(-1)).toBe("client: llembas-nvim/1.0.0, protocol 2")
|
|
// A client from the future: answered 3, in the field and in words.
|
|
const four = stdioClient({ clientInfo: { name: "llembas-tty", version: "9.0.0" }, clientCapabilities: { _meta: { lembas: { protocol: 4 } } } })
|
|
const b = await four.init
|
|
expect(b._meta.lembas.protocol).toBe(3)
|
|
expect(b._meta.lembas.notice).toContain("speaks protocol 3, and the client said 4: both use 3")
|
|
expect(logged.at(-1)).toContain("client: llembas-tty/9.0.0, protocol 3 — ")
|
|
// No name, and plain ACP: said as such; a name with control characters is cleaned for the log.
|
|
const plain = stdioClient({ clientCapabilities: {} })
|
|
await plain.init
|
|
expect(logged.at(-1)).toBe("client: unnamed, protocol none (plain ACP)")
|
|
expect(clientName({ name: "ed\u001b[31mitor\n", version: "1" })).toBe("ed [31mitor/1")
|
|
expect(clientName({ name: "x".repeat(500) })!.length).toBe(80)
|
|
expect(clientName(undefined)).toBeUndefined()
|
|
expect(clientName({ version: "1" })).toBeUndefined()
|
|
})
|
|
|
|
// ---- the smaller rules --------------------------------------------------------------------
|
|
|
|
test("a line from the client with no end is given up on, not read into memory", async () => {
|
|
const input = new PassThrough()
|
|
const output = new PassThrough()
|
|
const said: string[] = []
|
|
const error = console.error
|
|
console.error = (...a: unknown[]) => void said.push(a.join(" "))
|
|
stops.push(() => (console.error = error))
|
|
const t = stdioTransport(input, output, 1024)
|
|
const got: string[] = []
|
|
let closed = 0
|
|
t.onMessage((m) => void got.push(m))
|
|
t.onClose(() => void closed++)
|
|
// Lines within the limit pass, however many arrive in one chunk.
|
|
input.write(`{"a":1}\n{"b":"${"x".repeat(900)}"}\n`)
|
|
await Bun.sleep(10)
|
|
expect(got.length).toBe(2)
|
|
expect(closed).toBe(0)
|
|
input.write("y".repeat(2000))
|
|
await Bun.sleep(10)
|
|
expect(closed).toBe(1)
|
|
expect(said.at(-1)).toContain("a line longer than")
|
|
// Nothing after it is read, and the end is not said twice.
|
|
input.write('\n{"c":1}\n')
|
|
input.end()
|
|
await Bun.sleep(10)
|
|
expect(got.length).toBe(2)
|
|
expect(closed).toBe(1)
|
|
expect(CONNECTION.stdio.line_bytes).toBe(64 * 1024 * 1024)
|
|
})
|
|
|
|
test("the service's lock: made exclusively, refused while its holder runs, taken over from one that is gone", () => {
|
|
const dir = mkdtempSync(join(tmpdir(), "ph-lock-"))
|
|
const file = join(dir, "service.lock")
|
|
const release = takeLock(file)
|
|
// This process is not "another copy": a lock naming itself is stale (a restart reusing a pid).
|
|
expect(holdsLock(process.pid)).toBe(false)
|
|
release()
|
|
// A pid nobody has: stale, taken over.
|
|
writeFileSync(file, "2147483646")
|
|
expect(holdsLock(2147483646)).toBe(false)
|
|
takeLock(file)()
|
|
// A pid that is alive but is not a `lembas service` (pid 1, where /proc says what it is): a
|
|
// number recycled since a crash does not hold the lock.
|
|
if (process.platform === "linux") {
|
|
expect(holdsLock(1)).toBe(false)
|
|
writeFileSync(file, "1")
|
|
takeLock(file)()
|
|
}
|
|
// Garbage in the file: stale.
|
|
writeFileSync(file, "not a pid")
|
|
const again = takeLock(file)
|
|
// Releasing gives up only this process's own lock, never one somebody else has taken since.
|
|
writeFileSync(file, "2147483646")
|
|
again()
|
|
expect(Bun.file(file).size).toBeGreaterThan(0)
|
|
})
|
|
|
|
test("Retry-After on a 429 is honoured: the request is made again after it, and the header is read as seconds", async () => {
|
|
let hits = 0
|
|
let agent = ""
|
|
const srv = Bun.serve({
|
|
port: 0,
|
|
fetch(req) {
|
|
agent = req.headers.get("user-agent") ?? ""
|
|
return ++hits === 1 ? new Response("slow down", { status: 429, headers: { "retry-after": "1" } }) : new Response("ok")
|
|
},
|
|
})
|
|
stops.push(() => srv.stop(true))
|
|
const url = `http://127.0.0.1:${srv.port}/v1/chat/completions`
|
|
const e = await request(url, { method: "POST", body: "{}" }, "m").catch((x) => x)
|
|
expect(e).toBeInstanceOf(ProviderError)
|
|
expect([e.status, e.retryAfter]).toEqual([429, 1])
|
|
// Every request to the server says who is asking.
|
|
expect(agent).toBe(USER_AGENT)
|
|
// The retry rule waits what it said, says so, and asks again.
|
|
hits = 0
|
|
const events: StreamEvent[] = []
|
|
const started = Date.now()
|
|
for await (const ev of retrying(async function* () {
|
|
await request(url, { method: "POST", body: "{}" }, "m")
|
|
yield { type: "text", text: "done" } as StreamEvent
|
|
}))
|
|
events.push(ev)
|
|
expect(Date.now() - started).toBeGreaterThanOrEqual(950)
|
|
expect(events.map((x) => x.type)).toEqual(["notice", "text"])
|
|
expect((events[0] as { retry?: { in: number } }).retry?.in).toBe(1)
|
|
// Without a Retry-After the refusal stands, as before.
|
|
const bare = await (async () => {
|
|
for await (const _ of retrying(async function* (): AsyncGenerator<StreamEvent> {
|
|
throw new ProviderError("m: HTTP 429: slow down", 429)
|
|
})) void _
|
|
})().catch((x) => x)
|
|
expect(bare).toBeInstanceOf(ProviderError)
|
|
// A wait is given up when the turn is cancelled.
|
|
const stop = new AbortController()
|
|
setTimeout(() => stop.abort(), 30)
|
|
const t0 = Date.now()
|
|
const cancelled = await (async () => {
|
|
for await (const _ of retrying(
|
|
async function* (): AsyncGenerator<StreamEvent> {
|
|
const err = new ProviderError("m: HTTP 429: slow down", 429)
|
|
err.retryAfter = 30
|
|
throw err
|
|
},
|
|
undefined,
|
|
stop.signal,
|
|
)) void _
|
|
})().catch((x) => x)
|
|
expect(Date.now() - t0).toBeLessThan(2000)
|
|
expect((cancelled as Error).message).toBe("cancelled")
|
|
})
|
|
|
|
// ---- which address is stored, and the server's minimum ------------------------------------
|
|
|
|
/** A stand-in server for signing in with a token: discovery saying what the test tells it to say
|
|
* of itself, the instance and its models for one token, and what was signed out. */
|
|
function instance(o: { reported?: (asked: string) => string; endpoints?: (asked: string) => string; min_clients?: unknown } = {}) {
|
|
const state = { token: "lmb_new", signedOut: [] as { token: string; replacedBy?: string }[], heard: [] as string[] }
|
|
const srv = Bun.serve({
|
|
port: 0,
|
|
async fetch(req) {
|
|
const u = new URL(req.url)
|
|
const asked = `http://${u.host}`
|
|
state.heard.push(`${req.method} ${u.host}${u.pathname}`)
|
|
const at = o.endpoints?.(asked) ?? asked
|
|
if (u.pathname === "/.well-known/lembas.json")
|
|
return Response.json({
|
|
service: "lembas",
|
|
version: "2.0.0",
|
|
name: "Example",
|
|
connection: "example",
|
|
protocol: 3,
|
|
protocols: [3],
|
|
harness_spec: "3.11.0",
|
|
base_url: o.reported?.(asked) ?? asked,
|
|
...(o.min_clients === undefined ? {} : { min_clients: o.min_clients }),
|
|
api: { openai: `${at}/v1` },
|
|
login: { device: { code: `${at}/api/device/code`, token: `${at}/api/device/token`, verify: `${at}/device` } },
|
|
})
|
|
const auth = (req.headers.get("authorization") ?? "").replace(/^Bearer /, "")
|
|
if (u.pathname === "/api/v1/token" && req.method === "DELETE") {
|
|
const text = await req.text()
|
|
state.signedOut.push({ token: auth, replacedBy: text ? JSON.parse(text).replaced_by : undefined })
|
|
return new Response(null, { status: 204 })
|
|
}
|
|
if (auth !== state.token) return Response.json({ detail: "no" }, { status: 401, headers: { "www-authenticate": 'Bearer realm="lembas"' } })
|
|
if (u.pathname === "/v1/models") return Response.json({ object: "list", data: [{ id: "qwen", default: true }] })
|
|
if (u.pathname === "/api/v1/instance") return Response.json({ name: "Example", connection: "example", scope: "models memory link", account: { email: "sam@example.org" }, default_model: "qwen" })
|
|
return new Response("not found", { status: 404 })
|
|
},
|
|
})
|
|
stops.push(() => srv.stop(true))
|
|
// Two spellings of one server: what a person types, and what a proxy in front of it might make
|
|
// the server call itself.
|
|
return { state, port: srv.port, typed: `http://127.0.0.1:${srv.port}`, other: `http://localhost:${srv.port}` }
|
|
}
|
|
|
|
const index = () => JSON.parse(readFileSync(join(paths.config, "lembas.json"), "utf8")).instances as Record<string, { base_url: string; connection: string; min_clients?: Record<string, string> }>
|
|
const cleanConfig = () => {
|
|
rmSync(paths.config, { recursive: true, force: true })
|
|
mkdirSync(paths.config, { recursive: true })
|
|
}
|
|
|
|
test("a new login stores the typed address, normalised — never the base_url the server names", async () => {
|
|
cleanConfig()
|
|
const i = instance({ reported: () => "http://backend.example.org:8080" })
|
|
const r = await loginWithToken(`${i.typed}/chat/?tab=1`, i.state.token)
|
|
expect(r.instance.base_url).toBe(i.typed)
|
|
expect(index().example!.base_url).toBe(i.typed)
|
|
expect(readFileSync(join(paths.config, "connections.yaml"), "utf8")).toContain(`url: ${i.typed}\n`)
|
|
expect(readFileSync(join(paths.config, "connections.yaml"), "utf8")).not.toContain("backend.example.org")
|
|
// Nothing was asked of the address the server named.
|
|
expect(i.state.heard.every((h) => h.includes(`127.0.0.1:${i.port}`))).toBe(true)
|
|
// The link dials the stored address too.
|
|
expect(heldLogin().instance.base_url).toBe(i.typed)
|
|
})
|
|
|
|
test("a login kept from before: it works untouched, read through the one address rule", async () => {
|
|
cleanConfig()
|
|
const i = instance()
|
|
// As an older CLI left it: what the server said of itself, with a path and a slash.
|
|
mkdirSync(join(paths.config, "lembas"), { recursive: true })
|
|
writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { base_url: `HTTP://LOCALHOST:${i.port}/`, connection: "example", logged_in_at: "2026-01-01T00:00:00.000Z" } } }))
|
|
writeFileSync(join(paths.config, "lembas", "example.key"), `${i.state.token}\n`, { mode: 0o600 })
|
|
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n example:\n type: webui\n url: http://localhost:${i.port}/\n api_key: "{file:${join(paths.config, "lembas", "example.key")}}"\n`, { mode: 0o600 })
|
|
expect(instances().example!.base_url).toBe(i.other)
|
|
expect(heldLogin().instance.base_url).toBe(i.other)
|
|
// It still refreshes its models, at the address it has.
|
|
const r = await sync("example")
|
|
expect(r.models.map((m) => m.id)).toEqual(["qwen"])
|
|
expect(i.state.signedOut).toEqual([])
|
|
// Still one login, still at its own address: nothing is migrated without a new sign-in.
|
|
expect(Object.keys(instances())).toEqual(["example"])
|
|
expect(instances().example!.base_url).toBe(i.other)
|
|
})
|
|
|
|
test("a kept login whose address is the one the server names is the same login as the typed one: replaced, no twin", async () => {
|
|
cleanConfig()
|
|
// The server calls itself by another address than the one typed — what the old login stored.
|
|
const i = instance({ reported: (asked) => asked.replace("127.0.0.1", "localhost") })
|
|
mkdirSync(join(paths.config, "lembas"), { recursive: true })
|
|
writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { base_url: i.other, connection: "example", logged_in_at: "2026-01-01T00:00:00.000Z" } } }))
|
|
writeFileSync(join(paths.config, "lembas", "example.key"), "lmb_old\n", { mode: 0o600 })
|
|
writeFileSync(join(paths.config, "connections.yaml"), `connections:\n example:\n type: webui\n url: ${i.other}\n api_key: "{file:${join(paths.config, "lembas", "example.key")}}"\n`, { mode: 0o600 })
|
|
const r = await loginWithToken(i.typed, i.state.token)
|
|
// One login, under the same name, now at the typed address — and no `example-lembas` beside it.
|
|
expect(Object.keys(index())).toEqual(["example"])
|
|
expect(r.connection).toBe("example")
|
|
expect(index().example!.base_url).toBe(i.typed)
|
|
const yaml = readFileSync(join(paths.config, "connections.yaml"), "utf8")
|
|
expect(yaml).not.toContain("example-lembas")
|
|
expect(yaml).toContain(`url: ${i.typed}\n`)
|
|
// The older token was signed out — at the address it was stored with, and without naming the
|
|
// new one: that the two addresses are one server is only the server's word.
|
|
expect(i.state.signedOut).toEqual([{ token: "lmb_old", replacedBy: undefined }])
|
|
expect(i.state.heard.filter((h) => h.startsWith("DELETE"))).toEqual([`DELETE localhost:${i.port}/api/v1/token`])
|
|
expect(readFileSync(join(paths.config, "lembas", "example.key"), "utf8").trim()).toBe("lmb_new")
|
|
expect(r.changes.some((c) => c.includes("signed out of"))).toBe(false)
|
|
})
|
|
|
|
test("a server that names another server's address as its own gets neither that server's token nor the new one's name there", async () => {
|
|
cleanConfig()
|
|
const first = instance()
|
|
first.state.token = "lmb_first_servers"
|
|
await loginWithToken(first.typed, first.state.token)
|
|
// A second server whose discovery claims the first one's address.
|
|
const second = instance({ reported: () => first.typed })
|
|
await loginWithToken(second.typed, second.state.token)
|
|
// The first server's token never reached the second…
|
|
expect(second.state.signedOut).toEqual([])
|
|
expect(second.state.heard.some((h) => h.startsWith("DELETE"))).toBe(false)
|
|
// …it was signed out where it belongs, and the second server's token was not named there.
|
|
expect(first.state.signedOut).toEqual([{ token: "lmb_first_servers", replacedBy: undefined }])
|
|
// One login is left, at the address that was typed.
|
|
expect(Object.keys(index())).toEqual(["example"])
|
|
expect(index().example!.base_url).toBe(second.typed)
|
|
})
|
|
|
|
test("logging in again at the same address hands the old token over to the new one, as before", async () => {
|
|
cleanConfig()
|
|
const i = instance()
|
|
i.state.token = "lmb_old"
|
|
await loginWithToken(i.typed, "lmb_old")
|
|
i.state.token = "lmb_new"
|
|
// Typed another way: still the same server by the one address rule.
|
|
await loginWithToken(`HTTP://127.0.0.1:${i.port}/`, "lmb_new")
|
|
expect(i.state.signedOut).toEqual([{ token: "lmb_old", replacedBy: "lmb_new" }])
|
|
expect(Object.keys(index())).toEqual(["example"])
|
|
})
|
|
|
|
test("an endpoint discovery names on another origin is not followed: refused in words, nothing written", async () => {
|
|
cleanConfig()
|
|
// Sign-in endpoints on another spelling of the host: another origin, as far as anybody can tell.
|
|
const i = instance({ endpoints: (asked) => asked.replace("127.0.0.1", "localhost") })
|
|
let shown = 0
|
|
const e = await login(i.typed, { onCode: () => void shown++ }).catch((x) => x)
|
|
expect(e).toBeInstanceOf(LembasError)
|
|
expect(e.code).toBe("other_origin")
|
|
expect(e.message).toContain(`names an address on another server (http://localhost:${i.port}/api/device/`)
|
|
expect(e.message).toContain("does not follow it")
|
|
expect(shown).toBe(0)
|
|
// Only discovery was asked: the code endpoint never heard from this machine.
|
|
expect(i.state.heard).toEqual([`GET 127.0.0.1:${i.port}/.well-known/lembas.json`])
|
|
expect(existsSync(join(paths.config, "lembas.json"))).toBe(false)
|
|
// What the CLI reaches by its own paths on the typed address is not affected: a token handed
|
|
// over (as the desktop app does) signs in.
|
|
const r = await loginWithToken(i.typed, i.state.token)
|
|
expect(r.instance.base_url).toBe(i.typed)
|
|
})
|
|
|
|
test("min_clients: a CLI below the server's minimum is told so at discovery, with both versions, and goes no further", async () => {
|
|
cleanConfig()
|
|
const below = instance({ min_clients: { cli: "99.0.0", nvim: "1.2.0" } })
|
|
const e = await loginWithToken(below.typed, below.state.token).catch((x) => x)
|
|
expect(e).toBeInstanceOf(LembasError)
|
|
expect(e.code).toBe("client_too_old")
|
|
expect(e.message).toBe(`127.0.0.1:${below.port} needs LLeMbas CLI 99.0.0 or later, and this is ${VERSION}. Update LLeMbas CLI. Run lembas update.`)
|
|
expect(below.state.heard).toEqual([`GET 127.0.0.1:${below.port}/.well-known/lembas.json`])
|
|
expect(existsSync(join(paths.config, "lembas.json"))).toBe(false)
|
|
// No minimum for this product, an empty table, a value that is not a version, a minimum met: fine.
|
|
for (const min_clients of [{}, { desktop: "99.0.0" }, { cli: "soon" }, { cli: "0.0.1" }, { cli: VERSION }, "nonsense", null]) {
|
|
cleanConfig()
|
|
const ok = instance({ min_clients })
|
|
expect((await loginWithToken(ok.typed, ok.state.token)).instance.base_url).toBe(ok.typed)
|
|
}
|
|
})
|
|
|
|
test("the stdio agent tells its client the server's minimum for the client's own product: _meta.lembas.min_client", async () => {
|
|
cleanConfig()
|
|
const i = instance({ min_clients: { nvim: "1.2.0", vscode: "1.0.0-beta.9", desktop: "not a version" } })
|
|
await loginWithToken(i.typed, i.state.token)
|
|
expect(index().example!.min_clients).toEqual({ nvim: "1.2.0", vscode: "1.0.0-beta.9", desktop: "not a version" })
|
|
const quiet = console.error
|
|
console.error = () => {}
|
|
stops.push(() => (console.error = quiet))
|
|
const ask = async (clientInfo?: Record<string, unknown>) => (await stdioClient({ ...(clientInfo ? { clientInfo } : {}), clientCapabilities: { _meta: { lembas: { protocol: 3 } } } }).init)._meta.lembas.min_client
|
|
expect(await ask({ name: "llembas-nvim", version: "1.0.0" })).toBe("1.2.0")
|
|
expect(await ask({ name: "llembas-vscode", version: "1.0.0" })).toBe("1.0.0-beta.9")
|
|
// No minimum for the product, one that is not a version, a client that is no LLeMbas product, none named: absent.
|
|
expect(await ask({ name: "llembas-tty", version: "1.0.0" })).toBeUndefined()
|
|
expect(await ask({ name: "llembas-desktop", version: "1.0.0" })).toBeUndefined()
|
|
expect(await ask({ name: "some-editor", version: "1.0.0" })).toBeUndefined()
|
|
expect(await ask()).toBeUndefined()
|
|
expect(minClientFor("llembas-nvim")).toBe("1.2.0")
|
|
// What the server says later is kept at the next look (a refresh, the service's dial).
|
|
const next = instance({ min_clients: { nvim: "1.3.0" } })
|
|
writeFileSync(join(paths.config, "lembas.json"), JSON.stringify({ instances: { example: { ...index().example, base_url: next.typed } } }))
|
|
await refreshDiscovery()
|
|
expect(minClientFor("llembas-nvim")).toBe("1.3.0")
|
|
// Not logged in: absent.
|
|
cleanConfig()
|
|
expect(await ask({ name: "llembas-nvim", version: "1.0.0" })).toBeUndefined()
|
|
})
|