// Tests for the web console. Run with: node --test scripts/test-web-console.mjs
//
// Lives in scripts/ rather than src/web-console/ on purpose: everything under
// src/web-console/ is copied verbatim into two skills, and tests should not ship.
//
// PLAN2CODE_PICKER_ECHO (tests only, beside PLAN2CODE_NO_BROWSER): when set
// in the server's environment, /workspace/browse returns it as the picked
// folder instead of opening a picker, and "-" as a cancelled one.
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 { execFileSync, spawn, spawnSync } from "node:child_process";
import { EventEmitter } from "node:events";
import http from "node:http";
import { PassThrough } from "node:stream";
import { fileURLToPath } from "node:url";
// 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 {
ALL_DONE_LEAD,
ALL_DONE_REST,
answerLines,
APPROVAL_HINT,
APPROVAL_HINT_MS,
APPROVAL_TIP,
approvalHint,
attachmentKind,
DOC_TYPES,
docExt,
formatBytes,
IMAGE_LONG_EDGE,
MAX_ATTACHMENTS,
MAX_DOC_BYTES,
pickerAccept,
sortAttachments,
briefPhrase,
cardAvailability,
cardPresentation,
CATALOG_GROUPS,
CONTINUE_IN_CONSOLE,
choiceAnswer,
CONSOLE_WORKFLOWS,
DASHBOARD_COMMAND,
DASHBOARD_NOTE,
DASHBOARD_REPLY,
dashboardOffer,
DONE_REPLY,
finishPaused,
fitWithin,
handoffShape,
handoffText,
HOME_REPLY,
homeButtonState,
launchReply,
MAX_NOTE_IMAGES,
noteAction,
noteReplyLines,
progressTotal,
staleLaunchFeedback,
quietLimitMs,
recordedAnswer,
resumeCommand,
REVIEW_REPLY,
reviewOffer,
SKILL_CATALOG,
SPEC_STATE_LABELS,
STALE_MS,
START_POSES,
startPose,
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
suggestionFrom,
turnGate,
verdictLabel,
verdictText,
lastOpenCard,
nextOpenAfter,
} from "../src/web-console/public/answers.js";
import {
CHAT_LAST_WAIT_TEXT,
CHAT_LIMIT,
CHAT_LIMIT_TEXT,
CHAT_MAX_CHARS,
CHAT_OFFLINE_TEXT,
CHAT_WAITING_TEXT,
CHAT_WORKING_TEXT,
chatOffline,
chatView,
contextOptions,
newestReplyId,
nextAbout,
sendState as chatSendState,
shouldChime,
unreadDot,
} from "../src/web-console/public/chat.js";
import {
ACCENTS,
CARD_WIDTHS,
cardWidth,
DEFAULT_ACCENT,
DEFAULT_CARD_WIDTH,
SOUND_EVENTS,
soundKey,
soundPrefs,
} from "../src/web-console/public/palette.js";
import { activityLabel, BUILD_WORKFLOWS, taskLabel, workingLine } from "../src/web-console/public/labels.js";
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js";
import {
needsRoleNudge,
normalizeRole,
ROLE_NOT_SET,
ROLES,
STARTER_SET_FOR,
STARTER_SETS,
startersFor,
TEMPLATE_ORDERS,
TEMPLATE_WORKFLOWS,
TEMPLATES,
templatesFor,
templateSwap,
} from "../src/web-console/public/starters.js";
import {
changeLine,
defaultName,
FOOTER_TIERS,
footerLabel,
freeName,
NAME_MAX,
nameProblem,
} from "../src/web-console/public/workspace.js";
import {
levelFor,
breakdownFrom,
meterView,
pointsFrom,
RED_AT,
ANSWERS_PER_POINT,
ringFraction,
runPoints,
tooltipFor,
WEIGHTS,
YELLOW_AT,
} from "../src/web-console/public/meter.js";
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
import { runHint } from "../src/web-console/public/render.js";
import { pickerCommand, pickFolder, WINDOWS_PICKER_SOURCE, WORKSPACE_PICKER_PROMPT } from "../src/web-console/picker.mjs";
import {
appendLedger,
attachmentName,
bindLoopback,
chatReplyLines,
checkDocument,
cwdHash,
handOff,
initialWorkspace,
parseArgs,
pendingWorkspaceChanges,
PROTECTED_CONSOLE_FILES,
readChat,
readLedger,
readWorkspaceCursor,
readOverview,
removeScratch,
removeSessions,
repoRoots,
scanProject,
SESSION_MAX_AGE_MS,
SPEC_STATES,
staleScratch,
staleSessions,
STATE_LOCK_FILE,
sweepUploads,
terminalLine,
UPLOAD_MAX_AGE_MS,
validate,
WORKSPACE_FILE,
writeWorkspaceCursor,
} from "../src/web-console/lib.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
const MODELS_DIR = path.join(HOME, "plan2code");
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1" };
// The session cookie is named for the server's port: browsers ignore the port
// when they scope a cookie, so one shared name let each session's server
// overwrite the one before it.
function cli(args, { expectFail = false, env, cwd = ROOT } = {}) {
const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], {
env: env ? { ...ENV, ...env } : ENV,
encoding: "utf8",
cwd,
});
if (!expectFail && res.status !== 0 && res.status !== 10 && res.status !== 20 && res.status !== 30) {
throw new Error(`console ${args.join(" ")} failed (${res.status}): ${res.stderr}`);
}
return { ...res, json: safeJson(res.stdout) };
}
async function post(pathname, body) {
for (let attempt = 0; attempt < 3; attempt++) {
try {
return await fetch(baseUrl + pathname, {
method: "POST",
headers: { "content-type": "application/json", cookie: consoleCookie(baseUrl, token), connection: "close" },
body: JSON.stringify(body ?? {}),
});
} catch (err) {
if (attempt === 2) throw err;
}
}
}
// The session cookie is named per port, so two consoles on 127.0.0.1 keep
// their own; a request has to carry the one for the server it is talking to.
function consoleCookie(base, tok) {
return `p2c_console_${new URL(base).port}=${tok}`;
}
function safeJson(s) {
const line = String(s).trim().split("\n").filter(Boolean).pop();
try {
return JSON.parse(line);
} catch {
return null;
}
}
function payload(file, obj) {
const p = path.join(HOME, file);
fs.writeFileSync(p, JSON.stringify(obj));
return p;
}
const BASE = {
workflow: "pathfinder",
title: "Test session",
items: [
{
id: "q1",
kind: "choice",
title: "Export format",
body: "Pick one.",
options: [
{ k: "A", text: "CSV", recommended: true },
{ k: "B", text: "Excel" },
],
token: { A: "a", B: "b" },
},
],
agent: { status: "waiting" },
};
let sid;
let session;
let baseUrl;
let 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/);
// Named for this server's port: cookies ignore ports, so one shared name let
// a second console overwrite the first one's cookie.
assert.ok(res.headers.get("set-cookie").startsWith(`p2c_console_${new URL(baseUrl).port}=${token};`));
});
test("another console's cookie beside ours does not lock this one out", async () => {
const port = Number(new URL(baseUrl).port);
const other = `p2c_console_${port + 1}=someone-else`;
const both = await fetch(baseUrl + "/state", { headers: { cookie: `${other}; ${consoleCookie(baseUrl, token)}` } });
assert.equal(both.status, 200);
await both.arrayBuffer();
const theirsOnly = await fetch(baseUrl + "/state", { headers: { cookie: other } });
assert.equal(theirsOnly.status, 403);
await theirsOnly.arrayBuffer();
// The old shared name is no longer honoured.
const legacy = await fetch(baseUrl + "/state", { headers: { cookie: `p2c_console=${token}` } });
assert.equal(legacy.status, 403);
await legacy.arrayBuffer();
});
test("the page is served with a CSP that forbids inline script", async () => {
const res = await fetch(baseUrl + "/", { headers: { cookie: consoleCookie(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'"));
});
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.equal(res.json.status, "waiting");
assert.equal(res.json.total, 1);
});
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.type, "submit");
assert.equal(res.json.reply, "Export format: b");
assert.equal(res.json.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.actions[0].type, "brief");
assert.equal(res.json.actions[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.actions[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.actions[0].i, "__launch");
assert.equal(res.json.actions[0].skill, "plan2code-3-implement");
assert.equal(res.json.actions[0].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");
});
// 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.actions, [{ i: "__dashboard", type: "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 send any message. 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);
const frame = new Promise((resolve, reject) => {
const req = http.request(
{ host: "127.0.0.1", port, path: "/events", method: "GET", headers: { cookie: consoleCookie(baseUrl, token) } },
(res) => {
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 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.actions.map((a) => a.type),
["answer", "stop"],
"the answers and the stop arrive together"
);
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.actions.map((a) => a.type), ["answer", "dashboard"], "the answers and the way home arrive together");
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 app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
const css = fs.readFileSync(path.join(dir, "app.css"), "utf8");
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");
assert.ok(app.includes('{ i: "__dashboard", type: "dashboard" }'), "the confirm sends __dashboard");
assert.ok(app.includes("stagedPayload()") && app.includes("HOME_REPLY"), "the staged answers ride along with the reply line");
});
test("the way home cannot be mistaken for a brief request", () => {
assert.doesNotMatch(HOME_REPLY, /\b(brief|recap|minutes)\b/i);
});
test("console.md, building.md and the dashboard prompt teach the mid-workflow way home", () => {
const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8");
const consoleMd = read("src", "web-console", "console.md");
assert.ok(consoleMd.includes("### Back to the dashboard, mid-workflow"));
assert.ok(consoleMd.includes(HOME_REPLY), "console.md quotes the reply line the agent will see");
assert.match(consoleMd, /No `finish` and no `stop` in between/);
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"));
});
// 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"]);
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".js"))) {
const src = fs.readFileSync(path.join(dir, f), "utf8");
for (const m of src.matchAll(/^\s*import\b[^"']*["']\.\/([^"']+)["']/gm)) wanted.add(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: consoleCookie(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: consoleCookie(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: consoleCookie(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: consoleCookie(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: consoleCookie(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(), /^