// 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(), /^