// Web console tests, the first shared session: open, auth, sends, serving, uploads, patches. // Run with: node --test scripts/test-web-console-session.mjs // // Shared setup (a per-process console home, the CLI runner, fixtures) lives in // web-console-test-helpers.mjs; see the comment at its top. import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import http from "node:http"; // The page's pure answer-shaping logic. app.js itself cannot be imported here // (it touches `document` at module scope and starts a session on import), which // is exactly why this lives in its own file. import { IMAGE_LONG_EDGE, MAX_ATTACHMENTS, MAX_DOC_BYTES, DASHBOARD_REPLY, HOME_REPLY, homeButtonState, noteAction, noteReplyLines, staleLaunchFeedback, REVIEW_REPLY, STOP_REPLY, STOP_HANDOFF_REPLY, threadText, threadWho, turnGate, } from "../src/web-console/public/answers.js"; import { CHAT_LIMIT, CHAT_MAX_CHARS } from "../src/web-console/public/chat.js"; import { ACCENTS, CARD_WIDTHS, SOUND_EVENTS, soundKey, soundPrefs } from "../src/web-console/public/palette.js"; import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js"; import { tabKeyTarget } from "../src/web-console/public/tabs.js"; import { PREFS_TABS, prefsOpenTab, prefsResetScope } from "../src/web-console/public/prefs.js"; import { DEFAULT_LOOKS, looks, resetLooks } from "../src/web-console/public/looks.js"; import { ROLE_NOT_SET } from "../src/web-console/public/starters.js"; import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js"; import { REMOTE_FOLD } from "../src/web-console/public/git-board.js"; import { readLedger, SERVER_MAX_LIFE_MS, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs"; import { applyPatch, validate } from "../src/web-console/patches.mjs"; import { joinedCss } from "./css-helpers.mjs"; import { ROOT, HOME, cookieFor, cli, payload, BASE, helpTemplate, JPEG, PDF, readState, ask, until, clientFor, } from "./web-console-test-helpers.mjs"; let sid; let session; let baseUrl; let token; const { post, raw } = clientFor(() => ({ baseUrl, token })); test("open starts a detached server and prints a loopback URL", () => { const res = cli(["open", "--file", payload("p1.json", BASE), "--no-open", "--title", "Test session"]); assert.equal(res.json.ok, true); sid = res.json.sid; session = res.json.session; assert.match(res.json.url, /^http:\/\/127\.0\.0\.1:\d+\/s\/[A-Za-z0-9_-]{22}\//); const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//); baseUrl = m[1]; token = m[2]; }); test("health reports the session id", async () => { const res = await fetch(baseUrl + "/health"); const body = await res.json(); assert.equal(body.sid, sid); }); // fetch() silently drops a Host header (it is a forbidden header name), so this // has to go out over a raw socket or it asserts nothing. function rawGet(pathname, host) { const port = Number(new URL(baseUrl).port); return new Promise((resolve, reject) => { const req = http.request( { host: "127.0.0.1", port, path: pathname, method: "GET", headers: { Host: host } }, (res) => { res.resume(); resolve(res.statusCode); } ); req.on("error", reject); req.end(); }); } test("rejects a mismatched Host header (DNS rebinding)", async () => { assert.equal(await rawGet("/health", "evil.example.com"), 403); assert.equal(await rawGet("/health", `127.0.0.1:${new URL(baseUrl).port}`), 200); }); test("rejects an unauthenticated read and a bad token", async () => { assert.equal((await fetch(baseUrl + "/state")).status, 403); assert.equal((await fetch(baseUrl + "/s/not-the-token/", { redirect: "manual" })).status, 403); }); test("the token path sets a cookie and redirects", async () => { const res = await fetch(`${baseUrl}/s/${token}/`, { redirect: "manual" }); assert.equal(res.status, 302); assert.equal(res.headers.get("location"), "/"); assert.match(res.headers.get("set-cookie"), /HttpOnly/); assert.match(res.headers.get("set-cookie"), /SameSite=Strict/); assert.ok(res.headers.get("set-cookie").startsWith(`${cookieFor(baseUrl, token)};`), "named for the port"); }); test("the page is served with a CSP that forbids inline script", async () => { const res = await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } }); const csp = res.headers.get("content-security-policy"); assert.ok(csp.includes("script-src 'self'")); assert.ok(!csp.includes("unsafe-inline")); // The two chime files load as media: without this, default-src 'none' blocks them. assert.ok(csp.includes("media-src 'self'")); }); // result.json keeps the whole send; the agent's output carries only `reply`, // the `__` session actions and the hop fields. const sentActions = () => JSON.parse(fs.readFileSync(path.join(session, "result.json"), "utf8")).actions; test("wait returns 10 with a progress summary while nobody has answered", () => { const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 10); assert.deepEqual(res.json, { waiting: true, open: 1 }, "nothing else rides on a quiet slice"); }); test("a submit round-trips to the agent with the literal reply token", async () => { await post("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }], reply: "Export format: b", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.reply, "Export format: b"); for (const dropped of ["type", "at", "sid", "rev", "consumedAt", "actions"]) assert.equal(res.json[dropped], undefined, `${dropped} stays in result.json`); const kept = JSON.parse(fs.readFileSync(path.join(session, "result.json"), "utf8")); assert.equal(kept.type, "submit"); assert.equal(kept.actions[0].k, "B"); }); test("a collected answer is written to the meter ledger once, and a button press is not", async () => { const answers = () => readLedger(session).filter((e) => e.kind === "answer"); const mine = answers().filter((e) => e.id.endsWith(":q1")); assert.equal(mine.length, 1, "the round-trip above left one answer for q1"); assert.match(mine[0].id, /^L\d+:answer:.+:q1$/); // Collecting the same send again (a kill before consumedAt) adds nothing. const resultFile = path.join(session, "result.json"); const collected = JSON.parse(fs.readFileSync(resultFile, "utf8")); const before = answers().length; fs.writeFileSync(resultFile, JSON.stringify({ ...collected, consumedAt: undefined })); assert.equal(cli(["wait", "--session", sid, "--seconds", "5"]).status, 0); assert.equal(new Set(answers().map((e) => e.id)).size, before, "a re-collected send dedupes by id"); }); // The page shows a settled question's answer back to the person. If it had to // wait for the agent to record one, a model that forgot would leave someone // looking at a card marked "Settled" with nothing in it. test("a submit is recorded on the item, so the page can show the answer back", () => { const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); const q1 = state.items.find((i) => i.id === "q1"); assert.equal(q1.submitted.k, "B"); assert.ok(q1.submitted.at, "the server stamps the time, the client never does"); assert.equal(q1.status, "open", "only the agent settles a question"); }); // The Brief button is a send like any other, which is the whole reason it needs // no new transport. What matters is that the range reaches the agent in the // grammar its playbook parses. test("a brief request round-trips with a range the playbook can read", async () => { await post("/submit", { actions: [{ i: "__brief", type: "brief", range: "since 2026-09-15" }], reply: "Write a brief covering everything since 2026-09-15.", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__brief"); assert.equal(res.json.session[0].range, "since 2026-09-15"); assert.match(res.json.reply, /since 2026-09-15/); // `__brief` is not an item, so nothing on the board may have been touched. const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__brief"), "a brief must not become a question"); assert.equal(state.items.find((i) => i.id === "q1").status, "open"); }); // The review button on a finished build is a send like the brief: it names no // question, and it reaches the agent through the same wait loop. test("a review request round-trips without touching any question", async () => { await post("/submit", { actions: [{ i: "__review", type: "review" }], reply: REVIEW_REPLY, }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__review"); assert.equal(res.json.reply, REVIEW_REPLY); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__review"), "a review request must not become a question"); assert.equal(state.items.find((i) => i.id === "q1").status, "open"); }); // The dashboard's card click is a send like the brief and the review button: // it names no question, and the skill it carries reaches the agent through // the same wait loop. test("a launch request round-trips with the skill the dashboard resumes as", async () => { await post("/submit", { actions: [{ i: "__launch", type: "launch", skill: "plan2code-3-implement", workflow: "implement" }], reply: "Start Implement (/plan2code-3-implement), right here in this session.", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__launch"); assert.equal(res.json.session[0].skill, "plan2code-3-implement"); assert.equal(res.json.session[0].workflow, "implement"); assert.match(res.json.resume, /--no-open --workflow implement$/); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__launch"), "a launch must not become a question"); }); // Continue here sends the same launch from a finished screen, so the hop's // resume names the next skill's workflow and the spec, and the skill file to read. test("a launch sent from a finished screen carries the resume for the next skill and spec", async () => { await post("/submit", { actions: [{ i: "__launch", type: "launch", skill: "plan2code-2-document", workflow: "document", spec: "specs/lunch-vote" }], reply: "Start Document (/plan2code-2-document) for specs/lunch-vote, right here in this session.", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__launch"); assert.match(res.json.resume, /--no-open --workflow document --spec specs\/lunch-vote$/); }); // The page tells the person the hop gives the next skill a clean page: a resume // into a different workflow drops the finish it was launched from. test("resuming into another skill after Continue here drops the finish", async () => { const stateFile = path.join(session, "state.json"); const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8")); cli(["post", "--session", sid, "--file", payload("fin-continue.json", { finish: { headline: "The plan is documented", command: "/plan2code-5-changelog", dashboard: true }, })]); const snapshot = fs.readFileSync(stateFile, "utf8"); await post("/submit", { actions: [{ i: "__launch", type: "launch", skill: "plan2code-changelog", workflow: "changelog" }], reply: "Start Changelog (/plan2code-changelog), right here in this session.", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); cli(["open", "--resume", sid, "--no-open", "--workflow", "changelog"]); const resumed = readState(); assert.equal(resumed.workflow, "changelog"); assert.equal(resumed.finish, undefined, "the old finish is gone"); fs.writeFileSync(stateFile, snapshot); }); // A delete from the dashboard's picker is a send like a launch, but no hop: // the agent stays the dashboard, so it carries no resume and no skill file. test("a delete request round-trips with the spec folder and no resume", async () => { await post("/submit", { actions: [{ i: "__delete", type: "delete", spec: "specs/lunch-vote" }], reply: "Delete the spec folder specs/lunch-vote/ for good, right here in this session.", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__delete"); assert.equal(res.json.session[0].spec, "specs/lunch-vote"); assert.equal(res.json.resume, undefined); assert.equal(res.json.skillFile, undefined); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__delete"), "a delete must not become a question"); }); // Back to the dashboard is a send like the review button: it names no // question, it is refused while an earlier send is uncollected, and the agent // answers it by resuming the same session as the dashboard. test("a dashboard request round-trips and the session resumes as the dashboard", async () => { const stateFile = path.join(session, "state.json"); const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8")); cli(["post", "--session", sid, "--file", payload("fin-dash-rt.json", { finish: { headline: "Phase 3 is done", command: "/plan2code-3-implement specs/lunch-vote/overview.md", dashboard: true }, })]); const submittedBefore = readState().items.map((i) => (i.submitted ? i.submitted.at : null)); const first = await post("/submit", { actions: [{ i: "__dashboard", type: "dashboard" }], reply: DASHBOARD_REPLY }); assert.equal(first.status, 200); const second = await post("/submit", { actions: [{ i: "__dashboard", type: "dashboard" }], reply: DASHBOARD_REPLY }); assert.equal(second.status, 409, "a second press is refused while the first is uncollected"); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.deepEqual(res.json.session, [{ i: "__dashboard" }]); assert.equal(res.json.reply, DASHBOARD_REPLY); const after = readState(); assert.ok(after.items.every((i) => i.id !== "__dashboard"), "a dashboard request must not become a question"); assert.deepEqual( after.items.map((i) => (i.submitted ? i.submitted.at : null)), submittedBefore, "no item gained a submitted record" ); const snapshot = fs.readFileSync(stateFile, "utf8"); cli(["open", "--resume", sid, "--no-open", "--workflow", "dashboard"]); cli(["post", "--session", sid, "--file", payload("fin-dash-null.json", { finish: null })]); const resumed = readState(); assert.equal(resumed.workflow, "dashboard"); assert.equal(resumed.finish, undefined); assert.ok(resumed.scan, "resuming as the dashboard scans the project"); // Put it back for the tests that follow: the switch blanked the session. fs.writeFileSync(stateFile, snapshot); }); test("a stale dashboard launch says the pick is saved and how to wake the agent", () => { assert.deepEqual(staleLaunchFeedback("Pathfinder", true), { kicker: "Saved", title: "Pathfinder is saved and waiting", quip: "Plan2Code is not running right now.", hint: "Return to the terminal and type continue. Plan2Code will collect this launch and continue here.", }); // Under the desktop app the Reconnect to agent button is on the screen, so // the hint points at it instead of the terminal. assert.equal( staleLaunchFeedback("Pathfinder", true, true).hint, "Press Reconnect to agent below. Plan2Code will collect this launch and continue here." ); assert.equal(staleLaunchFeedback("Pathfinder", false), null); }); // The page clears staged answers when it hears a submit landed, because a send // from a second tab really has taken them. The event has to say WHICH ones, or // a brief request -- a submit carrying no answers at all -- wipes work that was // never sent. test("the submitted event names the items that went", async () => { const port = Number(new URL(baseUrl).port); // Resolved once the stream is connected: a submit posted before then is // never delivered to it, which timed out on a slow runner. let connected; const open = new Promise((resolve) => (connected = resolve)); const frame = new Promise((resolve, reject) => { const req = http.request( { host: "127.0.0.1", port, path: "/events", method: "GET", headers: { cookie: cookieFor(baseUrl, token) } }, (res) => { connected(); let buf = ""; res.setEncoding("utf8"); res.on("data", (chunk) => { buf += chunk; const m = buf.match(/event: submitted\ndata: (.+)\n/); if (!m) return; req.destroy(); try { resolve(JSON.parse(m[1])); } catch (err) { reject(err); } }); } ); req.on("error", (err) => { if (err.code !== "ECONNRESET") reject(err); }); req.setTimeout(5000, () => { req.destroy(); reject(new Error("no submitted frame within 5s")); }); req.end(); }); await open; await post("/submit", { actions: [{ i: "__brief", type: "brief", range: "today" }], reply: "Write a brief for today.", }); const data = await frame; assert.deepEqual(data.ids, ["__brief"], "only the brief went, so only it may be cleared"); cli(["wait", "--session", sid, "--seconds", "10"]); }); // The heartbeat is the only thing that tells a page the agent has come or // gone: the watcher fires on state.json, which is the agent POSTING, and an // agent that collects a result or is merely alive and thinking touches // neither. Without these fields a page can insist for minutes that nobody has // picked its answers up when something already has. test("the heartbeat reports agent liveness and whether a send is still uncollected", async () => { // post() hands back the Response, not the body. const ping = async () => (await post("/ping", {})).json(); const before = await ping(); assert.equal(before.ok, true); assert.equal(before.pendingResult, false); assert.equal(typeof before.rev, "number"); assert.ok(Date.parse(before.agentLastSeen) > 0, "agentLastSeen must be a timestamp"); await post("/submit", { rev: before.rev, actions: [{ i: "q1", type: "answer", kind: "choice", k: "A" }], reply: "a", }); assert.equal((await ping()).pendingResult, true, "an uncollected send must show on the heartbeat"); cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal((await ping()).pendingResult, false, "collecting it must show on the heartbeat too"); }); // Stop session rides the ordinary submit, so the last staged answers go with // it in one piece, and reaches the agent as an ordinary send (exit 0), not as // a cancel. The server also reports it, because the page's own memory of it // does not survive a resume on a new port. test("a stop request carries the staged answers, reaches the agent as a send, and is reported until collected", async () => { const ping = async () => (await post("/ping", {})).json(); const before = await ping(); assert.equal(before.pendingStop, false); await post("/submit", { rev: before.rev, actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }, { i: "__stop", type: "stop" }], reply: "Export format: b\n" + STOP_REPLY, }); assert.equal((await ping()).pendingStop, true, "an uncollected stop must show on the heartbeat"); const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 0, "a stop is a send, not a cancel"); assert.deepEqual(res.json.session, [{ i: "__stop" }], "the stop arrives whole, the answer in reply"); assert.match(res.json.reply, /^Export format: b/, "the staged answer arrives with it"); assert.equal((await ping()).pendingStop, false); }); // "Stop with a handoff" is the same send with `handoff: true` on the action. // The source tree has no built Handoff skill beside it, so no handoffSkill. test("a handoff stop keeps its flag, reports as a stop until collected, and names no skill file in the source tree", async () => { const ping = async () => (await post("/ping", {})).json(); const before = await ping(); await post("/submit", { rev: before.rev, actions: [{ i: "__stop", type: "stop", handoff: true }], reply: STOP_HANDOFF_REPLY, }); assert.equal((await ping()).pendingStop, true, "an uncollected handoff stop shows on the heartbeat"); const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].handoff, true, "the flag reaches the agent"); assert.equal(res.json.handoffSkill, undefined, "no built skill beside the source tree"); assert.equal((await ping()).pendingStop, false); }); // The top bar's triangle is a stop that lands on the menu: the staged answers // and `__dashboard` go as one send with no finish on the page, the agent gets // both at once, and the resume through the dashboard blanks the skill's page. test("a mid-workflow way home carries the staged answers and resumes as the dashboard", async () => { const stateFile = path.join(session, "state.json"); const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8")); const snapshot = fs.readFileSync(stateFile, "utf8"); // Earlier tests leave a finish on the shared session; the way home is sent mid-workflow. cli(["post", "--session", sid, "--file", payload("home-unfinish.json", { finish: null })]); assert.equal(readState().finish, undefined, "the way home is sent before any finish"); const res = await post("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "A" }, { i: "__dashboard", type: "dashboard" }], reply: "Export format: a\n" + HOME_REPLY, }); assert.equal(res.status, 200); const got = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(got.status, 0, "the way home is a send, not a cancel"); assert.deepEqual(got.json.session, [{ i: "__dashboard" }], "the way home arrives whole, the answer in reply"); assert.match(got.json.reply, /^Export format: a/, "the staged answer arrives with it"); assert.ok(got.json.reply.endsWith(HOME_REPLY)); cli(["open", "--resume", sid, "--no-open", "--workflow", "dashboard"]); cli(["post", "--session", sid, "--file", payload("home-menu.json", { finish: null, menu: { note: "Back from the plan" }, agent: { status: "waiting" } })]); const home = readState(); assert.equal(home.workflow, "dashboard"); assert.equal(home.finish, undefined, "no finish card on the way home"); assert.deepEqual(home.items, [], "the skill's questions do not follow it to the menu"); assert.equal(home.menu.note, "Back from the plan"); fs.writeFileSync(stateFile, snapshot); }); test("the way home follows Stop's turn rules and hides where it has no job", () => { const turn = { gone: false, pendingResult: false, waiting: false }; assert.equal(turnGate(turn), null); assert.equal(turnGate({ ...turn, waiting: true }), "waiting"); assert.equal(turnGate({ ...turn, pendingResult: true, waiting: true }), "pending"); assert.equal(turnGate({ gone: true, pendingResult: true, waiting: true }), "gone"); for (const hidden of [ { workflow: "dashboard" }, { workflow: undefined }, { workflow: "plan", finished: true }, { workflow: "plan", stopping: true }, ]) { assert.equal(homeButtonState({ ...turn, ...hidden }).hidden, true, JSON.stringify(hidden)); } for (const workflow of ["plan", "pathfinder", "implement", "quick-task", "review", "init"]) { const st = homeButtonState({ ...turn, workflow }); assert.equal(st.hidden, false, workflow); assert.equal(st.disabled, false, workflow); assert.match(st.title, /dashboard/i); } // `waiting` already excludes an adrift agent, so an agent that stopped // checking in leaves the button pressable -- the caller passes false. assert.equal(homeButtonState({ ...turn, workflow: "plan", waiting: true }).disabled, true); assert.equal(homeButtonState({ ...turn, workflow: "plan", pendingResult: true }).disabled, true); assert.equal(homeButtonState({ ...turn, workflow: "plan", gone: true }).disabled, true); const going = homeButtonState({ ...turn, workflow: "plan", homeward: true }); assert.deepEqual([going.hidden, going.disabled], [false, true], "pressed once, it waits for the page to turn"); const stranded = homeButtonState({ ...turn, workflow: "plan", homeward: true, adrift: true }); assert.equal(stranded.disabled, false, "an agent gone quiet after collecting it gives the button back"); assert.equal(homeButtonState({ ...turn, workflow: "plan", homeward: true, adrift: true, pendingResult: true }).disabled, true, "still one send at a time"); }); test("the page carries the way home: the triangle, its confirm, and the wiring", () => { const dir = path.join(ROOT, "src", "web-console", "public"); const html = fs.readFileSync(path.join(dir, "index.html"), "utf8"); const css = joinedCss(); assert.ok(html.indexOf('id="btn-home"') < html.indexOf('id="btn-stop"'), "the triangle sits left of Stop session"); assert.match(html, /id="btn-home"[\s\S]{0,200}aria-label="Back to the dashboard"/, "the icon button has a name"); for (const id of ["home-modal", "home-blurb", "home-warn", "home-cancel", "home-go"]) { assert.ok(html.includes(`id="${id}"`), `index.html must carry #${id}`); } assert.ok(html.includes("Leave this workflow?")); assert.match(css, /\.home-btn path\s*\{\s*fill:\s*var\(--accent\)/, "the triangle is filled with the highlight color"); }); test("the way home cannot be mistaken for a brief request", () => { assert.doesNotMatch(HOME_REPLY, /\b(brief|recap|minutes)\b/i); }); test("console-stop.md, building.md and the dashboard prompt teach the mid-workflow way home", () => { const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8"); const stopMd = read("src", "web-console", "console-stop.md"); assert.ok(stopMd.includes("## `__dashboard` with no finish up (home, mid-workflow)")); assert.match(stopMd, /No `finish` and no `stop`: the menu is the ending/); assert.ok(stopMd.includes("## `__stop` with a handoff")); for (const word of ["handoff new", "--from-stop", "handoffSkill"]) assert.ok(stopMd.includes(word), `console-stop.md names ${word}`); assert.match(read("src", "web-console", "console.md"), /`__stop`, `__dashboard`[^\n]*covered by the topic file `read` names/, "the card hands a stop and a dashboard press to the topic file its pointer names"); assert.ok(read("src", "web-console", "building.md").includes("mid-build `__dashboard`")); assert.ok(read("src", "plan2code.md").includes("mid-workflow from the top bar's triangle")); }); test("console-launches.md and the dashboard prompt teach the handoff pick-up and delete", () => { const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8"); const launches = read("src", "web-console", "console-launches.md"); for (const word of ["__pickup", "handoffFile", "delete-handoff", "handoffsDir", "fallback"]) { assert.ok(launches.includes(word), `console-launches.md names ${word}`); } assert.ok(launches.includes("handoffs,handoffsDir"), "console-launches.md lists the scan fields"); const prompt = read("src", "plan2code.md"); for (const word of ["__pickup", "delete-handoff"]) assert.ok(prompt.includes(word), `src/plan2code.md names ${word}`); }); // The server serves a hardcoded allow-list, so a new module that nobody adds // to it 404s, the import fails, and the page never starts: a blank console // with the default title and one line in the browser's console. Every module // any page script imports must come back. test("every module the page imports is actually served", async () => { const dir = path.join(ROOT, "src", "web-console", "public"); const wanted = new Set(["app.js"]); // The modules beside app.js and the screens under screens/ (subfolders too: // screens/agents/ is a directory), each import resolved from the file that // makes it (a screen's "../state.js" is state.js). const screens = (abs, rel) => fs.readdirSync(abs, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? screens(path.join(abs, e.name), `${rel}${e.name}/`) : e.name.endsWith(".js") ? [`${rel}${e.name}`] : []); const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...screens(path.join(dir, "screens"), "screens/")]; for (const f of files) { const src = fs.readFileSync(path.join(dir, f), "utf8"); for (const m of src.matchAll(/^\s*import\b[^"']*["'](\.\.?\/[^"']+)["']/gm)) wanted.add(path.posix.join(path.posix.dirname(f), m[1])); } const html = fs.readFileSync(path.join(dir, "index.html"), "utf8"); for (const m of html.matchAll(/ 1, "found the imports"); for (const f of wanted) { const res = await fetch(`${baseUrl}/${f}`, { headers: { cookie: cookieFor(baseUrl, token), connection: "close" } }); assert.equal(res.status, 200, `${f} is imported but the server will not serve it`); } }); // The wake-up module is imported by app.js and preloaded by the page, and it // promises no DOM access at module scope: importing it here must not throw. test("boot.js is served as JavaScript and imports without a DOM", async () => { const res = await fetch(`${baseUrl}/boot.js`, { headers: { cookie: cookieFor(baseUrl, token), connection: "close" } }); assert.equal(res.status, 200); assert.match(res.headers.get("content-type"), /javascript/); const { playWake, GLIDE_AT_MS, DONE_AT_MS } = await import("../src/web-console/public/boot.js"); assert.equal(typeof playWake, "function"); assert.ok(GLIDE_AT_MS < DONE_AT_MS, "the glide starts before the run ends"); }); // The chimes are fetched like the modules are: the allow-list means a name // nobody adds serves 404 and the sound just never plays, so assert every file // the page asks for comes back as audio. test("the chime files are served as audio", async () => { for (const f of ["start-stop.mp3", "next.mp3", "insert.mp3", "sleeping.mp3", "bootup.mp3", "start-skill.mp3"]) { const res = await fetch(`${baseUrl}/${f}`, { headers: { cookie: cookieFor(baseUrl, token) } }); assert.equal(res.status, 200, `${f} is played but the server will not serve it`); assert.match(res.headers.get("content-type"), /^audio\//); } }); // Every sound event in palette.js has its own box in User Preferences, every box // names a real event, and every event's file is served. A box with no event // saves a setting nothing reads; an event with no box can never be muted. test("every sound event has a preference box and a served file", async () => { assert.equal(SOUND_EVENTS.startSkill.file, "start-skill", "starting a skill has its own sound"); const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8"); const boxes = [...html.matchAll(/data-sound="(\w+)"/g)].map((m) => m[1]); assert.deepEqual([...boxes].sort(), Object.keys(SOUND_EVENTS).sort()); for (const file of new Set(Object.values(SOUND_EVENTS).map((e) => e.file))) { const res = await fetch(`${baseUrl}/${file}.mp3`, { headers: { cookie: cookieFor(baseUrl, token) } }); assert.equal(res.status, 200, `${file}.mp3 is played but the server will not serve it`); assert.match(res.headers.get("content-type"), /^audio\//); } }); // A looks.json from before the per-event switches has none of their keys and // must keep every sound; a saved switch survives; junk falls back to on. test("soundPrefs: missing switches are on, saved booleans hold, anything else is on", () => { const keys = Object.keys(SOUND_EVENTS).map(soundKey); assert.equal(soundKey("startSkill"), "soundStartSkill"); for (const saved of [null, undefined, {}, { theme: "dark", sound: false }]) { const prefs = soundPrefs(saved); assert.deepEqual(Object.keys(prefs).sort(), [...keys].sort()); assert.ok(Object.values(prefs).every((v) => v === true), `every sound on for ${JSON.stringify(saved)}`); } const prefs = soundPrefs({ soundQuestion: false, soundBootup: "x", soundNewTab: 0, soundStartSkill: true, extra: false }); assert.equal(prefs.soundQuestion, false); assert.equal(prefs.soundBootup, true); assert.equal(prefs.soundNewTab, true); assert.equal(prefs.soundStartSkill, true); assert.ok(!("extra" in prefs), "only the sound switches come back"); }); // The favicon rides the same allow-list, so a missing entry is a silent 404 // and the tab falls back to a blank icon. test("the favicon is served as an SVG with a PNG fallback and the page points at both", async () => { const svg = await fetch(`${baseUrl}/favicon.svg`, { headers: { cookie: cookieFor(baseUrl, token) } }); assert.equal(svg.status, 200, "favicon.svg is linked but the server will not serve it"); assert.equal(svg.headers.get("content-type"), "image/svg+xml"); assert.match(await svg.text(), /^]*viewBox="0 0 32 32"/); const res = await fetch(`${baseUrl}/favicon.png`, { headers: { cookie: cookieFor(baseUrl, token) } }); assert.equal(res.status, 200, "favicon.png is linked but the server will not serve it"); assert.equal(res.headers.get("content-type"), "image/png"); const bytes = new Uint8Array(await res.arrayBuffer()); assert.deepEqual([...bytes.slice(0, 4)], [0x89, 0x50, 0x4e, 0x47]); const html = await (await fetch(baseUrl + "/", { headers: { cookie: cookieFor(baseUrl, token) } })).text(); assert.ok(html.includes('href="/favicon.svg"')); assert.ok(html.includes('href="/favicon.png"')); assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/); }); /* ---------------------------------------------------------------- help */ test("help: 21 tabs with unique ids", () => { assert.equal(HELP_TABS.length, 21); assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 21); assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen"); const ids = HELP_TABS.map((t) => t.id); assert.equal(ids.indexOf("loop"), ids.indexOf("build") + 1, "Implementation Loop comes right after Watching a build"); assert.equal(HELP_TABS[ids.indexOf("loop")].label, "Implementation Loop"); assert.equal(ids.indexOf("git"), ids.indexOf("loop") + 1, "The git board comes right after Implementation Loop"); assert.equal(HELP_TABS[ids.indexOf("git")].label, "The git board"); assert.equal(helpTabFor({ workflow: "git" }), "git"); assert.equal(ids.indexOf("activities"), ids.indexOf("ask") + 1, "Activities comes right after Ask a quick question"); assert.equal(HELP_TABS[ids.indexOf("activities")].label, "Activities"); const tpl = helpTemplate(); for (const id of ids) assert.match(tpl, new RegExp(`
`), `${id} has a section`); // The die sits right of the megaphone, so the megaphone is no longer the far-right button. assert.doesNotMatch(tpl, /far right/, "no line calls a top-bar button the far-right one"); const around = tpl.match(/
([\s\S]*?)<\/section>/)[1]; assert.match(around, /
die<\/strong>[\s\S]*?"Activities"/, "Finding your way around points the die at the Activities topic"); }); test("help: the template's icons and panels match HELP_TABS in order, headed by their labels", () => { const tpl = helpTemplate(); const ids = HELP_TABS.map((t) => t.id); assert.deepEqual([...tpl.matchAll(/ m[1]), ids); const panels = [...tpl.matchAll(/
([\s\S]*?)<\/section>/g)]; assert.deepEqual(panels.map((m) => m[1]), ids); assert.equal((tpl.match(/([\s\S]*?)<\/h3>/); assert.ok(h3, `${m[1]} has a heading`); assert.ok(m[2].trimStart().startsWith("

"), `${m[1]} starts with its heading`); assert.equal(h3[1].trim(), HELP_TABS[i].label); } }); test("help: every diagram tab has one labeled picture, the rest none; no inline styles or scripts", () => { const tpl = helpTemplate(); assert.doesNotMatch(tpl, /\sstyle=/); assert.doesNotMatch(tpl, /"), "text/plain; charset=utf-8"], ["logo.svg", MD, null], ["notes.md", MD, "text/plain; charset=utf-8"], ]) { const up = await uploadDoc(name, buf); if (!type) { assert.equal(up.status, 415, "an svg is not an allowed document"); continue; } const text = await raw("GET", `/uploads/${up.json.id}.${name.split(".").pop()}`); assert.equal(text.status, 200, name); assert.equal(text.headers["content-type"], type, "text and code are never served as html"); assert.equal(text.headers["content-security-policy"], "sandbox"); assert.deepEqual(text.body, buf); assert.equal((await raw("DELETE", `/uploads/${up.json.id}.${name.split(".").pop()}`)).status, 204); } assert.equal((await raw("GET", url, undefined, { cookie: "" })).status, 403); for (const p of ["/uploads/../state.json.md", "/uploads/%2e%2e/x.pdf", "/uploads/not-a-uuid.md"]) { assert.equal((await raw("GET", p)).status, 404, p); } for (const p of ["/uploads/../state.json.md", "/uploads/%2e%2e/x.pdf", "/uploads/not-a-uuid.md"]) { assert.equal((await raw("DELETE", p)).status, 404, p); } assert.equal((await raw("DELETE", url, undefined, { origin: "http://evil.example.com" })).status, 403); assert.ok(fs.existsSync(file)); assert.equal((await raw("DELETE", url)).status, 204); assert.equal(fs.existsSync(file), false); assert.equal((await raw("DELETE", url)).status, 404); }); test("a send takes documents as files, counts them with images, and keeps each kind in its own list", async () => { const comment = (images, files) => ({ actions: [{ i: "q1", type: "comment", text: "See these.", images, files }] }); const img = async () => { const j = (await uploadJpeg("shot.png")).json; return { path: j.path, name: j.name }; }; const doc = async (name, buf) => { const j = (await uploadDoc(name, buf)).json; return { path: j.path, name: j.name }; }; const i1 = await img(); const i2 = await img(); const i3 = await img(); const d1 = await doc("a.md", MD); const d2 = await doc("b.pdf", PDF); const d3 = await doc("c.json", Buffer.from("{}")); assert.equal((await post("/submit", comment([i1, i2, i3], [d1, d2, d3]))).status, 400, "six in all is too many"); assert.equal((await post("/submit", comment(undefined, [i1]))).status, 400, "an image is not a file"); assert.equal((await post("/submit", comment([d1], undefined))).status, 400, "a file is not an image"); const otherId = "0f0e0d0c-0b0a-4908-8706-050403020101"; const other = path.join(HOME, "sessions", "20260101-000000-abcdef", "uploads"); fs.mkdirSync(other, { recursive: true }); fs.writeFileSync(path.join(other, otherId + ".md"), MD); assert.equal((await post("/submit", comment(undefined, [{ path: path.join(other, otherId + ".md") }]))).status, 400); const attachments = [ { ...i1, kind: "image" }, { ...d1, kind: "file" }, { ...i2, kind: "image" }, { ...d2, kind: "file" }, { ...d3, kind: "file" }, ]; const ok = await post("/submit", { actions: [noteAction("q1", "", attachments)], reply: noteReplyLines("Export format", "", attachments).join("\n"), }); assert.equal(ok.status, 200); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); const note = sentActions().find((x) => x.type === "comment"); assert.deepEqual(note.images, [i1, i2]); assert.deepEqual(note.files, [d1, d2, d3]); assert.match(res.json.reply, /^Note on Export format: \(attachments only\)$/m); assert.ok(res.json.reply.includes(` File: ${d1.path} (a.md)`)); assert.ok(res.json.reply.includes(` File: ${d2.path} (b.pdf)`)); assert.ok(res.json.reply.includes(` Image: ${i1.path} (shot.png)`)); }); test("a result is consumed only once", () => { const res = cli(["wait", "--session", sid, "--seconds", "3"]); assert.equal(res.status, 10, "an already-consumed result must not be handed over twice"); }); test("a send records its note and attachments on the item, so the page can show them after a reload", async () => { const readState = () => JSON.parse(fs.readFileSync(path.join(HOME, "sessions", sid, "state.json"), "utf8")); const j = (await uploadJpeg("shot.png")).json; const d = (await uploadDoc("spec.pdf", PDF)).json; const atts = [ { path: j.path, name: j.name, kind: "image" }, { path: d.path, name: d.name, kind: "file" }, ]; const ok = await post("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }, noteAction("q1", "see these", atts)], reply: "x", }); assert.equal(ok.status, 200); const q1 = readState().items.find((i) => i.id === "q1"); assert.equal(q1.submitted.k, "B"); assert.equal(q1.submitted.images, undefined, "the answer record stays the answer"); assert.ok(q1.sentNote.at); assert.equal(q1.sentNote.at, q1.submitted.at, "one send, one clock reading"); assert.equal(q1.sentNote.text, "see these"); assert.deepEqual(q1.sentNote.images, [{ path: j.path, name: j.name }]); assert.deepEqual(q1.sentNote.files, [{ path: d.path, name: d.name }]); // Earlier tests in this session sent notes on q1 too: the newest is this one. const mine = q1.thread.filter((m) => m.who === "user").at(-1); assert.equal(mine.text, "see these", "the note goes into the Notes thread, where the agent's reply will sit under it"); assert.equal(mine.at, q1.sentNote.at); assert.deepEqual(mine.images, [{ path: j.path, name: j.name }]); assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); const only = await post("/submit", { actions: [noteAction("q1", "just a note", [])], reply: "y" }); assert.equal(only.status, 200); const after = readState().items.find((i) => i.id === "q1"); assert.equal(after.sentNote.text, "just a note"); assert.deepEqual(after.sentNote.images ?? [], []); assert.deepEqual( after.thread.filter((m) => m.who === "user").map((m) => m.text).slice(-2), ["see these", "just a note"], "every note stays in the thread, not just the latest one", ); assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); }); test("a request for suggestions is recorded with its flag and threaded even with no note; a non-boolean flag is dropped", async () => { const readState = () => JSON.parse(fs.readFileSync(path.join(HOME, "sessions", sid, "state.json"), "utf8")); const userCount = () => readState().items.find((i) => i.id === "q1").thread.filter((m) => m.who === "user").length; let before = userCount(); const ok = await post("/submit", { actions: [{ i: "q1", type: "comment", text: "", suggest: true }], reply: "Suggestions wanted on q1: (no note)" }); assert.equal(ok.status, 200); let q1 = readState().items.find((i) => i.id === "q1"); assert.equal(q1.sentNote.suggest, true); const mine = q1.thread.filter((m) => m.who === "user").at(-1); assert.equal(userCount(), before + 1, "an empty request still goes into the thread"); assert.equal(mine.who, "user"); assert.equal(mine.suggest, true); assert.equal(mine.at, q1.sentNote.at); assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); before = userCount(); assert.equal((await post("/submit", { actions: [{ i: "q1", type: "comment", text: "", suggest: "yes" }], reply: "z" })).status, 200); q1 = readState().items.find((i) => i.id === "q1"); assert.equal("suggest" in q1.sentNote, false, "only true is kept"); assert.equal(userCount(), before, "a plain empty comment still adds no thread entry"); assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0); }); test("what the person attached is not scanned for markers either", () => { const statePath = path.join(HOME, "sessions", sid, "state.json"); const state = JSON.parse(fs.readFileSync(statePath, "utf8")); state.items.find((i) => i.id === "q1").sentNote = { at: new Date().toISOString(), text: "TASK_COMPLETE Risk 3" }; fs.writeFileSync(statePath, JSON.stringify(state, null, 2)); const res = cli(["post", "--session", sid, "--file", payload("after2.json", { headline: { stage: "Working" } })]); assert.equal(res.status, 0); }); test("cancel surfaces as exit 30", async () => { await post("/cancel", {}); const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 30); }); /* ------------------------------------------------------------ guardrails */ test("rejects more than three open required questions", () => { const many = { items: [1, 2, 3, 4].map((n) => ({ id: "x" + n, kind: "text", title: "Question " + n, body: "b" })), }; const res = cli(["post", "--session", sid, "--file", payload("many.json", many)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /open at once/); }); test("rejects internal vocabulary in a title", () => { const p = { items: [{ id: "j1", kind: "text", title: "Frontier grill posture", body: "b", required: false }] }; const res = cli(["post", "--session", sid, "--file", payload("jargon.json", p)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /internal vocabulary/); }); // Menu options carry `text`, verdicts carry `label`. An agent that crosses // them used to get a sign-off card with blank buttons, so the post is refused // with the fix spelled out. test("rejects a review verdict with no label", () => { const p = { items: [ { id: "v1", kind: "review", title: "Approve the tech stack", verdicts: [ { id: "approve", text: "Approve the tech stack" }, { id: "changes", label: "Needs changes" }, ], required: false, }, ], }; const res = cli(["post", "--session", sid, "--file", payload("verdict.json", p)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /verdict "approve" needs a "label"/); assert.doesNotMatch(res.stderr, /verdict "changes"/); }); test("rejects a choice option with no text", () => { const p = { items: [ { id: "o1", kind: "choice", title: "Where should we go next", options: [ { k: "A", label: "Reproduce first", desc: "Run it" }, { k: "B", text: "Plan the fixes", detail: "Write a plan" }, ], required: false, }, ], }; const res = cli(["post", "--session", sid, "--file", payload("option.json", p)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /option "A" needs "text"/); assert.doesNotMatch(res.stderr, /option "B"/); }); test("rejects loop completion markers and metrics-scraper bait", () => { const p = { items: [{ id: "j2", kind: "text", title: "Coverage", body: "Requirements 22 of 25. TASK_COMPLETE", required: false }], }; const res = cli(["post", "--session", sid, "--file", payload("bait.json", p)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /completion marker/); assert.match(res.stderr, /metrics collector/); }); // Those two scans read agent-authored text. A person who happens to type // "TASK_COMPLETE" into an answer must not wedge the session by making every // later patch unpostable. test("what the person typed is not scanned for markers", () => { const dir = path.join(HOME, "sessions", sid); const statePath = path.join(dir, "state.json"); const state = JSON.parse(fs.readFileSync(statePath, "utf8")); state.items.find((i) => i.id === "q1").submitted = { at: new Date().toISOString(), text: "Risk 3 if this is not done before TASK_COMPLETE", }; fs.writeFileSync(statePath, JSON.stringify(state, null, 2)); const res = cli(["post", "--session", sid, "--file", payload("after.json", { headline: { stage: "Working" } })]); assert.equal(res.status, 0); }); test("rejects two recommended options", () => { const p = { items: [ { id: "j3", kind: "choice", title: "Storage", body: "b", required: false, options: [ { k: "A", text: "one", recommended: true }, { k: "B", text: "two", recommended: true }, ], }, ], }; const res = cli(["post", "--session", sid, "--file", payload("recs.json", p)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /recommended/); }); test("rejects a second authoritative gate", () => { const p = { items: [ { id: "g1", kind: "review", title: "Sign off A", body: "b", required: false, gate: { id: "a", authoritative: true } }, { id: "g2", kind: "review", title: "Sign off B", body: "b", required: false, gate: { id: "b", authoritative: true } }, ], }; const res = cli(["post", "--session", sid, "--file", payload("gates.json", p)], { expectFail: true }); assert.equal(res.status, 3); assert.match(res.stderr, /authoritative approval gates/); }); test("a rejected patch leaves the state untouched", () => { const before = fs.readFileSync(path.join(session, "state.json"), "utf8"); cli(["post", "--session", sid, "--file", payload("many2.json", { items: [1, 2, 3, 4, 5].map((n) => ({ id: "y" + n, kind: "text", title: "Q" + n, body: "b" })), })], { expectFail: true }); assert.equal(fs.readFileSync(path.join(session, "state.json"), "utf8"), before); }); test("rejects __proto__ in a patch", () => { const p = path.join(HOME, "proto.json"); fs.writeFileSync(p, '{"agent":{"__proto__":{"polluted":true}}}'); const res = cli(["post", "--session", sid, "--file", p], { expectFail: true }); assert.notEqual(res.status, 0); assert.equal({}.polluted, undefined); }); /* --------------------------------------------------------------- merge */ test("patches merge by id and append threads", () => { cli(["post", "--session", sid, "--file", payload("merge.json", { items: [{ id: "q1", status: "answered", thread: [{ who: "agent", text: "noted" }] }], })]); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); const q1 = state.items.find((i) => i.id === "q1"); assert.equal(q1.status, "answered"); assert.equal(q1.title, "Export format", "untouched fields survive a merge"); const replies = q1.thread.filter((m) => m.who === "agent"); assert.equal(replies.length, 1); assert.ok(replies[0].at, "the server stamps the time the agent left out"); }); test("finish.changelog is accepted on quick-task and finalize, and refused on implement and on a non-boolean", () => { const problems = (workflow, changelog, headline = "Done") => validate({ workflow, items: [], finish: { headline, command: "git add -A", commit: true, changelog } }); for (const workflow of ["quick-task", "finalize"]) assert.deepEqual(problems(workflow, true), [], workflow); assert.match(problems("implement", true).join(), /only for a finished quick-task or finalize/); assert.match(problems("implement-review", true).join(), /only for a finished quick-task or finalize/); assert.match(problems("quick-task", "yes").join(), /must be true or false/); // false is always fine, and a pause ignores it assert.deepEqual(problems("implement", false), []); assert.deepEqual(problems("implement", true, "Paused at Phase 2"), []); }); // Update CHANGELOG first is a hop like Commit it now, into Changelog. test("a changelog request from a finished screen carries the resume into the changelog workflow and its skill file", async () => { await post("/submit", { actions: [{ i: "__changelog", type: "changelog" }], reply: "Update the CHANGELOG before I commit: open Changelog, right here in this session.", }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__changelog"); assert.match(res.json.resume, /--no-open --workflow changelog$/); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__changelog"), "a changelog request must not become a question"); }); test("a thread reply in another shape is lifted into { who, text }, and an empty one is refused", () => { const base = { items: [{ id: "n1", kind: "text", title: "Name", status: "open", thread: [{ who: "user", text: "why?", at: "2026-10-05T10:00:00Z" }] }] }; const next = applyPatch(base, { items: [{ id: "n1", thread: [ { from: "agent", md: "Because." }, { role: "assistant", content: "Also this." }, { who: "user", text: "why?" }, ] }], }); const thread = next.items[0].thread; assert.deepEqual(thread.map((m) => [m.who, m.text]), [["user", "why?"], ["agent", "Because."], ["agent", "Also this."]], "aliases lifted, and the echoed note is not shown twice"); assert.equal(thread[1].md, undefined); assert.equal(thread[1].from, undefined); assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent" }] }] }), /an entry has no "text"/); assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent", md: " " }] }] }), /no "text"/); }); test("the page reads older { from, md } thread entries", () => { assert.equal(threadWho({ from: "agent", md: "x" }), "agent"); assert.equal(threadWho({ who: "user", text: "x" }), "user"); assert.equal(threadText({ from: "agent", md: "Older shape." }), "Older shape."); assert.equal(threadText({ who: "agent", text: "Now." }), "Now."); assert.equal(threadText({ who: "agent" }), ""); }); /* --------------------------------- output shape at each exit code (FR-1 to FR-3) */ test("the shape of every exit: 0 for an answer and a launch, 10, 30, 3 and 2", async (t) => { const opened = cli(["open", "--file", payload("shape-open.json", BASE), "--no-open"]); const s = opened.json; // open names the link; the very next post and wait do not repeat it. assert.equal(typeof s.terminalLine, "string"); assert.ok(s.terminalLine.length > 0); const m = s.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//); const sendTo = (pathname, body) => fetch(m[1] + pathname, { method: "POST", headers: { "content-type": "application/json", cookie: cookieFor(m[1], m[2]), connection: "close" }, body: JSON.stringify(body), }); try { await t.test("post prints only ok and open, no terminalLine", () => { const res = cli(["post", "--session", s.sid, "--file", payload("shape-post.json", { headline: { stage: "Working" } })]); assert.deepEqual(Object.keys(res.json).sort(), ["ok", "open"]); }); await t.test("exit 10 is {waiting, open} and nothing else", () => { const res = cli(["wait", "--session", s.sid, "--seconds", "5"]); assert.equal(res.status, 10); assert.deepEqual(res.json, { waiting: true, open: 1 }); }); await t.test("exit 0 for an answer: reply only, the rest stays in result.json", async () => { assert.equal((await sendTo("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }], reply: "Export format: b" })).status, 200); const res = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.deepEqual(res.json, { reply: "Export format: b" }); const kept = JSON.parse(fs.readFileSync(path.join(s.session, "result.json"), "utf8")); for (const k of ["type", "at", "sid", "rev", "consumedAt", "actions"]) assert.ok(k in kept, `result.json keeps ${k}`); }); await t.test("exit 0 for a launch carries the session action whole, with resume", async () => { const send = { actions: [{ i: "__launch", type: "launch", skill: "plan2code-3-implement", workflow: "implement" }], reply: "Start Implement." }; assert.equal((await sendTo("/submit", send)).status, 200); const res = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(res.status, 0); assert.equal(res.json.session[0].i, "__launch"); assert.match(res.json.resume, /--no-open --workflow implement$/); assert.equal(res.json.actions, undefined); assert.equal(res.json.terminalLine, undefined, "the link is not repeated"); }); await t.test("exit 30 for a cancel", async () => { await sendTo("/cancel", {}); const res = cli(["wait", "--session", s.sid, "--seconds", "5"]); assert.equal(res.status, 30); }); await t.test("exit 3 names the item id, the field and a way to do it right", () => { const bad = { items: [{ id: "bad1", kind: "choice", title: "Pick", options: [{ k: "A", label: "x" }] }] }; const res = cli(["post", "--session", s.sid, "--file", payload("shape-bad.json", bad)], { expectFail: true }); assert.equal(res.status, 3); assert.equal(res.stdout.trim(), ""); assert.match(res.stderr, /bad1/); assert.match(res.stderr, /options/); assert.match(res.stderr, /Like this:/); }); await t.test("exit 2 gives the line, column and a caret for a cut-off patch", () => { const file = path.join(HOME, "shape-cut.json"); fs.writeFileSync(file, '{\n "headline": { "stage": "Working"\n'); const res = cli(["post", "--session", s.sid, "--file", file], { expectFail: true }); assert.equal(res.status, 2); assert.match(res.stderr, /line \d+, column \d+/); assert.match(res.stderr, /\^/); }); } finally { cli(["stop", "--session", s.sid, "--force"]); } }); test("exit 20 is {gone, fix} naming the session, and a resume to a restarted server prints the link again", () => { const opened = cli(["open", "--file", payload("shape-gone.json", BASE), "--no-open"]); const sid2 = opened.json.sid; assert.equal(typeof opened.json.terminalLine, "string"); cli(["stop", "--session", sid2, "--force"]); const gone = cli(["wait", "--session", sid2, "--seconds", "5"]); assert.equal(gone.status, 20); assert.deepEqual(gone.json, { gone: true, fix: `open --resume ${sid2} --workflow ` }); const again = cli(["open", "--resume", sid2, "--no-open"]); try { assert.notEqual(again.json.url, opened.json.url, "a restart has a new link"); assert.equal(typeof again.json.terminalLine, "string", "the new link is printed again"); const post = cli(["post", "--session", sid2, "--file", payload("shape-after.json", { headline: { stage: "Working" } })]); assert.equal(post.json.terminalLine, undefined, "and not again on the next post"); } finally { cli(["stop", "--session", sid2, "--force"]); } });