// 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,
GIT_CLEAN_REASON,
GIT_INIT_NOTE,
handoffShape,
handoffText,
HOME_REPLY,
homeButtonState,
launchReply,
MAX_NOTE_IMAGES,
noteAction,
noteReplyLines,
progressTotal,
staleLaunchFeedback,
quietLimitMs,
recordedAnswer,
resumeCommand,
REVIEW_REPLY,
commitOffer,
pendingNote,
reviewOffer,
SKILL_CATALOG,
SPEC_STATE_LABELS,
STALE_MS,
START_POSES,
startPose,
STOP_REPLY,
sentAnswer,
submittedAwaiting,
noteAwaiting,
threadText,
threadWho,
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,
progressEntry,
RED_AT,
ANSWERS_PER_POINT,
ringFraction,
runPoints,
tooltipFor,
WEIGHTS,
YELLOW_AT,
} from "../src/web-console/public/meter.js";
import {
blockFor,
CHECKIN_LINE,
checkHelper,
checkHelpers,
cleanSetting,
defaultInstruction,
defaultSetting,
effectiveInstruction,
FRAME_LINES,
helperRows,
offered,
offLine,
showSwitch,
showTab,
SUBAGENT_WORKFLOWS,
switchLabel,
} from "../src/web-console/public/subagents.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 { CACHE_MS, RELEASES_URL, REPO_URL, checkForUpdate, compareVersions, latestTag } from "../src/web-console/update-check.mjs";
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,
applyPatch,
attachmentName,
bindLoopback,
chatReplyLines,
checkDocument,
cleanupFindings,
cwdHash,
handOff,
initialWorkspace,
insideGitRepo,
pendingFiles,
latestOpenCaps,
parseArgs,
pendingWorkspaceChanges,
PROTECTED_CONSOLE_FILES,
readChat,
readLedger,
readSubagentCursor,
readSubagentSetting,
readWorkspaceCursor,
resetSubagentCursor,
writeSubagentCursor,
writeSubagentSetting,
readOverview,
removeCleanup,
removeScratch,
removeSessions,
repoRoots,
scanProject,
SESSION_MAX_AGE_MS,
SPEC_STATES,
staleScratch,
STRAY_GRACE_MS,
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" };
// Every server these tests start runs the release check at boot. A fresh
// cached failure keeps the whole suite off the network and bannerless.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
// 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(), /^]*viewBox="0 0 32 32"/);
const res = await fetch(`${baseUrl}/favicon.png`, { headers: { cookie: consoleCookie(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: consoleCookie(baseUrl, token) } })).text();
assert.ok(html.includes('href="/favicon.svg"'));
assert.ok(html.includes('href="/favicon.png"'));
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
});
// Each skill's starting and waiting screens clone its pose from index.html.
// A pose with no drawing silently falls back to the flight, and a style
// attribute in one would be refused by the CSP, so hold the markup to the list.
test("every skill has a pose drawn in the page, with no inline styles", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const tpl = html.match(/([\s\S]*?)<\/template>/);
assert.ok(tpl, "index.html has the start-poses template");
const drawn = [...tpl[1].matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
assert.deepEqual(drawn.sort(), [...START_POSES].sort());
assert.doesNotMatch(tpl[1], /\sstyle=/);
for (const pose of START_POSES) {
assert.ok(SKILL_CATALOG.some((e) => e.workflow === pose), `${pose} is a real workflow`);
assert.equal(startPose(pose), pose);
}
assert.equal(startPose("implement-review"), "implement");
assert.equal(startPose("revise-plan"), "plan");
assert.equal(startPose("init-update"), "init");
for (const e of SKILL_CATALOG) assert.ok(startPose(e.workflow), `${e.workflow} has a pose`);
assert.equal(startPose("dashboard"), null);
assert.equal(startPose(undefined), null);
});
/* ---------------------------------------------------------------- help */
const helpTemplate = () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const tpl = html.match(/([\s\S]*?)<\/template>/);
assert.ok(tpl, "index.html has the help-content template");
return tpl[1];
};
test("help: 17 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 17);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 17);
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
});
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 labelled 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 = res.json.actions.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("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("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" }] }] }), /thread 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" }), "");
});
/* ------------------------------------------- result handoff (regressions) */
test("a second submit is refused while the first is uncollected", async () => {
// Two tabs, or one impatient second press. Overwriting here silently
// destroyed whatever was in the first batch, including an approval verdict.
const first = await post("/submit", {
actions: [{ i: "q1", type: "answer", kind: "choice", k: "A" }],
reply: "Export format: a",
});
assert.equal(first.status, 200);
const second = await post("/submit", {
actions: [{ i: "q1", type: "answer", kind: "text", text: "second" }],
reply: "Export format: second",
});
assert.equal(second.status, 409, "the server must refuse, not overwrite");
const got = cli(["wait", "--session", sid, "--seconds", "10"]);
assert.equal(got.status, 0);
assert.equal(got.json.reply, "Export format: a", "the FIRST batch must survive");
});
test("the page is told a send is still uncollected", async () => {
await post("/submit", { actions: [{ i: "q1", type: "answer", kind: "text", text: "x" }], reply: "r" });
const res = await fetch(baseUrl + "/state", { headers: { cookie: consoleCookie(baseUrl, token) } });
const body = await res.json();
assert.equal(body.pendingResult, true, "the client needs this to disable Send");
// The opening frame of the stream has to say so too. A reconnecting tab that
// learns it from /state but not from /events briefly believes its last
// answers have been dealt with, and unlocks the question it just sent.
const first = await firstStateEvent();
assert.equal(first.pendingResult, true, "the first SSE frame must carry it as well");
cli(["wait", "--session", sid, "--seconds", "10"]);
});
// Read the stream up to its first `state` frame, then hang up.
function firstStateEvent() {
const port = Number(new URL(baseUrl).port);
return 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: state\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 state frame within 5s"));
});
req.end();
});
}
test("open --resume never discards an uncollected result", async () => {
// The documented crash-recovery path: the agent dies, the person presses
// Send anyway, a fresh session resumes. Deleting here destroyed their work.
await post("/submit", {
actions: [{ i: "q1", type: "answer", kind: "text", text: "TWENTY MINUTES OF WORK" }],
reply: "Export format: TWENTY MINUTES OF WORK",
});
const reopened = cli(["open", "--resume", sid, "--no-open"]);
assert.equal(reopened.json.ok, true);
assert.equal(reopened.json.pendingResult, true, "open must report the waiting result");
const got = cli(["wait", "--session", sid, "--seconds", "10"]);
assert.equal(got.status, 0);
assert.equal(got.json.reply, "Export format: TWENTY MINUTES OF WORK");
});
test("open clears a result that was already collected", () => {
const before = cli(["open", "--resume", sid, "--no-open"]);
assert.equal(before.json.pendingResult, false);
const res = cli(["wait", "--session", sid, "--seconds", "3"]);
assert.equal(res.status, 10, "a consumed result must not be handed over again");
});
// A paused finish is a bookmark: `open --resume` picks the session up, so the
// bookmark comes down with it -- left in place, the page says PAUSED over
// every question the resumed session asks. So do the questions left open at
// the pause: whatever the new session still needs it asks again, and kept
// leftovers sit beside the new asks as duplicates nobody owns. A real ending
// survives untouched, so re-sharing a finished session's link still shows
// its card.
test("open --resume takes a pause down, and only a pause", () => {
const stateFile = path.join(session, "state.json");
const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8"));
cli(["post", "--session", sid, "--file", payload("fin-pause.json", {
topics: [{ id: "t-stale", title: "Stale section" }],
items: [{ id: "q-stale", topic: "t-stale", kind: "text", title: "Left mid-way", body: "Still open at the pause." }],
finish: { headline: "Paused — your answers so far are saved", command: "/plan2code-1-plan" },
})]);
assert.ok(readState().finish, "the pause was posted");
cli(["open", "--resume", sid, "--no-open"]);
const resumed = readState();
assert.equal(resumed.finish, undefined, "resuming clears a paused finish");
assert.equal(resumed.items.some((i) => i.id === "q-stale"), false, "questions left open at the pause come down with it");
assert.equal(resumed.topics.some((t) => t.id === "t-stale"), false, "and the section only they lived under");
assert.equal(resumed.items.find((i) => i.id === "q1").status, "answered", "settled items are the record and stay");
cli(["post", "--session", sid, "--file", payload("fin-done.json", {
finish: { headline: "The map is written", command: "/plan2code-2-document" },
})]);
cli(["open", "--resume", sid, "--no-open"]);
assert.equal(readState().finish.headline, "The map is written", "resuming keeps a real ending");
// Leave the session the way later tests expect to find it.
cli(["post", "--session", sid, "--file", payload("fin-clear.json", { finish: null })]);
});
// The dashboard hands its live session to the skill it launched: one
// `open --resume` turns the page (workflow, title, spec) while reusing the
// server. If the flags did not apply on resume, the launched skill would
// either strand the page or have to make a second call to turn it.
test("open --resume restates workflow, title and spec on the live session", () => {
const stateFile = path.join(session, "state.json");
const snapshot = fs.readFileSync(stateFile, "utf8");
const before = JSON.parse(snapshot);
assert.equal(before.workflow, "pathfinder");
const res = cli(["open", "--resume", sid, "--no-open", "--workflow", "implement", "--title", "Lunch vote: Phase 2", "--spec", "specs/lunch-vote"]);
assert.equal(res.json.ok, true);
assert.equal(res.json.sid, sid);
assert.equal(res.json.reused, true, "the live server must be reused, not replaced");
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.workflow, "implement");
assert.equal(state.title, "Lunch vote: Phase 2");
assert.equal(state.specDir, "specs/lunch-vote");
// And flags left off a later resume leave the fields alone.
cli(["open", "--resume", sid, "--no-open"]);
const still = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(still.workflow, "implement", "no --workflow means keep the one the launch set");
// Put it back for the tests that follow: the switch blanked the session.
fs.writeFileSync(stateFile, snapshot);
});
// Plan -> Back to the dashboard -> Document used to show Plan's questions,
// sections and doc tabs under Document's name: the resume only renamed the
// workflow. A switch through the dashboard is a fresh start, so it is blank.
test("open --resume through the dashboard starts the next skill on a clean page", () => {
const stateFile = path.join(session, "state.json");
const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8"));
const draftFile = path.join(session, "draft.json");
const snapshot = fs.readFileSync(stateFile, "utf8");
cli(["post", "--session", sid, "--file", payload("wf-plan.json", {
workflow: "plan",
title: "Planny mood board",
specDir: "specs/mood-board",
headline: { stage: "Planning", cleared: 21, total: 21, note: "Writing the plan" },
topics: [{ id: "t-plan", title: "The drawings" }],
items: [{ id: "q-plan", topic: "t-plan", kind: "text", title: "Write the plan", body: "Ready?" }],
docs: [{ id: "techspec", title: "Technical spec", blocks: [{ id: "b", state: "settled", md: "# Spec" }] }],
menu: { note: "stale" },
stopWarning: "",
finish: { headline: "The plan is written", dashboard: true },
})]);
fs.writeFileSync(draftFile, JSON.stringify({ staged: { "q-plan": { text: "yes" } } }));
const before = readState();
cli(["open", "--resume", sid, "--no-open", "--workflow", "dashboard"]);
const dash = readState();
assert.equal(dash.workflow, "dashboard");
assert.equal(dash.sid, before.sid, "the session itself carries across");
assert.equal(dash.created, before.created);
assert.deepEqual(dash.items, [], "no questions from the last skill");
assert.deepEqual(dash.topics, []);
assert.deepEqual(dash.docs, [], "no doc tabs from the last skill");
assert.equal(dash.finish, undefined, "no ending from the last skill");
assert.equal(dash.menu, undefined);
assert.equal(dash.stopWarning, undefined);
assert.equal(dash.headline.cleared, 0);
assert.equal(dash.specDir, "");
assert.notEqual(dash.title, "Planny mood board", "the title falls back to the folder, like a fresh open");
assert.ok(dash.scan, "the dashboard still gets its scan");
assert.equal(fs.existsSync(draftFile), false, "a draft staged against the old questions is dropped");
cli(["post", "--session", sid, "--file", payload("wf-dash-menu.json", { menu: { note: "fresh" } })]);
cli(["open", "--resume", sid, "--no-open", "--workflow", "document", "--spec", "specs/mood-board", "--title", "Document: Planny mood board"]);
const doc = readState();
assert.equal(doc.workflow, "document");
assert.equal(doc.title, "Document: Planny mood board");
assert.equal(doc.specDir, "specs/mood-board");
assert.equal(doc.menu, undefined, "the dashboard's menu does not follow the launch");
assert.deepEqual(doc.items, []);
// The same workflow again (a reconnect) keeps everything.
cli(["post", "--session", sid, "--file", payload("wf-doc-q.json", {
items: [{ id: "q-doc", kind: "text", title: "Which draft", body: "Pick one." }],
})]);
cli(["open", "--resume", sid, "--no-open", "--workflow", "document"]);
assert.ok(readState().items.some((i) => i.id === "q-doc"), "resuming the same workflow is not a switch");
cli(["open", "--resume", sid, "--no-open"]);
assert.ok(readState().items.some((i) => i.id === "q-doc"), "nor is a resume with no --workflow");
// A skill run inline from another (a quick task's Review it now) never
// passes the dashboard: it takes the page over with everything on it.
cli(["post", "--session", sid, "--file", payload("wf-qt.json", {
workflow: "quick-task",
docs: [{ id: "qt-notes", title: "What changed", blocks: [{ id: "b", state: "settled", md: "# Diff" }] }],
})]);
cli(["open", "--resume", sid, "--no-open", "--workflow", "review"]);
const inline = readState();
assert.equal(inline.workflow, "review");
assert.ok(inline.items.some((i) => i.id === "q-doc"), "an inline switch keeps the questions");
assert.ok(inline.docs.some((d) => d.id === "qt-notes"), "and the docs");
assert.equal(inline.title, "Document: Planny mood board", "and the title");
fs.writeFileSync(stateFile, snapshot);
});
// The dashboard's one payload field has to survive validation: a patch
// carrying `menu` is agent-authored text the page renders, not a question.
test("the menu payload lands on the state the dashboard page reads", () => {
const menu = {
note: "AGENTS.md is missing — start with setup.",
recommend: "plan2code-init",
details: { "plan2code-3-implement": "Phase 2 of 4 is next" },
};
const res = cli(["post", "--session", sid, "--file", payload("menu.json", { menu })]);
assert.equal(res.json.ok, true);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.deepEqual(state.menu, menu);
});
// `saved` is how the page knows a doc is already a file on disk and drops the
// download button for the path instead; it has to survive the doc merge.
test("a doc's saved path lands on the state the page reads", () => {
const res = cli([
"post",
"--session",
sid,
"--file",
payload("saved-doc.json", {
docs: [
{
id: "agents",
title: "AGENTS.md",
saved: "AGENTS.md",
blocks: [{ id: "b1", state: "settled", md: "# Lunch picker\n\n..." }],
},
],
}),
]);
assert.equal(res.json.ok, true);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
const doc = state.docs.find((d) => d.id === "agents");
assert.equal(doc.saved, "AGENTS.md");
});
// An approval settles a proposal by patching only the blocks' states. Replacing
// `blocks` whole used to wipe every block's text and drop the ones not named,
// leaving a v2 tab with nothing on it.
test("a doc patch merges blocks by id, so settling a block keeps its text", () => {
const readDoc = () =>
JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")).docs.find((d) => d.id === "stack");
cli(["post", "--session", sid, "--file", payload("stack-v1.json", {
docs: [{
id: "stack", title: "Tech stack", version: 1, note: "Proposal",
blocks: [
{ id: "confirmed", state: "settled", md: "## Already in use" },
{ id: "proposed", state: "assumed", md: "## Proposed additions" },
{ id: "extra", state: "draft", md: "## Maybe later" },
],
}],
})]);
cli(["post", "--session", sid, "--file", payload("stack-v2.json", {
docs: [{
id: "stack", version: 2, note: "Approved",
blocks: [{ id: "proposed", state: "settled" }, { id: "extra", _delete: true }, { id: "new", state: "settled", md: "## Added" }],
}],
})]);
const doc = readDoc();
assert.equal(doc.version, 2);
assert.equal(doc.title, "Tech stack");
assert.deepEqual(doc.blocks, [
{ id: "confirmed", state: "settled", md: "## Already in use" },
{ id: "proposed", state: "settled", md: "## Proposed additions" },
{ id: "new", state: "settled", md: "## Added" },
]);
});
// The person's colors are saved by the SERVER, not the browser: localStorage
// is tied to the origin, the origin carries the ephemeral port, and the next
// session's port is different. looks.json under the console home is the copy
// that follows the app. (Runs while this test's server is still up: the forged
// -handle test below stops everything.)
test("looks round-trip through the server, and junk never reaches the file", async () => {
const get = () => fetch(baseUrl + "/looks", { headers: { cookie: consoleCookie(baseUrl, token) } });
assert.equal((await get()).status, 404, "nothing saved yet");
assert.equal((await post("/looks", { looks: { theme: "dark", accent: "cobalt" } })).status, 200);
const body = await (await get()).json();
assert.deepEqual(body.looks, { theme: "dark", accent: "cobalt" });
assert.ok(Date.parse(body.at) > 0, "the server stamps the time, the client never does");
const onDisk = JSON.parse(fs.readFileSync(path.join(HOME, "looks.json"), "utf8"));
assert.deepEqual(onDisk.looks, body.looks, "the file is what the next port reads");
// A settings file, not free storage: nested objects are stripped, and a POST
// left with nothing usable is refused rather than blanking what is saved.
assert.equal((await post("/looks", { looks: { deep: { nested: true } } })).status, 400);
assert.equal((await post("/looks", { looks: "nope" })).status, 400);
assert.equal((await post("/looks", { nope: true })).status, 400);
assert.deepEqual(
(await (await get()).json()).looks,
{ theme: "dark", accent: "cobalt" },
"a refused write must not touch what is saved"
);
});
test("a partial looks write merges onto the saved file, so a stale tab cannot undo another tab's change", async () => {
const get = async () => (await (await fetch(baseUrl + "/looks", { headers: { cookie: consoleCookie(baseUrl, token) } })).json()).looks;
assert.equal((await post("/looks", { set: { sound: false } })).status, 200);
assert.deepEqual(await get(), { theme: "dark", accent: "cobalt", sound: false });
assert.equal((await post("/looks", { set: { accent: "sky" } })).status, 200);
assert.deepEqual(await get(), { theme: "dark", accent: "sky", sound: false }, "keys this write did not name stay put");
assert.equal((await post("/looks", { set: { deep: { nested: true } } })).status, 400);
assert.deepEqual(await get(), { theme: "dark", accent: "sky", sound: false });
assert.equal((await post("/looks", { looks: { theme: "dark", accent: "cobalt" } })).status, 200);
});
test("the tab title carries the session's short id, so tabs from different agents can be told apart", async () => {
const html = await (await fetch(baseUrl + "/", { headers: { cookie: consoleCookie(baseUrl, token) } })).text();
assert.match(html, new RegExp(`[^<]* · #${sid.slice(-6)} · Plan2Code `));
});
test("models: the user's additions round-trip, XHigh and Max are refused, and the shipped list is read-only", async () => {
fs.mkdirSync(path.join(MODELS_DIR, "bin"), { recursive: true });
fs.writeFileSync(path.join(MODELS_DIR, "bin", "models.json"), JSON.stringify({ claude: [{ id: "opus", label: "Opus" }], devin: [{ id: "adaptive", label: "Adaptive" }] }));
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: consoleCookie(baseUrl, token) } })).json();
assert.deepEqual((await get()).shipped.devin, [{ id: "adaptive", label: "Adaptive" }]);
assert.deepEqual((await get()).user, { claude: [], devin: [] });
const saved = await post("/models", { models: { devin: [{ id: " new-model-medium ", label: "" }, { id: "new-model-medium" }, { id: "" }] } });
assert.equal(saved.status, 200);
assert.deepEqual((await get()).user, { claude: [], devin: [{ id: "new-model-medium", label: "new-model-medium" }] });
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(MODELS_DIR, "models.json"), "utf8")).devin.length, 1, "the launcher reads this file");
for (const id of ["some-model-xhigh", "some-model-MAX", "bad id!"]) {
assert.equal((await post("/models", { models: { devin: [{ id }] } })).status, 400, id);
}
assert.equal((await post("/models", { nope: true })).status, 400);
assert.equal((await get()).user.devin.length, 1, "a refused write must not touch what is saved");
assert.equal((await post("/models", { models: {} })).status, 200, "reset to default");
assert.deepEqual((await get()).user, { claude: [], devin: [] });
});
test("cleanup over HTTP: a scan lists strays in the console home, and a delete removes only what the scan found", async () => {
const stray = path.join(HOME, "stray-cleanup.json");
fs.writeFileSync(stray, "{}");
backdate(stray);
const res = await post("/cleanup", { scan: true });
assert.equal(res.status, 200);
const scan = await res.json();
const ids = scan.items.map((i) => i.id);
assert.ok(ids.includes("console:stray-cleanup.json"), ids.join(", "));
for (const id of ["console:looks.json", "console:update-check.json", "console:sessions", "console:runtime"]) assert.ok(!ids.includes(id), id);
assert.ok(!ids.includes("session:" + sid), "never the session serving the page");
assert.ok(scan.items.every((i) => !("path" in i)), "no paths go to the page");
assert.ok(!scan.items.some((i) => i.where === "root"), "a console from another home never reaches ~/.plan2code");
const done = await post("/cleanup", { delete: ["console:stray-cleanup.json", "console:looks.json", "session:" + sid] });
assert.equal(done.status, 200);
assert.deepEqual((await done.json()).removed, ["console:stray-cleanup.json"]);
assert.equal(fs.existsSync(stray), false);
assert.ok(fs.existsSync(path.join(HOME, "update-check.json")));
});
test("stop leaves a process it cannot identify as ours alone", () => {
// A handle file can outlive a reboot in the system temp dir and its pid can
// be reused. Killing on the strength of a number alone can hit anything.
const handleDir = path.join(HOME, "runtime");
const bucket = fs.readdirSync(handleDir)[0];
const forged = path.join(handleDir, bucket, "20000101-000000-dead99.json");
fs.writeFileSync(
forged,
JSON.stringify({
v: 1,
sid: "20000101-000000-dead99",
pid: process.pid, // this test runner: alive, but emphatically not our server
port: 1,
url: "http://127.0.0.1:1/",
startedAt: "2000-01-01T00:00:00.000Z",
})
);
// A young one too: a server that died a minute ago leaves a fresh startedAt
// behind, and its pid can already belong to something else. Being alive and
// recent is not being ours; only /health says that.
const young = path.join(handleDir, bucket, "20000101-000000-dead98.json");
fs.writeFileSync(
young,
JSON.stringify({
v: 1,
sid: "20000101-000000-dead98",
pid: process.pid,
port: 1,
url: "http://127.0.0.1:1/",
startedAt: new Date().toISOString(),
})
);
const res = cli(["stop", "--all"]);
// Still here to assert anything at all is the proof neither pid was killed.
assert.ok(res.json.skippedStaleHandles >= 2, "the unidentified handles must be skipped, not killed");
assert.equal(fs.existsSync(forged), false, "and the stale handle file cleaned up");
assert.equal(fs.existsSync(young), false, "the young one too");
});
test("a server removes its own handle file when it exits, and only its own", async () => {
const project = fs.mkdtempSync(path.join(HOME, "handle-exit-"));
const dir = fs.mkdtempSync(path.join(HOME, "handle-exit-session-"));
fs.writeFileSync(path.join(dir, "state.json"), JSON.stringify({ sid: path.basename(dir), phase: "collecting" }));
const handleDir = path.join(HOME, "runtime");
// A clean exit on request, the same on every platform: kill() on Windows is
// TerminateProcess, which runs no exit hook at all. The preload stands in
// for the idle deadline, whose process.exit() is what this hook is for.
const preload = path.join(HOME, "exit-on-message.cjs");
fs.writeFileSync(preload, 'process.on("message", (m) => { if (m === "exit") process.exit(0); });\n');
const start = () =>
new Promise((resolve, reject) => {
const child = spawn(
process.execPath,
["-r", preload, path.join(ROOT, "src", "web-console", "server.mjs"), `--session=${dir}`, "--token=t", `--project=${project}`],
{ env: ENV, stdio: ["ignore", "pipe", "ignore", "ipc"], windowsHide: true }
);
let buf = "";
child.stdout.on("data", (c) => {
buf += c;
if (buf.includes('"ready"')) resolve(child);
});
child.on("exit", () => reject(new Error("server exited before it was ready")));
});
const handleOf = () => {
for (const bucket of fs.readdirSync(handleDir)) {
const file = path.join(handleDir, bucket, path.basename(dir) + ".json");
if (fs.existsSync(file)) return file;
}
return null;
};
const stopped = (child) => new Promise((r) => (child.exitCode !== null ? r() : child.once("exit", r)));
const first = await start();
const file = handleOf();
assert.ok(file, "the server wrote its handle");
first.send("exit");
await stopped(first);
assert.equal(fs.existsSync(file), false, "an exit takes the handle with it");
// A handle rewritten by a replacement server is left alone.
const second = await start();
const mine = JSON.parse(fs.readFileSync(file, "utf8"));
fs.writeFileSync(file, JSON.stringify({ ...mine, pid: process.pid }));
second.send("exit");
await stopped(second);
assert.equal(fs.existsSync(file), true, "another process's handle survives this one's exit");
fs.rmSync(file, { force: true });
});
/* ----------------------------------------------------------- lifecycle */
test("stop shuts the server down and wait then reports exit 20", () => {
cli(["stop", "--session", sid]);
const res = cli(["wait", "--session", sid, "--seconds", "12"]);
assert.equal(res.status, 20);
assert.equal(res.json.status, "server-gone");
});
// A 127.0.0.1 link is only the person's machine if the agent is on it too.
// Reported, not refused: a forwarded port in a devcontainer works fine, so the
// agent gets told and decides.
test("open flags an environment where the link may not reach the person", () => {
const res = cli(["open", "--file", payload("remote.json", BASE), "--no-open"], {
env: { SSH_CONNECTION: "10.0.0.1 22 10.0.0.2 22" },
});
assert.equal(res.json.ok, true, "it still starts");
assert.equal(res.json.remote, "SSH_CONNECTION");
assert.match(res.json.note, /not necessarily theirs/);
cli(["stop", "--session", res.json.sid]);
});
test("the runtime dir is isolated by PLAN2CODE_CONSOLE_HOME", () => {
// Otherwise a test run's `stop --all` would reach outside its own world and
// kill a console session a developer is actually using in this repo.
const handles = path.join(HOME, "runtime");
assert.ok(fs.existsSync(handles), "handles must live under the overridden home, not the system temp dir");
});
test("resume brings the session back on a new port with state intact", async () => {
const res = cli(["open", "--resume", sid, "--no-open"]);
assert.equal(res.json.ok, true);
assert.equal(res.json.sid, sid);
assert.notEqual(res.json.url, baseUrl + `/s/${token}/`);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.items.find((i) => i.id === "q1").status, "answered");
// The port is new, the app is the same: the colors saved before the stop are
// still served, which is the whole reason they live server-side.
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
const looksRes = await fetch(m[1] + "/looks", { headers: { cookie: consoleCookie(m[1], m[2]) } });
assert.deepEqual((await looksRes.json()).looks, { theme: "dark", accent: "cobalt" });
cli(["stop", "--session", sid]);
});
/* ------------------------------------------------- the page's own logic */
// Every case below is one a placeholder is actually written in. The lead-in is
// the agent talking ABOUT the example; the example is what the person accepts.
test("a placeholder becomes an answer they could accept", () => {
const strip = (placeholder, extra) => suggestionFrom({ placeholder, ...extra });
assert.equal(strip("For example: about 8 of us."), "About 8 of us.");
assert.equal(strip("For instance, two people."), "Two people.");
assert.equal(strip("For example - about 8 of us."), "About 8 of us.");
assert.equal(strip("Such as: CSV"), "CSV");
// The abbreviations. These used to leave the punctuation behind, so the box
// filled with ". compliance reviewers" and the stray dot was theirs to spot.
assert.equal(strip("e.g. compliance reviewers."), "Compliance reviewers.");
assert.equal(strip("E.g., the finance team."), "The finance team.");
assert.equal(strip("eg. the finance team"), "The finance team");
// A lead-in has to be followed by a separator, or these lose their first word.
assert.equal(strip("Egypt office, about 8 people."), "Egypt office, about 8 people.");
assert.equal(strip("Exampled output stays put"), "Exampled output stays put");
assert.equal(strip("Say when you need it by."), "Say when you need it by.");
// A kebab-case suggestion has to survive intact, hyphens and case included,
// or it fails the `pattern` on the very field it was offered for.
assert.equal(strip("audit-export", { pattern: "^[a-z-]+$" }), "audit-export");
assert.equal(strip("example-name-here", { pattern: "^[a-z-]+$" }), "example-name-here");
assert.equal(strip(""), "");
assert.equal(strip(undefined), "");
});
test("an answer is stated back in the page's words, not the agent's shorthand", () => {
const choice = {
options: [
{ k: "A", text: "Continue without it" },
{ k: "B", text: "Run the setup first" },
],
};
assert.deepEqual(answerLines(choice, { k: "B" }), ["B · Run the setup first"]);
assert.deepEqual(answerLines(choice, { ks: ["A", "B"] }), [
"A · Continue without it",
"B · Run the setup first",
]);
assert.deepEqual(answerLines({}, { yes: false, noLabel: "Leave it" }), ["No"]);
assert.deepEqual(answerLines({ noLabel: "Leave it" }, { yes: false }), ["Leave it"]);
assert.deepEqual(answerLines({}, { verdict: "changes" }), ["I want changes"]);
assert.deepEqual(answerLines({}, { state: "blocked" }), ["I am stuck"]);
assert.deepEqual(answerLines({}, { done: [0, 2] }), ["Steps done: 1, 3"]);
assert.deepEqual(answerLines({}, { skipped: true }), ["Skipped"]);
assert.deepEqual(answerLines({}, null), []);
// Free text is shown as prose, not as a picked label.
assert.deepEqual(answerLines({}, { text: "audit-export" }), []);
});
test("what the agent recorded wins over the raw click, and either will do", () => {
assert.equal(recordedAnswer({ answer: { k: "A" } }).k, "A");
assert.equal(recordedAnswer({ submitted: { k: "B" } }).k, "B");
assert.equal(recordedAnswer({ submitted: { k: "B" }, answer: { k: "A" } }).k, "A");
// The note they sent with the click survives a narrower recorded answer.
assert.equal(recordedAnswer({ submitted: { k: "B", text: "keep the header" }, answer: { k: "A" } }).text,
"keep the header");
assert.equal(recordedAnswer({}), null);
});
// What the agent receives from a single-choice question. Picking an option and
// then writing "none of these, because..." used to send both, joined, with the
// pick first, so the answer argued with itself.
test("a single-choice answer is one thing or the other, never both", () => {
assert.deepEqual(choiceAnswer({ k: "A" }), { type: "answer", kind: "choice", k: "A" });
assert.deepEqual(choiceAnswer({ text: " neither, actually " }), {
type: "answer",
kind: "choice",
text: "neither, actually",
});
// A pick wins over stale text, and never travels with it.
assert.deepEqual(choiceAnswer({ k: "A", text: "left over in the box" }), {
type: "answer",
kind: "choice",
k: "A",
});
// Nothing to stage reads as "not answered yet", the same as everywhere else.
assert.equal(choiceAnswer({}), null);
assert.equal(choiceAnswer({ text: " " }), null);
assert.equal(choiceAnswer(), null);
});
// The exact words a brief request reaches the agent as. The Pathfinder brief
// playbook parses this range grammar, so a wording change here is a silent
// change to what gets written.
test("a brief request is phrased in the range grammar the playbook parses", () => {
assert.equal(briefPhrase("today"), "Write a brief for today.");
assert.equal(briefPhrase("this week"), "Write a brief for this week.");
assert.equal(briefPhrase("full"), "Write a full brief.");
assert.equal(
briefPhrase("since 2026-09-15"),
"Write a brief covering everything since 2026-09-15."
);
// Nothing chosen is the playbook's own default, not an empty request.
assert.equal(briefPhrase(), "Write a brief for today.");
});
// The rule that keeps a question answerable. A send carrying only a note is on
// its way, but it is not an answer, and treating it as one locks the form on a
// question the person has not answered yet.
test("a note on its own is not an answer in flight", () => {
assert.equal(sentAnswer({ at: 1, summary: "", value: null }), null);
assert.equal(sentAnswer(undefined), null);
assert.deepEqual(sentAnswer({ at: 1, summary: "b", value: { k: "B" } }), { k: "B" });
});
// The server's copy of a send (`submitted` on the item) is what lets a sent
// question still read as sent after a reload -- and, more importantly, after
// an agent took the answer and moved on without settling the item, which used
// to hand the question back looking as though the send never happened.
test("a send the agent never settled is still a send in flight", () => {
const sub = { at: "2026-09-23T03:00:00Z", kind: "multi", ks: ["1", "2"] };
// Nothing sent yet: nothing in flight.
assert.equal(submittedAwaiting({}), null);
assert.equal(submittedAwaiting(null), null);
assert.equal(submittedAwaiting({ submitted: "not-an-object" }), null);
// Sent and never replied to: still in flight.
assert.equal(submittedAwaiting({ submitted: sub }), sub);
// A note from the person is not the agent replying.
assert.equal(
submittedAwaiting({ submitted: sub, thread: [{ who: "user", text: "and one more thing", at: "2026-09-23T03:10:00Z" }] }),
sub
);
// The agent said something after the send: the question is theirs again.
assert.equal(
submittedAwaiting({ submitted: sub, thread: [{ who: "agent", text: "On it.", at: "2026-09-23T03:05:00Z" }] }),
null
);
// But an agent note from BEFORE the send does not clear it.
assert.equal(
submittedAwaiting({ submitted: sub, thread: [{ who: "agent", text: "Earlier.", at: "2026-09-23T02:00:00Z" }] }),
sub
);
// A recorded answer means the agent settled it at some point: the leftover
// submitted is the old send, not one in flight.
assert.equal(submittedAwaiting({ submitted: sub, answer: { ks: ["1"] } }), null);
// No clock to compare by: give the agent the benefit of the doubt rather
// than lock a question it may have answered.
assert.equal(submittedAwaiting({ submitted: sub, thread: [{ who: "agent", text: "No time on me." }] }), null);
});
test("a note the agent has not answered yet is still on its way", () => {
const note = { at: "2026-09-23T03:00:00Z", text: "look at this" };
assert.equal(noteAwaiting({}), null);
assert.equal(noteAwaiting(null), null);
assert.equal(noteAwaiting({ sentNote: "nope" }), null);
assert.equal(noteAwaiting({ sentNote: note }), note);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Earlier.", at: "2026-09-23T02:00:00Z" }] }), note);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Seen.", at: "2026-09-23T03:01:00Z" }] }), null);
assert.equal(
noteAwaiting({ sentNote: note, thread: [{ who: "user", text: "look at this", at: "2026-09-23T03:00:00Z" }] }),
note,
"the person's own note in the thread is not a reply to it",
);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ from: "agent", md: "Older shape.", at: "2026-09-23T03:01:00Z" }] }), null);
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "No clock." }] }), null);
});
// --- the session's ending ------------------------------------------------
//
// Everything else the page shows is a pause. `finish` is the one signal that
// says the session is OVER, which is what lets the page stop promising a next
// question, hand over the command, and treat the server going away as the
// expected last step rather than a fault.
// A finish with no command is a finished session with nothing left to run.
test("a finish is accepted with or without a command", () => {
const bare = cli(["post", "--session", sid, "--file", payload("fin-bare.json", { finish: { headline: "Done" } })]);
assert.equal(bare.status, 0);
const next = cli([
"post",
"--session",
sid,
"--file",
payload("fin-next.json", { finish: { headline: "Done", command: "/plan2code-2-document specs/x/overview.md" } }),
]);
assert.equal(next.status, 0);
});
test("a present finish command must be a non-empty string without a placeholder", () => {
for (const [name, command] of [["fin-empty.json", ""], ["fin-num.json", 42]]) {
const res = cli(["post", "--session", sid, "--file", payload(name, { finish: { headline: "Done", command } })], {
expectFail: true,
});
assert.equal(res.status, 3);
assert.match(res.stderr, /"finish\.command" must be a non-empty string, or left out when there is nothing to run/);
}
const tmpl = cli(
[
"post",
"--session",
sid,
"--file",
payload("fin-tmpl2.json", { finish: { headline: "Done", command: "/plan2code-3-implement specs//overview.md" } }),
],
{ expectFail: true }
);
assert.equal(tmpl.status, 3);
assert.match(tmpl.stderr, /placeholder/);
});
test("a rejected finish leaves the state untouched", () => {
const before = fs.readFileSync(path.join(session, "state.json"), "utf8");
cli(["post", "--session", sid, "--file", payload("fin-empty2.json", { finish: { headline: "Done", command: "" } })], {
expectFail: true,
});
assert.equal(fs.readFileSync(path.join(session, "state.json"), "utf8"), before);
});
// A rendered command is copied and run verbatim, so a leftover placeholder
// reaches someone with no way to know what fills it.
test("a finish is refused while its command still has a placeholder", () => {
const file = payload("fin-tmpl.json", {
finish: { headline: "Done", command: "/plan2code-0-pathfinder specs//pathfinder" },
});
const res = cli(["post", "--session", sid, "--file", file], { expectFail: true });
assert.equal(res.status, 3);
assert.match(res.stderr, /placeholder/);
});
test("a finish faces the same jargon and completion-marker scan as everything else", () => {
const jargon = cli(
["post", "--session", sid, "--file", payload("fin-j.json", { finish: { headline: "The grilling is over", command: "/x" } })],
{ expectFail: true }
);
assert.equal(jargon.status, 3);
assert.match(jargon.stderr, /internal vocabulary/);
const marker = cli(
["post", "--session", sid, "--file", payload("fin-t.json", { finish: { headline: "Done", command: "/x", body: "SPEC_COMPLETE" } })],
{ expectFail: true }
);
assert.equal(marker.status, 3);
assert.match(marker.stderr, /completion marker/);
});
test("a good finish lands on the state the page reads", () => {
const fin = {
headline: "The map is written",
body: "It is all under `specs/lunch-vote/pathfinder/`.",
command: "/plan2code-0-pathfinder specs/lunch-vote/pathfinder",
};
const res = cli(["post", "--session", sid, "--file", payload("fin-ok.json", { finish: fin })]);
assert.equal(res.json.ok, true);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.deepEqual(state.finish, fin);
});
// The review offer rides on the finish of a build. Its heading is read by the
// person, so it faces the vocabulary check, and a malformed one is refused.
test("a finish can carry the review offer, in either shape", () => {
const base = { headline: "Phase 3 is done", command: "/plan2code-3-implement specs/lunch-vote/overview.md" };
for (const review of [true, { label: "Review Phase 3 before you go" }]) {
const res = cli(["post", "--session", sid, "--file", payload("fin-rev.json", { finish: { ...base, review } })]);
assert.equal(res.json.ok, true);
}
const bad = cli(["post", "--session", sid, "--file", payload("fin-rev-bad.json", { finish: { ...base, review: "yes" } })], {
expectFail: true,
});
assert.equal(bad.status, 3);
assert.match(bad.stderr, /finish\.review/);
const jargon = cli(
["post", "--session", sid, "--file", payload("fin-rev-j.json", { finish: { ...base, review: { label: "Grill the frontier" } } })],
{ expectFail: true }
);
assert.equal(jargon.status, 3);
assert.match(jargon.stderr, /internal vocabulary/);
});
// The way back to the dashboard is an agent opt-in flag, so an older skill
// never shows a button nobody answers. Anything but a boolean is refused.
test("a finish can carry the dashboard flag, and only as a boolean", () => {
const base = { headline: "Phase 3 is done", command: "/plan2code-3-implement specs/lunch-vote/overview.md" };
for (const dashboard of [true, false]) {
const res = cli(["post", "--session", sid, "--file", payload("fin-dash.json", { finish: { ...base, dashboard } })]);
assert.equal(res.json.ok, true);
}
const bad = cli(["post", "--session", sid, "--file", payload("fin-dash-bad.json", { finish: { ...base, dashboard: "yes" } })], {
expectFail: true,
});
assert.equal(bad.status, 3);
assert.match(bad.stderr, /"finish\.dashboard" must be true or false \(or left out: no dashboard button\)/);
});
// The Commit it now button is the same kind of opt-in.
test("a finish can carry the commit flag, and only as a boolean", () => {
const base = { headline: "The task is built", command: "git add -A && git commit -m \"x\" -m \"AI Assisted\"" };
for (const commit of [true, false]) {
const res = cli(["post", "--session", sid, "--file", payload("fin-commit.json", { finish: { ...base, commit } })]);
assert.equal(res.json.ok, true);
}
const bad = cli(["post", "--session", sid, "--file", payload("fin-commit-bad.json", { finish: { ...base, commit: "yes" } })], {
expectFail: true,
});
assert.equal(bad.status, 3);
assert.match(bad.stderr, /"finish.commit" must be true or false/);
});
// Taking the review up is the agent posting `"finish": null`: the session goes
// back to work, so the page must stop saying it is over.
test("a finish can be taken back, which puts the session back to work", () => {
const res = cli(["post", "--session", sid, "--file", payload("fin-null.json", { finish: null, agent: { status: "working" } })]);
assert.equal(res.json.ok, true);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.finish, undefined);
});
// A build tells the page how long a silence is normal. Bounded, because a huge
// number would hide a session that really has died.
test("a build's quiet stretch is accepted within bounds and refused outside them", () => {
const ok = cli(["post", "--session", sid, "--file", payload("quiet-ok.json", {
agent: { status: "working", activity: "Task 3.5 of 9: the rate limiter", quietMinutes: 20 },
})]);
assert.equal(ok.json.ok, true);
for (const quietMinutes of [0, 61, "20"]) {
const bad = cli(["post", "--session", sid, "--file", payload("quiet-bad.json", { agent: { quietMinutes } })], {
expectFail: true,
});
assert.equal(bad.status, 3, `quietMinutes ${JSON.stringify(quietMinutes)} must be refused`);
assert.match(bad.stderr, /quietMinutes/);
}
const cleared = cli(["post", "--session", sid, "--file", payload("quiet-clear.json", {
agent: { status: "waiting", quietMinutes: null, activity: null },
})]);
assert.equal(cleared.json.ok, true);
const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.agent.quietMinutes, undefined);
assert.equal(state.agent.activity, undefined);
});
test("a top-level activity line is filed under agent, where the page reads it", () => {
const res = cli(["post", "--session", sid, "--file", payload("activity-top.json", {
agent: { status: "working" },
activity: "Reading the plan",
})]);
assert.equal(res.json.ok, true);
let state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.agent.activity, "Reading the plan");
assert.equal(state.activity, undefined);
cli(["post", "--session", sid, "--file", payload("activity-both.json", {
agent: { activity: "From agent" },
activity: "From top",
})]);
state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.agent.activity, "From agent");
cli(["post", "--session", sid, "--file", payload("activity-clear.json", { activity: null })]);
state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
assert.equal(state.agent.activity, undefined);
assert.equal(state.agent.status, "working");
cli(["post", "--session", sid, "--file", payload("activity-rest.json", { agent: { status: "waiting" } })]);
});
// Someone who worked the whole session in the browser should land back in it.
// Every Plan2Code skill ships a console, so the sentence goes on all of
// them: anything else would send the next session looking for a page that
// does not exist.
test("the copied hand-off asks for the console only where there is one", () => {
const pf = "/plan2code-0-pathfinder specs/lunch-vote/pathfinder";
assert.equal(handoffText({ command: pf }), `${pf} ${CONTINUE_IN_CONSOLE}`);
assert.equal(handoffText({ command: "/plan2code-1-plan" }), "/plan2code-1-plan --web");
assert.equal(handoffText({ command: "/plan2code-1-plan" }), `/plan2code-1-plan ${CONTINUE_IN_CONSOLE}`);
assert.equal(handoffText({ command: "/plan2code-2-document" }), `/plan2code-2-document ${CONTINUE_IN_CONSOLE}`);
assert.equal(handoffText({ command: "/plan2code-init" }), `/plan2code-init ${CONTINUE_IN_CONSOLE}`);
// A prefix match, not a substring one.
assert.equal(handoffText({ command: "/plan2code-1-planner" }), "/plan2code-1-planner");
});
// The dashboard and every step it launches ship the console too, so their
// next session lands back in the browser.
test("the hand-off asks for the console on every step that ships one, and nowhere else", () => {
for (const cmd of [
"/plan2code",
"/plan2code-init",
"/plan2code-init-update",
"/plan2code-3-implement specs/lunch-vote/overview.md",
"/plan2code-3-implement-review specs/lunch-vote/overview.md",
"/plan2code-1b-revise-plan specs/lunch-vote/overview.md",
"/plan2code-quick-task",
"/plan2code-2-document specs/lunch-vote/overview.md",
"/plan2code-review",
"/plan2code-4-finalize specs/lunch-vote/overview.md",
"/plan2code-handoff",
]) {
assert.equal(handoffText({ command: cmd }), `${cmd} ${CONTINUE_IN_CONSOLE}`, cmd);
}
const commit = 'git add -A && git commit -m "Add the rate limiter" -m "AI Assisted"';
assert.equal(handoffText({ command: commit }), commit, "a commit command is not a skill");
// A prefix match, so a longer unrelated name must not pick up the sentence.
assert.equal(handoffText({ command: "/plan2code-3-implementation" }), "/plan2code-3-implementation");
assert.equal(handoffText({ command: "/plan2code-extra" }), "/plan2code-extra");
});
// Every CONSOLE_WORKFLOWS entry has to be a skill install.js really bundles
// the console into, or the copied sentence sends the next session looking for
// a page that does not exist.
test("every console workflow the page names ships the console", () => {
for (const cmd of CONSOLE_WORKFLOWS) {
const skill = cmd.slice(1);
const dir = path.join(ROOT, "skills", skill, "references", "web-console");
assert.ok(fs.existsSync(path.join(dir, "console.mjs")), `${skill} must bundle the console`);
assert.ok(fs.existsSync(path.join(dir, "building.md")), `${skill} must bundle building.md`);
}
// And the other way round: a skill that ships the console but is missing
// from the list would hand off a bare command, and its next session would
// ask the interface question of someone who was already in the browser.
for (const skill of fs.readdirSync(path.join(ROOT, "skills"))) {
if (!fs.existsSync(path.join(ROOT, "skills", skill, "references", "web-console"))) continue;
assert.ok(CONSOLE_WORKFLOWS.includes("/" + skill), `${skill} ships the console but is not in CONSOLE_WORKFLOWS`);
}
});
// The dashboard draws its cards from the page's own catalog, so the catalog
// is the contract: every card has to be a skill that really installs, every
// installed skill has to be a card (a skill that is missing launches nothing),
// and every card's workflow has to be one the console names.
test("the dashboard catalog is exactly the set of installable skills", () => {
const skillsDir = path.join(ROOT, "skills");
const installed = fs.readdirSync(skillsDir).filter((d) => fs.statSync(path.join(skillsDir, d)).isDirectory());
const cataloged = SKILL_CATALOG.map((e) => e.skill);
// The dashboard itself is the hub, not a card.
assert.ok(!cataloged.includes("plan2code"), "the dashboard does not launch itself");
for (const skill of installed) {
if (skill === "plan2code") continue;
assert.ok(cataloged.includes(skill), `${skill} installs but has no card on the dashboard`);
}
for (const e of SKILL_CATALOG) {
assert.ok(installed.includes(e.skill), `${e.skill} is a card but does not install`);
assert.ok(CONSOLE_WORKFLOWS.includes(e.command), `${e.command} must be a console workflow`);
assert.ok(CATALOG_GROUPS.some((g) => g.id === e.group), `${e.skill}: unknown group ${e.group}`);
for (const field of ["workflow", "chip", "title", "blurb"]) {
assert.ok(e[field] && String(e[field]).trim(), `${e.skill}.${field} must be filled in`);
}
// The skill file the dashboard reads for the hand-off must exist.
assert.ok(
fs.existsSync(path.join(skillsDir, e.skill, "SKILL.md")),
`${e.skill} has no SKILL.md to launch into`
);
// The launch reply is the human-readable record of the pick; like the
// other session phrases it keeps clear of Pathfinder's brief words.
assert.doesNotMatch(launchReply(e), /\b(brief|recap|minutes)\b/i);
assert.ok(launchReply(e).includes(e.command), "the reply names the command it stands for");
}
// Every group with a card renders; an empty one is a heading over nothing.
for (const g of CATALOG_GROUPS) {
assert.ok(SKILL_CATALOG.some((e) => e.group === g.id), `group ${g.id} has no cards`);
}
});
// The review button runs review.md inside the build's own session, so the
// skills that offer it have to carry review.md and its references.
test("the skills that run a review on the page carry the review", () => {
for (const skill of ["plan2code-3-implement", "plan2code-quick-task", "plan2code-3-implement-review"]) {
const refs = path.join(ROOT, "skills", skill, "references");
for (const f of ["review.md", "dimensions.md", "false-positives.md", "session-end.md", "verification-protocol.md"]) {
assert.ok(fs.existsSync(path.join(refs, f)), `${skill} must carry references/${f}`);
}
}
});
test("the hand-off sentence respects an explicit choice and is never doubled", () => {
const pf = "/plan2code-0-pathfinder specs/x/pathfinder";
assert.equal(handoffText({ command: pf, console: false }), pf, "they asked for the terminal");
assert.equal(handoffText({ command: "/custom", console: true }), `/custom ${CONTINUE_IN_CONSOLE}`);
// A --web flag states the choice already.
const flagged = "/plan2code-1-plan --web a lunch voting app";
assert.equal(handoffText({ command: flagged }), flagged);
});
test("the copied hand-off always uses --web, never the long sentence", () => {
const pf = "/plan2code-0-pathfinder specs/x/pathfinder";
assert.equal(handoffText({ command: `${pf} Use the web console for this session.` }), `${pf} --web`);
assert.equal(handoffText({ command: `${pf} use the web console for this session` }), `${pf} --web`);
assert.equal(handoffText({ command: `/custom Use the web console for this session.` }), "/custom --web");
assert.equal(
handoffText({ command: `${pf} Use the web console for this session.`, console: false }),
pf,
"they asked for the terminal"
);
});
// Pathfinder reads these words in its argument as a request for a brief, so
// the sentence riding on the command must never contain one.
test("the hand-off sentence cannot be mistaken for a brief request", () => {
assert.doesNotMatch(CONTINUE_IN_CONSOLE, /(brief|recap|minutes)/i);
});
// When the agent cannot answer a stop, the page offers the resume command
// itself, from the session state alone. It must never invent a path.
test("the page's own resume command is built only from what the session says", () => {
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "specs\\lunch-vote\\" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
assert.equal(resumeCommand({ workflow: "pathfinder" }), "/plan2code-0-pathfinder");
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "/etc/passwd" }), "/plan2code-0-pathfinder");
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "specs/a/../../b" }), "/plan2code-0-pathfinder");
assert.equal(resumeCommand({ workflow: "plan", specDir: "specs/x" }), "/plan2code-1-plan");
assert.equal(resumeCommand({ workflow: "implement", specDir: "specs/x" }), "/plan2code-3-implement specs/x/overview.md");
assert.equal(resumeCommand({ workflow: "implement" }), "/plan2code-3-implement");
assert.equal(resumeCommand({ workflow: "implement", specDir: "../x" }), "/plan2code-3-implement");
assert.equal(
resumeCommand({ workflow: "implement-review", specDir: "specs/x/" }),
"/plan2code-3-implement-review specs/x/overview.md"
);
assert.equal(resumeCommand({ workflow: "revise-plan", specDir: "specs/x" }), "/plan2code-1b-revise-plan specs/x/overview.md");
assert.equal(resumeCommand({ workflow: "quick-task", specDir: "specs/x" }), "/plan2code-quick-task");
assert.equal(resumeCommand({ workflow: "finalize", specDir: "specs/x" }), "/plan2code-4-finalize specs/x/overview.md");
assert.equal(resumeCommand({ workflow: "finalize" }), "/plan2code-4-finalize");
// The dashboard generation: the menu itself, the setup pair, and the
// utilities all resume as their bare commands — none keep anything on disk
// that a path would point at.
assert.equal(resumeCommand({ workflow: "dashboard" }), "/plan2code");
assert.equal(resumeCommand({ workflow: "init" }), "/plan2code-init");
assert.equal(resumeCommand({ workflow: "init-update" }), "/plan2code-init-update");
assert.equal(resumeCommand({ workflow: "document", specDir: "specs/x" }), "/plan2code-2-document specs/x/overview.md");
assert.equal(resumeCommand({ workflow: "document" }), "/plan2code-2-document");
assert.equal(resumeCommand({ workflow: "review" }), "/plan2code-review");
assert.equal(resumeCommand({ workflow: "handoff" }), "/plan2code-handoff");
});
test("the review offer is read from true or a label, and absent otherwise", () => {
assert.equal(reviewOffer({ command: "/x" }), null);
assert.equal(reviewOffer({ command: "/x", review: false }), null);
assert.equal(reviewOffer({ command: "/x", review: true }).label, "Review what was just built");
assert.equal(reviewOffer({ command: "/x", review: { label: " Review Phase 3 " } }).label, "Review Phase 3");
assert.equal(reviewOffer({ command: "/x", review: { label: "" } }).label, "Review what was just built");
assert.equal(reviewOffer(null), null);
});
// A pause has no flag on the finish: the stop playbook asks for a headline
// that says it is paused rather than done, and the rail's PAUSED item reads
// the same words the person does.
test("a pause is told apart from an ending by its headline", () => {
assert.equal(finishPaused({ headline: "Paused — your answers so far are saved" }), true);
assert.equal(finishPaused({ headline: " paused, saved where we stopped" }), true);
assert.equal(finishPaused({ headline: "The map is written" }), false);
assert.equal(finishPaused({ headline: "The unpaused work is done" }), false, "paused inside a word is not the state");
assert.equal(finishPaused({ headline: "Phase 3 is done" }), false);
assert.equal(finishPaused({ command: "/x" }), false);
assert.equal(finishPaused(null), false);
});
// A finish with no command has nothing left to run, and points at the
// dashboard instead of a next step. A pause always offers its resume command.
test("the hand-off shape follows the pause and the command", () => {
assert.equal(handoffShape({ headline: "Done", command: "/plan2code-2-document" }), "next");
assert.equal(handoffShape({ headline: "AGENTS.md is updated" }), "all-done");
assert.equal(handoffShape({ headline: "Done", command: " " }), "all-done");
assert.equal(handoffShape({ headline: "Paused at Phase 4", command: "/plan2code-1-plan" }), "paused");
assert.equal(handoffShape({ headline: "Paused here" }), "paused");
assert.equal(
`${ALL_DONE_LEAD} ${ALL_DONE_REST}`,
"All done, nothing left to run. To start something else, run `/plan2code` in a new conversation to open the dashboard."
);
assert.equal(handoffText({ command: DASHBOARD_COMMAND }), "/plan2code --web");
});
// The dashboard button shows only when the agent opted in, and never on a
// pause, whichever finished shape it sits on.
test("the dashboard offer follows the flag and never shows on a pause", () => {
assert.equal(dashboardOffer({ headline: "Done", command: "/plan2code-2-document" }), false);
assert.equal(dashboardOffer({ headline: "Done", dashboard: false }), false);
assert.equal(dashboardOffer({ headline: "Done", dashboard: "yes" }), false);
assert.equal(dashboardOffer(null), false);
assert.equal(dashboardOffer({ headline: "Done", command: "/plan2code-2-document", dashboard: true }), true);
assert.equal(dashboardOffer({ headline: "AGENTS.md is updated", dashboard: true }), true);
assert.equal(dashboardOffer({ headline: "Paused at Phase 4", command: "/plan2code-1-plan", dashboard: true }), false);
assert.equal(
DASHBOARD_NOTE,
"This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start."
);
for (const word of ["brief", "recap", "minutes"]) {
assert.ok(!DASHBOARD_REPLY.toLowerCase().includes(word), `the reply must not say "${word}"`);
}
});
// A build task can honestly run twenty minutes with nothing to post. The page
// stretches its "is it stuck?" thresholds only while the agent says it is
// working, never below the default, and never past an hour.
test("a quiet stretch stretches the stuck thresholds only while working", () => {
const base = 2 * 60 * 1000;
assert.equal(quietLimitMs(null, base), base);
assert.equal(quietLimitMs({ status: "working" }, base), base);
assert.equal(quietLimitMs({ status: "working", quietMinutes: 20 }, base), 20 * 60 * 1000);
assert.equal(quietLimitMs({ status: "waiting", quietMinutes: 20 }, base), base, "a waiting agent is polling");
assert.equal(quietLimitMs({ status: "working", quietMinutes: 1 }, base), base, "never below the default");
assert.equal(quietLimitMs({ status: "working", quietMinutes: 500 }, base), 60 * 60 * 1000, "capped at an hour");
assert.equal(quietLimitMs({ status: "working", quietMinutes: "soon" }, base), base);
});
// A build that grew tasks mid-phase can post cleared past total; the label
// must never read "7 of 5", so the total rises to meet it.
test("the progress label never reads above its total", () => {
assert.equal(progressTotal(3, 5), 5);
assert.equal(progressTotal(7, 5), 7);
assert.equal(progressTotal(0, 0), 0);
assert.equal(progressTotal("4", undefined), 4);
});
test("an image is shrunk to fit its long edge, aspect kept, never upscaled", () => {
assert.equal(MAX_NOTE_IMAGES, 5);
assert.deepEqual(fitWithin(4000, 3000, 2000), { w: 2000, h: 1500 });
assert.deepEqual(fitWithin(1000, 3000, 2000), { w: 667, h: 2000 });
assert.deepEqual(fitWithin(800, 600, 2000), { w: 800, h: 600 });
});
test("a note's action carries only each image's path and name, and no images key when it has none", () => {
assert.equal("images" in noteAction("q3", "Gap here", []), false);
const action = noteAction("q3", "Gap here", [
{ key: "k1", id: "i1", path: "C:\\x\\a.jpg", url: "/uploads/i1.jpg", name: "a.png", status: "ready" },
{ key: "k2", id: "i2", path: "C:\\x\\b.jpg", url: "/uploads/i2.jpg", name: "b.png", status: "ready" },
]);
assert.deepEqual(action, {
i: "q3",
type: "comment",
text: "Gap here",
images: [
{ path: "C:\\x\\a.jpg", name: "a.png" },
{ path: "C:\\x\\b.jpg", name: "b.png" },
],
});
});
test("a note's reply lines list one indented Image line per attachment", () => {
assert.deepEqual(noteReplyLines("Layout", "Gap here", [{ path: "C:\\x\\a.jpg", name: "shot.png" }]), [
"Note on Layout: Gap here",
" Image: C:\\x\\a.jpg (shot.png)",
]);
assert.deepEqual(noteReplyLines("Layout", "", [{ path: "C:\\x\\a.jpg", name: "shot.png" }]), [
"Note on Layout: (images only)",
" Image: C:\\x\\a.jpg (shot.png)",
]);
assert.deepEqual(noteReplyLines("Layout", "Just words", []), ["Note on Layout: Just words"]);
});
test("a note with documents splits them into files, keeps attach order in its lines, and says attachments only", () => {
const mixed = [
{ key: "k1", path: "C:\\x\\a.jpg", url: "/uploads/a.jpg", name: "shot.png", status: "ready" },
{ key: "k2", kind: "file", path: "C:\\x\\b.pdf", name: "spec.pdf", size: 10, status: "ready" },
{ key: "k3", kind: "image", path: "C:\\x\\c.jpg", name: "c.png", status: "ready" },
];
assert.deepEqual(noteAction("q3", "See", mixed), {
i: "q3",
type: "comment",
text: "See",
images: [
{ path: "C:\\x\\a.jpg", name: "shot.png" },
{ path: "C:\\x\\c.jpg", name: "c.png" },
],
files: [{ path: "C:\\x\\b.pdf", name: "spec.pdf" }],
});
assert.equal("files" in noteAction("q3", "See", [mixed[0]]), false, "an image-only note has no files key");
assert.deepEqual(noteReplyLines("Layout", "", mixed), [
"Note on Layout: (attachments only)",
" Image: C:\\x\\a.jpg (shot.png)",
" File: C:\\x\\b.pdf (spec.pdf)",
" Image: C:\\x\\c.jpg (c.png)",
]);
});
test("document helpers: the extension allow-list, the picker's accept, sizes, and the kind of an old entry", () => {
assert.equal(MAX_ATTACHMENTS, 5);
assert.equal(MAX_DOC_BYTES, 10 * 1024 * 1024);
assert.equal(docExt("README.MD"), "md");
assert.equal(docExt("x.PDF"), "pdf");
assert.equal(docExt("archive.tar.gz"), null);
assert.equal(docExt(".env"), null);
assert.equal(docExt("Dockerfile"), null);
assert.equal(docExt("trailing."), null);
assert.equal(docExt("report.docx"), null);
assert.ok(Object.keys(DOC_TYPES).every((ext) => ext === ext.toLowerCase()));
const accept = pickerAccept();
assert.ok(accept.startsWith("image/*,"));
assert.ok(accept.split(",").includes(".pdf") && accept.split(",").includes(".md"));
// Formatted in the machine's own locale, so the expected text is too: this
// pins the unit and the rounding, not one language's spelling of them.
const unit = (value, u, digits) =>
new Intl.NumberFormat(undefined, { style: "unit", unit: u, maximumFractionDigits: digits }).format(value);
assert.equal(formatBytes(512), "512 B");
assert.equal(formatBytes(2048), unit(2, "kilobyte", 0));
assert.equal(formatBytes(1536), unit(2, "kilobyte", 0), "kilobytes round to whole numbers");
assert.equal(formatBytes(3.5 * 1024 * 1024), unit(3.5, "megabyte", 1));
assert.equal(attachmentKind({}), "image");
assert.equal(attachmentKind({ kind: "file" }), "file");
});
test("sortAttachments goes by extension first, refuses by name, and keeps the order given", () => {
const ts = { name: "a.ts", type: "video/mp2t", size: 10 };
const md = { name: "n.md", type: "", size: 10 };
const png = { name: "shot.png", type: "image/png", size: 10 };
const docx = { name: "r.docx", type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document", size: 10 };
const bigPdf = { name: "big.pdf", type: "application/pdf", size: MAX_DOC_BYTES + 1 };
const pdf = { name: "ok.pdf", type: "application/pdf", size: MAX_DOC_BYTES };
const jpg = { name: "b.jpg", type: "image/jpeg", size: 10 };
const env = { name: ".env", type: "", size: 10 };
const out = sortAttachments([ts, png, docx, md, bigPdf, pdf, jpg, env]);
assert.deepEqual(out.docs, [ts, md, pdf], ".ts as video/mp2t and .md with no type are documents");
assert.deepEqual(out.images, [png, jpg]);
assert.deepEqual(out.refused, [
{ name: "r.docx", reason: "type" },
{ name: "big.pdf", reason: "too-large" },
{ name: ".env", reason: "type" },
]);
assert.deepEqual(sortAttachments(undefined), { images: [], docs: [], refused: [] });
});
test("checkDocument trusts the bytes, not the name", () => {
assert.equal(checkDocument(Buffer.from("%PDF-1.4 rest"), "pdf"), null);
assert.equal(checkDocument(Buffer.from("%PDF"), "pdf"), "type");
assert.equal(checkDocument(Buffer.from("hello"), "pdf"), "type");
assert.equal(checkDocument(Buffer.from("# ok — ünïcode\n", "utf8"), "md"), null);
assert.equal(checkDocument(Buffer.alloc(0), "txt"), null, "an empty text file is fine");
assert.equal(checkDocument(Buffer.from([0x61, 0x00, 0x62]), "md"), "type");
assert.equal(checkDocument(Buffer.from([0xc3, 0x28]), "csv"), "type");
assert.equal(checkDocument(Buffer.from("x"), "docx"), "type");
assert.equal(checkDocument(Buffer.from("x"), "constructor"), "type");
});
test("chat lines list documents after images, and chatView carries files on sent and pending rows", () => {
const lines = chatReplyLines([
{
kind: "message",
text: "Read these",
images: [{ path: "/u/a.jpg", name: "a.png" }],
files: [{ path: "/u/b.md", name: "b.md" }],
},
]);
assert.equal(lines, "Quick question: Read these\n Image: /u/a.jpg (a.png)\n File: /u/b.md (b.md)");
const view = chatView(
{ conversation: 1, messages: [{ from: "person", kind: "message", seq: 1, text: "Read", files: [{ path: "/u/b.md", name: "b.md" }] }] },
{ pendingSends: [{ tempId: "t", text: "More", files: [{ path: "/u/c.pdf", name: "c.pdf" }] }] }
);
assert.deepEqual(view.rows[0].files, [{ path: "/u/b.md", name: "b.md" }]);
assert.deepEqual(view.rows[0].images, []);
assert.deepEqual(view.rows[1].files, [{ path: "/u/c.pdf", name: "c.pdf" }]);
});
// The soft approval line comes in at 30 s of a working agent's silence. A
// build's quietMinutes stretches it in step with the stale line, at a quarter
// of it, so the soft line always gets its turn before "has not checked in".
test("the approval hint appears after 30 s of a working agent's silence", () => {
assert.equal(APPROVAL_HINT_MS, 30_000);
assert.equal(approvalHint({ status: "waiting" }, 10 * 60 * 1000), "");
assert.equal(approvalHint({ status: "working" }, 29_000), "");
assert.equal(approvalHint({ status: "working" }, 30_000), APPROVAL_HINT);
assert.equal(approvalHint({ status: "working", quietMinutes: 5 }, 74_000), "");
assert.equal(approvalHint({ status: "working", quietMinutes: 5 }, 75_000), APPROVAL_HINT);
for (const quietMinutes of [undefined, 5, 15, 60]) {
const agent = { status: "working", quietMinutes };
const stale = quietLimitMs(agent, STALE_MS);
const firstHint = [0, 1, 2, 3, 4].map((q) => (stale * q) / 4).find((ms) => approvalHint(agent, ms));
assert.ok(firstHint < stale, `the soft line comes before the stale message (quietMinutes ${quietMinutes})`);
}
assert.equal(approvalHint(null, 60_000), "");
assert.ok(APPROVAL_TIP.includes("`auto` mode in Claude Code"));
assert.ok(APPROVAL_TIP.includes("`smart` mode in Devin"));
});
test("the build's session phrases cannot be mistaken for a brief request", () => {
assert.doesNotMatch(REVIEW_REPLY, /\b(brief|recap|minutes)\b/i);
assert.doesNotMatch(DONE_REPLY, /\b(brief|recap|minutes)\b/i);
});
test("the stop request cannot be mistaken for a brief request", () => {
assert.doesNotMatch(STOP_REPLY, /\b(brief|recap|minutes)\b/i);
});
// Nineteen highlight colors, four shades each, two themes: far too many to
// trust to eyeballing, and a failure here is a label nobody can read.
const hexLum = (h) => {
const c = [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16) / 255).map((v) => (v <= 0.03928 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4));
return 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
};
const contrast = (a, b) => {
const [x, y] = [hexLum(a), hexLum(b)].sort((p, q) => q - p);
return (x + 0.05) / (y + 0.05);
};
test("every highlight color is readable in both themes", () => {
const panel = { light: "#ffffff", dark: "#201d1a" };
assert.ok(Object.keys(ACCENTS).length >= 32);
assert.ok(ACCENTS[DEFAULT_ACCENT], "the default must be in the list");
const names = new Set();
for (const [id, a] of Object.entries(ACCENTS)) {
assert.ok(!names.has(a.name), `duplicate name ${a.name}`);
names.add(a.name);
for (const theme of ["light", "dark"]) {
const [fill, soft, ink, line] = a[theme];
for (const c of a[theme]) assert.match(c, /^#[0-9a-f]{6}$/, `${id} ${theme}: ${c}`);
assert.ok(contrast(ink, fill) >= 4.5, `${id} ${theme}: label on the fill is ${contrast(ink, fill).toFixed(2)}:1`);
assert.ok(contrast(fill, soft) >= 4.5, `${id} ${theme}: badge text on the tint is ${contrast(fill, soft).toFixed(2)}:1`);
assert.ok(contrast(line, panel[theme]) >= 1.8, `${id} ${theme}: border barely shows at ${contrast(line, panel[theme]).toFixed(2)}:1`);
}
}
});
/* ------------------------------------------------- the spec-aware dashboard */
// The console scans the repo itself, so the states the picker shows have to
// be read off real folder shapes — a fixture per stage, then the matrix that
// turns a stage into lit or greyed cards.
function fakeSpec(root, name, files) {
const dir = path.join(root, "specs", name);
for (const [rel, text] of Object.entries(files)) {
const abs = path.join(dir, rel);
fs.mkdirSync(path.dirname(abs), { recursive: true });
fs.writeFileSync(abs, text);
}
return dir;
}
test("the project scan reads each spec's pipeline stage off its files", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scan-"));
try {
fakeSpec(root, "exploring", {
"pathfinder/map.md": "**Status:** Working\n",
"pathfinder/questions/00-a.md": "State: resolved\n",
"pathfinder/questions/01-b.md": "State: open\n",
});
fakeSpec(root, "mapped", {
"pathfinder/map.md": "**Status:** Cleared\n",
"pathfinder/questions/00-a.md": "State: resolved\n",
});
fakeSpec(root, "planned", { "PLAN-DRAFT-20260923.md": "# draft\n\n**Status:** Complete\n" });
fakeSpec(root, "draft-mid-plan", {
"PLAN-DRAFT-20260923.md": "# draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n",
"pathfinder/map.md": "**Status:** Cleared\n",
});
fakeSpec(root, "documented", {
"overview.md": "# spec\n",
"phase-1.md": "- [ ] Task one\n- [ ] Task two\n",
"phase-2.md": "- [ ] Task three\n",
});
fakeSpec(root, "building", {
"overview.md": "# spec\n",
"phase-1.md": "- [x] Task one\n- [ ] Task two\n",
});
fakeSpec(root, "built", {
"overview.md": "# spec\n",
"phase-1.md": "- [x] Task one\n- [x] Task two\n",
});
fakeSpec(root, "weird", { "DESIGN.md": "# notes\n" });
fs.writeFileSync(path.join(root, "AGENTS.md"), "# agents\n");
const scan = scanProject(root);
assert.equal(scan.hasAgents, true);
const byName = Object.fromEntries(scan.specs.map((s) => [s.name, s]));
for (const [name, state] of [
["exploring", "exploring"],
["mapped", "mapped"],
["planned", "planned"],
["draft-mid-plan", "mapped"],
["documented", "documented"],
["building", "building"],
["built", "built"],
["weird", "unrecognized"],
]) {
assert.ok(byName[name], `spec ${name} was scanned`);
assert.equal(byName[name].state, state, `spec ${name}`);
assert.ok(SPEC_STATES.has(byName[name].state));
assert.ok(SPEC_STATE_LABELS[byName[name].state], `state ${state} has a picker label`);
}
assert.equal(byName.exploring.detail, "1 of 2 decisions made");
assert.equal(byName.building.detail, "1 of 2 tasks done");
assert.equal(byName["draft-mid-plan"].detail, "plan draft, resume at Phase 4");
// A pathfinder folder with no map yet is still mid-exploration; a map
// whose status line is missing or unreadable is too.
fakeSpec(root, "no-map", { "pathfinder/questions/00-a.md": "State: open\n" });
const scan2 = scanProject(root);
assert.equal(scan2.specs.find((s) => s.name === "no-map").state, "exploring");
// No AGENTS.md reads false, and a repo with no specs scans empty rather
// than failing.
const empty = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scan-empty-"));
const scan3 = scanProject(empty);
assert.equal(scan3.hasAgents, false);
assert.deepEqual(scan3.specs, []);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
// The dashboard's Git commit card offers to start a repository when the folder
// is not one. The scan answers that from the filesystem, never from a git
// process, and a linked worktree (a .git file, not a folder) must count.
test("scanProject reports isGit for a repo, a subfolder, a linked worktree and a plain folder", () => {
const saved = {};
for (const k of ["GIT_DIR", "GIT_WORK_TREE", "GIT_COMMON_DIR"]) {
saved[k] = process.env[k];
delete process.env[k];
}
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-isgit-"));
try {
const repo = path.join(base, "repo");
fs.mkdirSync(path.join(repo, "sub"), { recursive: true });
const git = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
git(repo, "init", "-q");
git(repo, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "x");
git(repo, "worktree", "add", "-q", path.join(base, "wt"));
const plain = path.join(base, "plain");
fs.mkdirSync(plain);
assert.equal(scanProject(repo).isGit, true);
assert.equal(scanProject(path.join(repo, "sub")).isGit, true);
assert.equal(fs.statSync(path.join(base, "wt", ".git")).isFile(), true, "a linked worktree's .git is a file");
assert.equal(scanProject(path.join(base, "wt")).isGit, true);
assert.equal(scanProject(plain).isGit, false);
assert.equal(insideGitRepo(plain), false);
// When git is steered by the environment, git decides: count it as a repo.
process.env.GIT_DIR = path.join(plain, "nowhere");
assert.equal(insideGitRepo(plain), true);
} finally {
for (const [k, v] of Object.entries(saved)) {
if (v === undefined) delete process.env[k];
else process.env[k] = v;
}
fs.rmSync(base, { recursive: true, force: true });
}
});
test("the Git commit card stays clickable outside a repository and says what happens", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git-commit");
const outside = cardAvailability(entry, { hasAgents: true, isGit: false }, null);
assert.equal(outside.on, true);
assert.equal(outside.note, GIT_INIT_NOTE);
for (const scan of [{ hasAgents: true, isGit: true }, { hasAgents: true }, null]) {
const a = cardAvailability(entry, scan, null);
assert.equal(a.on, true);
assert.equal(a.note, undefined);
}
const scan = { hasAgents: true, isGit: false, specs: [] };
assert.equal(cardPresentation(entry, scan, null).detail, GIT_INIT_NOTE);
// The agent's own detail line still wins over the note.
const withSpec = { hasAgents: true, isGit: false, specs: [{ dir: "specs/x", name: "x", state: "building" }] };
const menu = { details: { "plan2code-git-commit": "Two changes ready" } };
assert.equal(cardPresentation(entry, withSpec, withSpec.specs[0], menu).detail, "Two changes ready");
});
test("the Git commit card shows the pending count and greys out on a clean tree", () => {
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git-commit");
const clean = cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null);
assert.equal(clean.on, false);
assert.equal(clean.reason, GIT_CLEAN_REASON);
const dirty = cardAvailability(entry, { hasAgents: true, isGit: true, pending: 3 }, null);
assert.deepEqual(dirty, { on: true, note: "3 files to commit" });
assert.equal(pendingNote(1), "1 file to commit");
// git could not say: stay clickable, and no repository still offers git init.
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: null }, null), { on: true });
assert.equal(cardAvailability(entry, { hasAgents: true, isGit: false, pending: 0 }, null).note, GIT_INIT_NOTE);
});
test("pendingFiles counts changed and untracked paths, and says null outside a repository", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pending-"));
const git = (...a) => spawnSync("git", a, { cwd: repo, encoding: "utf8" });
const repo = path.join(base, "repo");
const plain = path.join(base, "plain");
fs.mkdirSync(repo);
fs.mkdirSync(plain);
try {
if (git("init", "-q").status !== 0) return; // no git on this machine
git("config", "user.email", "t@example.com");
git("config", "user.name", "T");
assert.equal(pendingFiles(repo), 0, "an empty repository is clean");
fs.writeFileSync(path.join(repo, "a.txt"), "a");
git("add", "a.txt");
git("commit", "-q", "-m", "first");
assert.equal(pendingFiles(repo), 0);
fs.writeFileSync(path.join(repo, "a.txt"), "changed");
fs.writeFileSync(path.join(repo, "b.txt"), "new");
assert.equal(pendingFiles(repo), 2, "one modified, one untracked");
git("add", "b.txt");
assert.equal(pendingFiles(repo), 2, "staged counts too");
assert.equal(scanProject(repo).pending, 2);
assert.equal(scanProject(plain).pending, null, "no repository, no count");
} finally {
fs.rmSync(base, { recursive: true, force: true });
}
});
test("the commit offer is read from finish.commit and a pause never carries it", () => {
assert.equal(commitOffer({ headline: "Done", commit: true }), true);
assert.equal(commitOffer({ headline: "Done", commit: false }), false);
assert.equal(commitOffer({ headline: "Done" }), false);
assert.equal(commitOffer({ headline: "Paused here", commit: true }), false);
assert.equal(commitOffer(null), false);
});
test("a verdict's button text never renders blank", () => {
assert.equal(verdictText({ id: "approve", label: "Approve it" }), "Approve it");
assert.equal(verdictText({ id: "approve", text: "Approve it" }), "Approve it");
assert.equal(verdictText({ id: "approve" }), "approve");
const item = { verdicts: [{ id: "changes", text: "Needs changes" }] };
assert.equal(verdictLabel(item, "changes"), "Needs changes");
assert.equal(verdictLabel({}, "approve"), "Looks good, go ahead");
});
test("the dashboard matrix lights only the cards a spec state allows", () => {
const scan = { hasAgents: true };
const sel = (state) => ({ dir: "specs/x", name: "x", state });
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
const on = (skill, sc, s) => cardAvailability(entry(skill), sc, s).on;
// AGENTS.md gates the setup pair, whatever the picker holds.
assert.equal(on("plan2code-init", scan, null), false);
assert.equal(on("plan2code-init-update", scan, null), true);
assert.equal(on("plan2code-init", { hasAgents: false }, null), true);
assert.equal(on("plan2code-init-update", { hasAgents: false }, null), false);
// Utilities are always on.
for (const s of [null, sel("exploring"), sel("built"), sel("unrecognized")]) {
for (const u of ["plan2code-quick-task", "plan2code-review", "plan2code-handoff"]) {
assert.equal(on(u, scan, s), true, `${u} on for ${s && s.state}`);
}
}
// No spec (or an unrecognized one): Pathfinder, Plan and the utilities.
for (const s of [null, sel("unrecognized")]) {
for (const skill of ["plan2code-0-pathfinder", "plan2code-1-plan"]) {
assert.equal(on(skill, scan, s), true, `${skill} on for ${s && s.state}`);
}
for (const skill of [
"plan2code-1b-revise-plan",
"plan2code-2-document",
"plan2code-3-implement",
"plan2code-3-implement-review",
"plan2code-4-finalize",
]) {
assert.equal(on(skill, scan, s), false, `${skill} off for ${s && s.state}`);
}
}
assert.equal(on("plan2code-0-pathfinder", scan, sel("exploring")), true);
assert.equal(on("plan2code-1-plan", scan, sel("exploring")), false);
assert.equal(on("plan2code-0-pathfinder", scan, sel("mapped")), false);
assert.equal(on("plan2code-1-plan", scan, sel("mapped")), true);
assert.equal(on("plan2code-2-document", scan, sel("planned")), true);
for (const s of [sel("documented"), sel("building")]) {
for (const skill of ["plan2code-3-implement", "plan2code-3-implement-review", "plan2code-1b-revise-plan"]) {
assert.equal(on(skill, scan, s), true, `${skill} on for ${s.state}`);
}
}
assert.equal(on("plan2code-1b-revise-plan", scan, sel("built")), false);
assert.equal(on("plan2code-4-finalize", scan, sel("built")), true);
// A greyed card always says why, and a selected spec's next step is marked.
assert.ok(cardAvailability(entry("plan2code-3-implement"), scan, sel("exploring")).reason);
assert.equal(cardAvailability(entry("plan2code-3-implement"), scan, sel("documented")).next, true);
assert.ok(!cardAvailability(entry("plan2code-1-plan"), scan, sel("documented")).next);
});
test("dashboard card presentation follows the current picker selection", () => {
const scan = {
hasAgents: true,
specs: [
{ dir: "specs/current", name: "current", state: "documented", detail: "2 phases, 8 tasks ready" },
{ dir: "specs/planned", name: "planned", state: "planned", detail: "plan drafted" },
],
};
const menu = {
recommend: "plan2code-3-implement",
details: { "plan2code-3-implement": "Phase 1 of 2 is next" },
};
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
const current = cardPresentation(entry("plan2code-3-implement"), scan, scan.specs[0], menu);
assert.equal(current.recommended, true);
assert.equal(current.detail, "Phase 1 of 2 is next");
const stale = cardPresentation(entry("plan2code-3-implement"), scan, null, menu);
assert.equal(stale.on, false);
assert.equal(stale.recommended, false);
assert.equal(stale.detail, "");
const fresh = cardPresentation(entry("plan2code-0-pathfinder"), scan, null, menu);
assert.equal(fresh.on, true);
assert.equal(fresh.recommended, true);
const planned = cardPresentation(entry("plan2code-2-document"), scan, scan.specs[1], menu);
assert.equal(planned.on, true);
assert.equal(planned.recommended, true);
assert.equal(planned.detail, "plan drafted");
});
test("the launch reply names the picked spec", () => {
const e = SKILL_CATALOG.find((x) => x.skill === "plan2code-3-implement");
assert.equal(
launchReply(e, { dir: "specs/lunch-vote" }),
"Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session."
);
assert.equal(launchReply(e), "Start Implement (/plan2code-3-implement), right here in this session.");
assert.equal(launchReply(e, null), launchReply(e));
assert.doesNotMatch(launchReply(e, { dir: "specs/x" }), /\b(brief|recap|minutes)\b/i);
});
/* ------------------------------------------------------ fast start path */
// The roots used to come from two `git rev-parse` processes, 150ms+ each on
// Windows, on every `open`. They are read off the filesystem now, and must
// land on exactly what git says, or sessions stop sharing a handle space.
test("repoRoots matches git for a repo, a subdirectory, a linked worktree and a plain folder", () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-roots-"));
const repo = path.join(base, "repo");
fs.mkdirSync(path.join(repo, "sub", "deeper"), { recursive: true });
const git = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] }).trim();
git(repo, "init", "-q");
git(repo, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "x");
git(repo, "worktree", "add", "-q", path.join(base, "wt"));
const plain = path.join(base, "plain");
fs.mkdirSync(plain);
const viaGit = (cwd) => {
const [common, top] = git(cwd, "rev-parse", "--path-format=absolute", "--git-common-dir", "--show-toplevel").split(/\r?\n/);
return { project: fs.realpathSync(path.dirname(common)), worktree: fs.realpathSync(top) };
};
for (const cwd of [repo, path.join(repo, "sub", "deeper"), path.join(base, "wt")]) {
const { project, worktree } = repoRoots(cwd);
assert.deepEqual({ project, worktree }, viaGit(cwd), cwd);
}
// The worktree shares the main checkout's project key but scans its own disk.
assert.equal(repoRoots(path.join(base, "wt")).project, repoRoots(repo).project);
assert.notEqual(repoRoots(path.join(base, "wt")).worktree, repoRoots(repo).worktree);
// Not a repository at all: both roots are the folder itself, spelled out in
// full the way git spells a repo. The temp dir sits outside any checkout,
// so the walk has nothing to find.
const full = fs.realpathSync.native(plain);
assert.deepEqual(repoRoots(plain), { project: full, worktree: full, branch: "" });
fs.rmSync(base, { recursive: true, force: true });
});
// Every page load used to fetch /state, then /looks, then open the stream,
// before drawing anything real. The first state now rides in the page.
test("the page carries its first state, title and badge, so the first paint needs no fetch", async () => {
const hostile = "Lunch $& $' app";
const res = cli(["open", "--workflow", "implement", "--title", hostile, "--no-open"]);
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
const html = await (await fetch(m[1] + "/", { headers: { cookie: consoleCookie(m[1], m[2]) } })).text();
const block = html.match(/ is the block's own.
assert.equal(block[1].includes("<"), false);
assert.equal((html.match(/