diff --git a/.github/workflows/pm-console-edge-deploy.yml b/.github/workflows/pm-console-edge-deploy.yml index 698967d353..9713b2eeea 100644 --- a/.github/workflows/pm-console-edge-deploy.yml +++ b/.github/workflows/pm-console-edge-deploy.yml @@ -101,6 +101,35 @@ jobs: node build.mjs npx wrangler deploy --dry-run --outdir .wrangler/dry npx wrangler deploy --dry-run --config init/wrangler.jsonc --outdir .wrangler/dry-init + - name: Run the bundle in the Worker runtime, against a host on this runner + working-directory: pm-stack/console + run: | + # The tests above run the Worker's code under bun, which is not + # the runtime it is deployed to: a request's upload, for one, + # behaves differently there (a report that hung for twenty + # seconds on first contact passed every bun test). This runs + # the bundle in the Worker runtime itself, with a host on port + # 4898, and makes the checks that need no sign-in. + (cd edge && npx wrangler dev --port 8799 --persist-to "$RUNNER_TEMP/pm-edge-state" \ + --var PUBLIC_HOST:localhost --var HOST_ORIGIN:http://127.0.0.1:4898 --var VERSION:smoke \ + >"$RUNNER_TEMP/wrangler-dev.log" 2>&1 &) + up=false + for _ in $(seq 1 60); do + if curl -fsS --max-time 3 http://localhost:8799/console/health >/dev/null 2>&1; then + up=true + break + fi + sleep 2 + done + if [ "$up" != true ]; then + echo "the Worker runtime did not come up on this runner" >&2 + tail -n 60 "$RUNNER_TEMP/wrangler-dev.log" >&2 + exit 1 + fi + if ! bun run scripts/edge-smoke.ts; then + tail -n 60 "$RUNNER_TEMP/wrangler-dev.log" >&2 + exit 1 + fi - name: See whether this push changes how the Worker is stood up id: standup if: steps.secrets.outputs.ready == 'true' && inputs.rollback_version == '' diff --git a/pm-stack/console/edge/README.md b/pm-stack/console/edge/README.md index 88e246d053..114aeefca3 100644 --- a/pm-stack/console/edge/README.md +++ b/pm-stack/console/edge/README.md @@ -123,8 +123,10 @@ sign-in issuer's). Pushes to `main` that touch the console deploy it (`.github/workflows/pm-console-edge-deploy.yml`): the console's tests, which drive this Worker's routing and state against the laptop's real -handler; a bundle; the release; then a check that the deployed Worker -answers its health check as that commit. +handler; a bundle; a run of that bundle in the Worker runtime itself +(`scripts/edge-smoke.ts`, below), because the tests run under bun and +the two do not behave alike everywhere; the release; then a check that +the deployed Worker answers its health check as that commit. The release is [`release.mjs`](release.mjs), and it starts from whatever is there, including nothing: diff --git a/pm-stack/console/edge/src/edge.ts b/pm-stack/console/edge/src/edge.ts index 2b3a79eed7..2d6f91bd49 100644 --- a/pm-stack/console/edge/src/edge.ts +++ b/pm-stack/console/edge/src/edge.ts @@ -713,6 +713,14 @@ export class Edge { return refuse({ error: "this is not signed with the host's key" }, 401); } this.lastKeyFetch = now; + // The report is sent again once the key is known, from a second + // copy of the same upload. This copy has to be read to its end + // first: in the Worker runtime the two share one stream, and a + // copy left unread holds the other back until the laptop gives up + // waiting. (It is read at most once in KEY_FETCH_EVERY_MS, and + // only up to what a report may be, so this is no way to make the + // edge read at will.) + await req.arrayBuffer().catch(() => {}); return next("key", {}); } const body = new Uint8Array(await req.arrayBuffer()); diff --git a/pm-stack/console/public/app.css b/pm-stack/console/public/app.css index e7b6a820e9..266901c087 100644 --- a/pm-stack/console/public/app.css +++ b/pm-stack/console/public/app.css @@ -616,6 +616,18 @@ code.wrap { overflow-wrap: anywhere; font-size: 0.85rem; } -.card input + input { +.card input + input, +.card > select + textarea, +.card > textarea + .row, +.card > select + .row { margin-top: 0.5rem; } +/* A tick box is never stretched like a text field, wherever it sits. */ +input[type="checkbox"], +input[type="radio"] { + flex: 0 0 22px; + width: 22px; + min-height: 22px; + height: 22px; + padding: 0; +} diff --git a/pm-stack/console/public/app.js b/pm-stack/console/public/app.js index 5496d3a0f9..aa6f2b575f 100644 --- a/pm-stack/console/public/app.js +++ b/pm-stack/console/public/app.js @@ -54,6 +54,25 @@ export function ago(iso, now = Date.now()) { return `${Math.round(s / 86400)} d ago`; } +/** What a pull request's check found, in one line, from whatever of it + * GitHub gave: a part it did not give is left out, not shown as + * "undefined". */ +export function prCheck(d) { + if (!d || typeof d !== "object") return "GitHub did not say."; + const state = d.mergeable_state ? ` (${d.mergeable_state})` : ""; + const parts = [ + d.mergeable === true ? `can merge${state}` : d.mergeable === false ? `cannot merge${state}` : "mergeability not known yet", + Number.isFinite(d.additions) && Number.isFinite(d.deletions) + ? `+${d.additions} −${d.deletions}${Number.isFinite(d.changed_files) ? ` in ${d.changed_files} ${d.changed_files === 1 ? "file" : "files"}` : ""}` + : null, + Number.isFinite(d.review_comments) ? `${d.review_comments} review ${d.review_comments === 1 ? "comment" : "comments"}` : null, + ]; + return parts.filter(Boolean).join(" · "); +} + +/** A word with its first letter raised, for a button. */ +export const capital = (word) => (word ? word[0].toUpperCase() + word.slice(1) : ""); + /** The queue's priority bands, in words. */ export function band(priority) { const p = Number(priority); @@ -135,12 +154,18 @@ async function api(path, body) { throw new Error(signedOut ? "Your sign-in may have run out. Reload to sign in again." : "You are offline."); } let data = null; + let read = true; try { data = await res.json(); } catch { + read = false; if (res.status === 401 || res.status === 403) signedOut = true; } if (!res.ok) throw new Error((data && data.error) || `http ${res.status}`); + // Every read answers with JSON. Something else (an empty answer, a + // page from something in between) is no answer, and saying so here + // keeps each screen from tripping over it in its own way. + if (body === undefined && (!read || data === null)) throw new Error("the answer could not be read"); return data; } @@ -372,7 +397,7 @@ const RANKS = ["expedite", "priority/critical", "now", "priority/high", "next", function issueCard(i) { return card( h("h3", {}, ext(i.url, `#${i.number}`), ` ${i.title}`), - h("p", { class: "meta" }, `updated ${i.updated?.replace("T", " ")} · ${i.comments} comments`), + h("p", { class: "meta" }, `${i.updated ? `updated ${ago(i.updated)} · ` : ""}${i.comments} comments`), h( "div", { class: "row end" }, @@ -448,13 +473,17 @@ function flushPending() { } } -async function sendAnswer(kind, args, key) { +async function sendAnswer(kind, args, key, said) { try { const { result, held } = await api("act", { kind, args }); if (result?.refused?.length) toast(`Not recorded: ${result.refused[0].why}`, true); else { answeredHere.add(key); + // A choice was already acknowledged when it was made (with its + // Undo); anything else says so now, or the question would simply + // vanish. if (held) toast(HELD_NOTE); + else if (said) toast(said); } picks.delete(key); if (docs.questions?.questions) { @@ -549,7 +578,7 @@ function questionCard(q) { class: "small ghost", onclick: async () => { const text = await ask({ title: "Your own answer", text: q.q, label: "Answer", okLabel: "Send", required: true }); - if (text) sendAnswer("question.answer", { ...id, text }, key); + if (text) sendAnswer("question.answer", { ...id, text }, key, "Answer sent"); }, }, "Write an answer", @@ -1102,6 +1131,7 @@ async function viewSignin() { const id = h("input", { type: "text", placeholder: "Client ID", autocomplete: "off", autocapitalize: "none", spellcheck: false }); const secret = h("input", { type: "password", placeholder: "Client secret", autocomplete: "off" }); const send = async (e) => { + if (!id.value.trim() || !secret.value.trim()) return toast("Paste both values from Google first", true); const done = await act("sso.google", { clientId: id.value.trim(), clientSecret: secret.value.trim() }, "Google sign-in is on", e.target); secret.value = ""; if (done) draw(); @@ -1150,7 +1180,7 @@ async function viewPhone(sub) { const devices = await api("devices"); // Where a download would come from. Only the edge can say; the // laptop serving the app itself has no such answer. - const android = await api("android").catch(() => null); + const android = me.edge ? await api("android").catch(() => null) : null; // The phone has collected its token: the request is finished. if (linkApprovedAt !== null && devices.length > linkApprovedAt) { linkRequest = null; @@ -1303,7 +1333,7 @@ async function viewQueue() { ? data.tasks.map((t) => card( h("h3", {}, t.title), - h("p", { class: "meta" }, `${band(t.priority)} · updated ${String(t.updated ?? "").replace("T", " ")}`), + h("p", { class: "meta" }, [band(t.priority), t.updated ? `updated ${ago(t.updated)}` : ""].filter(Boolean).join(" · ")), t.why ? h("p", { class: "why" }, String(t.why)) : null, h( "div", @@ -1359,9 +1389,7 @@ function viewPrs() { e.target.disabled = true; try { const d = await api(`prs/${p.number}`); - detail.replaceChildren( - h("p", { class: d.mergeable ? "meta" : "why" }, `${d.mergeable === null ? "mergeability not known yet" : d.mergeable ? "can merge" : "cannot merge"} (${d.mergeable_state}) · +${d.additions} −${d.deletions} in ${d.changed_files} files · ${d.review_comments} review comments`), - ); + detail.replaceChildren(h("p", { class: d?.mergeable === false ? "why" : "meta" }, prCheck(d))); } catch (error) { toast(error.message, true); } @@ -1416,7 +1444,7 @@ async function viewAgents() { h( "div", { class: "row end" }, - h("label", { for: "cmd", class: "row meta" }, command, "Send as a command"), + h("label", { for: "cmd", class: "row check meta" }, command, "Send as a command"), h( "button", { @@ -1428,10 +1456,14 @@ async function viewAgents() { ), ); let recent = []; + // The roster below is still useful without the log; but a log that + // could not be read is not the same as one with nothing in it. + let unread = ""; try { - recent = await api("messages?limit=15"); - } catch { - // the roster below is still useful without the log + const log = await api("messages?limit=15"); + if (Array.isArray(log)) recent = log; + } catch (error) { + unread = error.message; } return [ compose, @@ -1442,7 +1474,7 @@ async function viewAgents() { h("h2", {}, "Recent messages"), ...(recent.length ? recent.map((m) => card(h("p", { class: "meta" }, `${ago(m.ts)} · ${m.direction} · ${m.agent} · ${m.kind}`), h("p", {}, String(m.body ?? "").slice(0, 600)))) - : [empty("No messages.")]), + : [empty(unread ? `The messages could not be read just now: ${unread}` : "No messages.")]), ]; } @@ -1457,11 +1489,11 @@ function viewServices() { { class: `small${danger ? " ghost" : ""}`, onclick: async (e) => { - const yes = await ask({ title: `${action} ${u.unit}?`, okLabel: action, danger }); + const yes = await ask({ title: `${capital(action)} ${u.unit}?`, okLabel: capital(action), danger }); if (yes !== null) act("unit.act", { unit: u.unit, action }, `${u.unit}: ${action} done`, e.target); }, }, - action, + capital(action), ); return h( "div", @@ -1526,6 +1558,10 @@ const VIEWS = { }; let route = "now"; let drawSeq = 0; +/** The screen whose content the view holds, once it has been drawn. */ +let drawn = null; +/** A screen that takes longer than this to fetch says it is loading. */ +const LOADING_AFTER_MS = 150; function parse(hash) { const r = hash.replace(/^#/, ""); @@ -1581,14 +1617,33 @@ async function draw() { drawFresh(); if (!docs.core) return view.replaceChildren(empty("Loading…")); if (extra && !docs[extra]) loadDoc(extra).then(() => seq === drawSeq && draw()).catch(() => {}); + // Moving to another screen: what the last one showed must not sit + // under this one's name while this one is fetched. A screen that has + // everything it needs is drawn before this fires, so nothing flickers; + // a screen being drawn again keeps what it shows until the new is in. + const moved = drawn !== route; + const waiting = moved + ? setTimeout(() => { + if (seq !== drawSeq) return; + view.replaceChildren(empty(`Loading ${title}…`)); + scrollTo(0, 0); + }, LOADING_AFTER_MS) + : null; try { const nodes = await render(sub); - if (seq === drawSeq) view.replaceChildren(...nodes.filter(Boolean)); + if (seq !== drawSeq) return; + view.replaceChildren(...nodes.filter(Boolean)); + if (moved) scrollTo(0, 0); + drawn = route; } catch (error) { if (seq !== drawSeq) return; view.replaceChildren( card(h("h3", {}, "This section could not load"), h("p", { class: "why" }, error.message), h("div", { class: "row end" }, h("button", { onclick: () => (signedOut ? location.reload() : draw()) }, signedOut ? "Reload" : "Try again"))), ); + if (moved) scrollTo(0, 0); + drawn = route; + } finally { + if (waiting) clearTimeout(waiting); } } diff --git a/pm-stack/console/scripts/demo-state.ts b/pm-stack/console/scripts/demo-state.ts index 1d4068c3c2..0a9aac9f2e 100644 --- a/pm-stack/console/scripts/demo-state.ts +++ b/pm-stack/console/scripts/demo-state.ts @@ -7,7 +7,7 @@ import { readConfig } from "../src/config.ts"; import { Devices, Limiter } from "../src/devices.ts"; import { Docs } from "../src/docs.ts"; import { fileStore } from "../src/file-store.ts"; -import { Ops, type Run } from "../src/ops.ts"; +import { type Fetch, Ops, type Run } from "../src/ops.ts"; import { Push } from "../src/push.ts"; import type { Deps } from "../src/server.ts"; @@ -356,6 +356,129 @@ const demoRun: Run = async (argv) => { return { code: 0, stdout: "[]", stderr: "" }; }; +/** The queue store, standing in for the real one, so that the Queue + * screen has something to read and nothing here goes out to the + * network. It answers the two reads that screen makes; a task that was + * unblocked or cancelled stays as it was, since nothing here changes. */ +const queueTasks = [ + { + id: 21043, + status: "blocked", + priority: 20, + title: "Fix #12538: modeline verbs agree with the queue's states", + dedupe_key: "issue-12538", + updated: iso(14), + why: "waiting on #12530 to merge", + }, + { + id: 20977, + status: "blocked", + priority: 30, + title: "Fix #12279: every test file sits in a registry row", + dedupe_key: "issue-12279", + updated: iso(95), + why: "36 test files are in no registry row; the lint this slice's pull request runs fails on them", + }, + { + id: 20412, + status: "blocked", + priority: 50, + title: "Review #12403: quota forecast accuracy ledger", + dedupe_key: "review-12403", + updated: iso(400), + why: "the author's session ended before answering the review", + }, + { + id: 19850, + status: "blocked", + priority: null, + title: "Fix #11871: watchdog registry row for the new claimant", + dedupe_key: "issue-11871", + updated: iso(2900), + why: "", + }, + { + id: 21101, + status: "queued", + priority: 10, + title: "Fix #12600: the session id reaches the resume path", + dedupe_key: "issue-12600", + updated: iso(3), + why: "", + }, + { + id: 21099, + status: "queued", + priority: 30, + title: "Fix #12588: stale claims are released after a restart", + dedupe_key: "issue-12588", + updated: iso(22), + why: "", + }, + { + id: 21050, + status: "claimed", + priority: 20, + title: "Fix #9075: session state — session id in env and a resume path", + dedupe_key: "issue-9075", + updated: iso(1), + why: "", + }, + { + id: 18002, + status: "parked", + priority: 70, + title: "Fix #10210: tidy the exporter's flags", + dedupe_key: "issue-10210", + updated: iso(9000), + why: "parked until the exporter is rewritten", + }, +]; +const demoQueue: Fetch = async (_url, init) => { + const requests = + ( + JSON.parse(init.body ?? "{}") as { + requests?: { type: string; stmt?: { sql: string; args: { value: string }[] } }[]; + } + ).requests ?? []; + const cell = (value: string | number | null) => + value === null ? { type: "null" } : { type: typeof value === "number" ? "integer" : "text", value }; + const results = requests + .filter((r) => r.type === "execute") + .map((r) => { + const sql = r.stmt?.sql ?? ""; + const args = (r.stmt?.args ?? []).map((a) => a.value); + let cols: string[] = []; + let rows: (string | number | null)[][] = []; + if (/count\(\*\) AS n FROM tasks/.test(sql)) { + cols = ["status", "n"]; + rows = Object.entries(state.board.counts); + } else if (/^SELECT id, status, priority, title/.test(sql)) { + const [, status, like] = args; + const want = String(like ?? "%%") + .slice(1, -1) + .replace(/\\([\\%_])/g, "$1") + .toLowerCase(); + cols = ["id", "status", "priority", "title", "dedupe_key", "updated", "why"]; + rows = queueTasks + .filter((t) => t.status === status && t.title.toLowerCase().includes(want)) + .map((t) => [t.id, t.status, t.priority, t.title, t.dedupe_key, t.updated.slice(0, 16), t.why]); + } + return { + type: "ok", + response: { + type: "execute", + result: { + cols: cols.map((name) => ({ name })), + rows: rows.map((row) => row.map(cell)), + affected_row_count: 0, + }, + }, + }; + }); + return { ok: true, status: 200, json: async () => ({ results }) }; +}; + const cfg = readConfig({ HOME: "/tmp", PM_CONSOLE_DASHBOARD_URL: "" }); const docs = new Docs( Object.fromEntries(Object.entries(state).map(([name, data]) => [name, { ttlMs: 3_600_000, load: async () => data }])), @@ -364,7 +487,7 @@ const done = (result: unknown) => ({ run: async () => result, touch: [] as strin // Linking a phone is the real thing, kept in a file under /tmp. const devices = new Devices(fileStore("/tmp/pm-console-demo-devices.json")); const phones = { devices, link: new Limiter(30, 60_000), refused: new Limiter(60, 60_000) }; -const real = realActions(new Ops(cfg, demoRun), undefined as never, undefined, devices); +const real = realActions(new Ops(cfg, demoRun, demoQueue), undefined as never, undefined, devices); const table = new Proxy({} as Record>, { get: (_t, kind) => typeof kind === "string" && (kind.startsWith("device.") || kind === "sso.google") @@ -383,7 +506,7 @@ const table = new Proxy({} as Record>, { /** The made-up host: canned state, and actions that all succeed. */ export const demoDeps: Deps = { cfg, - ops: new Ops(cfg, demoRun), + ops: new Ops(cfg, demoRun, demoQueue), docs, phones, push: new Push(fileStore("/tmp/pm-console-demo-push.json"), "mailto:you@example.com", async () => ({ diff --git a/pm-stack/console/src/ops.ts b/pm-stack/console/src/ops.ts index 24baf0b32c..e4e97f0abc 100644 --- a/pm-stack/console/src/ops.ts +++ b/pm-stack/console/src/ops.ts @@ -456,11 +456,13 @@ export class Ops { async messages(limit: unknown) { const n = limit === undefined || limit === null || limit === "" ? 30 : Math.min(id(limit, "limit"), 200); - return ( + const log = ( JSON.parse(await this.must([this.cfg.fleetBin, "bridge", "log", "--limit", String(n), "--order", "desc"])) as { - messages: unknown[]; - } - ).messages; + messages?: unknown; + } | null + )?.messages; + // A log with nothing in it is an empty list, never no answer at all. + return Array.isArray(log) ? log : []; } /** Send a message or a command to agents, groups, or everyone. */ diff --git a/pm-stack/console/test/app.test.ts b/pm-stack/console/test/app.test.ts index 77614f388f..1fd7ea1689 100644 --- a/pm-stack/console/test/app.test.ts +++ b/pm-stack/console/test/app.test.ts @@ -3,7 +3,17 @@ // Oracles: the elapsed-time phrases and the device labels are written // out here by hand for real inputs (two real browser names). import { expect, test } from "bun:test"; -import { ago, androidSource, awayState, band, deviceLabel, endpointMark, subscriptionState } from "../public/app.js"; +import { + ago, + androidSource, + awayState, + band, + capital, + deviceLabel, + endpointMark, + prCheck, + subscriptionState, +} from "../public/app.js"; import { androidRelease } from "../src/edge-proto.ts"; import { contact, endpointMark as serverMark } from "../src/push.ts"; @@ -165,3 +175,46 @@ test("a release's description is taken only when it is one", () => { for (const not of [null, undefined, "", "version", 4, [], "Not Found"]) expect(androidRelease(not)).toBeNull(); }); + +test("a pull request's check says what GitHub said, and nothing it did not", () => { + expect( + prCheck({ + mergeable: true, + mergeable_state: "clean", + additions: 120, + deletions: 8, + changed_files: 5, + review_comments: 2, + }), + ).toBe("can merge (clean) · +120 −8 in 5 files · 2 review comments"); + expect( + prCheck({ + mergeable: false, + mergeable_state: "dirty", + additions: 1, + deletions: 0, + changed_files: 1, + review_comments: 1, + }), + ).toBe("cannot merge (dirty) · +1 −0 in 1 file · 1 review comment"); + // GitHub works mergeability out after the fact: not known is not "cannot". + expect( + prCheck({ + mergeable: null, + mergeable_state: "unknown", + additions: 3, + deletions: 3, + changed_files: 2, + review_comments: 0, + }), + ).toBe("mergeability not known yet · +3 −3 in 2 files · 0 review comments"); + // An answer with parts missing never reads "undefined". + expect(prCheck({ mergeable: true })).toBe("can merge"); + expect(prCheck({})).toBe("mergeability not known yet"); + for (const nothing of [null, undefined, [], "x"]) expect(prCheck(nothing)).not.toContain("undefined"); + expect(prCheck(null)).toBe("GitHub did not say."); +}); + +test("a button's word starts with a capital", () => { + expect(["start", "restart", "stop", "", "Logs"].map(capital)).toEqual(["Start", "Restart", "Stop", "", "Logs"]); +}); diff --git a/pm-stack/console/test/edge.test.ts b/pm-stack/console/test/edge.test.ts index f2eae05f00..b4a39713ff 100644 --- a/pm-stack/console/test/edge.test.ts +++ b/pm-stack/console/test/edge.test.ts @@ -1807,6 +1807,35 @@ describe("the host's report is the host's", () => { ); }; + test("a report under a key the edge has not seen is read to its end before the key is asked for", async () => { + // In the Worker runtime the report is sent to the state a second + // time, once the key is known, from a second copy of the same + // upload, and a first copy left unread holds the second back until + // the laptop gives up waiting. That cannot be seen under bun, which + // keeps the whole upload in memory; what can be seen is whether the + // first copy was read. (scripts/edge-smoke.ts shows the real thing, + // and runs before every deploy.) + const w = await setup(); + const pair = await newKeyPair(); + const body = new TextEncoder().encode(JSON.stringify({ v: 1, at: w.now.t, sections: [], have: {}, acks: [] })); + const first = new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body, + headers: { "x-pm-key": await keyId(pair.publicJwk), "x-pm-signature": await sign(pair.privateJwk, body) }, + }); + const answer = await w.edge.now.fetch(first); + expect(answer.headers.get("x-pm-next")).toBe("key"); + expect(first.bodyUsed).toBe(true); + // A second stranger within the same minute is refused, and that one is not read at all. + const second = new Request(`https://${HOST}/console/edge/sync`, { + method: "POST", + body, + headers: { "x-pm-key": await keyId(pair.publicJwk), "x-pm-signature": await sign(pair.privateJwk, body) }, + }); + expect((await w.edge.now.fetch(second)).status).toBe(401); + expect(second.bodyUsed).toBe(false); + }); + test("an address whose reports keep failing is refused unread, and nobody else is", async () => { const w = await setup(); await w.hostReads(); diff --git a/pm-stack/console/test/signin.test.ts b/pm-stack/console/test/signin.test.ts index 5138da6931..8012db7a33 100644 --- a/pm-stack/console/test/signin.test.ts +++ b/pm-stack/console/test/signin.test.ts @@ -153,6 +153,27 @@ describe("sign-in", () => { ); }); + test("the message log is a list whatever the fleet printed for an empty one", async () => { + const two = [ + { ts: "2026-11-22T10:00:00Z", direction: "out", agent: "conductor", kind: "message", body: "one" }, + { ts: "2026-11-22T10:01:00Z", direction: "in", agent: "muse", kind: "command", body: "two" }, + ]; + for (const [printed, want] of [ + [JSON.stringify({ messages: two }), two], + [JSON.stringify({ messages: [] }), []], + // No log yet: the answer is still a list, never nothing at all (an + // empty answer used to stop the Agents screen from loading). + ["{}", []], + ["[]", []], + ["null", []], + [JSON.stringify({ messages: "none" }), []], + ] as const) { + const w = setup(() => ({ stdout: printed })); + expect(await w.ops.messages("15")).toEqual(want as unknown[]); + expect(w.calls[0].argv.slice(1)).toEqual(["bridge", "log", "--limit", "15", "--order", "desc"]); + } + }); + test("a script that fails says why, without either value even if the script printed one", async () => { const w = setup(() => ({ code: 1,