mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Split the web console into by-job files, add page tests and a docs-table test, plus docs
AI Assisted
This commit is contained in:
1 parent
699a827cae
commit
3edb4468a8
121 files changed
+25603
-20145
No files matched your search
@@ -16,15 +16,17 @@
|
||||
// fcp first contentful paint: the person sees something
|
||||
// ready the session is drawn from real state (the menu, or a question)
|
||||
//
|
||||
// plus the bytes and request count the page cost. Needs puppeteer-core in
|
||||
// node_modules and a local Chrome or Edge for the browser columns; without
|
||||
// them it still reports url/cliExit and an HTTP-only waterfall.
|
||||
// plus the bytes and request count the page cost. The browser columns need
|
||||
// playwright-core (from `npm install`) and a local Chrome or Edge, picked by
|
||||
// scripts/browser.mjs; without a browser it still reports url/cliExit and an
|
||||
// HTTP-only waterfall.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -44,20 +46,6 @@ const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER
|
||||
// so a slow GitHub never colours the timings.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
function findBrowser() {
|
||||
if (args.browser === "none") return null;
|
||||
if (typeof args.browser === "string") return args.browser;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
// Resolves at the first stdout line carrying a url, and again at exit.
|
||||
// --launch hook (default): `open` launches "the browser" the way it would for
|
||||
// a person, through PLAN2CODE_BROWSER, and the hook just writes the link to
|
||||
@@ -211,18 +199,22 @@ async function roundtrip() {
|
||||
|
||||
async function main() {
|
||||
if (args.roundtrip) return roundtrip();
|
||||
const browserPath = findBrowser();
|
||||
let puppeteer = null;
|
||||
if (browserPath) {
|
||||
// --browser none: no launch at all. --browser <path>: that executable.
|
||||
// Otherwise the helper's pick; a browser problem is one line, then the
|
||||
// HTTP-only waterfall.
|
||||
let browser = null;
|
||||
let browserName = null;
|
||||
if (args.browser !== "none") {
|
||||
const custom = typeof args.browser === "string" ? args.browser : null;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
console.error("puppeteer-core not installed; browser columns skipped");
|
||||
browser = await launchBrowser(custom ? { executablePath: custom } : {});
|
||||
const found = custom ? null : findBrowser();
|
||||
browserName = found ? `${found.channel} (${found.path})` : custom;
|
||||
} catch (e) {
|
||||
if (!e.browserProblem) throw e;
|
||||
console.error(e.message);
|
||||
}
|
||||
}
|
||||
const browser = puppeteer
|
||||
? await puppeteer.launch({ executablePath: browserPath, headless: true, args: ["--no-first-run", "--no-default-browser-check"] })
|
||||
: null;
|
||||
|
||||
const rows = [];
|
||||
// One throwaway run so disk caches and the Node binary are warm; the person
|
||||
@@ -231,7 +223,7 @@ async function main() {
|
||||
stopAll();
|
||||
// The tab exists before the clock starts: a person's browser is already
|
||||
// running, and creating a context is the harness's cost, not the page's.
|
||||
const ctx = browser ? await browser.createBrowserContext() : null;
|
||||
const ctx = browser ? await browser.newContext() : null;
|
||||
const page = ctx ? await ctx.newPage() : null;
|
||||
const { t0, urlP, exitP, openP } = runOpen();
|
||||
const o = await openP;
|
||||
@@ -246,7 +238,7 @@ async function main() {
|
||||
page.on("response", async (res) => {
|
||||
requests++;
|
||||
try {
|
||||
bytes += (await res.buffer()).length;
|
||||
bytes += (await res.body()).length;
|
||||
} catch {}
|
||||
});
|
||||
if (BROWSER_DELAY) await new Promise((r) => setTimeout(r, Math.max(0, o.at + BROWSER_DELAY - Date.now())));
|
||||
@@ -303,7 +295,7 @@ async function main() {
|
||||
};
|
||||
const summary = Object.fromEntries(cols.map((k) => [k, stat(k)]));
|
||||
console.log(`web console start-up, ${RUNS} runs, workflow=${WORKFLOW}, cwd=${CWD}`);
|
||||
console.log(`browser: ${browser ? browserPath : "none (HTTP-only waterfall)"}`);
|
||||
console.log(`browser: ${browser ? browserName : "none (HTTP-only waterfall)"}`);
|
||||
console.log("metric".padEnd(10) + "median".padStart(9) + "min".padStart(9) + "max".padStart(9));
|
||||
for (const k of cols) {
|
||||
const s = summary[k];
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Picks and launches the browser for page tests and the dev scripts. Dev-only:
|
||||
// lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// The first installed of Chrome then Edge, through playwright-core (a root
|
||||
// devDependency); PLAN2CODE_TEST_BROWSER=chrome or msedge forces one. Every
|
||||
// failure is one line in our own words, never Playwright's install hint.
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
// The fixed places each browser installs to, probed in order on every
|
||||
// platform (a path that cannot exist here is simply not found).
|
||||
export const BROWSER_PATHS = {
|
||||
chrome: [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/google-chrome-stable",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
],
|
||||
msedge: [
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/microsoft-edge",
|
||||
"/usr/bin/microsoft-edge-stable",
|
||||
],
|
||||
};
|
||||
|
||||
const CHANNELS = Object.keys(BROWSER_PATHS);
|
||||
|
||||
// Returns { channel, path } for the first browser found, or null. Either way
|
||||
// findBrowser.checked lists every path this call looked at.
|
||||
export function findBrowser({ env = process.env, exists = fs.existsSync } = {}) {
|
||||
const forced = env.PLAN2CODE_TEST_BROWSER;
|
||||
if (forced && !CHANNELS.includes(forced)) {
|
||||
throw new Error(`PLAN2CODE_TEST_BROWSER must be ${CHANNELS.join(" or ")} (it is "${forced}").`);
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
for (const channel of forced ? [forced] : CHANNELS) {
|
||||
for (const p of BROWSER_PATHS[channel]) {
|
||||
findBrowser.checked.push(p);
|
||||
if (exists(p)) return { channel, path: p };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
|
||||
// null when page tests can run here, otherwise the one line that says why
|
||||
// not. `checked` defaults to the paths the last findBrowser() call probed.
|
||||
export function browserProblem({ nodeVersion = process.versions.node, found, checked = findBrowser.checked } = {}) {
|
||||
if (Number(nodeVersion.split(".")[0]) < 20) {
|
||||
return `Page tests need Node 20 or newer (this is ${nodeVersion}). Users of Plan2Code still only need Node 18.`;
|
||||
}
|
||||
if (!found) {
|
||||
return `Page tests need Chrome or Edge. Looked in: ${checked.join(", ")}. Install either one, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Launches the browser findBrowser() picks, headless. `options` go to
|
||||
// Playwright's chromium.launch() as they are (an `executablePath` there skips
|
||||
// the pick); `find` hands findBrowser() its env and exists, for tests. A
|
||||
// problem rejects with an Error whose message is our one line and whose
|
||||
// `browserProblem` is true, never Playwright's own launch text.
|
||||
export async function launchBrowser(options = {}, find = {}) {
|
||||
const found = options.executablePath ? { channel: null, path: options.executablePath } : findBrowser(find);
|
||||
const problem = browserProblem({ found });
|
||||
if (problem) throw Object.assign(new Error(problem), { browserProblem: true });
|
||||
let chromium;
|
||||
try {
|
||||
({ chromium } = await import("playwright-core"));
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("Page tests need playwright-core: run npm install.", { cause: e }), { browserProblem: true });
|
||||
}
|
||||
try {
|
||||
return await chromium.launch({
|
||||
executablePath: found.path,
|
||||
headless: true,
|
||||
args: ["--no-first-run", "--no-default-browser-check"],
|
||||
...options,
|
||||
});
|
||||
} catch (e) {
|
||||
// Playwright's own text stays out of the message, but is kept as the
|
||||
// cause for whoever needs to debug a real launch failure.
|
||||
const line = `Page tests could not start the browser at ${found.path}. Install Chrome or Edge, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
throw Object.assign(new Error(line, { cause: e }), { browserProblem: true });
|
||||
}
|
||||
}
|
||||
+197
-51
@@ -3,7 +3,7 @@
|
||||
// it never ships inside a skill.
|
||||
//
|
||||
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
|
||||
// [--out <dir>]
|
||||
// [--out <dir>] [--compare]
|
||||
//
|
||||
// Every shot is staged with no agent: a throwaway sample project called
|
||||
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
|
||||
@@ -14,16 +14,27 @@
|
||||
// it is the console's nearest to the Plan2Code blue the site and README use.
|
||||
//
|
||||
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask, git.
|
||||
// --compare adds workspace, stop, delete, help, prefs and cleanup: screens the
|
||||
// docs never show, for checking a change by eye against a "before" set. Its
|
||||
// --out must be outside docs/screenshots/, so the set is never published.
|
||||
//
|
||||
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
|
||||
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
|
||||
// folders and --out.
|
||||
// --snapshot <file> (used by scripts/css-snapshot.mjs) takes no pictures: it
|
||||
// writes every element's computed style, per screen, theme and width, to <file>.
|
||||
// It sees what these shots stage: choice, multi, text, review and confirm cards;
|
||||
// a checklist, list, recap or menu card is not staged, so a rule only they use
|
||||
// is not covered.
|
||||
//
|
||||
// Needs playwright-core (a root devDependency, so `npm install` brings it) and
|
||||
// a local Chrome or Edge, launched through scripts/browser.mjs. Playwright has
|
||||
// no WebP screenshots, so each shot is taken over CDP. Writes nothing outside
|
||||
// its temp folders and --out.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -72,6 +83,82 @@ const SHOTS = {
|
||||
git: { workflow: "git", posts: ["git"], repo: true },
|
||||
};
|
||||
|
||||
// --compare only: the screens the docs never show, shot so a change to the
|
||||
// console can be checked against a "before" set by eye. `open` runs on the
|
||||
// page after every load and clicks through to the screen. Never published.
|
||||
const COMPARE_SHOTS = {
|
||||
// The confirm dialog, with the handoff choice beside plain stop.
|
||||
stop: {
|
||||
workflow: "implement",
|
||||
posts: ["stop"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-stop");
|
||||
await page.waitForSelector("#stop-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// The first step of a spec chip's delete.
|
||||
delete: {
|
||||
workflow: "dashboard",
|
||||
posts: ["delete"],
|
||||
open: async (page) => {
|
||||
await page.locator(".spec-chip-del").first().click({ force: true });
|
||||
await page.waitForSelector("#delete-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Help on its first tab, whatever topic it opened on.
|
||||
help: {
|
||||
workflow: "plan",
|
||||
posts: ["help"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-about");
|
||||
await page.locator("#help-tabs .help-tab").first().click();
|
||||
await page.waitForSelector("#help-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
prefs: {
|
||||
workflow: "plan",
|
||||
posts: ["prefs"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Preferences scrolled to Cleanup once its scan has answered.
|
||||
cleanup: {
|
||||
workflow: "plan",
|
||||
posts: ["cleanup"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
await page.locator(".looks-cleanup").scrollIntoViewIfNeeded();
|
||||
await page.click("#cleanup-scan");
|
||||
await page.waitForFunction(() => document.getElementById("cleanup-status").textContent.trim() !== "", null, { timeout: 15000 }).catch(() => {});
|
||||
},
|
||||
},
|
||||
// The panel open with two folders: the project and a sibling added once.
|
||||
// Last, since the console remembers the folder for the project and every
|
||||
// later shot's footer would count it.
|
||||
workspace: {
|
||||
workflow: "plan",
|
||||
posts: ["workspace"],
|
||||
open: async (page) => {
|
||||
const extra = makeExtraFolder();
|
||||
await page.evaluate(async (dir) => {
|
||||
const now = await (await fetch("/workspace", { cache: "no-store" })).json();
|
||||
if ((now.folders || []).length < 2) {
|
||||
await fetch("/workspace/add", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ path: dir, name: "task-web", description: "The web app that calls the API" }),
|
||||
});
|
||||
}
|
||||
}, extra);
|
||||
await page.click("#footer-where");
|
||||
await page.waitForSelector("#workspace-modal[open] #workspace-list li:nth-child(2)", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// On Windows the temp dir sits under the user's profile, and the page can
|
||||
// show the project's path, so the sample project goes at the drive root
|
||||
// instead. Elsewhere the temp dir carries no username. Each run makes its own
|
||||
@@ -89,21 +176,6 @@ function fail(message) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
function phaseFile(n, name, tasks, done) {
|
||||
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
|
||||
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
|
||||
@@ -169,6 +241,14 @@ function makeSampleProject() {
|
||||
return project;
|
||||
}
|
||||
|
||||
// The Workspace shot's second folder, beside the sample project.
|
||||
function makeExtraFolder() {
|
||||
const dir = path.join(SCRATCH, "task-web");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "README.md"), "# task-web\n\nThe web app that lists and edits a team's tasks.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
function git(cwd, ...gitArgs) {
|
||||
const r = spawnSync("git", gitArgs, { cwd, env: ENV, encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`git ${gitArgs.join(" ")} failed: ${(r.stderr || "").trim()}`);
|
||||
@@ -225,8 +305,7 @@ function post(project, sid, name) {
|
||||
}
|
||||
|
||||
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
|
||||
function stage(project, shot) {
|
||||
const spec = SHOTS[shot];
|
||||
function stage(project, spec) {
|
||||
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
|
||||
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
|
||||
for (const name of spec.posts) post(project, r.out.sid, name);
|
||||
@@ -236,9 +315,9 @@ function stage(project, shot) {
|
||||
// Waits for the page to draw real state, then lets the animations finish
|
||||
// (the dashboard's wake-up is the longest).
|
||||
async function settle(page) {
|
||||
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
|
||||
await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc, .git-board", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(3500);
|
||||
await sleep(args.snapshot ? 1800 : 3500);
|
||||
}
|
||||
|
||||
async function openTab(page, label) {
|
||||
@@ -251,7 +330,7 @@ async function openTab(page, label) {
|
||||
|
||||
async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const problem = await page.evaluate(
|
||||
(topSel, showSel) => {
|
||||
([topSel, showSel]) => {
|
||||
const find = (sel) =>
|
||||
sel.startsWith("cmd:")
|
||||
? [...document.querySelectorAll(".dash-card")].find((c) => c.querySelector(".dash-card-cmd")?.textContent.trim() === sel.slice(4))
|
||||
@@ -265,24 +344,95 @@ async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const r = show.getBoundingClientRect();
|
||||
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
|
||||
},
|
||||
top,
|
||||
mustShow || null
|
||||
[top, mustShow || null]
|
||||
);
|
||||
if (problem) console.log(` warning: ${problem}`);
|
||||
await sleep(300);
|
||||
}
|
||||
|
||||
// The properties that change how a stylesheet move would look.
|
||||
const SNAP_PROPS = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
// Recorded after the properties above, for every element: what names its animation.
|
||||
// A property a running animation is moving is recorded as "~" (it differs from run
|
||||
// to run), so a rule that adds or removes an animation shows in these fields instead.
|
||||
const SNAP_ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
const SNAP = {};
|
||||
|
||||
async function snapshotNow(page) {
|
||||
return page.evaluate(
|
||||
([props, animation]) => {
|
||||
const out = {};
|
||||
const seen = new Map();
|
||||
for (const el of document.querySelectorAll("*")) {
|
||||
const parent = el.parentElement;
|
||||
const key = parent ? (seen.get(parent) || "") : "";
|
||||
const sib = parent ? [...parent.children].indexOf(el) : 0;
|
||||
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 3).join(".") : "";
|
||||
const path = (parent ? key + ">" : "") + el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (cls ? "." + cls : "") + "[" + sib + "]";
|
||||
seen.set(el, path);
|
||||
const cs = getComputedStyle(el);
|
||||
const moving = new Set();
|
||||
for (const a of el.getAnimations ? el.getAnimations() : []) {
|
||||
for (const kf of a.effect && a.effect.getKeyframes ? a.effect.getKeyframes() : []) {
|
||||
for (const k of Object.keys(kf)) if (!["offset", "easing", "composite", "computedOffset"].includes(k)) moving.add(k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()));
|
||||
}
|
||||
}
|
||||
out[path] = props.map((p) => (moving.has(p) ? "~" : cs.getPropertyValue(p))).concat(animation.map((p) => cs.getPropertyValue(p))).join("|");
|
||||
}
|
||||
return out;
|
||||
},
|
||||
[SNAP_PROPS, SNAP_ANIMATION]
|
||||
);
|
||||
}
|
||||
|
||||
async function snapshotShot(page, name, theme) {
|
||||
for (const [w, h] of [[1280, 800], [390, 844]]) {
|
||||
await page.setViewportSize({ width: w, height: h });
|
||||
await sleep(1500);
|
||||
SNAP[`${name}/${theme}/${w}`] = await snapshotNow(page);
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const written = [];
|
||||
// Math.random picks Planny's mood variants; pinned so two runs draw the same page.
|
||||
if (args.snapshot) await page.addInitScript(() => { Math.random = () => 0.5; });
|
||||
for (const theme of THEMES) {
|
||||
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
|
||||
await page.emulateMedia({ colorScheme: theme });
|
||||
// The theme is applied at load, so reload rather than trust a live switch.
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
if (page.__tab) await openTab(page, page.__tab);
|
||||
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
|
||||
if (page.__open) {
|
||||
await page.__open(page);
|
||||
await sleep(600);
|
||||
}
|
||||
if (args.snapshot) {
|
||||
await snapshotShot(page, name, theme);
|
||||
continue;
|
||||
}
|
||||
const file = path.join(OUT, `${name}-${theme}.webp`);
|
||||
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
// Without a clip the capture comes out in CSS pixels; a clip of the
|
||||
// viewport at scale 2 is the twice-density shot (byte for byte what
|
||||
// Playwright's own PNG screenshot takes).
|
||||
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
|
||||
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: QUALITY, captureBeyondViewport: false, clip });
|
||||
await cdp.detach();
|
||||
fs.writeFileSync(file, Buffer.from(data, "base64"));
|
||||
const kb = Math.round(fs.statSync(file).size / 1024);
|
||||
console.log(`${path.basename(file)} ${kb} KB`);
|
||||
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
|
||||
@@ -292,15 +442,15 @@ async function shoot(page, name) {
|
||||
}
|
||||
|
||||
// Opens the page for a staged session and saves both themes.
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow, open }) {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
page.__tab = tab || null;
|
||||
page.__scroll = { scrollTo: top, mustShow };
|
||||
page.__open = open || null;
|
||||
return await shoot(page, name);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
@@ -310,15 +460,14 @@ async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
// The Ask shot: a question typed and sent on the page, collected with `chat`
|
||||
// the way an agent would, and answered with a posted reply.
|
||||
async function captureAsk(browser, project, sid, url, question) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
await openTab(page, "Ask");
|
||||
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
|
||||
await page.type("#ask-input", question);
|
||||
await page.locator("#ask-input").pressSequentially(question);
|
||||
await page.evaluate(() => {
|
||||
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
|
||||
if (send) send.click();
|
||||
@@ -360,17 +509,14 @@ async function captureAsk(browser, project, sid, url, question) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const names = args.only ? [args.only] : Object.keys(SHOTS);
|
||||
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
|
||||
|
||||
let puppeteer;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
|
||||
const docs = path.join(ROOT, "docs", "screenshots");
|
||||
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
||||
if (args.compare && (fold(OUT) === fold(docs) || fold(OUT).startsWith(fold(docs) + path.sep))) {
|
||||
fail(`--compare never writes into ${path.relative(ROOT, docs)}: pass --out with a folder outside it.`);
|
||||
}
|
||||
const browserPath = findBrowser();
|
||||
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
|
||||
const table = args.compare ? { ...SHOTS, ...COMPARE_SHOTS } : SHOTS;
|
||||
const names = args.only ? [args.only] : Object.keys(table);
|
||||
for (const n of names) if (!table[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(table).join(", ")}`);
|
||||
|
||||
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
|
||||
HOME = path.join(SCRATCH, "console-home");
|
||||
@@ -385,21 +531,21 @@ async function main() {
|
||||
// and the Ocean highlight is the console's nearest to the Plan2Code blue
|
||||
// the landing page uses.
|
||||
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean", welcomeSeen: true } }));
|
||||
browser = await puppeteer.launch({
|
||||
executablePath: browserPath,
|
||||
headless: true,
|
||||
browser = await launchBrowser({
|
||||
...(typeof args.browser === "string" ? { executablePath: args.browser } : {}),
|
||||
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
|
||||
});
|
||||
for (const name of names) {
|
||||
const where = SHOTS[name].repo ? makeGitProject() : project;
|
||||
const { sid, url } = stage(where, name);
|
||||
const where = table[name].repo ? makeGitProject() : project;
|
||||
const { sid, url } = stage(where, table[name]);
|
||||
try {
|
||||
if (SHOTS[name].ask) await captureAsk(browser, where, sid, url, SHOTS[name].ask);
|
||||
else await capture(browser, url, name, SHOTS[name]);
|
||||
if (table[name].ask) await captureAsk(browser, where, sid, url, table[name].ask);
|
||||
else await capture(browser, url, name, table[name]);
|
||||
} finally {
|
||||
cli(where, "stop", "--session", sid);
|
||||
}
|
||||
}
|
||||
if (args.snapshot) fs.writeFileSync(path.resolve(String(args.snapshot)), JSON.stringify(SNAP));
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (project) cli(project, "stop", "--all");
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// The console's stylesheet as the tests read it: the files under
|
||||
// public/styles/ joined in the server's own order, without the accent rules.
|
||||
// A rule moving between files never breaks a test; only a rule that changes
|
||||
// or vanishes does.
|
||||
|
||||
import { joinedStyles } from "../src/web-console/static.mjs";
|
||||
|
||||
export function joinedCss() {
|
||||
return joinedStyles().toString("utf8");
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env node
|
||||
// The cheapest check for a stylesheet move: every element's computed style, on
|
||||
// every screen the console has, in both themes, at desktop and phone width.
|
||||
// Dev-only, not in `npm test`. Stages the screens the way
|
||||
// scripts/capture-screenshots.mjs does (its --snapshot mode), so the sample
|
||||
// project and payloads are the same.
|
||||
//
|
||||
// node scripts/css-snapshot.mjs [--out <file>] write a snapshot
|
||||
// node scripts/css-snapshot.mjs --compare <file> take one now and print every difference
|
||||
//
|
||||
// Take a baseline before moving any rule, then compare after each move. Two
|
||||
// runs in a row on the same stylesheet report nothing: Math.random is pinned,
|
||||
// a property a running animation is moving is recorded as "~" (its animation
|
||||
// fields are still compared), and heights within 4px are ignored (see jitter).
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
|
||||
}
|
||||
|
||||
function take(file) {
|
||||
// The screenshot script wants a folder to exist for --compare; nothing is written to it.
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-css-snap-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--snapshot", file, "--out", out], { stdio: ["ignore", "inherit", "inherit"] });
|
||||
if (r.status !== 0) {
|
||||
console.error("the snapshot run failed");
|
||||
process.exit(1);
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const NAMES = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
const ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
// A growing answer box at phone width settles a few pixels either way from one
|
||||
// run to the next with the same stylesheet; the heights it carries up the page
|
||||
// (and the transform origin, which is half of one) are not a stylesheet's doing.
|
||||
const JITTER = new Set(["height", "min-height", "transform-origin"]);
|
||||
function jitter(name, a, b) {
|
||||
if (!JITTER.has(name)) return false;
|
||||
const na = a.match(/-?\d+(?:\.\d+)?/g);
|
||||
const nb = b.match(/-?\d+(?:\.\d+)?/g);
|
||||
return !!na && !!nb && na.length === nb.length && na.every((n, i) => Math.abs(n - nb[i]) <= 4);
|
||||
}
|
||||
|
||||
function compare(before, after) {
|
||||
const diffs = [];
|
||||
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
||||
const a = before[key];
|
||||
const b = after[key];
|
||||
if (!a || !b) {
|
||||
diffs.push(`${key}: screen ${a ? "missing from the new run" : "is new"}`);
|
||||
continue;
|
||||
}
|
||||
for (const el of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[el] === b[el] || el.includes("p.dock-say")) continue; // the one line of Planny that types itself in, so its width moves
|
||||
if (a[el] === undefined || b[el] === undefined) {
|
||||
diffs.push(`${key} ${el}: element ${a[el] === undefined ? "added" : "gone"}`);
|
||||
continue;
|
||||
}
|
||||
const x = a[el].split("|");
|
||||
const y = b[el].split("|");
|
||||
const names = NAMES.concat(ANIMATION);
|
||||
x.forEach((v, i) => {
|
||||
if (v !== y[i] && v !== "~" && y[i] !== "~" && !jitter(names[i], v, y[i])) diffs.push(`${key} ${el} ${names[i] ?? i}: ${v} -> ${y[i]}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (args.compare === true) {
|
||||
console.error("usage: node scripts/css-snapshot.mjs --compare <snapshot file> (or --out <file> to take one)");
|
||||
process.exit(1);
|
||||
} else if (typeof args.compare === "string") {
|
||||
const tmp = path.join(os.tmpdir(), `p2c-css-snap-${process.pid}.json`);
|
||||
take(tmp);
|
||||
const diffs = compare(JSON.parse(fs.readFileSync(args.compare, "utf8")), JSON.parse(fs.readFileSync(tmp, "utf8")));
|
||||
fs.rmSync(tmp, { force: true });
|
||||
for (const d of diffs.slice(0, 200)) console.log(d);
|
||||
if (diffs.length > 200) console.log(`... and ${diffs.length - 200} more`);
|
||||
console.log(diffs.length ? `${diffs.length} difference(s)` : "no differences");
|
||||
process.exit(diffs.length ? 1 : 0);
|
||||
} else {
|
||||
const out = path.resolve(typeof args.out === "string" ? args.out : "css-snapshot.json");
|
||||
take(out);
|
||||
console.log(`wrote ${out} (${Math.round(fs.statSync(out).size / 1024)} KB)`);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Start a real console and open its page in a real browser, for the page tests
|
||||
// (scripts/test-web-console-page-*.mjs).
|
||||
//
|
||||
// One browser per test file (pageSuite), a fresh console session and browser
|
||||
// context per test (openSession). Sessions run against the file's own console
|
||||
// home from web-console-test-helpers.mjs, in a temp project unless a test
|
||||
// names one. Any uncaught error on the page fails the test that opened it, so
|
||||
// a later split that breaks a screen shows as a named error, not a blank page.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { cli, payload, until, HOME, REMEMBERED } from "./web-console-test-helpers.mjs";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
// `test` is node:test's test function (or any context with .after): the
|
||||
// browser is launched the first time a test asks for it and closed once the
|
||||
// file is done.
|
||||
export function pageSuite(test) {
|
||||
let launching = null;
|
||||
test.after(async () => {
|
||||
if (launching) await (await launching).close();
|
||||
});
|
||||
return {
|
||||
browser: () => (launching ??= launchBrowser()),
|
||||
};
|
||||
}
|
||||
|
||||
let projects = 0;
|
||||
let payloads = 0;
|
||||
|
||||
// A fresh project folder under the file's console home, removed with it.
|
||||
export function tempProject(files = {}) {
|
||||
const dir = path.join(HOME, "projects", `p${++projects}`);
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, rel), text);
|
||||
}
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens a console session the way an agent does (`console.mjs open`, then
|
||||
// `post`), and its page in a new browser context. Resolves once the page has
|
||||
// drawn from the session's real state, not the boot pane in the markup.
|
||||
// `t` is the test's context: stop() is registered with t.after, so a failing
|
||||
// test still cleans up, and a page error fails the test. `clock: true` gives
|
||||
// the page Playwright's fake clock before it loads (s.page.clock), so a test
|
||||
// can jump past the page's silence limits instead of sitting through them.
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
|
||||
fs.rmSync(REMEMBERED, { force: true });
|
||||
const cwd = project || tempProject();
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
|
||||
const s = {
|
||||
sid: opened.sid,
|
||||
session: opened.session,
|
||||
url: opened.url,
|
||||
project: cwd,
|
||||
errors: [],
|
||||
context: null,
|
||||
page: null,
|
||||
};
|
||||
|
||||
// The agent's side, run from the project like an agent would.
|
||||
s.post = (patch) => {
|
||||
const r = cli(["post", "--session", s.sid, "--file", payload(`page-post-${++payloads}.json`, patch)], { cwd });
|
||||
if (r.status !== 0) throw new Error(`post failed (${r.status}): ${r.stderr}`);
|
||||
return r.json;
|
||||
};
|
||||
s.wait = (seconds = 10) => {
|
||||
const r = cli(["wait", "--session", s.sid, "--seconds", String(seconds)], { cwd });
|
||||
return { code: r.status, ...(r.json || {}) };
|
||||
};
|
||||
// Whether the session's server still answers on its port.
|
||||
s.answers = async () => {
|
||||
try {
|
||||
await fetch(new URL("/health", s.url), { signal: AbortSignal.timeout(1000) });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let stopped = false;
|
||||
s.stop = async () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cli(["stop", "--session", s.sid], { cwd });
|
||||
if (s.context) await s.context.close().catch(() => {});
|
||||
await until(async () => !(await s.answers()), 5000);
|
||||
};
|
||||
t.after(async () => {
|
||||
await s.stop();
|
||||
if (s.errors.length) throw new Error(`uncaught error on the page: ${s.errors[0]}`);
|
||||
});
|
||||
|
||||
if (first) s.post(first);
|
||||
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
if (clock) await s.context.clock.install();
|
||||
s.page = await s.context.newPage();
|
||||
s.page.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
return s;
|
||||
}
|
||||
|
||||
// The page has adopted a state frame: app.js has replaced the boot pane the
|
||||
// markup ships with.
|
||||
export async function drawn(page) {
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
|
||||
}
|
||||
|
||||
// Presses Send on the page and collects the send the way an agent's `wait`
|
||||
// does: the same JSON an agent receives.
|
||||
export async function sendAndCollect(s) {
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
if (got.code !== 0) throw new Error(`nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The card for one item id.
|
||||
export const itemCard = (page, id) => page.locator(`[data-item="${id}"]`).first();
|
||||
|
||||
// A locator's visible text, trimmed.
|
||||
export const textOf = async (locator) => (await locator.innerText()).trim();
|
||||
|
||||
// The scroll offset of the first element matching `selector`.
|
||||
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
|
||||
@@ -17,3 +17,20 @@ and dark WebP images in `docs/screenshots/`.
|
||||
|
||||
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
|
||||
`--only <shot>`.
|
||||
|
||||
## Comparison-only shots
|
||||
|
||||
`--compare` adds the screens the docs never show, so a change to the console
|
||||
can be checked by eye against a "before" set. They are never published: the
|
||||
script refuses `--compare` with an `--out` inside `docs/screenshots/`.
|
||||
|
||||
| File | Stages |
|
||||
| --- | --- |
|
||||
| `stop.json` | A build with a question open, behind the Stop dialog and its handoff choice |
|
||||
| `delete.json` | The dashboard, behind the first step of a spec chip's Delete |
|
||||
| `help.json` | A Plan question, behind Help on its first tab |
|
||||
| `prefs.json` | A Plan question, behind User Preferences |
|
||||
| `cleanup.json` | A Plan question, behind User Preferences scrolled to Cleanup after a scan |
|
||||
| `workspace.json` | A Plan question, behind the Workspace panel with a second folder added (shot last: the console remembers the folder) |
|
||||
|
||||
`node scripts/capture-screenshots.mjs --compare --out <folder outside the repo>`
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"menu": {
|
||||
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
|
||||
"recommend": "plan2code-3-implement",
|
||||
"details": {
|
||||
"plan2code-3-implement": "Phase 3 of 4 is next"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"workflow": "implement",
|
||||
"title": "task-api: Phase 3",
|
||||
"specDir": "specs/task-api",
|
||||
"headline": {
|
||||
"stage": "Phase 3: API endpoints",
|
||||
"cleared": 2,
|
||||
"total": 4
|
||||
},
|
||||
"docs": [
|
||||
{
|
||||
"id": "phase",
|
||||
"title": "Phase 3 tasks",
|
||||
"blocks": [
|
||||
{
|
||||
"id": "tasks",
|
||||
"state": "settled",
|
||||
"md": "- [x] **Task 3.1:** Add GET /tasks with cursor paging\n- [x] **Task 3.2:** Add POST /tasks\n- [ ] **Task 3.3:** Add PATCH /tasks/:id\n- [ ] **Task 3.4:** Add DELETE /tasks/:id"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "keep",
|
||||
"kind": "confirm",
|
||||
"title": "Tests are failing",
|
||||
"body": "Two paging tests fail after Task 3.2. Fix them before going on?",
|
||||
"yesLabel": "Fix them now",
|
||||
"noLabel": "Note them and go on"
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Tests for the shared browser helper (scripts/browser.mjs) and the two dev
|
||||
// scripts that launch a browser through it. Run with:
|
||||
// node --test scripts/test-browser-helper.mjs
|
||||
//
|
||||
// The unit cases hand findBrowser() a fake `exists`, so they run anywhere. The
|
||||
// live cases launch a real Chrome or Edge and skip when none is installed.
|
||||
|
||||
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 { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
test("playwright-core is pinned exactly in the root devDependencies", () => {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
|
||||
assert.equal(pkg.devDependencies["playwright-core"], "1.64.1");
|
||||
});
|
||||
|
||||
// A fake file system holding only `present`.
|
||||
const only = (...present) => (p) => present.includes(p);
|
||||
|
||||
test("findBrowser picks Chrome, then Edge, and honours PLAN2CODE_TEST_BROWSER", async () => {
|
||||
const { findBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const chrome = BROWSER_PATHS.chrome[0];
|
||||
const edge = BROWSER_PATHS.msedge[0];
|
||||
|
||||
assert.deepEqual(findBrowser({ env: {}, exists: only(edge) }), { channel: "msedge", path: edge });
|
||||
assert.deepEqual(findBrowser({ env: {}, exists: only(chrome, edge) }), { channel: "chrome", path: chrome });
|
||||
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "msedge" }, exists: only(chrome, edge) }), { channel: "msedge", path: edge });
|
||||
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: only(edge) }), null);
|
||||
assert.deepEqual(findBrowser.checked, BROWSER_PATHS.chrome);
|
||||
assert.throws(() => findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "firefox" }, exists: only(chrome) }), (e) => /chrome/.test(e.message) && /msedge/.test(e.message));
|
||||
|
||||
assert.equal(findBrowser({ env: {}, exists: only() }), null);
|
||||
assert.deepEqual(findBrowser.checked, [...BROWSER_PATHS.chrome, ...BROWSER_PATHS.msedge]);
|
||||
});
|
||||
|
||||
test("browserProblem says what is missing in one line of our own words", async () => {
|
||||
const { browserProblem } = await import("./browser.mjs");
|
||||
const found = { channel: "chrome", path: "C:\chrome.exe" };
|
||||
|
||||
const oldNode = browserProblem({ nodeVersion: "18.19.0", found });
|
||||
assert.equal(oldNode, "Page tests need Node 20 or newer (this is 18.19.0). Users of Plan2Code still only need Node 18.");
|
||||
|
||||
const checked = ["C:\a\chrome.exe", "/usr/bin/microsoft-edge"];
|
||||
const none = browserProblem({ nodeVersion: "24.12.0", found: null, checked });
|
||||
assert.match(none, /^Page tests need Chrome or Edge\. Looked in: /);
|
||||
for (const p of checked) assert.ok(none.includes(p), `names ${p}`);
|
||||
assert.ok(none.endsWith("Install either one, or set PLAN2CODE_TEST_BROWSER."));
|
||||
|
||||
assert.equal(browserProblem({ nodeVersion: "24.12.0", found }), null);
|
||||
for (const line of [oldNode, none]) {
|
||||
assert.ok(!line.includes("\n"));
|
||||
assert.ok(!line.includes("playwright install"));
|
||||
}
|
||||
});
|
||||
|
||||
test("launchBrowser fails with our one line when the forced browser is missing", async () => {
|
||||
const { launchBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const edgeOnly = only(BROWSER_PATHS.msedge[0]);
|
||||
await assert.rejects(launchBrowser({}, { env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: edgeOnly }), (e) => {
|
||||
assert.equal(e.browserProblem, true);
|
||||
assert.match(e.message, /^Page tests need Chrome or Edge\. Looked in: /);
|
||||
assert.ok(!e.message.includes("\n"));
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test("launchBrowser opens a page in the installed browser", async (t) => {
|
||||
const { launchBrowser, findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.goto("data:text/html,<p>ok</p>");
|
||||
assert.equal(await page.textContent("p"), "ok");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Width and height from a WebP file's first chunk (lossy VP8, lossless VP8L,
|
||||
// or the extended VP8X header).
|
||||
function webpSize(buf) {
|
||||
assert.equal(buf.toString("ascii", 0, 4), "RIFF");
|
||||
assert.equal(buf.toString("ascii", 8, 12), "WEBP");
|
||||
const chunk = buf.toString("ascii", 12, 16);
|
||||
if (chunk === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
|
||||
if (chunk === "VP8L") {
|
||||
const bits = buf.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
if (chunk === "VP8X") return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 };
|
||||
throw new Error(`unknown WebP chunk ${chunk}`);
|
||||
}
|
||||
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
test("capture-screenshots writes both themes as 2560x1600 WebP (slow)", { timeout: 120000 }, async (t) => {
|
||||
const { findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shots-test-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--only", "question", "--out", out], { encoding: "utf8", timeout: 110000 });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const buf = fs.readFileSync(path.join(out, `question-${theme}.webp`));
|
||||
assert.deepEqual(webpSize(buf), { width: 2560, height: 1600 });
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("capture-screenshots --compare refuses to write into docs/screenshots", () => {
|
||||
// A shot that does not exist: were the guard ever to break, the run would
|
||||
// stop at "Unknown shot" (which never names docs/screenshots) rather than
|
||||
// shoot every screen into the published folder.
|
||||
const argv = [CAPTURE, "--compare", "--only", "__no-such-shot__", "--out", path.join(ROOT, "docs", "screenshots")];
|
||||
const r = spawnSync(process.execPath, argv, { encoding: "utf8", timeout: 30000 });
|
||||
assert.notEqual(r.status, 0);
|
||||
const lines = r.stderr.trim().split("\n");
|
||||
assert.equal(lines.length, 1, r.stderr);
|
||||
assert.match(lines[0], /docs[\\/]screenshots/);
|
||||
});
|
||||
|
||||
test("capture-screenshots --compare shoots the comparison-only screens (slow)", { timeout: 120000 }, async (t) => {
|
||||
const { findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-compare-test-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--only", "help", "--out", out], { encoding: "utf8", timeout: 110000 });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
for (const theme of ["light", "dark"]) assert.ok(fs.statSync(path.join(out, `help-${theme}.webp`)).size > 0);
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
unreadDot,
|
||||
} from "../src/web-console/public/chat.js";
|
||||
import { WEIGHTS } from "../src/web-console/public/meter.js";
|
||||
import { readChat } from "../src/web-console/lib.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { readChat, terminalLine } from "../src/web-console/lib.mjs";
|
||||
import { terminalLine } from "../src/web-console/sessions.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -12,7 +12,10 @@ import path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import http from "node:http";
|
||||
import { meterView } from "../src/web-console/public/meter.js";
|
||||
import { cwdHash, readLedger, repoRoots, STATE_LOCK_FILE, validate, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
|
||||
import { STATE_LOCK_FILE } from "../src/web-console/files.mjs";
|
||||
import { cwdHash, readLedger, repoRoots } from "../src/web-console/sessions.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -47,7 +50,11 @@ test("helpers: a dashboard hop clears them, a same-workflow or paused resume kee
|
||||
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
|
||||
assert.equal(readState(s.session).helpers.length, 2, "a resume into the same workflow keeps them");
|
||||
|
||||
assert.equal(postPatch(s, { finish: { headline: "Paused at Task 2" } }).status, 0);
|
||||
// A finish is refused while a helper still shows as running, so the pause settles them.
|
||||
assert.equal(
|
||||
postPatch(s, { helpers: [reportedHelper("h1", { state: "done" }), reportedHelper("h2", { state: "failed" })], finish: { headline: "Paused at Task 2" } }).status,
|
||||
0
|
||||
);
|
||||
cli(["open", "--resume", s.sid, "--no-open"]);
|
||||
const resumed = readState(s.session);
|
||||
assert.equal("finish" in resumed, false, "the pause came down");
|
||||
@@ -240,7 +247,7 @@ test("stop never kills a live process that does not answer /health as ours", ()
|
||||
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
const sidForged = "20000101-000000-beef01";
|
||||
// Under the test home, as the CLI sees it: this process has no override of
|
||||
// its own, and lib.mjs would name the real runtime dir.
|
||||
// its own, and files.mjs would name the real runtime dir.
|
||||
const dir = path.join(HOME, "runtime", cwdHash(repoRoots(ROOT).project));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const forged = path.join(dir, `${sidForged}.json`);
|
||||
|
||||
@@ -495,30 +495,24 @@ test("git board view: a .gitignore-only pick commits just .gitignore, and never
|
||||
assert.equal(gitReply("commit", { files: ["a.js"], ignore: ["dist/"] }), "Commit this file: a.js. Add dist/ to .gitignore.");
|
||||
});
|
||||
|
||||
test("git board host: app.js draws the board only through drawGitBoard, and the server serves the view", () => {
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
test("git board host: the host draws the board only through drawGitBoard, and the server serves the view", () => {
|
||||
const host = fs.readFileSync(new URL("../src/web-console/public/screens/git-host.js", import.meta.url), "utf8");
|
||||
for (const gone of ["gitActionBar", "gitBranches", "smallButton", "gitHeader", "gitCommitPanel"]) {
|
||||
assert.ok(!app.includes(`function ${gone}(`), `app.js no longer defines ${gone}()`);
|
||||
assert.ok(!host.includes(`function ${gone}(`), `git-host.js no longer defines ${gone}()`);
|
||||
}
|
||||
const drawCalls = [...app.matchAll(/\bdrawGitBoard\(/g)].length;
|
||||
const drawCalls = [...host.matchAll(/\bdrawGitBoard\(/g)].length;
|
||||
assert.equal(drawCalls, 1, "one call to drawGitBoard");
|
||||
const host = app.slice(app.indexOf("function renderGitBoard("), app.indexOf("function rememberGitTabScroll("));
|
||||
assert.ok(host.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
|
||||
const server = fs.readFileSync(new URL("../src/web-console/server.mjs", import.meta.url), "utf8");
|
||||
const body = host.slice(host.indexOf("function renderGitBoard("), host.indexOf("function rememberGitTabScroll("));
|
||||
assert.ok(body.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
|
||||
const server = fs.readFileSync(new URL("../src/web-console/static.mjs", import.meta.url), "utf8");
|
||||
const servable = server.slice(server.indexOf("const SERVABLE = new Set(["), server.indexOf("]);", server.indexOf("const SERVABLE = new Set([")));
|
||||
assert.ok(servable.includes('"git-board-view.js"'), "SERVABLE includes git-board-view.js");
|
||||
assert.ok(servable.includes('"screens/git-host.js"'), "SERVABLE includes screens/git-host.js");
|
||||
});
|
||||
|
||||
test("git board host: the always-on commit table keeps the person's ticks, and a click re-seeds them", () => {
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("const gitOn = {"));
|
||||
assert.match(send, /board\.ticks = null;\s*board\.ignore = new Set\(\);/, "a click drops the old picks");
|
||||
const commit = app.slice(app.indexOf("function openCommit("), app.indexOf("function openCleanup("));
|
||||
assert.ok(!commit.includes("commitTicks("), "opening the panel never re-seeds over their ticks");
|
||||
assert.ok(commit.includes("tablePicks(git)"), "a detached commit carries the table's picks");
|
||||
const panel = app.slice(app.indexOf("function openPanel("), app.indexOf("const closePanel ="));
|
||||
assert.match(panel, /opts\.commit && !opts\.files\) return openCreate\(git, \{ \.\.\.opts, \.\.\.tablePicks\(git\) \}\)/, "Start a branch takes what is ticked");
|
||||
});
|
||||
// The commit table's ticks and the click that re-seeds them are page tests now
|
||||
// ("the commit table keeps the person's ticks across an agent post, and a click
|
||||
// re-seeds them" and its neighbours in test-web-console-page-git.mjs).
|
||||
|
||||
test("git board docs: the agent prose, Help topic and readme describe the tabbed board", () => {
|
||||
const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8");
|
||||
|
||||
@@ -14,12 +14,11 @@ import { spawnSync } from "node:child_process";
|
||||
// is exactly why this lives in its own file.
|
||||
import {
|
||||
cardAvailability,
|
||||
CONSOLE_WORKFLOWS,
|
||||
GIT_INIT_NOTE,
|
||||
resumeCommand,
|
||||
SKILL_CATALOG,
|
||||
START_POSES,
|
||||
} from "../src/web-console/public/answers.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { breakdownFrom, pointsFrom } from "../src/web-console/public/meter.js";
|
||||
import {
|
||||
BRANCH_TYPES,
|
||||
@@ -38,7 +37,7 @@ import {
|
||||
refreshedLine,
|
||||
} from "../src/web-console/public/git-board.js";
|
||||
import { prUrl } from "../src/web-console/public/pr-url.js";
|
||||
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/lib.mjs";
|
||||
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/sessions.mjs";
|
||||
import {
|
||||
CONSOLE_CLI,
|
||||
HOME,
|
||||
@@ -290,8 +289,6 @@ test("git: the Git card is never greyed, and its resume command is /plan2code-gi
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null), { on: true });
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: null }, null), { on: true });
|
||||
assert.equal(resumeCommand({ workflow: "git" }), "/plan2code-git");
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes("/plan2code-git"));
|
||||
assert.ok(START_POSES.includes("git"));
|
||||
});
|
||||
|
||||
test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)", async () => {
|
||||
@@ -303,8 +300,11 @@ test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)
|
||||
);
|
||||
assert.equal(entry.group, "extra");
|
||||
assert.equal(entry.chip, "Utility");
|
||||
assert.equal(SKILL_CATALOG.at(-2), entry, "the Git card comes right before Handoff");
|
||||
assert.equal(SKILL_CATALOG.at(-1).skill, "plan2code-handoff", "the Handoff card is last");
|
||||
// The card order is skills.js's order.
|
||||
const order = SKILLS.filter((s) => s.card).map((s) => s.skill);
|
||||
assert.equal(order.indexOf("plan2code-git") + 1, order.indexOf("plan2code-handoff"), "the Git card comes right before Handoff");
|
||||
assert.equal(order.at(-1), "plan2code-handoff", "the Handoff card is last");
|
||||
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), order, "the catalog draws in that order");
|
||||
for (const isGit of [true, false, undefined]) {
|
||||
for (const pending of [0, 3, null]) {
|
||||
const scan = { hasAgents: true, pending, ...(isGit === undefined ? {} : { isGit }) };
|
||||
@@ -327,12 +327,10 @@ test("git: the board stays locked from a click until the agent's next post, not
|
||||
assert.equal(boardAwaiting({ sentAt, updatedAt: "2026-10-10T05:15:51.000Z", cardsAwaiting: 2 }), true);
|
||||
assert.equal(boardAwaiting({ sentAt, cardsAwaiting: 1, adrift: true }), false, "an agent gone quiet releases the lock");
|
||||
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
assert.match(app, /const gitMode = \(\) =>[^;]*gitAwaiting\(\)/, "the busy mode includes gitAwaiting()");
|
||||
assert.match(app, /const gitLocked = \(\) => gitMode\(\) !== "idle";/, "gitLocked is anything but idle");
|
||||
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("function renderGitBoard("));
|
||||
assert.match(send, /local\.gitSentAt = Date\.now\(\);\s*save\(\);/, "a board click records when it was sent, and saves it");
|
||||
assert.match(app, /sentAt: local\.gitSentAt[\s\S]{0,80}updatedAt: S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
|
||||
// gitMode, gitLocked and the click's gitSentAt are page tests now (the board
|
||||
// stays locked in test-web-console-page-git.mjs); what feeds them is here.
|
||||
const selectors = fs.readFileSync(new URL("../src/web-console/public/selectors.js", import.meta.url), "utf8");
|
||||
assert.match(selectors, /sentAt: page\.local\.gitSentAt[\s\S]{0,80}updatedAt: page\.S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
|
||||
});
|
||||
|
||||
/* ------------------------------------------- the git board's pure helpers */
|
||||
@@ -563,19 +561,12 @@ test("git board: boardPrLink builds the link for a pushed feature branch only",
|
||||
|
||||
test("git board: the page draws it from git-board.js, with no inline styles", () => {
|
||||
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
|
||||
assert.match(app, /^import [^;]+ from "\.\/git-board\.js";/m, "app.js imports git-board.js");
|
||||
assert.match(app, /^import [^;]+ from "\.\/git-board-view\.js";/m, "app.js imports git-board-view.js");
|
||||
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.match(app, /const isGitBoard = \(\) => S && S\.workflow === "git" && S\.git;/);
|
||||
assert.match(app, /i: "__git", type: "git", op/, "a click is one __git action");
|
||||
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
|
||||
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
|
||||
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
||||
const start = app.indexOf("/* ------------------------------------------------------------ git board */");
|
||||
const end = app.indexOf("/* ------------------------------------------------------------- welcome */");
|
||||
assert.ok(start > 0 && end > start);
|
||||
assert.doesNotMatch(app.slice(start, end), /setAttribute\(\s*["']style["']|\.style\./, "the board sets no inline styles");
|
||||
assert.doesNotMatch(view, /setAttribute\(\s*["']style["']|\.style\./, "nor does its view");
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { parseArgs } from "../src/web-console/lib.mjs";
|
||||
import { parseArgs } from "../src/web-console/files.mjs";
|
||||
import { BASE, cli, consoleSession, cookieFor, ENV, HOME, payload, ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
||||
|
||||
@@ -783,6 +783,19 @@ test("a finish is refused while its command still has a placeholder", () => {
|
||||
assert.match(res.stderr, /placeholder/);
|
||||
});
|
||||
|
||||
// The Subagents tab would otherwise spin on a helper long after the session ended.
|
||||
test("a finish is refused while a reported helper still shows as running", () => {
|
||||
const helper = (state, result) => ({ id: "h1", title: "Check the tests", ask: "Run them.", state, ...(result ? { result } : {}) });
|
||||
const running = cli(["post", "--session", sid, "--file", payload("fin-h-run.json", { helpers: [helper("running")], finish: { headline: "Done", command: "/x" } })], {
|
||||
expectFail: true,
|
||||
});
|
||||
assert.equal(running.status, 3);
|
||||
assert.match(running.stderr, /still shows as running/);
|
||||
assert.match(running.stderr, /"h1"/);
|
||||
const settled = cli(["post", "--session", sid, "--file", payload("fin-h-done.json", { helpers: [helper("done", "All pass.")], finish: { headline: "Done", command: "/x" } })]);
|
||||
assert.equal(settled.status, 0);
|
||||
});
|
||||
|
||||
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" } })],
|
||||
|
||||
@@ -147,30 +147,33 @@ import {
|
||||
import {
|
||||
appendLedger,
|
||||
attachmentName,
|
||||
chatReplyLines,
|
||||
checkDocument,
|
||||
initialWorkspace,
|
||||
insideGitRepo,
|
||||
pendingFiles,
|
||||
latestOpenCaps,
|
||||
pendingWorkspaceChanges,
|
||||
PROTECTED_CONSOLE_FILES,
|
||||
readLedger,
|
||||
repoRoots,
|
||||
} from "../src/web-console/sessions.mjs";
|
||||
import { scanProject, removeSpec, SPEC_STATES } from "../src/web-console/scan.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
initialWorkspace,
|
||||
pendingWorkspaceChanges,
|
||||
readWorkspaceCursor,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
} from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
latestOpenCaps,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspaceCursor,
|
||||
resetSubagentCursor,
|
||||
writeSubagentCursor,
|
||||
writeSubagentSetting,
|
||||
repoRoots,
|
||||
scanProject,
|
||||
removeSpec,
|
||||
SPEC_STATES,
|
||||
validate,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
} from "../src/web-console/settings.mjs";
|
||||
import { ROOT, HOME, cli, PDF, postPatch, ask } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
// 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
|
||||
@@ -223,34 +226,17 @@ test("every console workflow the page names ships the 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", () => {
|
||||
// The dashboard draws its cards from the page's own catalog, so every card
|
||||
// has to be filled in and launch into a real SKILL.md. Which skills have a
|
||||
// card is held against install.js in test-web-console-skills.mjs.
|
||||
test("every dashboard card is filled in and launches a real skill", () => {
|
||||
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");
|
||||
assert.ok(!SKILL_CATALOG.some((e) => e.skill === "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`);
|
||||
@@ -1773,7 +1759,6 @@ test("skip: the last open card goes to Send, a middle one to the next unstaged,
|
||||
test("page: the Workspace dialog, meter pill and new modules are in the page, with no inline styles or scripts", () => {
|
||||
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");
|
||||
for (const id of [
|
||||
"workspace-modal",
|
||||
"workspace-title",
|
||||
@@ -1800,7 +1785,6 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
|
||||
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
|
||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.match(app, new RegExp(`^import [^;]+ from "\\./${m.replace(".", "\\.")}";`, "m"), `app.js imports ${m}`);
|
||||
}
|
||||
// The CSP refuses style attributes and inline script: the new markup has neither.
|
||||
const added = [
|
||||
@@ -1812,23 +1796,18 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.doesNotMatch(block, /<script/i);
|
||||
assert.doesNotMatch(block, /\son[a-z]+=/i, "no inline event handlers");
|
||||
}
|
||||
assert.doesNotMatch(app, /setAttribute\(\s*["']style["']/, "no style attributes set from script");
|
||||
});
|
||||
|
||||
test("page: the footer label opens the workspace instead of copying", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.ok(app.includes('$("footer-where").addEventListener("click", openWorkspace)'));
|
||||
assert.doesNotMatch(app, /\$\("footer-where"\)\.addEventListener\("blur"/, "the copied-state blur handler is gone");
|
||||
assert.ok(app.includes('"Open workspace: " + label'));
|
||||
assert.ok(app.includes("footerLabel(") && app.includes("FOOTER_TIERS"));
|
||||
// The dashboard keeps the footer for the workspace label, minus the summary and Send.
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
assert.ok(app.includes('foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()))'));
|
||||
assert.doesNotMatch(app, /foot\.hidden = Boolean\(isDashboard\(\)/, "the dashboard no longer hides the whole footer");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.footer\.is-dash \.footer-summary,\s*\.footer\.is-dash \.footer-actions \{ display: none; \}/);
|
||||
assert.match(css, /\.footer\.is-dash \.footer-where:not\(\[hidden\]\) \{ display: block;/, "narrow screens keep the label on the dashboard");
|
||||
// Every typing place offers @name suggestions.
|
||||
assert.equal((app.match(/attachMentions\((ta|input)\);/g) || []).length, 4, "Ask, card note, notes panel, text answer");
|
||||
// Every typing place offers @name suggestions: the Ask pane and the notes panel
|
||||
// (screens/ask.js) and the card note and text answer (screens/cards.js).
|
||||
const read = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", f), "utf8");
|
||||
const count = (text) => (text.match(/attachMentions\((ta|input)\);/g) || []).length;
|
||||
assert.equal(count(read("ask.js")) + count(read("cards.js")), 4, "Ask, card note, notes panel, text answer");
|
||||
});
|
||||
|
||||
// The quoted flags between -NoProfile and -EncodedCommand, whichever quote style.
|
||||
@@ -2086,7 +2065,7 @@ test("subagents: the store round-trips per project and workflow under the consol
|
||||
try {
|
||||
const project = path.join(home, "My Repo");
|
||||
const script = `
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/lib.mjs", import.meta.url).href)});
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/settings.mjs", import.meta.url).href)});
|
||||
const project = ${JSON.stringify(project)};
|
||||
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5 });
|
||||
const flipped = project.replace(/My Repo$/, "MY REPO");
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// Page tests for the Ask tab: a Quick question and the agent's reply, the
|
||||
// starters, a retry after a failed send, a new conversation, a picture attached
|
||||
// to a note, and the Subagents tab. Run with:
|
||||
// node --test scripts/test-web-console-page-ask.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
|
||||
import { reportedHelper } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question, the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// A real 1x1 PNG. The page decodes and re-encodes every picture before it
|
||||
// uploads, so the fake JPEG the server tests use would be refused here.
|
||||
const PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||
"base64"
|
||||
);
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The questions in a send's chat entries (the first send also carries the
|
||||
// conversation's start, which is not a question).
|
||||
const messages = (got) => got.chat.filter((e) => e.kind === "message");
|
||||
|
||||
// Opens the Ask tab and returns its question box.
|
||||
async function openAsk(s) {
|
||||
await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click();
|
||||
const box = s.page.locator("#ask-input");
|
||||
await box.waitFor();
|
||||
return box;
|
||||
}
|
||||
|
||||
// Types a question and presses Send in the Ask pane.
|
||||
async function askQuestion(s, text) {
|
||||
const box = s.page.locator("#ask-input");
|
||||
await box.fill(text);
|
||||
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
|
||||
}
|
||||
|
||||
// What a person sees break: a question typed in Ask that never reaches the
|
||||
// agent, or an answer that never shows.
|
||||
test("a Quick question typed in Ask reaches the agent under chat, and the agent's reply shows in the pane", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "Where does the export live?");
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "chat");
|
||||
const [asked, ...more] = messages(got);
|
||||
assert.equal(more.length, 0, "one question, one message");
|
||||
assert.equal(asked.text, "Where does the export live?");
|
||||
assert.match(got.reply, /^Quick question: Where does the export live\?$/m);
|
||||
// The question is in the pane, and the box is empty for the next one.
|
||||
await s.page.locator(".ask-row.person").getByText("Where does the export live?").waitFor();
|
||||
assert.equal(await s.page.locator("#ask-input").inputValue(), "");
|
||||
|
||||
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md: "It lives in `exports/`." }] } });
|
||||
const reply = s.page.locator(".ask-row.agent");
|
||||
await reply.getByText("It lives in").waitFor();
|
||||
assert.match(await textOf(reply), /exports\//);
|
||||
assert.match(await textOf(s.page.locator(".ask-counter")), /1/);
|
||||
});
|
||||
|
||||
// What a person sees break: starters that send for them, or that are missing
|
||||
// from an empty conversation.
|
||||
test("an empty Ask offers starters, a click only fills the box, and nothing is sent until Send", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const box = await openAsk(s);
|
||||
const starters = s.page.locator(".ask-starters .ask-starter");
|
||||
await starters.first().waitFor();
|
||||
assert.ok((await starters.count()) >= 1, "no starter questions are offered");
|
||||
const first = (await textOf(starters.first())).trim();
|
||||
await starters.first().click();
|
||||
assert.equal(await box.inputValue(), first, "the starter fills the box");
|
||||
assert.equal(s.wait(1).code === 0, false, "a starter click sent something");
|
||||
|
||||
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
|
||||
assert.deepEqual(messages(collect(s)).map((e) => e.text), [first]);
|
||||
// With a question in the list the starters are gone.
|
||||
await s.page.locator(".ask-starters").waitFor({ state: "detached" });
|
||||
});
|
||||
|
||||
// What a person sees break: a question lost when the network hiccups, or
|
||||
// sent twice when they press Retry.
|
||||
test("a failed send shows Not sent with Retry, and Retry delivers the question once", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
// The page's own request fails as a dropped connection would.
|
||||
await s.page.route("**/chat", (route) => route.abort());
|
||||
await askQuestion(s, "Is the header row kept?");
|
||||
const row = s.page.locator(".ask-row.person.pending");
|
||||
await row.getByText("Not sent").waitFor();
|
||||
assert.equal(s.wait(1).code === 0, false, "a failed send reached the agent");
|
||||
|
||||
await s.page.unroute("**/chat");
|
||||
await row.getByRole("button", { name: "Retry" }).click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(messages(got).map((e) => e.text), ["Is the header row kept?"]);
|
||||
await s.page.locator(".ask-row.person:not(.pending)").getByText("Is the header row kept?").waitFor();
|
||||
assert.equal(s.wait(1).code === 0, false, "the question was sent twice");
|
||||
});
|
||||
|
||||
// What a person sees break: New conversation that leaves the old rows, or
|
||||
// that does not start the next question in a fresh conversation.
|
||||
test("New conversation clears the pane back to the starters, and the next question belongs to the new conversation", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "First question");
|
||||
const first = collect(s);
|
||||
assert.equal(messages(first)[0].conversation, 1);
|
||||
await s.page.locator(".ask-row.person:not(.pending)").waitFor();
|
||||
|
||||
await s.page.getByRole("button", { name: "New conversation" }).click();
|
||||
await s.page.locator(".ask-row").waitFor({ state: "detached" });
|
||||
await s.page.locator(".ask-starters").waitFor();
|
||||
|
||||
await askQuestion(s, "Second question");
|
||||
const second = collect(s);
|
||||
assert.deepEqual(messages(second).map((e) => e.text), ["Second question"]);
|
||||
assert.equal(messages(second)[0].conversation, 2);
|
||||
});
|
||||
|
||||
// What a person sees break: a picture that shows in the tray but never goes
|
||||
// to the agent, or goes without the note it belongs to.
|
||||
test("a picture attached to a note uploads, and the send carries it in the note's images entry", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").waitFor();
|
||||
const aside = s.page.locator("#aside");
|
||||
await aside.locator('input[type="file"]').setInputFiles({ name: "shot.png", mimeType: "image/png", buffer: PNG });
|
||||
await aside.locator(".attach-thumb.is-ready").waitFor();
|
||||
await aside.locator("#thread-q1").fill("See the screenshot.");
|
||||
|
||||
await s.page.click("#btn-send");
|
||||
const got = collect(s);
|
||||
const note = got.actions.find((a) => a.i === "q1" && a.type === "comment");
|
||||
assert.ok(note, `a note action for q1: ${JSON.stringify(got.actions)}`);
|
||||
assert.equal(note.text, "See the screenshot.");
|
||||
assert.equal(note.images.length, 1);
|
||||
assert.equal(note.images[0].name, "shot.png");
|
||||
assert.ok(note.images[0].path, "the image names the file the console saved");
|
||||
});
|
||||
|
||||
// What a person sees break: the Subagents tab missing once helpers are
|
||||
// reported, or showing the wrong state.
|
||||
test("posting helpers adds a Subagents tab that lists each with its state and result", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 2" }, items: PLAN_QUESTION.items },
|
||||
});
|
||||
const tab = s.page.locator("nav").getByRole("button", { name: /^Subagents/ });
|
||||
assert.equal(await tab.count(), 0, "no tab before any helper is reported");
|
||||
|
||||
s.post({
|
||||
helpers: [
|
||||
reportedHelper("h1", { title: "Read the store helpers", state: "running" }),
|
||||
reportedHelper("h2", { title: "Check the tests", state: "done", result: "All 9 pass." }),
|
||||
],
|
||||
});
|
||||
await tab.waitFor();
|
||||
await tab.click();
|
||||
const card = s.page.locator("#main .sa-card");
|
||||
await card.getByRole("heading", { name: "Subagents" }).waitFor();
|
||||
const rows = card.locator(".sa-row");
|
||||
assert.equal(await rows.count(), 2);
|
||||
const running = rows.filter({ hasText: "Read the store helpers" });
|
||||
const done = rows.filter({ hasText: "Check the tests" });
|
||||
assert.match(await textOf(running.locator(".sa-pill")), /running/i);
|
||||
assert.match(await textOf(done.locator(".sa-pill")), /done/i);
|
||||
assert.match(await textOf(done), /All 9 pass\./);
|
||||
assert.match(await textOf(running), /Find the callers of applyPatch/);
|
||||
});
|
||||
@@ -0,0 +1,689 @@
|
||||
// Page tests for question cards: every kind answered on the page and sent, the
|
||||
// sign-off card, and a redraw keeping your place. Run with:
|
||||
// node --test scripts/test-web-console-page-cards.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf } from "./page-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
test("a session with nothing posted yet shows its starting screen, and stop ends its server", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
assert.match(await s.page.innerText("#main"), /Starting Plan/);
|
||||
assert.equal(await s.page.locator("#main .pose-stage").count(), 1);
|
||||
await s.stop();
|
||||
assert.equal(await s.answers(), false, "the server still answers after stop()");
|
||||
});
|
||||
|
||||
test("a text answer typed on the page reaches the agent as it was typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type, text }) => ({ i, type, text })),
|
||||
[{ i: "q1", type: "answer", text: "audit-export" }]
|
||||
);
|
||||
assert.match(got.reply, /audit-export/);
|
||||
});
|
||||
|
||||
// The agent's side of one question: settle what came before, post `item`
|
||||
// alone, and wait for its card.
|
||||
async function ask(s, item) {
|
||||
s.post({ settle: true, items: [item] });
|
||||
const card = itemCard(s.page, item.id);
|
||||
await card.waitFor();
|
||||
return card;
|
||||
}
|
||||
|
||||
// The answer an agent reads for item `id`, without the routing fields.
|
||||
function answerTo(got, id) {
|
||||
const action = got.actions.find((a) => a.i === id);
|
||||
assert.ok(action, `the send carries an answer to ${id}: ${JSON.stringify(got.actions)}`);
|
||||
const { i, type, kind, ...answer } = action;
|
||||
assert.equal(type, "answer");
|
||||
return answer;
|
||||
}
|
||||
|
||||
const opt = (k, text) => ({ k, text, detail: `The ${text.toLowerCase()} option.` });
|
||||
|
||||
test("every kind of question card sends the answer shape the agent reads", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
|
||||
let card = await ask(s, { id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] });
|
||||
await card.getByLabel("JSON").check();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c1"), { k: "B" });
|
||||
assert.equal(got.reply, "Export format: B");
|
||||
|
||||
card = await ask(s, { id: "c2", kind: "choice", title: "Where it goes", body: "Where?", allowOther: true, options: [opt("A", "Email"), opt("B", "Slack")] });
|
||||
await card.getByRole("radio", { name: "Something else, in your own words" }).check();
|
||||
await card.locator("textarea").fill("A shared drive");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c2"), { text: "A shared drive" });
|
||||
assert.equal(got.reply, "Where it goes: A shared drive");
|
||||
|
||||
card = await ask(s, { id: "m1", kind: "multi", title: "Columns", body: "Which?", options: [opt("1", "Date"), opt("2", "User"), opt("3", "Action")], presets: [{ label: "Date and user", ks: ["1", "2"] }] });
|
||||
await card.getByRole("button", { name: "Date and user" }).click();
|
||||
await card.getByLabel("Action").check();
|
||||
await card.locator("textarea").fill("and the IP");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "m1"), { ks: ["1", "2", "3"], text: "and the IP" });
|
||||
assert.equal(got.reply, "Columns: 1, 2, 3; and the IP");
|
||||
|
||||
card = await ask(s, { id: "t1", kind: "text", title: "What to call it", body: "A name.", pattern: "^[a-z][a-z0-9-]*$", patternHint: "Lowercase letters, digits and hyphens.", placeholder: "For example: audit-export" });
|
||||
const field = card.locator("input[type=text]");
|
||||
// The suggestion is the placeholder without its "For example:" lead-in.
|
||||
await card.getByRole("button", { name: "Autofill suggestion" }).click();
|
||||
assert.equal(await field.inputValue(), "audit-export");
|
||||
await field.fill("Audit Export");
|
||||
await card.getByText("Lowercase letters, digits and hyphens.").waitFor();
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a value that breaks the pattern is not sendable");
|
||||
await field.fill("audit-export");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "t1"), { text: "audit-export" });
|
||||
assert.equal(got.reply, "What to call it: audit-export");
|
||||
|
||||
card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
await card.getByRole("button", { name: "Yes" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y1"), { yes: true });
|
||||
assert.equal(got.reply, "Keep going: yes");
|
||||
|
||||
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Is this right?", summary: "- CSV\n- Mondays" });
|
||||
await card.getByRole("button", { name: "Yes, that is right" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "r1"), { ok: true });
|
||||
assert.equal(got.reply, "What we decided: confirmed");
|
||||
|
||||
card = await ask(s, { id: "k1", kind: "checklist", title: "Set up access", body: "Only you can do these.", steps: ["Create the app", "Paste its key"] });
|
||||
await card.locator("input[type=checkbox]").first().check();
|
||||
await card.getByRole("button", { name: "All done" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "k1"), { done: [0], state: "done" });
|
||||
assert.equal(got.reply, "Set up access: all done; did steps 1");
|
||||
|
||||
card = await ask(s, { id: "n1", kind: "menu", title: "What next", body: "Pick one.", options: [opt("1", "Keep planning"), opt("2", "Stop here")] });
|
||||
await card.getByLabel("Stop here").check();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "n1"), { k: "2" });
|
||||
assert.equal(got.reply, "What next: 2");
|
||||
|
||||
const rows = [
|
||||
{ id: "a", title: "Read the data", body: "x" },
|
||||
{ id: "b", title: "Write the file", body: "y" },
|
||||
];
|
||||
card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Reorder or rename.", rows });
|
||||
await card.getByRole("button", { name: "No changes" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "l1"), { text: "no changes" });
|
||||
assert.equal(got.reply, "The steps: no changes");
|
||||
|
||||
card = await ask(s, { id: "l2", kind: "list", title: "The steps again", body: "Reorder or rename.", rows });
|
||||
await card.locator("input[type=text]").first().fill("Read the audit log");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(
|
||||
answerTo(got, "l2").rows.map((r) => [r.id, r.title]),
|
||||
[["a", "Read the audit log"], ["b", "Write the file"]]
|
||||
);
|
||||
assert.equal(got.reply, "The steps again: the list: Read the audit log, then Write the file; renamed Read the data to Read the audit log");
|
||||
|
||||
s.post({ settle: true, items: [{ id: "x1", kind: "notice", title: "Heads up", body: "The export runs **nightly**." }] });
|
||||
await s.page.getByText("The export runs").waitFor();
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a notice alone gives nothing to send");
|
||||
});
|
||||
|
||||
test("a sign-off card opens its document, and each verdict reaches the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: {
|
||||
docs: [{ id: "report", title: "Completion report", blocks: [{ id: "b1", state: "settled", md: "## Summary\n\nPhase 3 adds the /tasks endpoints." }] }],
|
||||
},
|
||||
});
|
||||
const signoff = (id, extra = {}) => ({
|
||||
id,
|
||||
kind: "review",
|
||||
title: "Approve this phase",
|
||||
doc: "report",
|
||||
body: "Read the report, then approve it or say what to change.",
|
||||
verdicts: [
|
||||
{ id: "approve", label: "Approve this phase" },
|
||||
{ id: "changes", label: "I want changes" },
|
||||
{ id: "discard", label: "Throw it away", danger: true },
|
||||
],
|
||||
...extra,
|
||||
});
|
||||
|
||||
let card = await ask(s, signoff("so1"));
|
||||
await card.getByRole("button", { name: /Read .*Completion report.* in full/ }).click();
|
||||
await s.page.getByText("Phase 3 adds the /tasks endpoints.").waitFor();
|
||||
assert.ok(await s.page.getByText("Phase 3 adds the /tasks endpoints.").isVisible(), "the report is on screen");
|
||||
// The danger verdict is marked as such: here the class is the behaviour.
|
||||
await s.page.locator("#views").getByRole("button", { name: /^Questions/ }).click();
|
||||
card = itemCard(s.page, "so1");
|
||||
assert.match(await card.getByRole("button", { name: "Throw it away" }).getAttribute("class"), /danger/);
|
||||
assert.doesNotMatch(await card.getByRole("button", { name: "Approve this phase" }).getAttribute("class"), /danger/);
|
||||
|
||||
await card.getByRole("button", { name: "Approve this phase" }).click();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "so1"), { verdict: "approve" });
|
||||
|
||||
card = await ask(s, signoff("so2"));
|
||||
await card.getByRole("button", { name: "I want changes" }).click();
|
||||
await card.locator("textarea").fill("Keep the header row.");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "so2"), { verdict: "changes", text: "Keep the header row." });
|
||||
});
|
||||
|
||||
const longText = (n) => Array.from({ length: n }, (_, i) => `Paragraph ${i + 1}. The export runs every night and keeps a year of rows.`).join("\n\n");
|
||||
|
||||
// The agent posts something unrelated, and the page redraws: wait until the
|
||||
// new title is drawn.
|
||||
async function unrelatedPost(s, title) {
|
||||
s.post({ title });
|
||||
await s.page.waitForFunction((want) => document.getElementById("title").textContent.includes(want), title);
|
||||
}
|
||||
|
||||
test("a redraw keeps your place: the scroll and the focused field survive an agent post", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }],
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: longText(80) }] }],
|
||||
},
|
||||
});
|
||||
|
||||
// Reading a question part-way down: the card scrolls itself.
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.evaluate((el) => (el.scrollTop = 400));
|
||||
assert.equal(await card.evaluate((el) => el.scrollTop), 400, "the question card scrolls");
|
||||
await unrelatedPost(s, "Audit export, take two");
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), 400);
|
||||
|
||||
// Typing in its answer box: the box keeps the focus and the caret, and the
|
||||
// card stays where it was.
|
||||
const field = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
await field.click();
|
||||
await field.pressSequentially("audit-ex");
|
||||
await field.evaluate((el) => el.setSelectionRange(3, 3));
|
||||
const typingAt = await itemCard(s.page, "q1").evaluate((el) => el.scrollTop);
|
||||
await unrelatedPost(s, "Audit export, take three");
|
||||
const after = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
assert.deepEqual(await after.evaluate((el) => [el === document.activeElement, el.value, el.selectionStart]), [true, "audit-ex", 3]);
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), typingAt);
|
||||
|
||||
// On a doc: the column scrolls.
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
await s.page.getByText("Paragraph 80.").waitFor();
|
||||
await s.page.locator("#main").evaluate((el) => (el.scrollTop = 900));
|
||||
const docBefore = await scrollTopOf(s.page, "#main");
|
||||
assert.ok(docBefore > 0, "the doc column scrolls");
|
||||
await unrelatedPost(s, "Audit export, take four");
|
||||
assert.equal(await scrollTopOf(s.page, "#main"), docBefore);
|
||||
});
|
||||
|
||||
// The progress line under the title, once the page has drawn `want`.
|
||||
async function progressSays(s, want) {
|
||||
await s.page.waitForFunction((w) => document.getElementById("progress-text").textContent === w, want, { timeout: 5000 }).catch(() => {});
|
||||
return (await s.page.innerText("#progress-text")).trim();
|
||||
}
|
||||
|
||||
// One answered question, so a question workflow has something to count.
|
||||
const answered = { id: "a1", kind: "text", title: "What to call it", body: "A name.", status: "answered", answer: { text: "audit-export" } };
|
||||
const open = { id: "o1", kind: "text", title: "Who uses it", body: "Who?" };
|
||||
|
||||
test("a build's header counts its tasks, 0 done included, and a question workflow counts its answers", async (t) => {
|
||||
for (const workflow of ["implement", "implement-review", "quick-task"]) {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow,
|
||||
payload: { headline: { stage: "Phase 3", cleared: 3, total: 9 }, items: [answered] },
|
||||
});
|
||||
assert.equal(await progressSays(s, "3 of 9 done"), "3 of 9 done", `${workflow} counts its tasks`);
|
||||
s.post({ headline: { cleared: 0 } });
|
||||
assert.equal(await progressSays(s, "0 of 9 done"), "0 of 9 done", `${workflow}: 0 done is 0 done, not the answered card`);
|
||||
// A build between counts (a review starting at total 0) shows its stage.
|
||||
s.post({ headline: { stage: "Reviewing the phase", cleared: 0, total: 0 }, items: [open] });
|
||||
assert.equal(await progressSays(s, "Reviewing the phase"), "Reviewing the phase", `${workflow} shows its stage at total 0`);
|
||||
assert.equal(await s.page.locator("#progress-bar").isHidden(), true, `${workflow}: no track for a stage`);
|
||||
await s.stop();
|
||||
}
|
||||
|
||||
// A question workflow that set a total and never moved `cleared` fills as
|
||||
// cards are answered, and at total 0 counts its cards instead of the stage.
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { headline: { stage: "Charting", cleared: 0, total: 4 }, items: [answered] },
|
||||
});
|
||||
assert.equal(await progressSays(s, "1 of 4 answered"), "1 of 4 answered");
|
||||
s.post({ headline: { total: 0 }, items: [open] });
|
||||
assert.equal(await progressSays(s, "1 of 2 answered"), "1 of 2 answered");
|
||||
});
|
||||
|
||||
test("an answer typed over several lines reaches the agent under its title, never as reply lines of its own", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").locator("textarea").fill("audit-export\nIdea name: not a heading");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.equal(answerTo(got, "q1").text, "audit-export\nIdea name: not a heading");
|
||||
assert.ok(got.reply.includes("What to call it: audit-export\n Idea name: not a heading"), `the second line is not indented under its title: ${JSON.stringify(got.reply)}`);
|
||||
});
|
||||
|
||||
test("a redraw keeps the place of the dashboard, the waiting screen and the finished screen, and a new question starts at its top", async (t) => {
|
||||
// The dashboard's menu scrolls itself.
|
||||
let s = await openSession(await suite.browser(), { t, workflow: "dashboard" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
await s.page.getByRole("button", { name: "Skip the intro" }).click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
await s.page.locator("#main > .dash").evaluate((el) => (el.scrollTop = 150));
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard scrolls");
|
||||
await unrelatedPost(s, "Dashboard, take two");
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard lost its place");
|
||||
await s.stop();
|
||||
|
||||
// A build with nothing to ask yet: the waiting screen, and then its finish.
|
||||
s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
|
||||
});
|
||||
await s.page.setViewportSize({ width: 1280, height: 300 });
|
||||
const pane = "#main > .waiting-pane";
|
||||
await s.page.locator(pane).waitFor();
|
||||
await s.page.locator(pane).evaluate((el) => (el.scrollTop = 60));
|
||||
const waitingAt = await scrollTopOf(s.page, pane);
|
||||
assert.ok(waitingAt > 0, "the waiting screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take two");
|
||||
assert.equal(await scrollTopOf(s.page, pane), waitingAt, "the waiting screen lost its place");
|
||||
|
||||
s.post({ finish: { headline: "Phase 1 is done", body: longText(30), command: "/plan2code-3-implement specs/audit-export/overview.md" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
const end = "#main > .card";
|
||||
await s.page.locator(end).evaluate((el) => (el.scrollTop = 300));
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take three");
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen lost its place");
|
||||
await s.stop();
|
||||
|
||||
// Part-way down one question, a new one arrives: it starts at its top.
|
||||
s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").evaluate((el) => (el.scrollTop = 400));
|
||||
s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: longText(40) }] });
|
||||
await itemCard(s.page, "q2").waitFor();
|
||||
assert.equal(await itemCard(s.page, "q2").evaluate((el) => el.scrollTop), 0, "the new question opened part-way down");
|
||||
});
|
||||
|
||||
// The accent colour as the browser resolves it, and a button's outline colour,
|
||||
// so "wears the accent" is read off the screen, not off a class name.
|
||||
const accentOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--accent)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
});
|
||||
const outlineOf = (button) => button.evaluate((b) => getComputedStyle(b).borderTopColor);
|
||||
const warnOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--warn)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
});
|
||||
|
||||
// What a person sees break: the way forward on a sign-off card looks like any
|
||||
// other choice.
|
||||
test("on a sign-off card, approve and yes are outlined in the accent until picked, and the others are not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement" });
|
||||
const accent = await accentOf(s.page);
|
||||
const review = (id, verdicts) => ({ id, kind: "review", title: "Sign off " + id, body: "Read it.", verdicts });
|
||||
|
||||
let card = await ask(s, review("so1", [{ id: "approve", label: "Approve this phase" }, { id: "changes", label: "I want changes" }]));
|
||||
const approve = card.getByRole("button", { name: "Approve this phase" });
|
||||
assert.equal(await outlineOf(approve), accent, "an unpicked approve is outlined in the accent");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "I want changes" })), accent, "the other verdict is not");
|
||||
await approve.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await approve.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, approve fills with the accent");
|
||||
|
||||
card = await ask(s, review("so2", [{ id: "yes", label: "Build it" }, { id: "no", label: "Not yet" }]));
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Build it" })), accent, "an unpicked yes is outlined too");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "Not yet" })), accent);
|
||||
});
|
||||
|
||||
// What a person sees break: Skip this one turns into a full-size button, or
|
||||
// the quick answer under a note box does.
|
||||
test("Skip this one and a comment box's quick answer are the same small accent button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }];
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", required: false, rows });
|
||||
const skip = card.getByRole("button", { name: "Skip this one" });
|
||||
const quick = card.getByRole("button", { name: "No changes" });
|
||||
const look = (b) => b.evaluate((x) => { const c = getComputedStyle(x); return [c.fontSize, c.paddingTop, c.paddingLeft, c.color]; });
|
||||
assert.deepEqual(await look(skip), await look(quick), "the two chips look alike");
|
||||
const [size, , , colour] = await look(skip);
|
||||
assert.equal(size, "12px", "small, not a full-size button");
|
||||
assert.equal(colour, await accentOf(s.page), "in the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: a safe yes looks like any button, or a risky yes
|
||||
// stops warning.
|
||||
test("a confirm's safe yes and a recap's yes are outlined in the accent, and a dangerous yes stays red", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const accent = await accentOf(s.page);
|
||||
const warn = await warnOf(s.page);
|
||||
|
||||
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
const yes = card.getByRole("button", { name: "Yes" });
|
||||
assert.equal(await outlineOf(yes), accent, "a safe, unpicked yes wears the accent");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "No" })), accent, "the no does not");
|
||||
await yes.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await yes.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, it fills");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "Delete it", body: "Really?", danger: true });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes" })), warn, "a dangerous yes stays red");
|
||||
|
||||
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Right?", summary: "- CSV" });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes, that is right" })), accent, "the recap's yes wears the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: a long question runs off the window with nothing
|
||||
// to say there is more, or the fade stays on at the very end.
|
||||
test("a card cut by the window fades at its bottom edge while there is more below", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: longText(40) });
|
||||
const fades = () => card.evaluate((el) => { const c = getComputedStyle(el); return (c.maskImage || c.webkitMaskImage || "none") !== "none"; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); return c && c.scrollHeight > c.clientHeight + 4; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") !== "none"; });
|
||||
assert.equal(await fades(), true, "a cut card fades at the bottom");
|
||||
await card.evaluate((el) => (el.scrollTop = el.scrollHeight));
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") === "none"; });
|
||||
assert.equal(await fades(), false, "at the end, the fade is gone");
|
||||
});
|
||||
|
||||
// What a person sees break: a rename typed in a list is lost when the agent
|
||||
// posts or Ctrl+Enter sends before the field was left.
|
||||
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }, { id: "b", title: "Write the file", body: "y" }];
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", rows });
|
||||
const first = card.locator("input.row-title").first();
|
||||
await first.click();
|
||||
await first.fill("Read the audit log");
|
||||
// The field is still focused: it has not changed or blurred.
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
await unrelatedPost(s, "Steps, take two");
|
||||
assert.equal(await itemCard(s.page, "l1").locator("input.row-title").first().inputValue(), "Read the audit log", "the agent post kept the typed name");
|
||||
await itemCard(s.page, "l1").locator("input.row-title").first().focus();
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "Ctrl+Enter sent");
|
||||
assert.deepEqual(answerTo(got, "l1").rows.map((r) => [r.id, r.title]), [["a", "Read the audit log"], ["b", "Write the file"]]);
|
||||
});
|
||||
|
||||
// What a person sees break: a send the agent already collected still shows as
|
||||
// being with the agent, locking a question it left open.
|
||||
test("a send made before the last collection is never shown as still with the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: "A name." });
|
||||
// Sent from another tab: this page never learns of it except from the session.
|
||||
await s.page.evaluate(() =>
|
||||
fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [{ i: "q1", type: "answer", kind: "text", text: "audit-export" }], reply: "What to call it: audit-export" }),
|
||||
})
|
||||
);
|
||||
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
|
||||
await lock.waitFor();
|
||||
assert.equal(await card.locator("textarea").count(), 0, "before the agent collects it, the card is locked");
|
||||
// The agent collects it, leaves the question open and waits again.
|
||||
assert.equal(s.wait(10).code, 0);
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await card.locator("textarea").waitFor();
|
||||
assert.equal(await lock.count(), 0, "after the collection, it is not shown as sent");
|
||||
});
|
||||
|
||||
// What a person sees break: a note box on a card above the git board grows and
|
||||
// squeezes the board, or the card is cut short under it.
|
||||
test("a note box over the git board grows no box, and the card flows at its own height", async (t) => {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
const confirm = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
|
||||
const git = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "git",
|
||||
project: dir,
|
||||
payload: { reread: true, board: { describe: "export-more" }, items: [confirm] },
|
||||
});
|
||||
await git.page.getByRole("tablist").waitFor();
|
||||
const gitCard = itemCard(git.page, "y1");
|
||||
await gitCard.waitFor();
|
||||
const note = gitCard.locator("textarea").first();
|
||||
const gitBox = await note.evaluate((el) => ({ min: el.style.minHeight, height: el.offsetHeight }));
|
||||
assert.equal(gitBox.min, "", "no height was filled in for the note box");
|
||||
assert.ok(gitBox.height < 120, `the note box keeps its ordinary height over the board: ${gitBox.height}`);
|
||||
assert.ok(await gitCard.evaluate((el) => el.scrollHeight <= el.clientHeight + 1), "the card is not shrunk under the board");
|
||||
|
||||
// The same card away from the board does fill the free height of the card.
|
||||
const plan = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [confirm] } });
|
||||
const planBox = plan.page.locator('[data-item="y1"] textarea').first();
|
||||
await planBox.waitFor();
|
||||
await plan.page.waitForFunction(() => document.querySelector('[data-item="y1"] textarea').offsetHeight >= 160);
|
||||
assert.ok((await planBox.evaluate((el) => el.offsetHeight)) > gitBox.height, "away from the board, the note box grows");
|
||||
});
|
||||
|
||||
const three = ["First", "Second", "Third"].map((name, n) => ({ id: `q${n + 1}`, kind: "text", title: `${name} question`, body: `Body ${n + 1}.` }));
|
||||
|
||||
// What a person sees break: Previous and Next stop walking the open questions.
|
||||
test("Previous and Next walk the questions still waiting, and the ends have no button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: three } });
|
||||
const pager = s.page.getByRole("navigation", { name: "Move between the questions waiting" });
|
||||
const shown = () => s.page.locator("#main [data-item]").first().getAttribute("data-item");
|
||||
await pager.getByText("1 of 3 waiting").waitFor();
|
||||
assert.equal(await pager.getByRole("button", { name: /Previous/ }).count(), 0, "nothing before the first");
|
||||
await pager.getByRole("button", { name: /Next.*Second question/ }).click();
|
||||
await pager.getByText("2 of 3 waiting").waitFor();
|
||||
assert.equal(await shown(), "q2");
|
||||
await pager.getByRole("button", { name: /Next.*Third question/ }).click();
|
||||
await pager.getByText("3 of 3 waiting").waitFor();
|
||||
assert.equal(await pager.getByRole("button", { name: /Next/ }).count(), 0, "nothing after the last");
|
||||
await pager.getByRole("button", { name: /Previous.*Second question/ }).click();
|
||||
await pager.getByText("2 of 3 waiting").waitFor();
|
||||
assert.equal(await shown(), "q2");
|
||||
});
|
||||
|
||||
// What a person sees break: Skip this one does nothing, or leaves you on the
|
||||
// card you skipped.
|
||||
test("Skip this one on an optional card moves on, and the skip reaches the agent", async (t) => {
|
||||
const items = three.map((q, n) => ({ ...q, required: n !== 2 ? false : true }));
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items } });
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.getByRole("button", { name: "Skip this one" }).click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#main [data-item]")?.dataset.item === "q2");
|
||||
assert.equal(await itemCard(s.page, "q3").getByRole("button", { name: "Skip this one" }).count(), 0, "a required card cannot be skipped");
|
||||
await itemCard(s.page, "q2").locator("textarea").fill("Ana");
|
||||
await s.page.getByRole("navigation", { name: "Move between the questions waiting" }).getByRole("button", { name: /Next/ }).click();
|
||||
await itemCard(s.page, "q3").locator("textarea").fill("Bo");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type, text }) => ({ i, type, text })),
|
||||
[{ i: "q1", type: "skip", text: undefined }, { i: "q2", type: "answer", text: "Ana" }, { i: "q3", type: "answer", text: "Bo" }]
|
||||
);
|
||||
});
|
||||
|
||||
// What a person sees break: an answered question can be edited again, or says
|
||||
// nothing about what was answered.
|
||||
test("a settled card is a record: your answer in words, the options as marks, and no form", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
s.post({
|
||||
settle: true,
|
||||
items: [
|
||||
{ id: "c1", kind: "choice", title: "Export format", body: "Which?", options: [opt("A", "CSV"), opt("B", "JSON")], status: "answered", answer: { k: "B" } },
|
||||
{ id: "q9", kind: "text", title: "Still open", body: "Next." },
|
||||
],
|
||||
});
|
||||
await s.page.locator("#sidebar").getByRole("button", { name: /Export format/ }).click();
|
||||
const card = itemCard(s.page, "c1");
|
||||
await card.waitFor();
|
||||
const record = card.locator(".answered");
|
||||
assert.match(await record.innerText(), /Your answer[\s\S]*JSON/i);
|
||||
assert.match(await record.innerText(), /Locked\./);
|
||||
assert.equal(await card.locator("input, textarea").count(), 0, "a record has no inputs");
|
||||
});
|
||||
|
||||
// What a person sees break: a card still takes edits after Send, or never
|
||||
// opens again when the agent hands it back.
|
||||
test("a sent card locks, and the agent's next post on it unlocks it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [three[0]] } });
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.locator("textarea").fill("Ana");
|
||||
await s.page.click("#btn-send");
|
||||
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
|
||||
await lock.waitFor();
|
||||
assert.match(await card.locator(".answered").innerText(), /Sent[\s\S]*Ana/i);
|
||||
assert.equal(await card.locator("textarea").count(), 0, "no form while the agent has it");
|
||||
s.wait(10);
|
||||
s.post({ items: [{ id: "q1", status: "reopened", thread: [{ who: "agent", text: "Which Ana?" }] }], agent: { status: "waiting" } });
|
||||
await card.locator("textarea").waitFor();
|
||||
assert.equal(await lock.count(), 0, "the next post gives the card back");
|
||||
});
|
||||
|
||||
// What a person sees break: the "something else" box takes the words but the
|
||||
// pick sent is still the listed option, or the pick is lost on a switch back.
|
||||
test("Something else in your own words replaces the pick, and picking an option again drops the words", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const card = await ask(s, { id: "c1", kind: "choice", title: "Where", body: "Where?", options: [opt("A", "Email"), opt("B", "Slack")] });
|
||||
await card.getByLabel("Email").check();
|
||||
const other = card.getByRole("radio", { name: "Something else, in your own words" });
|
||||
await other.check();
|
||||
await card.locator("textarea.other-text").fill("A shared drive");
|
||||
assert.equal(await card.getByLabel("Email").isChecked(), false, "the options and the other share one group");
|
||||
await card.getByLabel("Slack").check();
|
||||
await other.check();
|
||||
assert.equal(await card.locator("textarea.other-text").inputValue(), "A shared drive", "the words survive a switch");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c1"), { text: "A shared drive" });
|
||||
});
|
||||
|
||||
// What a person sees break: a note typed on a card is dropped by the verdict,
|
||||
// or is lost when the verdict comes first.
|
||||
test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
await card.getByLabel("Anything to add?").fill("Only on weekdays.");
|
||||
await card.getByRole("button", { name: "Yes" }).click();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y1"), { yes: true, text: "Only on weekdays." });
|
||||
assert.equal(got.reply, "Keep going: yes; Only on weekdays.");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "And this", body: "Also?" });
|
||||
await card.getByRole("button", { name: "No" }).click();
|
||||
await card.getByLabel("Anything to add?").fill("Not this quarter.");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y2"), { yes: false, text: "Not this quarter." });
|
||||
});
|
||||
|
||||
/* ----------------------------------------------------------------- docs */
|
||||
|
||||
// What a person sees break: a guess reads like a decision, or a draft does.
|
||||
test("a doc tags an assumed block and a draft block, and shows a file block's text", async (t) => {
|
||||
const project = tempProject({ "notes/facts.md": "The export keeps **a year** of rows.\n" });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
project,
|
||||
payload: {
|
||||
docs: [
|
||||
{
|
||||
id: "map",
|
||||
title: "What we've agreed",
|
||||
blocks: [
|
||||
{ id: "b1", state: "settled", md: "Runs nightly." },
|
||||
{ id: "b2", state: "assumed", md: "Output is CSV." },
|
||||
{ id: "b3", state: "draft", md: "Maybe a weekly digest." },
|
||||
{ id: "b4", file: "notes/facts.md" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const block = (id) => s.page.locator(`#main [data-block="${id}"]`);
|
||||
await block("b4").waitFor();
|
||||
assert.equal(await block("b1").innerText(), "Runs nightly.", "a settled block has no tag");
|
||||
assert.match(await block("b2").innerText(), /^assumed for now, still open\s+Output is CSV\.$/i);
|
||||
assert.match(await block("b3").innerText(), /^draft\s+Maybe a weekly digest\.$/i);
|
||||
assert.match(await block("b4").innerText(), /The export keeps a year of rows\./, "the file's text is on the page");
|
||||
});
|
||||
|
||||
// What a person sees break: Download hands over something other than the
|
||||
// document, or loses which parts are still guesses.
|
||||
test("Download offers a Markdown file with the doc's title, blocks and marks", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: "Runs nightly." }, { id: "b2", state: "assumed", md: "Output is CSV." }] }],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const [download] = await Promise.all([s.page.waitForEvent("download"), s.page.getByRole("button", { name: "Download" }).click()]);
|
||||
assert.equal(download.suggestedFilename(), "what-we-ve-agreed.md");
|
||||
const chunks = [];
|
||||
for await (const c of await download.createReadStream()) chunks.push(c);
|
||||
assert.equal(Buffer.concat(chunks).toString("utf8"), "# What we've agreed\n\nRuns nightly.\n\n> **Assumed for now, still open.**\n\nOutput is CSV.");
|
||||
});
|
||||
|
||||
// What a person sees break: the brief button turns up where no playbook
|
||||
// answers it, or sends a different range than the one picked.
|
||||
test("a pathfinder session offers Write a brief, and the picked range reaches the agent", async (t) => {
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
assert.equal(await plain.page.locator("#btn-brief").isHidden(), true, "no brief button outside pathfinder");
|
||||
await plain.stop();
|
||||
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: { agent: { status: "waiting" } } });
|
||||
await s.page.getByRole("button", { name: "Write a brief" }).first().click();
|
||||
const dialog = s.page.locator("#brief-modal");
|
||||
await dialog.getByLabel("This week").check();
|
||||
await dialog.getByRole("button", { name: "Write the brief" }).click();
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "a brief request was sent");
|
||||
assert.deepEqual(got.actions.map(({ i, type, range }) => ({ i, type, range })), [{ i: "__brief", type: "brief", range: "this week" }]);
|
||||
assert.equal(got.reply, "Write a brief for this week.");
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
// Page tests for the dashboard: a spec in the picker, a card picked and
|
||||
// started, the launch send the agent collects, and its `resume` turning the
|
||||
// page into the launched skill's starting screen. Run with:
|
||||
// node --test scripts/test-web-console-page-dashboard.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
||||
import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A project that is set up (AGENTS.md) with one spec holding a Plan draft.
|
||||
// A PLAN-DRAFT whose Status line says only "Draft" (no "Resume at Phase N")
|
||||
// scans as `planned`, which the picker labels "Ready to document". Plan is
|
||||
// still lit for it (only exploring, fixed and documented-or-later grey Plan
|
||||
// out); Document is the state's own next step.
|
||||
const DRAFT_PROJECT = {
|
||||
"AGENTS.md": "# AGENTS.md\n\nA small demo project.\n",
|
||||
"specs/demo/PLAN-DRAFT-20261017.md": "# Plan draft: demo\n\n**Status:** Draft\n\nA lunch vote for the team.\n",
|
||||
};
|
||||
|
||||
// What a real agent posts on the dashboard (plan2code.md, "The menu"): its
|
||||
// judgment on top of the scan, then it waits.
|
||||
const MENU = {
|
||||
menu: {
|
||||
note: "One spec on disk, with a plan drafted.",
|
||||
recommend: "plan2code-2-document",
|
||||
details: { "plan2code-2-document": "Plan drafted" },
|
||||
},
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
test("a Plan launch from the dashboard carries the picked spec, and its resume turns the page to Starting Plan", async (t) => {
|
||||
const project = tempProject(DRAFT_PROJECT);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
|
||||
// The picker shows the spec with its state, and opens on it.
|
||||
const chip = main.getByRole("button").filter({ hasText: /^demo/ });
|
||||
await chip.waitFor();
|
||||
// The state is drawn in capitals, so the match ignores case.
|
||||
const chipText = await textOf(chip);
|
||||
assert.match(chipText, /Ready to document/i, "the spec chip names its state");
|
||||
assert.match(chipText, /plan drafted/, "the spec chip says how far it got");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "true", "the picker opens on the only spec");
|
||||
|
||||
// The Plan card is lit for this spec; picking it asks to confirm.
|
||||
const planCard = main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) });
|
||||
assert.equal(await planCard.isEnabled(), true, "the Plan card is greyed for a drafted plan");
|
||||
await planCard.click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const launch = got.actions.find((a) => a.i === "__launch");
|
||||
assert.ok(launch, `the send carries a launch: ${JSON.stringify(got.actions)}`);
|
||||
assert.deepEqual(
|
||||
{ i: launch.i, skill: launch.skill, workflow: launch.workflow, spec: launch.spec },
|
||||
{ i: "__launch", skill: "plan2code-1-plan", workflow: "plan", spec: "specs/demo" }
|
||||
);
|
||||
|
||||
// `resume` is the one command to run, naming the session, workflow and spec.
|
||||
const head = `node "${CONSOLE_CLI}" `;
|
||||
assert.ok(got.resume.startsWith(head), `resume runs this console: ${got.resume}`);
|
||||
const args = got.resume.slice(head.length).split(" ");
|
||||
assert.deepEqual(args, ["open", "--resume", s.sid, "--no-open", "--workflow", "plan", "--spec", "specs/demo"]);
|
||||
|
||||
// `skillFile` is offered only when the skill's SKILL.md sits beside the
|
||||
// console's own folder, as in an install. Run from this repo's source tree
|
||||
// (src/web-console/), that is a plan2code-1-plan/ folder next to the repo,
|
||||
// which does not exist, so the send leaves it out (console-launches.md:
|
||||
// "absent outside an install").
|
||||
assert.equal("skillFile" in got, false, `a source-tree launch names no skillFile: ${got.skillFile}`);
|
||||
|
||||
// The agent runs `resume` first: the page leaves the menu for Plan's
|
||||
// starting screen while the skill is read.
|
||||
const r = cli(args, { cwd: s.project });
|
||||
assert.equal(r.status, 0, `resume failed: ${r.stderr}`);
|
||||
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
|
||||
});
|
||||
|
||||
// A project holding one fixed bug (a diagnosis Quick Task marked Fixed) and
|
||||
// one drafted plan. The fixed bug is touched last, so it is the newest spec on
|
||||
// disk: the picker must still open on the plan, since a finished spec is never
|
||||
// the default.
|
||||
function fixedProject() {
|
||||
const project = tempProject({
|
||||
...DRAFT_PROJECT,
|
||||
"specs/old-bug/DIAGNOSIS-20261017.md": "# Diagnosis: old bug\n\n**Status:** Fixed\n\nThe save button lost its handler.\n",
|
||||
});
|
||||
const later = new Date(Date.now() + 60_000);
|
||||
fs.utimesSync(path.join(project, "specs/old-bug/DIAGNOSIS-20261017.md"), later, later);
|
||||
return project;
|
||||
}
|
||||
|
||||
// Past Planny's wake-up and, on this console home's first run, the Welcome,
|
||||
// to the menu.
|
||||
async function toTheMenu(s) {
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.click();
|
||||
await skip.waitFor({ state: "hidden" });
|
||||
const main = s.page.locator("#main");
|
||||
const heading = main.getByRole("heading", { name: "What are we doing today?" });
|
||||
await heading.waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) {
|
||||
await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
}
|
||||
return main;
|
||||
}
|
||||
|
||||
// Sets the picker's "Hide unavailable workflows" switch. Looks are kept per
|
||||
// console home, so each test sets the one it needs rather than trusting the
|
||||
// default.
|
||||
async function hideUnavailable(main, on) {
|
||||
const box = main.getByRole("switch", { name: "Hide unavailable workflows" });
|
||||
if ((await box.isChecked()) !== on) await main.getByText("Hide unavailable workflows").click();
|
||||
assert.equal(await box.isChecked(), on);
|
||||
}
|
||||
|
||||
const chipFor = (main, name) => main.getByRole("button").filter({ hasText: new RegExp(`^${name}`) });
|
||||
|
||||
test("a fixed bug is hidden while unavailable workflows are, dimmed when they show, and never the picker's default", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
|
||||
const main = await toTheMenu(s);
|
||||
|
||||
// Hidden while the switch is on.
|
||||
await hideUnavailable(main, true);
|
||||
const demo = chipFor(main, "demo");
|
||||
await demo.waitFor();
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the picker opens on the plan, not the newer fixed bug");
|
||||
assert.equal(await chipFor(main, "old-bug").count(), 0, "the fixed bug's chip is hidden while unavailable workflows are");
|
||||
|
||||
// Switched off: the chip shows, labelled and dimmed, and still not picked.
|
||||
await hideUnavailable(main, false);
|
||||
const bug = chipFor(main, "old-bug");
|
||||
await bug.waitFor();
|
||||
assert.match(await textOf(bug), /Bug fixed/i, "the chip names its state");
|
||||
assert.doesNotMatch(await textOf(bug), /bug fixed\s+bug fixed/i, "the scan's detail does not repeat the label");
|
||||
assert.equal(await bug.getAttribute("aria-current"), "false", "the fixed bug is not picked");
|
||||
const opacity = await bug.evaluate((b) => Number(getComputedStyle(b).opacity));
|
||||
assert.ok(opacity < 1, `the fixed bug's chip is dimmed (opacity ${opacity})`);
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the plan stays picked");
|
||||
});
|
||||
|
||||
test("a fixed bug's Delete asks once with no name to type, while any other spec asks for its name", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
|
||||
const main = await toTheMenu(s);
|
||||
await hideUnavailable(main, false);
|
||||
await chipFor(main, "old-bug").waitFor();
|
||||
|
||||
const dialog = s.page.locator("#delete-modal");
|
||||
const go = s.page.locator("#delete-go");
|
||||
const nameStep = s.page.locator("#delete-confirm");
|
||||
|
||||
// Any other spec: the first press only reveals the name step.
|
||||
await main.getByRole("button", { name: "Delete the spec demo" }).click({ force: true });
|
||||
await dialog.waitFor();
|
||||
assert.equal(await textOf(go), "Delete this spec…");
|
||||
await go.click();
|
||||
await nameStep.waitFor();
|
||||
assert.equal(await go.isDisabled(), true, "the final button waits for the name");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
|
||||
// The fixed bug: a visible Delete, its own warning, and one press sends it.
|
||||
const del = main.getByRole("button", { name: "Delete the spec old-bug" });
|
||||
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labelled button");
|
||||
await del.click();
|
||||
await dialog.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#delete-warn")), /The bug is fixed, so this only clears the write-up/);
|
||||
assert.equal(await textOf(go), "Delete it");
|
||||
assert.equal(await nameStep.isHidden(), true, "no name step for a fixed bug");
|
||||
await go.click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(await nameStep.isHidden(), true, "the name step never showed");
|
||||
const action = got.actions.find((a) => a.i === "__delete");
|
||||
assert.deepEqual({ type: action?.type, spec: action?.spec }, { type: "delete", spec: "specs/old-bug" });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The picker's switching, the first-open wake-up, handoffs, the update banner,
|
||||
// the workspace scope, and the pose that carries a launch into the work.
|
||||
|
||||
const lightOf = (main, command) => main.getByRole("button").filter({ has: main.page().locator("code", { hasText: new RegExp(`^${command}$`) }) });
|
||||
const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { hasText: new RegExp(`^${name}`) });
|
||||
|
||||
// What a person would see break: picking another target leaves the launch
|
||||
// aimed at the old spec, or the cards lit for it.
|
||||
test("picking Start from scratch instead of a spec greys Document, and a launch then carries no spec", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(s);
|
||||
const document = lightOf(main, "/plan2code-2-document");
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
assert.equal(await document.isEnabled(), true, "Document is lit for the drafted spec");
|
||||
|
||||
// From scratch there is no draft to document: the card greys.
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
assert.equal(await document.isDisabled(), true, "Document is greyed with no spec picked");
|
||||
assert.equal(await chipFor(main, "demo").getAttribute("aria-current"), "false");
|
||||
|
||||
// Back on the spec it is lit again; then from scratch once more to launch.
|
||||
await chipFor(main, "demo").click();
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
assert.equal(await document.isEnabled(), true, "Document is lit again for the spec");
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
await lightOf(main, "/plan2code-1-plan").click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
const launch = collect(s).actions.find((a) => a.i === "__launch");
|
||||
assert.equal(launch.skill, "plan2code-1-plan");
|
||||
assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`);
|
||||
});
|
||||
|
||||
// What a person would see break: the intro cannot be skipped, or it replays
|
||||
// on every reload of the same tab.
|
||||
test("Skip the intro ends the first-open wake-up at once, and a reload of the tab does not play it again", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.waitFor();
|
||||
await toTheMenu(s);
|
||||
assert.equal(await skip.isVisible(), false);
|
||||
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
assert.equal(await skip.isVisible(), false, "the intro does not play again in this tab");
|
||||
});
|
||||
|
||||
// A project with no spec, only a handoff written for it (the Handoff skill's
|
||||
// file pair under the test's own handoffs folder), removed with the test.
|
||||
const HANDOFF_DOC = "# Handoff: Lunch vote\n\n## Next task\n\nWire the vote button to the tally.\n\n## Notes\n\nA long body line.\n";
|
||||
function handoffProject(t) {
|
||||
const project = tempProject({ "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n" });
|
||||
const made = cli(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"], { cwd: project }).json;
|
||||
fs.writeFileSync(made.path, HANDOFF_DOC);
|
||||
t.after(() => {
|
||||
fs.rmSync(made.path, { force: true });
|
||||
fs.rmSync(made.path.replace(/\.md$/, ".json"), { force: true });
|
||||
});
|
||||
return { project, made };
|
||||
}
|
||||
|
||||
async function openHandoffMenu(t) {
|
||||
const { project, made } = handoffProject(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
const chip = chipFor(main, "Lunch vote");
|
||||
await chip.waitFor();
|
||||
return { s, main, chip, made };
|
||||
}
|
||||
|
||||
// What a person would see break: a handoff is not offered when it is all the
|
||||
// project has, or picking it still shows the skill cards beside the preview.
|
||||
test("a handoff shows as a dashed Handoff chip even with no spec, and picking it swaps the cards for a preview of four buttons", async (t) => {
|
||||
const { main, chip } = await openHandoffMenu(t);
|
||||
assert.match(await textOf(chip), /Handoff/i, "the chip is labelled Handoff");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "false", "a handoff is offered, not picked for you");
|
||||
assert.equal(await chip.evaluate((b) => getComputedStyle(b).borderTopStyle), "dashed", "the chip's border is dashed");
|
||||
assert.ok(await lightOf(main, "/plan2code-1-plan").isVisible(), "the cards show before a handoff is picked");
|
||||
|
||||
await chip.click();
|
||||
assert.equal(await chip.getAttribute("aria-current"), "true");
|
||||
await main.getByRole("heading", { name: "Lunch vote" }).waitFor();
|
||||
assert.match(await textOf(main), /Wire the vote button to the tally\./, "the preview quotes the Next task");
|
||||
for (const name of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
|
||||
assert.equal(await main.getByRole("button", { name, exact: true }).count(), 1, `the preview has ${name}`);
|
||||
}
|
||||
assert.equal(await lightOf(main, "/plan2code-1-plan").count(), 0, "the skill cards give way to the preview");
|
||||
assert.equal(await main.getByRole("switch", { name: "Hide unavailable workflows" }).count(), 0, "and so does their toggle");
|
||||
});
|
||||
|
||||
// What a person would see break: Pick it up here sends nothing, or sends more
|
||||
// than the handoff's id.
|
||||
test("Pick it up here sends a pickup naming the handoff, and the page turns to its launch screen", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await chip.click();
|
||||
await main.getByRole("button", { name: "Pick it up here" }).click();
|
||||
const got = collect(s);
|
||||
const pick = got.actions.find((a) => a.i === "__pickup");
|
||||
assert.deepEqual({ type: pick?.type, handoff: pick?.handoff }, { type: "pickup", handoff: made.id });
|
||||
assert.match(got.resume, /--workflow quick-task$/, "the CLI read the handoff's own workflow");
|
||||
await main.getByRole("heading", { name: "Waking up Lunch vote" }).waitFor();
|
||||
});
|
||||
|
||||
// What a person would see break: Read it all opens nothing, or Copy puts the
|
||||
// wrong words on the clipboard.
|
||||
test("Read it all opens the handoff's text, and Copy puts a prompt naming its file on the clipboard", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
await chip.click();
|
||||
|
||||
await main.getByRole("button", { name: "Read it all" }).click();
|
||||
const reader = s.page.locator("#handoff-modal");
|
||||
await reader.getByText("A long body line.").waitFor();
|
||||
await s.page.keyboard.press("Escape");
|
||||
await reader.waitFor({ state: "hidden" });
|
||||
|
||||
const copy = main.getByRole("button", { name: "Copy for a new conversation" });
|
||||
await copy.click();
|
||||
await main.getByRole("button", { name: "Copied" }).waitFor();
|
||||
const text = await s.page.evaluate(() => navigator.clipboard.readText());
|
||||
assert.match(text, /^Read the handoff at .*\.md and carry on with its Next task\.$/);
|
||||
assert.ok(text.includes(made.id), `the prompt names the handoff's file: ${text}`);
|
||||
});
|
||||
|
||||
// What a person would see break: Delete asks for a name, or sends a spec
|
||||
// delete instead of the handoff's.
|
||||
test("a handoff's Delete asks once in its own dialog and sends a delete naming the handoff", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await chip.click();
|
||||
await main.getByRole("button", { name: "Delete", exact: true }).click();
|
||||
const dialog = s.page.locator("#delete-modal");
|
||||
await dialog.waitFor();
|
||||
assert.equal(await textOf(s.page.locator("#delete-title")), "Delete this handoff?");
|
||||
assert.equal(await s.page.locator("#delete-warn-handoff").isVisible(), true, "the warning says where handoffs live");
|
||||
assert.equal(await s.page.locator("#delete-confirm").isHidden(), true, "no name to type");
|
||||
await s.page.locator("#delete-go").click();
|
||||
const action = collect(s).actions.find((a) => a.i === "__delete");
|
||||
assert.deepEqual({ type: action?.type, handoff: action?.handoff, spec: action?.spec }, { type: "delete", handoff: made.id, spec: undefined });
|
||||
});
|
||||
|
||||
// A newer release on record, so a console that boots now has an update to
|
||||
// announce (the check reads this file for an hour instead of asking the
|
||||
// network). The file is put back as the suite had it.
|
||||
function aNewerReleaseExists(t) {
|
||||
const file = path.join(HOME, "update-check.json");
|
||||
const before = fs.readFileSync(file, "utf8");
|
||||
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
|
||||
t.after(() => fs.writeFileSync(file, before));
|
||||
}
|
||||
|
||||
// What a person would see break: the banner shows on a build's page, or the
|
||||
// dashboard never offers it.
|
||||
test("the update banner shows on the dashboard only, and its dismiss hides it", async (t) => {
|
||||
aNewerReleaseExists(t);
|
||||
const browser = await suite.browser();
|
||||
const build = await openSession(browser, { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const dash = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(dash);
|
||||
const banner = main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ });
|
||||
await banner.waitFor();
|
||||
// The build's server booted under the same record; a later frame has landed
|
||||
// on its page by the time this text shows, and it still has no banner.
|
||||
build.post({ agent: { status: "working", activity: "Task 1 of 1, one more look" } });
|
||||
await build.page.getByText("Task 1 of 1, one more look").first().waitFor();
|
||||
assert.equal(await build.page.getByText("UPDATE AVAILABLE").count(), 0, "a build's page has no banner");
|
||||
|
||||
await main.getByRole("button", { name: "Dismiss until next time" }).click();
|
||||
await banner.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
// What a person would see break: two dashboard tabs of one session, on
|
||||
// different picks, keep taking the workspace's folders back from each other.
|
||||
test("two dashboard tabs on different picks leave the workspace scope with the last pick and ask for it no more", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const mainA = await toTheMenu(s);
|
||||
const second = await s.context.newPage();
|
||||
second.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await second.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
const mainB = await toTheMenu({ page: second });
|
||||
const asks = { a: 0, b: 0 };
|
||||
s.page.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.a++);
|
||||
second.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.b++);
|
||||
const scopeOf = () => s.page.evaluate(async () => (await (await fetch("/workspace?check=1", { cache: "no-store" })).json()).scope || "");
|
||||
assert.equal(await scopeOf(), "specs/demo", "both tabs opened on the spec");
|
||||
|
||||
// The second tab moves to Start from scratch: its folders become the project's own.
|
||||
await chipFor(mainB, "Start from scratch").click();
|
||||
await pickedChip(mainB, "Start from scratch").waitFor();
|
||||
assert.ok(await until(async () => (await scopeOf()) === ""), "the scope followed the second tab");
|
||||
|
||||
// The first tab keeps its pick and takes a frame from the agent after the change.
|
||||
s.post({ menu: { ...MENU.menu, note: "A second look from the agent." } });
|
||||
await mainA.getByText("A second look from the agent.").waitFor();
|
||||
assert.equal(await pickedChip(mainA, "demo").count(), 1, "the first tab still has its own pick");
|
||||
assert.equal(asks.a, 0, "the tab that did not move never asked for its own scope back");
|
||||
assert.equal(asks.b, 1, "the tab that moved asked once");
|
||||
assert.equal(await scopeOf(), "", "the scope stays with the last pick");
|
||||
});
|
||||
|
||||
// What a person would see break: Planny is rebuilt on every screen change, so
|
||||
// his animation restarts as the launch becomes the work.
|
||||
test("the pose pane a launch shows is the very element the starting and waiting screens keep, and the waiting pane shows the agent's activity", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(s);
|
||||
await lightOf(main, "/plan2code-1-plan").click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
// The launching screen, with its pose; mark that exact element.
|
||||
const pane = s.page.locator("#main > [data-pose]");
|
||||
await pane.waitFor();
|
||||
const pose = await pane.getAttribute("data-pose");
|
||||
await pane.evaluate((el) => (el.__sameElement = true));
|
||||
|
||||
// The agent resumes the session as Plan: the starting screen reuses the pane.
|
||||
const got = collect(s);
|
||||
const args = got.resume.slice(`node "${CONSOLE_CLI}" `.length).split(" ");
|
||||
assert.equal(cli(args, { cwd: s.project }).status, 0);
|
||||
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
|
||||
assert.equal(await pane.getAttribute("data-pose"), pose, "the same pose carries into the starting screen");
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane was kept, not rebuilt");
|
||||
|
||||
// The agent starts work and says what it is doing: the waiting screen shows it,
|
||||
// still in the same pane.
|
||||
s.post({ agent: { status: "working", activity: "Reading the plan draft" } });
|
||||
await main.getByText("Reading the plan draft").waitFor();
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane survives into the waiting screen");
|
||||
s.post({ agent: { status: "working", activity: "Writing the first questions" } });
|
||||
await main.getByText("Writing the first questions").waitFor();
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "and survives each state frame after it");
|
||||
});
|
||||
|
||||
// What a person would see break: a quick-task build points at a Plan tab that
|
||||
// does not open, or another skill's page gains a pointer it has no list for.
|
||||
test("a quick-task build's waiting pane points at its Plan tab, and a plan session with the same tab gets no pointer", async (t) => {
|
||||
const plan = { id: "plan", title: "Plan", blocks: [{ id: "steps", state: "settled", md: "## Steps\n\n- [ ] **1.** Wire the vote button" }] };
|
||||
const working = { agent: { status: "working", activity: "Step 1 of 1" } };
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { docs: [plan], ...working } });
|
||||
const pane = s.page.locator("#main > .waiting-pane");
|
||||
await pane.waitFor();
|
||||
const jump = pane.getByRole("button", { name: "Plan", exact: true });
|
||||
await jump.waitFor();
|
||||
await jump.click();
|
||||
await s.page.locator("#main").getByText("Wire the vote button").waitFor();
|
||||
|
||||
const other = await openSession(await suite.browser(), { t, workflow: "plan", payload: { docs: [plan], ...working } });
|
||||
const otherPane = other.page.locator("#main > .waiting-pane");
|
||||
await otherPane.waitFor();
|
||||
assert.equal(await otherPane.getByRole("button", { name: "Plan", exact: true }).count(), 0, "a plan session has no live task list to point at");
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
// Page tests for the git board: the Changes, Branches and Sync tabs drawn
|
||||
// from a real repository, each tab's content on show when it is picked. Run
|
||||
// with:
|
||||
// node --test scripts/test-web-console-page-git.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test. The fixture repo is built under the scrubbed git config
|
||||
// that skill-script-helpers.mjs sets for the whole process, so the console's
|
||||
// own snapshot reads it the way the fixture wrote it.
|
||||
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, tempProject, textOf, itemCard } from "./page-test-helpers.mjs";
|
||||
import { until } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A repo with one commit on main, a second branch, and one file changed on
|
||||
// the tree since that commit.
|
||||
function gitProject() {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
g("branch", "feature/export-csv");
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
// What a real Git skill posts once the board is up (notes/git.md): a reread,
|
||||
// so the console snapshots the repo, and the description of what changed.
|
||||
const BOARD = { reread: true, board: { describe: "export-more" } };
|
||||
|
||||
test("the git board shows Changes, Branches and Sync, and each tab shows its own content", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
|
||||
const { page } = s;
|
||||
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const panel = page.getByRole("tabpanel");
|
||||
|
||||
await page.getByRole("tablist").waitFor();
|
||||
assert.deepEqual(
|
||||
(await page.getByRole("tab").allInnerTexts()).map((x) => x.trim().split(/\s/)[0]),
|
||||
["Changes", "Branches", "Sync"]
|
||||
);
|
||||
|
||||
await tab("Changes").click();
|
||||
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.startsWith("Changes"));
|
||||
await panel.getByText("src/app.js", { exact: true }).waitFor();
|
||||
assert.match(await textOf(panel), /src\/app\.js/);
|
||||
|
||||
await tab("Branches").click();
|
||||
await panel.getByText("feature/export-csv").first().waitFor();
|
||||
const branches = await textOf(panel);
|
||||
assert.match(branches, /feature\/export-csv/);
|
||||
assert.doesNotMatch(branches, /src\/app\.js/, "the Branches tab still shows the changed files");
|
||||
|
||||
await tab("Sync").click();
|
||||
await panel.getByText(/nothing to sync/).waitFor();
|
||||
const sync = await textOf(panel);
|
||||
assert.match(sync, /No remote yet, so nothing to sync/);
|
||||
assert.doesNotMatch(sync, /feature\/export-csv/, "the Sync tab still lists the branches");
|
||||
});
|
||||
|
||||
test("each git tab keeps its own scroll place, across a tab switch and an agent post", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await page.setViewportSize({ width: 1280, height: 260 });
|
||||
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const column = () => page.locator("#main").evaluate((el) => el.scrollTop);
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
await page.locator("#main").evaluate((el) => (el.scrollTop = 120));
|
||||
const changesAt = await column();
|
||||
assert.ok(changesAt > 0, "the board's column scrolls");
|
||||
// Another tab opens at its own place, not where Changes was left.
|
||||
await tab("Branches").click();
|
||||
await page.getByRole("tabpanel").getByText("feature/export-csv").first().waitFor();
|
||||
assert.equal(await column(), 0, "Branches opened at the place Changes was left");
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
assert.equal(await column(), changesAt, "Changes lost its place across the switch");
|
||||
// An agent post redraws the board: still the same place.
|
||||
s.post({ title: "Git, take two" });
|
||||
await page.waitForFunction(() => document.getElementById("title").textContent.includes("Git, take two"));
|
||||
assert.equal(await column(), changesAt, "Changes lost its place across a redraw");
|
||||
});
|
||||
|
||||
// The agent is sitting in `wait`, so the board is the person's to use. A fresh
|
||||
// session has the agent working, which locks every button but the tabs.
|
||||
const READY = { ...BOARD, agent: { status: "waiting" } };
|
||||
|
||||
// A repo with one commit, then two changes on the tree: src/app.js edited and
|
||||
// notes.md new. `branch` checks out a branch of its own (or "detached" a bare
|
||||
// commit), so the commit panel is the next step; on main the next step is to
|
||||
// start a branch. `remotes` names the remotes to add.
|
||||
function changesProject({ branch = null, remotes = [] } = {}) {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
g("branch", "feature/export-csv");
|
||||
for (const name of remotes) {
|
||||
const bare = tempProject();
|
||||
g("init", "-q", "--bare", bare);
|
||||
g("remote", "add", name, bare);
|
||||
}
|
||||
if (branch === "detached") g("checkout", "-q", "--detach");
|
||||
else if (branch) g("checkout", "-q", "-b", branch);
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
fs.writeFileSync(path.join(dir, "notes.md"), "Notes.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
const confirmCard = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
|
||||
const tabButton = (page, label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const tickBox = (page, file) => page.getByLabel(`Commit ${file}`);
|
||||
// The Branches tab's Switch button, for the one other branch.
|
||||
const switchButton = (page) => page.getByRole("tabpanel").getByRole("button", { name: "Switch" });
|
||||
// The board's step button, in the strip above the tab's content.
|
||||
const stepButton = (page, name) => page.locator(".git-step-actions").getByRole("button", { name });
|
||||
|
||||
// Whether the board's own controls (not its tabs or the pointer to another
|
||||
// tab) are all off, or at least one is on. Whatever tab the board has moved to,
|
||||
// a locked board has every one of them disabled.
|
||||
const boardControls = (page) => page.locator(".git-panel-tab").locator("button, input[type=checkbox], select");
|
||||
const usable = async (page) => {
|
||||
const off = await boardControls(page).evaluateAll((all) => all.filter((x) => !x.classList.contains("git-hint")).map((x) => x.disabled));
|
||||
return off.some((x) => !x);
|
||||
};
|
||||
// The board redraws a moment after its cause, so each check gets time to settle.
|
||||
const settles = (control, enabled) => until(async () => (await control.isEnabled()) === enabled, 8000);
|
||||
const settlesUsable = (page, want) => until(async () => (await usable(page)) === want, 8000);
|
||||
const titled = (page, text) => page.waitForFunction((x) => document.getElementById("title").textContent.includes(x), text);
|
||||
|
||||
test("the commit dialog sends the ticked files as one __git action, with its reply sentence", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "feature/x" }), payload: READY });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("button", { name: "Close" }).waitFor();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await panel.getByRole("button", { name: "Commit 1 file" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "the agent collected the click");
|
||||
assert.deepEqual(got.actions, [{ i: "__git", type: "git", op: "commit", files: ["src/app.js"], ignore: [] }]);
|
||||
assert.equal(got.reply, "Commit this file: src/app.js.");
|
||||
});
|
||||
|
||||
test("a board click is exactly one __git action", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Branches").click();
|
||||
await switchButton(page).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions.length, 1, "one click, one action");
|
||||
assert.equal(got.actions[0].i, "__git");
|
||||
assert.equal(got.actions[0].type, "git");
|
||||
assert.equal(got.reply, "Switch to feature/export-csv.");
|
||||
assert.notEqual(s.wait(1).code, 0, "nothing else was sent beside it");
|
||||
});
|
||||
|
||||
test("the board stays locked from a click until the agent's next post, not just until it is collected", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Branches").click();
|
||||
assert.ok(await settlesUsable(page, true), "the board is the person's before any click");
|
||||
await switchButton(page).click();
|
||||
assert.ok(await settlesUsable(page, false), "locked from the click");
|
||||
// The agent has the click now (it is running git), and the board still waits.
|
||||
assert.equal(s.wait(10).code, 0);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
assert.equal(await usable(page), false, "collected is not yet answered");
|
||||
// The agent's next post lets the board go.
|
||||
s.post({ title: "Switched", agent: { status: "waiting" } });
|
||||
await titled(page, "Switched");
|
||||
assert.ok(await settlesUsable(page, true), "the agent's post gave the board back");
|
||||
});
|
||||
|
||||
test("an open card of the agent's holds the board, and a notice does not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
assert.ok(await settlesUsable(page, true));
|
||||
s.post({ items: [{ id: "n1", kind: "notice", title: "Heads up", body: "Nothing to act on." }], agent: { status: "waiting" } });
|
||||
await page.getByText("Heads up", { exact: true }).waitFor();
|
||||
assert.equal(await usable(page), true, "a notice leaves the board alone");
|
||||
s.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
await itemCard(page, "y1").waitFor();
|
||||
assert.ok(await settlesUsable(page, false), "a question card holds the board");
|
||||
});
|
||||
|
||||
test("the git board lets go of a working agent that went adrift", async (t) => {
|
||||
const working = { agent: { status: "working", activity: "Looking at the repo" } };
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), clock: true, payload: { ...BOARD, ...working } });
|
||||
const { page } = s;
|
||||
assert.equal(await usable(page), false, "a working agent holds the board");
|
||||
// Nobody has listened for longer than the adrift limit. The board only
|
||||
// redraws on a post, and the agent is still "working" in it: the lock must
|
||||
// not outlive the agent.
|
||||
await page.clock.fastForward(200_000);
|
||||
s.post({ title: "Still on it", ...working });
|
||||
await titled(page, "Still on it");
|
||||
assert.ok(await settlesUsable(page, true), "an agent gone quiet gave the board back");
|
||||
});
|
||||
|
||||
test("the commit table keeps the person's ticks across an agent post, and a click re-seeds them", async (t) => {
|
||||
const dir = changesProject({ branch: "feature/x" });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: dir, payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// An agent post redraws the board: the person's tick stays off.
|
||||
s.post({ title: "Still looking", agent: { status: "waiting" } });
|
||||
await titled(page, "Still looking");
|
||||
assert.equal(await tickBox(page, "notes.md").isChecked(), false, "an agent post put the tick back");
|
||||
assert.equal(await tickBox(page, "src/app.js").isChecked(), true);
|
||||
// Their click goes out with the one file. Then the agent commits it and a new file turns up.
|
||||
await page.locator(".git-panel-actions").getByRole("button", { name: "Commit 1 file" }).click();
|
||||
assert.deepEqual(s.wait(10).actions[0].files, ["src/app.js"]);
|
||||
const g = gitInit(dir, "feature/x");
|
||||
g("add", "src/app.js");
|
||||
g("commit", "-q", "-m", "Edit app");
|
||||
fs.writeFileSync(path.join(dir, "later.md"), "Later.\n");
|
||||
s.post({ reread: true, title: "Committed", agent: { status: "waiting" } });
|
||||
await titled(page, "Committed");
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "later.md").waitFor();
|
||||
assert.equal(await tickBox(page, "notes.md").isChecked(), true, "the click dropped the old picks, so the table was seeded afresh");
|
||||
});
|
||||
|
||||
test("starting a branch for the changes carries the files ticked in the commit table", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await stepButton(page, /^Start a branch for/).click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
assert.ok(await settles(create, true), "a free name is composed from the description");
|
||||
await create.click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions.length, 1);
|
||||
assert.equal(got.actions[0].op, "create");
|
||||
assert.equal(got.actions[0].then, "commit");
|
||||
assert.deepEqual(got.actions[0].files, ["src/app.js"], "the unticked file stayed out");
|
||||
assert.match(got.reply, /^Create \S+ from main\. Then commit this file: src\/app\.js\.$/);
|
||||
});
|
||||
|
||||
test("a commit with no branch to land on carries the ticked files into the new branch", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "detached" }), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// The step is on the Branches tab, and its Commit button finds no branch to commit on.
|
||||
await tabButton(page, "Branches").click();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
assert.ok(await settles(create, true));
|
||||
await create.click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions[0].op, "create");
|
||||
assert.deepEqual(got.actions[0].files, ["src/app.js"]);
|
||||
assert.match(got.reply, /Then commit this file: src\/app\.js\.$/);
|
||||
});
|
||||
|
||||
test("Publish names a remote only when there is exactly one", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const published = async (remotes) => {
|
||||
const s = await openSession(browser, { t, workflow: "git", project: changesProject({ branch: "feature/x", remotes }), payload: READY });
|
||||
await tabButton(s.page, "Sync").click();
|
||||
await s.page.locator(".git-sync-actions").getByRole("button", { name: "Publish" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
await s.stop();
|
||||
return got;
|
||||
};
|
||||
const one = await published(["origin"]);
|
||||
assert.equal(one.actions[0].remote, "origin");
|
||||
assert.equal(one.reply, "Publish to origin.");
|
||||
const two = await published(["origin", "backup"]);
|
||||
assert.equal(Object.hasOwn(two.actions[0], "remote"), false, "with two remotes the agent is the one to ask which");
|
||||
assert.equal(two.reply, "Publish.");
|
||||
});
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
s.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
const note = itemCard(s.page, "y1").locator("textarea").first();
|
||||
await note.waitFor();
|
||||
const before = await note.evaluate((el) => el.offsetHeight);
|
||||
await note.fill(Array.from({ length: 8 }, (_, n) => `Line ${n + 1} of a longer note.`).join("\n"));
|
||||
const after = await note.evaluate((el) => el.offsetHeight);
|
||||
assert.ok(after > before + 40, `the note box grew with its text: ${before} to ${after}`);
|
||||
|
||||
// A folder that is no repository: the note points up only once there is a card up there.
|
||||
const bare = await openSession(await suite.browser(), { t, workflow: "git", payload: { reread: true, agent: { status: "waiting" } } });
|
||||
const aside = bare.page.locator(".git-note");
|
||||
await aside.waitFor();
|
||||
assert.match(await textOf(aside), /will ask what to do here in a moment/);
|
||||
bare.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
await itemCard(bare.page, "y1").waitFor();
|
||||
assert.match(await textOf(aside), /asks above what to do/);
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
// Page tests for Help, the first-run Welcome and the update notice's modal. Run
|
||||
// with:
|
||||
// node --test scripts/test-web-console-page-help.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test. Help's prose stays untested; these cover how the dialog
|
||||
// behaves.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, tempProject, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME } from "./web-console-test-helpers.mjs";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// The console home's saved looks, shared by every session of this file. Each
|
||||
// test that cares sets it first and the file is removed once the test is done.
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
function savedLooks(t, looks) {
|
||||
if (looks) fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks }));
|
||||
else fs.rmSync(LOOKS_FILE, { force: true });
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
|
||||
// A plan session on the person's turn: one text question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The dashboard, past Planny's wake-up. The Welcome may be on top of it. The
|
||||
// wake-up plays once per tab, so a reloaded page has no intro to skip.
|
||||
async function toTheDashboard(s) {
|
||||
const heading = s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" });
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.or(heading).first().waitFor();
|
||||
if (await skip.isVisible()) await skip.click();
|
||||
await heading.waitFor();
|
||||
}
|
||||
|
||||
const helpModal = (s) => s.page.locator("#help-modal");
|
||||
const tabButton = (s, id) => s.page.locator("#help-tab-" + id);
|
||||
const selectedTab = (s) => s.page.locator('#help-tabs [role="tab"][aria-selected="true"]');
|
||||
const focusedId = (s) => s.page.evaluate(() => document.activeElement && document.activeElement.id);
|
||||
|
||||
async function openHelp(s) {
|
||||
await s.page.click("#btn-about");
|
||||
await helpModal(s).waitFor();
|
||||
}
|
||||
|
||||
test("Help opens on a tab, moves between tabs with the arrow, Home and End keys, and closes with Escape", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Built on first open: the tab buttons are not in the page before it.
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), 0, "Help is built before it is opened");
|
||||
await openHelp(s);
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length, "one tab button per Help topic");
|
||||
|
||||
// A plain workflow page opens on the first topic, with focus on its tab.
|
||||
const ids = HELP_TABS.map((x) => x.id);
|
||||
assert.equal(await selectedTab(s).count(), 1, "exactly one tab is selected");
|
||||
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + ids[0]);
|
||||
assert.equal(await focusedId(s), "help-tab-" + ids[0], "focus starts on the selected tab");
|
||||
|
||||
// Roving focus: only the selected tab is in the tab order, and its panel is the one shown.
|
||||
const onlySelected = async (id) => {
|
||||
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + id);
|
||||
assert.equal(await focusedId(s), "help-tab-" + id, `focus is on ${id}`);
|
||||
assert.equal(await tabButton(s, id).getAttribute("tabindex"), "0");
|
||||
assert.equal(await s.page.locator('#help-tabs [role=tab][tabindex="0"]').count(), 1, "one tab stop");
|
||||
assert.equal(await s.page.locator("#help-panel-" + id).isVisible(), true, `${id}'s panel is shown`);
|
||||
assert.equal(await s.page.locator('#help-panels [role=tabpanel]:not([hidden])').count(), 1, "one panel is shown");
|
||||
};
|
||||
await onlySelected(ids[0]);
|
||||
await s.page.keyboard.press("ArrowDown");
|
||||
await onlySelected(ids[1]);
|
||||
await s.page.keyboard.press("ArrowRight");
|
||||
await onlySelected(ids[2]);
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await onlySelected(ids[1]);
|
||||
await s.page.keyboard.press("End");
|
||||
await onlySelected(ids[ids.length - 1]);
|
||||
await s.page.keyboard.press("ArrowDown");
|
||||
await onlySelected(ids[0]);
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await onlySelected(ids[ids.length - 1]);
|
||||
await s.page.keyboard.press("Home");
|
||||
await onlySelected(ids[0]);
|
||||
// A click picks a tab too.
|
||||
await tabButton(s, ids[3]).click();
|
||||
await onlySelected(ids[3]);
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
assert.equal(await focusedId(s), "btn-about", "focus goes back to the Help button");
|
||||
// Reopened, the built dialog is reused: no second set of tabs.
|
||||
await openHelp(s);
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length);
|
||||
});
|
||||
|
||||
test("Help shows the live connection line and the version as a safe link to the Releases page", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openHelp(s);
|
||||
const live = s.page.locator("#about-live");
|
||||
assert.match(await textOf(live), /^Right now: both halves are talking to each other\./);
|
||||
assert.equal(await live.evaluate((n) => n.classList.contains("is-good")), true);
|
||||
|
||||
const link = s.page.locator("#help-version a");
|
||||
await link.waitFor();
|
||||
assert.match(await textOf(link), /^Plan2Code v\d+\.\d+\.\d+/, "the link names the installed version");
|
||||
assert.equal(await link.getAttribute("href"), RELEASES_URL);
|
||||
assert.equal(await link.getAttribute("rel"), "noopener noreferrer");
|
||||
assert.equal(await link.getAttribute("target"), "_blank");
|
||||
|
||||
// The line is written on open: a finished session says so the next time.
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
await openHelp(s);
|
||||
assert.match(await textOf(live), /^Right now: the session is finished/);
|
||||
});
|
||||
|
||||
test("a click on Help's backdrop closes it, and a click inside it does not", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openHelp(s);
|
||||
await s.page.locator("#help-title").click();
|
||||
assert.equal(await helpModal(s).isVisible(), true, "a click inside closed Help");
|
||||
// The top-left corner of the page is the backdrop, well outside the dialog.
|
||||
await s.page.mouse.click(4, 4);
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("Ctrl+Enter does not send while Help is open, and sends once it is closed", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.locator('[data-item="q1"]').first().locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await openHelp(s);
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
await s.page.keyboard.press("Meta+Enter");
|
||||
assert.equal(s.wait(1).code === 0, false, "something was sent from behind Help");
|
||||
assert.equal(await helpModal(s).isVisible(), true, "the key closed Help");
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "Ctrl+Enter sends nothing with Help closed");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type }) => ({ i, type })),
|
||||
[{ i: "q1", type: "answer" }]
|
||||
);
|
||||
});
|
||||
|
||||
test("the Welcome shows on a first dashboard, saves that it was seen, and Help's Show the welcome again brings it back", async (t) => {
|
||||
savedLooks(t, null);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
const welcome = s.page.locator("#welcome-modal");
|
||||
await welcome.waitFor();
|
||||
assert.equal(await s.page.locator("#welcome-title").isVisible(), true);
|
||||
await s.page.getByRole("button", { name: "Start building" }).click();
|
||||
await welcome.waitFor({ state: "hidden" });
|
||||
// Saved with the other looks, so it holds for the next page too.
|
||||
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).welcomeSeen === true);
|
||||
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await toTheDashboard(s);
|
||||
await s.page.waitForTimeout(800);
|
||||
assert.equal(await welcome.isVisible(), false, "the Welcome came back on a later page");
|
||||
|
||||
// Help's first topic offers it again, and Help steps aside for it.
|
||||
// (On the dashboard Help opens on the dashboard topic, so go to the first.)
|
||||
await openHelp(s);
|
||||
await tabButton(s, HELP_TABS[0].id).click();
|
||||
await s.page.getByRole("button", { name: "Show the welcome again" }).click();
|
||||
await welcome.waitFor();
|
||||
assert.equal(await helpModal(s).isVisible(), false, "Help stayed open under the Welcome");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await welcome.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("the Welcome stays away when the person has seen it, and off the dashboard", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const seen = await openSession(browser, { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(seen);
|
||||
await seen.page.waitForTimeout(800);
|
||||
assert.equal(await seen.page.locator("#welcome-modal").isVisible(), false, "a seen Welcome showed again");
|
||||
|
||||
// Unseen, but a workflow page is not a first dashboard.
|
||||
savedLooks(t, null);
|
||||
const plan = await openSession(browser, { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await plan.page.waitForTimeout(800);
|
||||
assert.equal(await plan.page.locator("#welcome-modal").isVisible(), false, "the Welcome showed on a workflow page");
|
||||
});
|
||||
|
||||
// A newer release on record, so a console that boots now has an update to
|
||||
// announce (the check reads this file for an hour instead of asking the
|
||||
// network). The file is put back as the suite had it.
|
||||
function aNewerReleaseExists(t) {
|
||||
const file = path.join(HOME, "update-check.json");
|
||||
const before = fs.readFileSync(file, "utf8");
|
||||
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
|
||||
t.after(() => fs.writeFileSync(file, before));
|
||||
}
|
||||
|
||||
test("the update banner opens a modal with the exact update commands, and its dismissal is remembered for the session", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
aNewerReleaseExists(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ }).click();
|
||||
|
||||
const modal = s.page.locator("#update-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#update-versions")), /^Version v99\.0\.0 is out/);
|
||||
const releases = s.page.locator("#update-versions a");
|
||||
assert.equal(await releases.getAttribute("href"), RELEASES_URL);
|
||||
assert.equal(await releases.getAttribute("rel"), "noopener noreferrer");
|
||||
assert.equal(await textOf(s.page.locator("#update-command code")), "plan2code update");
|
||||
assert.equal(
|
||||
await textOf(s.page.locator("#update-fallback code")),
|
||||
"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"
|
||||
);
|
||||
await s.page.locator("#update-done").click();
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
|
||||
// The ×: gone now, remembered under this session's key, and still gone after a reload.
|
||||
await main.getByRole("button", { name: "Dismiss until next time" }).click();
|
||||
await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).waitFor({ state: "hidden" });
|
||||
assert.equal(await s.page.evaluate((k) => sessionStorage.getItem(k), "p2c-update-dismissed:" + s.sid), "99.0.0");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await toTheDashboard(s);
|
||||
assert.equal(await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).count(), 0, "the banner came back after a reload");
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
// Page tests for User Preferences: the saved looks (highlight and theme), the
|
||||
// launcher's model menus and the Cleanup tab. Run with:
|
||||
// node --test scripts/test-web-console-page-prefs.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME, MODELS_DIR, backdate } from "./web-console-test-helpers.mjs";
|
||||
import { formatBytes } from "../src/web-console/public/answers.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The console home's saved looks are shared by every session of this file, so
|
||||
// each test starts with none and leaves none.
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
function noSavedLooks(t) {
|
||||
fs.rmSync(LOOKS_FILE, { force: true });
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
}
|
||||
|
||||
const root = (s, attr) => s.page.evaluate((a) => document.documentElement.getAttribute(a), attr);
|
||||
// The highlight the page paints with: an inline override while it is not the default.
|
||||
const accentVar = (s) => s.page.evaluate(() => document.documentElement.style.getPropertyValue("--accent"));
|
||||
const swatch = (s, id) => s.page.locator(`#looks-swatches [data-accent="${id}"]`);
|
||||
|
||||
// The page as the server first sends it, before any script has run: the saved
|
||||
// theme and highlight are in the markup so a reload never flashes the defaults.
|
||||
async function firstPaintAttrs(s) {
|
||||
const html = await (await s.context.request.get(s.url)).text();
|
||||
const tag = html.match(/<html\b[^>]*>/i)[0];
|
||||
return { theme: tag.match(/data-theme="([^"]*)"/)?.[1] ?? null, accent: tag.match(/data-looks-accent="([^"]*)"/)?.[1] ?? null };
|
||||
}
|
||||
|
||||
test("the violet highlight and dark theme chosen in preferences stick across a reload, and Back to default clears them", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
assert.equal(await root(s, "data-theme"), null, "the theme starts on the system's");
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#looks-modal[open]").waitFor();
|
||||
await swatch(s, "violet").click();
|
||||
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true");
|
||||
assert.equal(await accentVar(s), "#a785e2", "the dark violet is painted");
|
||||
// Saved on the server (looks.json), not only in this tab.
|
||||
await s.page.waitForFunction(async () => {
|
||||
const saved = (await (await fetch("/looks")).json()).looks || {};
|
||||
return saved.accent === "violet" && saved.theme === "dark";
|
||||
});
|
||||
await s.page.click("#looks-done");
|
||||
|
||||
// What the server sends first, and what the page settles on, both keep the choice.
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: "dark", accent: "violet" }, "the first paint carries the saved looks");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
assert.equal(await root(s, "data-theme"), "dark", "the theme did not stick");
|
||||
await s.page.waitForFunction(() => document.documentElement.style.getPropertyValue("--accent") === "#a785e2");
|
||||
await s.page.click("#btn-looks");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true", "the violet swatch is not the chosen one after a reload");
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="dark"]').isChecked(), true);
|
||||
|
||||
// Back to default returns both, here and for the next page.
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await accentVar(s), "", "the chosen highlight is still painted");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "false");
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true);
|
||||
await s.page.waitForFunction(async () => {
|
||||
const saved = (await (await fetch("/looks")).json()).looks || {};
|
||||
return saved.theme === "system" && saved.accent !== "violet";
|
||||
});
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks");
|
||||
});
|
||||
|
||||
test("the launcher's model menus have Claude, Devin and Codex tabs, and a model id typed on the Codex tab is saved", async (t) => {
|
||||
noSavedLooks(t);
|
||||
// The file the launcher reads: put back as the suite had it (no file).
|
||||
t.after(() => fs.rmSync(path.join(MODELS_DIR, "models.json"), { force: true }));
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-looks");
|
||||
const tabs = s.page.getByRole("group", { name: "Which agent" });
|
||||
for (const name of ["Claude", "Devin", "Codex"]) assert.equal(await tabs.getByRole("button", { name, exact: true }).count(), 1, `a ${name} tab`);
|
||||
const pressed = async () => (await tabs.locator('button[aria-pressed="true"]').allInnerTexts()).map((x) => x.trim());
|
||||
assert.deepEqual(await pressed(), ["Claude"], "the menus open on Claude");
|
||||
|
||||
await tabs.getByRole("button", { name: "Codex", exact: true }).click();
|
||||
assert.deepEqual(await pressed(), ["Codex"]);
|
||||
await s.page.click("#models-add");
|
||||
const id = s.page.locator("#models-user").getByRole("textbox", { name: "Model id" });
|
||||
await id.fill("gpt-test-codex-1");
|
||||
await id.press("Tab");
|
||||
await s.page.locator("#models-status").filter({ hasText: /^Saved\./ }).waitFor();
|
||||
const saved = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user);
|
||||
assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-1"], "the id was not saved under Codex");
|
||||
assert.deepEqual([saved.claude, saved.devin], [[], []], "the id leaked into another agent's menu");
|
||||
|
||||
// Back on Claude the typed id is not listed; on Codex it is, after a reload.
|
||||
await tabs.getByRole("button", { name: "Claude", exact: true }).click();
|
||||
assert.equal(await s.page.locator("#models-user .models-row").count(), 0);
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#models-tab-codex").click();
|
||||
await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).waitFor();
|
||||
assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1");
|
||||
});
|
||||
|
||||
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Made after the session opens: opening sweeps old sessions away. A session
|
||||
// is old when nothing in it has been touched for 30 days.
|
||||
const sid = "20250801-101010-aaaaaa";
|
||||
const dir = path.join(HOME, "sessions", sid);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const state = path.join(dir, "state.json");
|
||||
fs.writeFileSync(state, "x".repeat(3000));
|
||||
backdate(state);
|
||||
backdate(dir);
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
await s.page.click("#btn-looks");
|
||||
const list = s.page.locator("#cleanup-list");
|
||||
assert.equal(await list.locator(".cleanup-row").count(), 0, "Cleanup lists things before a scan");
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true, "Delete is offered before a scan");
|
||||
await s.page.click("#cleanup-scan");
|
||||
const row = list.locator(".cleanup-row").filter({ hasText: sid });
|
||||
await row.waitFor();
|
||||
assert.match(await textOf(row), new RegExp(`^Session ${sid}`));
|
||||
const size = await textOf(row.locator(".cleanup-size"));
|
||||
assert.match(size, /^\d/, "the row names a size");
|
||||
assert.ok(size === formatBytes(3000) || /^[\d.,]+\s*(kB|KB|MB|B)\b/.test(size), `the size reads as a size: ${size}`);
|
||||
assert.match(await textOf(list.locator(".cleanup-summary")), /1 old session/);
|
||||
assert.match(await textOf(s.page.locator("#cleanup-status")), /^Found \d+ items?\./);
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isVisible(), true, "Delete these is offered once something is found");
|
||||
// The scan only looks.
|
||||
assert.equal(fs.existsSync(dir), true, "a scan deleted the folder");
|
||||
|
||||
// Closing preferences forgets the scan: a reopened dialog starts clean.
|
||||
await s.page.click("#looks-done");
|
||||
await s.page.click("#btn-looks");
|
||||
assert.equal(await list.locator(".cleanup-row").count(), 0, "the old scan is still listed");
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true);
|
||||
});
|
||||
@@ -0,0 +1,497 @@
|
||||
// Page tests for how a session ends and comes back: the finished screen and
|
||||
// its buttons, Stop and Stop with a handoff, and a page that loses its server
|
||||
// and finds it again after a resume. Run with:
|
||||
// node --test scripts/test-web-console-page-session.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject } from "./page-test-helpers.mjs";
|
||||
import { cli, until } from "./web-console-test-helpers.mjs";
|
||||
import { STOP_HANDOFF_REPLY, HOME_REPLY } from "../src/web-console/public/answers.js";
|
||||
// How long the page waits without contact before it calls itself offline:
|
||||
// the page's own constant, so this file never drifts from it.
|
||||
import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
|
||||
// The banner the page raises when it loses its server mid-session.
|
||||
const LOST_CONTACT = /Lost contact with Plan2Code\. Nothing you have typed is lost\./;
|
||||
|
||||
// A plan session on the person's turn, the way an agent opens one: one text
|
||||
// question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The agent's side of `stop`, leaving the browser context open (s.stop()
|
||||
// closes it, which would hide what the page does next).
|
||||
async function stopServer(s) {
|
||||
cli(["stop", "--session", s.sid], { cwd: s.project });
|
||||
assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop");
|
||||
}
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// Local helper: checks `fn` keeps returning true for `ms`. A sleep would
|
||||
// prove nothing; this fails the moment the page shows what it must not.
|
||||
async function holds(fn, ms) {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) {
|
||||
if (!(await fn())) return false;
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
test("the finished screen shows the next command with --web, copies it, turns Send off, and Back to the dashboard reaches the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
s.post({
|
||||
settle: true,
|
||||
finish: {
|
||||
headline: "The plan is written",
|
||||
body: "Everything is under `specs/audit-export/`. Read `PLAN.md` first.",
|
||||
command: "/plan2code-2-document",
|
||||
dashboard: true,
|
||||
},
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
|
||||
const shown = main.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
|
||||
assert.equal(await shown.count(), 1, "the command is shown once, with --web appended");
|
||||
// The Copy that belongs to this command: the innermost block holding both,
|
||||
// whatever wraps them.
|
||||
// (`has` is matched inside each candidate, so these start from the page.)
|
||||
const code = s.page.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
|
||||
const copy = s.page.getByRole("button", { name: "Copy", exact: true });
|
||||
await main.locator("*", { has: code }).filter({ has: copy }).last().getByRole("button", { name: "Copy", exact: true }).click();
|
||||
await s.page.waitForFunction(async () => (await navigator.clipboard.readText()) === "/plan2code-2-document --web");
|
||||
assert.equal(await s.page.evaluate(() => navigator.clipboard.readText()), "/plan2code-2-document --web");
|
||||
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is still on after the finish");
|
||||
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type }) => ({ i, type })),
|
||||
[{ i: "__dashboard", type: "dashboard" }]
|
||||
);
|
||||
});
|
||||
|
||||
test("Stop session, confirmed, sends __stop with no handoff", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
await s.page.locator("#stop-go").click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const stop = got.actions.find((a) => a.i === "__stop");
|
||||
assert.deepEqual(stop, { i: "__stop", type: "stop" });
|
||||
});
|
||||
|
||||
test("Stop with a handoff sends __stop with handoff, and the paused finish and stop that follow end on the paused screen, not an error", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
const handoff = s.page.locator("#stop-handoff");
|
||||
assert.equal(await handoff.isVisible(), true, "the handoff choice is offered off the dashboard");
|
||||
await handoff.click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const stop = got.actions.find((a) => a.i === "__stop");
|
||||
assert.deepEqual(stop, { i: "__stop", type: "stop", handoff: true });
|
||||
|
||||
// What the agent does next (console-stop.md): a paused finish without
|
||||
// --wait and no dashboard, then `stop`.
|
||||
s.post({
|
||||
settle: true,
|
||||
finish: {
|
||||
headline: "Paused at the naming question",
|
||||
body: "Your place is saved, and a handoff is waiting on the dashboard. The naming question is still open.",
|
||||
command: "/plan2code-1-plan",
|
||||
},
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "Paused at the naming question" }).waitFor();
|
||||
await stopServer(s);
|
||||
|
||||
// The page needs GONE_AFTER_MS without contact before it would call the
|
||||
// server lost. Through that window and past it, the paused screen stays.
|
||||
const settled = async () =>
|
||||
!LOST_CONTACT.test(await s.page.locator("#banner").innerText()) &&
|
||||
!(await s.page.locator("#planny").getAttribute("class")).includes("is-gone");
|
||||
assert.ok(await holds(settled, GONE_AFTER_MS + 3000), "the page raised a lost-contact state after a paused finish");
|
||||
assert.match(await main.innerText(), /Session paused/i);
|
||||
assert.match(await textOf(s.page.locator("#agent-text")), /^Paused\./);
|
||||
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code-1-plan --web$/ }).count(), "the resume command is gone");
|
||||
});
|
||||
|
||||
test("a page that loses its server goes offline, and after a resume it shows the session again with the unsent answer still typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const field = () => itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
await field().fill("audit-export");
|
||||
// Typed, not sent: the page mirrors it to the server's draft.json, which
|
||||
// is what a page on a new port reads back (localStorage is per origin).
|
||||
const draftFile = path.join(s.session, "draft.json");
|
||||
assert.ok(
|
||||
await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes("audit-export"), 5000),
|
||||
"the typed answer never reached the server's draft"
|
||||
);
|
||||
|
||||
await stopServer(s);
|
||||
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, {
|
||||
timeout: GONE_AFTER_MS + 10000,
|
||||
});
|
||||
assert.match(await textOf(s.page.locator("#agent-text")), /^Not connected\. Your answers are saved\./);
|
||||
assert.match(await s.page.locator("#banner").innerText(), LOST_CONTACT);
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is on with no server");
|
||||
|
||||
const resumed = cli(["open", "--resume", s.sid, "--workflow", "plan", "--no-open"], { cwd: s.project }).json;
|
||||
assert.ok(resumed && resumed.url, "the resume printed no url");
|
||||
await s.page.goto(resumed.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await itemCard(s.page, "q1").getByText("What to call it").first().waitFor();
|
||||
assert.equal(await field().inputValue(), "audit-export", "the unsent answer was lost across the resume");
|
||||
assert.equal(await s.page.locator("#planny").evaluate((n) => n.classList.contains("is-gone")), false);
|
||||
});
|
||||
|
||||
// The status line beside Planny, and its "What to check" button when it has
|
||||
// one. The button opens Help on the stuck tab.
|
||||
const statusLine = (s) => s.page.locator("#agent-text");
|
||||
const whatToCheck = (s) => statusLine(s).getByRole("button", { name: "What to check" });
|
||||
async function lineSays(s, re) {
|
||||
await s.page.waitForFunction((src) => new RegExp(src).test(document.getElementById("agent-text").textContent), re.source, { timeout: 10000 });
|
||||
return textOf(statusLine(s));
|
||||
}
|
||||
|
||||
test("the quiet, not running and not connected lines offer What to check, opening Help on the stuck tab, and the plain lines do not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
clock: true,
|
||||
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
|
||||
});
|
||||
// Working, and heard from just now: the plain working line.
|
||||
await lineSays(s, /Task 1 of 3: the reader/);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the working line is plain");
|
||||
// Quiet for 30 s: the approval hint, with the button.
|
||||
await s.page.clock.fastForward(40_000);
|
||||
await lineSays(s, /waiting on an approval in your terminal/);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the approval hint carries What to check");
|
||||
// Quiet for two minutes: still working, and the button stays.
|
||||
await s.page.clock.fastForward(100_000);
|
||||
await lineSays(s, /^Still working on it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the quiet working line carries What to check");
|
||||
|
||||
// Back to real time, and the agent asks something: the person's turn is plain.
|
||||
await s.page.clock.setSystemTime(Date.now());
|
||||
s.post({ items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } });
|
||||
await lineSays(s, /^Your turn: 1 question waiting\./);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the your-turn line is plain");
|
||||
// Nobody listening for three minutes: not running, with the button.
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running right now\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not running line carries What to check");
|
||||
await whatToCheck(s).click();
|
||||
await s.page.locator("#help-modal[open]").waitFor();
|
||||
assert.equal(await s.page.locator("#help-tab-stuck").getAttribute("aria-selected"), "true", "Help opened on the stuck tab");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.locator("#help-modal[open]").waitFor({ state: "detached" });
|
||||
|
||||
// Answered and sent, never collected, and nobody listening: the saved line.
|
||||
await s.page.clock.setSystemTime(Date.now());
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the sent line is plain");
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the saved-and-waiting line carries What to check");
|
||||
|
||||
// No server at all: not connected, with the button.
|
||||
await stopServer(s);
|
||||
for (let i = 0; i < 20 && !(await s.page.locator("#planny.is-gone").count()); i++) {
|
||||
await s.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await lineSays(s, /^Not connected\. Your answers are saved\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
|
||||
});
|
||||
|
||||
test("an answered finish offer comes back unanswered on a later finish, once the first finish has gone", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const finishWith = (headline) => s.post({ finish: { headline, command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
|
||||
const main = s.page.locator("#main");
|
||||
finishWith("Phase 1 is done");
|
||||
await main.getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).click();
|
||||
assert.deepEqual(collect(s).actions.map(({ i }) => i), ["__dashboard"]);
|
||||
await lineSays(s, /^Opening the dashboard…/);
|
||||
// The agent takes the press somewhere that clears the finish, and a later
|
||||
// phase ends: that finish starts with its own offer unanswered.
|
||||
s.post({ finish: null, agent: { status: "working", activity: "Task 1 of 1" } });
|
||||
await lineSays(s, /Task 1 of 1/);
|
||||
finishWith("Phase 2 is done");
|
||||
await main.getByRole("heading", { name: "Phase 2 is done" }).waitFor();
|
||||
await lineSays(s, /^Done\. Head back to the dashboard, or close this tab\./);
|
||||
assert.equal(await main.getByRole("button", { name: "Back to the dashboard" }).count(), 1, "the later finish offers the way back again");
|
||||
});
|
||||
|
||||
test("a finished session never puts a sent answer back on its form", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea").fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
collect(s);
|
||||
// Collected and left open, then the session ends: nothing more can be sent,
|
||||
// so the answer stays sent rather than coming back to edit. It would show
|
||||
// once the finish goes away (a review taken up), as an answer ready to send.
|
||||
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" }, agent: { status: "waiting" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
s.post({ finish: null, agent: { status: "waiting" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor({ state: "detached" });
|
||||
const q1 = s.page.locator("#sidebar").getByRole("button", { name: /What to call it/ });
|
||||
await q1.click();
|
||||
await itemCard(s.page, "q1").waitFor();
|
||||
const mark = q1.locator(".rail-mark");
|
||||
assert.notEqual(await mark.getAttribute("title"), "ready to send", "the sent answer came back on the form");
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
assert.notEqual((await box.count()) ? await box.inputValue() : "", "audit-export", "the sent answer is back in its box");
|
||||
});
|
||||
|
||||
test("the footer keeps its workspace label on the dashboard, and the label opens the Workspace dialog", async (t) => {
|
||||
const project = tempProject();
|
||||
const name = path.basename(project);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", project });
|
||||
// Past Planny's wake-up and, on this console home's first run, the Welcome.
|
||||
await s.page.getByRole("button", { name: "Skip the intro" }).click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
const foot = s.page.locator("footer.footer");
|
||||
const where = s.page.locator("#footer-where");
|
||||
await where.waitFor();
|
||||
// The dashboard drops the summary and Send, never the label.
|
||||
assert.equal(await foot.evaluate((f) => f.classList.contains("is-dash")), true, "the dashboard's footer is marked is-dash");
|
||||
assert.equal(await s.page.locator("#footer-summary").isVisible(), false, "the summary shows on the dashboard");
|
||||
assert.equal(await s.page.locator("#btn-send").isVisible(), false, "Send shows on the dashboard");
|
||||
assert.match(await textOf(where), new RegExp(`^${name}`), "the label names the project");
|
||||
assert.equal(await where.getAttribute("title"), "Open workspace");
|
||||
assert.match(await where.getAttribute("aria-label"), new RegExp(`^Open workspace: ${name}`));
|
||||
// A click opens the Workspace dialog on the session's folders; leaving the
|
||||
// label leaves it as it was (no copied state to undo).
|
||||
await where.click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor();
|
||||
assert.match(await textOf(s.page.locator("#workspace-list")), new RegExp(name));
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
await s.page.locator("body").click({ position: { x: 5, y: 5 } });
|
||||
assert.match(await textOf(where), new RegExp(`^${name}`), "the label changed after a click away");
|
||||
});
|
||||
|
||||
test("a workflow page uses its modules: the full footer, the session meter, @ suggestions and the tab icon", async (t) => {
|
||||
const project = tempProject();
|
||||
const name = path.basename(project);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", project, payload: PLAN_QUESTION });
|
||||
// Off the dashboard the footer is whole (workspace.js names the label).
|
||||
assert.equal(await s.page.locator("footer.footer").evaluate((f) => f.classList.contains("is-dash")), false);
|
||||
assert.equal(await s.page.locator("#btn-send").isVisible(), true);
|
||||
// meter.js: the pill shows once a frame carries the meter.
|
||||
await s.page.locator("#meter-pill").waitFor();
|
||||
assert.ok((await textOf(s.page.locator("#meter-words"))).length, "the meter pill has no words");
|
||||
// mentions.js: an @ in a text box offers the workspace's folders.
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
await box.click();
|
||||
await box.pressSequentially("See @");
|
||||
await s.page.locator("#mention-pop").waitFor();
|
||||
assert.match(await textOf(s.page.locator("#mention-pop")), new RegExp(name));
|
||||
// favicon.js: the person's move puts a bar on the tab icon.
|
||||
await s.page.waitForFunction(() => document.querySelector('link[rel="icon"][type="image/svg+xml"]').href.startsWith("data:image/svg+xml"));
|
||||
});
|
||||
|
||||
// The dashboard, past Planny's wake-up and the first-run Welcome.
|
||||
async function pastTheIntro(s) {
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
}
|
||||
|
||||
// What a person sees break: a handoff offered where there is nothing to hand off.
|
||||
test("the stop dialog offers a handoff in a workflow and one plain Stop on the dashboard", async (t) => {
|
||||
const plan = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await plan.page.click("#btn-stop");
|
||||
const modal = plan.page.locator("#stop-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(modal), /Stop with a handoff/);
|
||||
assert.match(await textOf(modal.locator("#stop-go")), /Just stop and save/);
|
||||
|
||||
const dash = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } } });
|
||||
await pastTheIntro(dash);
|
||||
await dash.page.click("#btn-stop");
|
||||
await dash.page.locator("#stop-modal").waitFor();
|
||||
assert.equal(await dash.page.locator("#stop-handoff").isVisible(), false, "the dashboard offers a handoff");
|
||||
assert.match(await textOf(dash.page.locator("#stop-go")), /Stop\s+Ends the console session\./);
|
||||
assert.doesNotMatch(await textOf(dash.page.locator("#stop-modal")), /Stop with a handoff/);
|
||||
});
|
||||
|
||||
// What the agent would misread: a handoff stop that carries the plain stop's words.
|
||||
test("Stop with a handoff sends its own reply line beside the stop, and a plain stop sends another", async (t) => {
|
||||
const handoff = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await handoff.page.click("#btn-stop");
|
||||
await handoff.page.locator("#stop-handoff").click();
|
||||
const got = collect(handoff);
|
||||
assert.deepEqual(got.actions.find((a) => a.i === "__stop"), { i: "__stop", type: "stop", handoff: true });
|
||||
assert.ok(got.reply.includes(STOP_HANDOFF_REPLY), `the handoff stop's words: ${got.reply}`);
|
||||
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await plain.page.click("#btn-stop");
|
||||
await plain.page.locator("#stop-go").click();
|
||||
const sent = collect(plain);
|
||||
assert.equal(sent.actions.find((a) => a.i === "__stop").handoff, undefined);
|
||||
assert.ok(!sent.reply.includes(STOP_HANDOFF_REPLY), "a plain stop asked for a handoff");
|
||||
});
|
||||
|
||||
// A finish that offers a review, a commit and the dashboard, on a build.
|
||||
const OFFERS = { headline: "Quick task done", command: "/plan2code-5-git", review: true, commit: true, dashboard: true };
|
||||
const closeGuide = (s) => s.page.getByRole("region", { name: "Before you close this" });
|
||||
|
||||
// What a person sees break: "Safe to close" printed under "Review requested", or the review offer coming back after a reload.
|
||||
test("Before you close this shows while a review is on offer, goes while it is asked, and the asked offer stays locked after a reload", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: OFFERS });
|
||||
const main = s.page.locator("#main");
|
||||
const reviewNow = main.getByRole("button", { name: "Review it now" });
|
||||
await reviewNow.waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 1, "a review only on offer must not hide the guide");
|
||||
assert.match(await textOf(main), /The review is optional\./);
|
||||
|
||||
await reviewNow.click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "__review", type: "review" }]);
|
||||
await main.getByRole("button", { name: "Review requested…" }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 0, "the guide shows while a review is starting");
|
||||
assert.equal(await main.getByRole("button", { name: "No thanks, I am done" }).count(), 0);
|
||||
|
||||
// The press is remembered: the buttons do not come back on a reload.
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await main.getByRole("button", { name: "Review requested…" }).waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Review it now" }).count(), 0);
|
||||
assert.equal(await closeGuide(s).count(), 0, "the guide came back on a reload");
|
||||
});
|
||||
|
||||
// What a person sees break: the guide missing while a commit or the dashboard
|
||||
// is starting (it would say "start a new one" under "Opening Git"), or missing
|
||||
// once they said they are done or the server is gone.
|
||||
test("Before you close this goes while a commit or the dashboard is starting, and stays once they are done or the server is gone", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const finishPage = async (opts) => {
|
||||
const s = await openSession(browser, { t, workflow: "quick-task", ...opts, payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: OFFERS });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Quick task done" }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 1, "a plain finish shows the guide");
|
||||
return s;
|
||||
};
|
||||
const cases = [
|
||||
["Commit it now", "__commit", "Opening Git…", 0],
|
||||
["Back to the dashboard", "__dashboard", "Opening the dashboard…", 0],
|
||||
["No thanks, I am done", "__done", null, 1],
|
||||
];
|
||||
for (const [button, id, asked, guides] of cases) {
|
||||
const s = await finishPage({});
|
||||
await s.page.locator("#main").getByRole("button", { name: button }).click();
|
||||
assert.deepEqual(collect(s).actions.map((a) => a.i), [id]);
|
||||
if (asked) await s.page.locator("#main").getByRole("button", { name: asked }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), guides, `the guide after ${button}`);
|
||||
}
|
||||
// A review asked, then the server gone: nothing is starting any more.
|
||||
const gone = await finishPage({ clock: true });
|
||||
await gone.page.locator("#main").getByRole("button", { name: "Review it now" }).click();
|
||||
collect(gone);
|
||||
assert.equal(await closeGuide(gone).count(), 0);
|
||||
await stopServer(gone);
|
||||
for (let i = 0; i < 20 && !(await gone.page.locator("#planny.is-gone").count()); i++) {
|
||||
await gone.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await closeGuide(gone).waitFor();
|
||||
});
|
||||
|
||||
// What a person sees break: a finished screen with no Before you close this,
|
||||
// a pause that promises the wrong thing, or the guide's own text going wrong.
|
||||
test("every finished shape shows Before you close this with its three rows, and a pause names the resume command", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const main = s.page.locator("#main");
|
||||
const shapes = [
|
||||
["A skill next", { command: "/plan2code-4-finalize" }, /A new session starts from clean context/, /Paste the command above in the new session, or start from the dashboard with \/plan2code\./],
|
||||
["A terminal command next", { command: "git status" }, /A new session starts from clean context/, /Run the command above in your terminal, then start the next step/],
|
||||
["Nothing left", {}, /A new session starts from clean context/, /In the new session, start from the dashboard with \/plan2code\./],
|
||||
["Paused here", { command: "/plan2code-3-implement specs/x/overview.md" }, /Your saved place is picked up by the resume command above\./, /Paste the command above/],
|
||||
];
|
||||
for (const [headline, rest, fresh, carry] of shapes) {
|
||||
s.post({ finish: { headline, ...rest } });
|
||||
await main.getByRole("heading", { name: headline }).waitFor();
|
||||
const guide = closeGuide(s);
|
||||
assert.equal(await guide.count(), 1, `${headline}: one guide`);
|
||||
assert.equal(await guide.locator("li").count(), 3, `${headline}: three rows`);
|
||||
const text = await textOf(guide);
|
||||
for (const label of ["Before you close this", "Safe to close", "Start fresh", "Carry on"]) assert.ok(text.includes(label), `${headline}: says "${label}"`);
|
||||
assert.match(text, fresh, `${headline}: the Start fresh sentence`);
|
||||
assert.match(text, carry, `${headline}: the Carry on sentence`);
|
||||
assert.ok(!text.includes("—"), `${headline}: the guide carries an em dash`);
|
||||
}
|
||||
// With a stop warning up, a pause's command starts the work again.
|
||||
s.post({ stopWarning: "Answers since the last save will not be kept." });
|
||||
await closeGuide(s).getByText(/The command above starts it again\./).waitFor();
|
||||
assert.equal(await s.page.locator("#btn-home").isVisible(), false, "a finished screen carries its own way back");
|
||||
});
|
||||
|
||||
// What a person sees break: the triangle leaving answers behind, or sending a
|
||||
// finish-style stop instead of the way home.
|
||||
test("the top bar's back triangle asks first, then sends __dashboard with the typed answers and the home reply", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-home");
|
||||
const modal = s.page.locator("#home-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(modal), /Leave this workflow\?/);
|
||||
assert.match(await textOf(modal.locator("#home-blurb")), /The answer you have ready goes with it\./);
|
||||
await modal.locator("#home-cancel").click();
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
assert.equal(s.wait(1).code === 0, false, "Cancel sent something");
|
||||
|
||||
await s.page.click("#btn-home");
|
||||
await modal.locator("#home-go").click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "q1", type: "answer" }, { i: "__dashboard", type: "dashboard" }]);
|
||||
assert.ok(got.reply.includes("audit-export") && got.reply.endsWith(HOME_REPLY), `the reply carries the answer, then the home line: ${got.reply}`);
|
||||
await s.page.waitForFunction(() => document.getElementById("btn-home").disabled);
|
||||
});
|
||||
|
||||
// What a person sees break: Back to default in Preferences does nothing.
|
||||
test("Back to default in Preferences returns the theme to follow the system and clears the chosen look", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true, "the system choice is ticked again");
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// Page tests for the Workspace dialog and @mentions: adding a folder from the
|
||||
// footer label, what the next send tells the agent, and picking a folder from
|
||||
// the list an @ opens in a note. Run with:
|
||||
// node --test scripts/test-web-console-page-workspace.mjs
|
||||
//
|
||||
// Each test drives the real console in a real Chrome or Edge through
|
||||
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
|
||||
// session per test.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
|
||||
import { tempFolder } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question, the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// A folder named `datasets` in its own temp parent, so its @name is known.
|
||||
function datasetsFolder() {
|
||||
const dir = path.join(tempFolder(), "datasets");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens Workspace from the footer label and adds `dir` by typing its path.
|
||||
async function addFolderFromDialog(s, dir) {
|
||||
await s.page.locator("#footer-where").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor();
|
||||
await s.page.locator("#workspace-path").fill(dir);
|
||||
await s.page.locator("#workspace-add").click();
|
||||
await s.page.locator("#workspace-add-msg.is-good").waitFor();
|
||||
}
|
||||
|
||||
// What a person sees break: a folder that does not show in the dialog, or
|
||||
// that the agent is never told about.
|
||||
test("a folder added in Workspace is listed with its @name, and the next send tells the agent in its reply", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const dir = datasetsFolder();
|
||||
await addFolderFromDialog(s, dir);
|
||||
|
||||
assert.equal(await textOf(s.page.locator("#workspace-add-msg")), "Added as @datasets.");
|
||||
const rows = s.page.locator("#workspace-list .ws-entry");
|
||||
assert.equal(await rows.count(), 2, "the project's own folder and the new one");
|
||||
const added = rows.filter({ hasText: "@datasets" });
|
||||
assert.equal(await added.count(), 1);
|
||||
assert.equal(await textOf(added.locator(".ws-path")), dir);
|
||||
assert.equal(await added.locator(".ws-original").count(), 0, "only the first folder is the original");
|
||||
assert.equal(await rows.first().locator(".ws-original").count(), 1);
|
||||
assert.equal(await s.page.locator("#workspace-path").inputValue(), "", "the path box empties after an add");
|
||||
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
|
||||
assert.ok(got.reply.includes("audit-export"), `the answer is in the reply: ${got.reply}`);
|
||||
assert.ok(got.reply.includes("Workspace: added @datasets"), `the Workspace line: ${got.reply}`);
|
||||
assert.ok(got.reply.includes(dir), `the Workspace line names the path: ${got.reply}`);
|
||||
});
|
||||
|
||||
// What a person sees break: an @ that offers nothing, or a pick that leaves
|
||||
// the box as it was.
|
||||
test("an @ in a note offers the workspace's folders, and picking one writes its @name into the note", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await addFolderFromDialog(s, datasetsFolder());
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
|
||||
const note = s.page.locator("#aside #thread-q1");
|
||||
await note.click();
|
||||
await note.pressSequentially("Look in @da");
|
||||
const pop = s.page.locator("#mention-pop");
|
||||
await pop.waitFor();
|
||||
const options = pop.locator(".mention-opt");
|
||||
assert.deepEqual(await options.allTextContents(), ["@datasets"], "only the folder that matches what was typed");
|
||||
await options.first().click();
|
||||
await pop.waitFor({ state: "detached" });
|
||||
assert.equal(await note.inputValue(), "Look in @datasets ");
|
||||
|
||||
// A bare @ lists every folder, the project's own first.
|
||||
await note.pressSequentially("and @");
|
||||
await pop.waitFor();
|
||||
assert.equal(await pop.locator(".mention-opt").count(), 2);
|
||||
await s.page.keyboard.press("Escape");
|
||||
await pop.waitFor({ state: "detached" });
|
||||
});
|
||||
@@ -13,11 +13,12 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { applyPatch, validate, blankState } from "../src/web-console/lib.mjs";
|
||||
import { applyPatch, validate, blankState } from "../src/web-console/patches.mjs";
|
||||
import { rebasingBranch } from "../src/web-console/git-repo.mjs";
|
||||
import { indentReply, noteReplyLines, agentRepliedAfterSend } from "../src/web-console/public/answers.js";
|
||||
import { chatView } from "../src/web-console/public/chat.js";
|
||||
import { ROOT, CONSOLE_CLI, ENV, cli, payload, readState, postPatch, EXPORT_A, openSession } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
const choice = (id, extra = {}) => ({
|
||||
id,
|
||||
@@ -32,8 +33,7 @@ const choice = (id, extra = {}) => ({
|
||||
});
|
||||
const waitFor = (s, seconds = 10) => cli(["wait", "--session", s.sid, "--seconds", String(seconds)]);
|
||||
const runCli = (args, opts = {}) => spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", ...opts });
|
||||
const app = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const css = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = () => joinedCss();
|
||||
|
||||
/* ------------------------------------------------------------ settling */
|
||||
|
||||
@@ -195,7 +195,6 @@ test("a rebase in progress names the branch it is rewriting", () => {
|
||||
test("a typed line never starts a reply line of its own", () => {
|
||||
assert.equal(indentReply("a\nIdea name: foo\r\n Image: C:\\x"), "a\n Idea name: foo\n Image: C:\\x");
|
||||
assert.deepEqual(noteReplyLines("Q", "one\ntwo", []), ["Note on Q: one\n two"]);
|
||||
assert.match(app(), /replyLines\.push\(`\$\{item\.title\}: \$\{indentReply\(tok\)\}`\)/);
|
||||
});
|
||||
|
||||
test("an approved edit stops saying 'please wait' once the agent has answered it", () => {
|
||||
@@ -211,32 +210,17 @@ test("an approved edit stops saying 'please wait' once the agent has answered it
|
||||
assert.equal(chatView(frame).rows[1].done, true);
|
||||
});
|
||||
|
||||
test("a build's own count wins, 0 done included; a question workflow still fills as cards are answered", () => {
|
||||
const chrome = app().slice(app().indexOf("function renderChrome("), app().indexOf("// Planny and the line beside him"));
|
||||
assert.match(chrome, /if \(Number\(h\.total\) > 0\)/);
|
||||
assert.match(chrome, /building \? Math\.max\(0, Number\(h\.cleared\) \|\| 0\) : Number\(h\.cleared\) \|\| answeredCount\(\)/);
|
||||
assert.match(chrome, /else if \(building && h\.stage\)/, "a review starting at total 0 shows its stage");
|
||||
});
|
||||
|
||||
test("the git board: Publish names a remote only when there is one, and an open card holds the board", () => {
|
||||
const js = app();
|
||||
test("the git board: Publish names a remote only when there is one, and Continue is always offered", () => {
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const action = view.slice(view.indexOf("function runStep("), view.indexOf("function stepButton("));
|
||||
assert.match(action, /remotes\.length === 1/);
|
||||
const at = js.indexOf("const gitMode = ");
|
||||
assert.match(js.slice(at, js.indexOf(";", at)), /myTurn\(\)\.some\(\(i\) => i\.kind !== "notice"\)/);
|
||||
const banner = view.slice(view.indexOf("function opBlock("), view.indexOf("function prBlock("));
|
||||
assert.ok(!/if \(conflicted\.every/.test(banner), "Continue is always offered; plan continue checks the files itself");
|
||||
});
|
||||
|
||||
test("a card cut by the window fades at its bottom edge while there is more below", () => {
|
||||
assert.match(app(), /function markMore\(\)[\s\S]*?classList\.toggle\("has-more"/);
|
||||
assert.match(css(), /\.main > \.card\.has-more \{[\s\S]*?mask-image/);
|
||||
});
|
||||
|
||||
test("kept attachments are served read-only from the session's spec, by their exact name shape", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const route = server.slice(server.indexOf('pathname.startsWith("/attachments/")'), server.indexOf('pathname.startsWith("/uploads/")'));
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
const route = server.slice(server.indexOf("function attachment("), server.indexOf("function shot("));
|
||||
assert.match(route, /req\.method !== "GET"/);
|
||||
assert.match(server, /const KEPT_ROUTE = new RegExp\(`\^\/attachments\/\(\[a-z0-9-\]\{1,40\}-\[0-9a-f-\]\{8\}/);
|
||||
const kept = server.slice(server.indexOf("function keptPath("), server.indexOf("function uploadPath("));
|
||||
@@ -274,12 +258,6 @@ test("a plain reopen (status and a thread reply only) moves the sent note into t
|
||||
assert.ok(card.thread.some((m) => m.who === "user" && m.text === "Add a dry-run flag."));
|
||||
});
|
||||
|
||||
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", () => {
|
||||
const js = app();
|
||||
const list = js.slice(js.indexOf("function buildList("), js.indexOf("function buildList(") + 6000);
|
||||
assert.match(list, /title\.addEventListener\("input", \(\) => \{[\s\S]*?stageQuiet\(item\.id/);
|
||||
});
|
||||
|
||||
test("the git board's Publish reply names no remote when it sent none, and key chips show only for short keys", async () => {
|
||||
const { gitReply } = await import("../src/web-console/public/git-board.js");
|
||||
assert.equal(gitReply("publish", {}), "Publish.");
|
||||
@@ -292,25 +270,17 @@ test("the git board's Publish reply names no remote when it sent none, and key c
|
||||
});
|
||||
|
||||
test("a skip is recorded as one, collected with the send, and settles as skipped", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
assert.match(server, /\.\.\.\(type === "skip" \? \{ skipped: true \} : \{\}\)/);
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
|
||||
assert.match(cli, /a\.type === "answer" \|\| a\.type === "skip"/);
|
||||
});
|
||||
|
||||
test("a send made before the last collection is never shown as still with the agent", () => {
|
||||
const js = app();
|
||||
const fn = js.slice(js.indexOf("const sendCollected = "), js.indexOf("const submittedInFlight = "));
|
||||
assert.match(fn, /String\(sub\.at\) <= String\(c\.at\)/);
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
|
||||
assert.match(cli, /collected: \{ at: result\.consumedAt \|\| nowIso\(\), ids \}/, "the collection time, which every earlier send precedes");
|
||||
});
|
||||
|
||||
test("two dashboards on different specs never trade the workspace back and forth", () => {
|
||||
const js = app();
|
||||
assert.match(js, /wantScope !== scopeMine\) syncWorkspaceScope\(\)/);
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------- round 3 */
|
||||
|
||||
test("a branch whose remote copy was deleted offers Publish again, not Pull or Push", async () => {
|
||||
@@ -331,13 +301,8 @@ test("a branch whose remote copy was deleted offers Publish again, not Pull or P
|
||||
assert.equal(acts.publish.enabled, true);
|
||||
});
|
||||
|
||||
test("a finished session never puts a sent answer back on its form", () => {
|
||||
const js = app();
|
||||
assert.match(js, /if \(effort && !finish\(\) && isOpen\(item\)/);
|
||||
});
|
||||
|
||||
test("keep names a copy from the upload's real path, so an 8.3 spelling reuses the same copy", () => {
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-small.mjs"), "utf8");
|
||||
assert.match(src, /attachmentName\(\{ upload: real\(upload\), name: args\.name \}\)/);
|
||||
});
|
||||
|
||||
|
||||
@@ -34,8 +34,9 @@ import {
|
||||
STRAY_GRACE_MS,
|
||||
staleSessions,
|
||||
terminalLine,
|
||||
validate,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
} from "../src/web-console/sessions.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HANDOFFS_DIR,
|
||||
@@ -528,7 +529,7 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
|
||||
|
||||
test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const dialog = html.match(/<dialog class="modal looks prefs" id="looks-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "the Preferences dialog carries the prefs class");
|
||||
const body = dialog[1].indexOf('<div class="prefs-body">');
|
||||
@@ -722,12 +723,6 @@ test("notes/quick-task.md has a quick-task build tick the Plan tab's steps live"
|
||||
assert.ok(section.includes("- [x] **1.** Step one"));
|
||||
});
|
||||
|
||||
test("the waiting pane points a quick-task build at its Plan tab", () => {
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function renderWaiting("), js.indexOf("function renderNotice("));
|
||||
assert.ok(fn.includes('S.workflow === "quick-task" && docs().find((d) => d.id === "plan")'));
|
||||
});
|
||||
|
||||
test("notes/quick-task.md has the finished quick task offer Back to the dashboard as well as the review", () => {
|
||||
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8");
|
||||
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
|
||||
@@ -791,3 +786,61 @@ test("an image block under the session's shots folder round-trips, and /shots/ s
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// /app.css is the files under public/styles/ joined in CSS_ORDER (one newline
|
||||
// after each), then the accent rules. The files themselves are never served.
|
||||
test("/app.css is the style files joined in CSS_ORDER with the accent rules last", async () => {
|
||||
const { CSS_ORDER, asset, etagOf } = await import("../src/web-console/static.mjs");
|
||||
const dir = path.join(ROOT, "src", "web-console", "public", "styles");
|
||||
const res = cli(["open", "--workflow", "review", "--no-open"]);
|
||||
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
const cookie = cookieFor(m[1], m[2]);
|
||||
try {
|
||||
const r = await fetch(m[1] + "/app.css", { headers: { cookie } });
|
||||
assert.equal(r.status, 200);
|
||||
assert.match(r.headers.get("content-type"), /^text\/css/);
|
||||
const body = await r.text();
|
||||
// One newline between files: each file's own last newline is that one.
|
||||
const joined = CSS_ORDER.map((f) => fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "")).join("\n") + "\n";
|
||||
assert.ok(body.startsWith(joined), "the body opens with the files, in CSS_ORDER, one newline between");
|
||||
const accents = body.slice(joined.length);
|
||||
assert.match(accents, /^\n*\/\* Generated by server\.mjs from palette\.js/, "the accent rules come last");
|
||||
assert.ok(accents.includes(`:root[data-looks-accent="violet"]`));
|
||||
// The tests' helper joins through the server's own function, so the two agree.
|
||||
assert.equal(body, joinedCss() + accents, "joinedCss() plus the accent rules is the body the server returns");
|
||||
// The ETag is a hash of the whole body, so a change to any one file moves it.
|
||||
assert.equal(r.headers.get("etag"), etagOf(Buffer.from(body)));
|
||||
assert.equal(asset("app.css").etag, etagOf(Buffer.from(body)));
|
||||
for (const f of CSS_ORDER) {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "");
|
||||
assert.notEqual(etagOf(Buffer.from(body.replace(text, text + "\n/* changed */"))), r.headers.get("etag"), `a change to ${f} moves the ETag`);
|
||||
}
|
||||
for (const f of CSS_ORDER) {
|
||||
const own = await fetch(m[1] + "/styles/" + f, { headers: { cookie } });
|
||||
assert.equal(own.status, 404, `/styles/${f} is not served on its own`);
|
||||
await own.arrayBuffer();
|
||||
}
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// The skills the build writes carry public/styles/ with every file in CSS_ORDER,
|
||||
// and a console started from that tree serves the same /app.css as this one.
|
||||
test("the built skills tree serves the same /app.css as the source console", async (t) => {
|
||||
const { CSS_ORDER, asset } = await import("../src/web-console/static.mjs");
|
||||
const built = path.join(ROOT, "skills", "plan2code", "references", "web-console");
|
||||
// npm test builds first; a bare run of this file may not have.
|
||||
if (!fs.existsSync(path.join(built, "console.mjs"))) return t.skip("skills/ is not built: run npm run build:skills");
|
||||
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(built, "public", "styles", f)), `the build is missing public/styles/${f}`);
|
||||
const out = execFileSync(process.execPath, [path.join(built, "console.mjs"), "open", "--workflow", "review", "--no-open"], { env: ENV, encoding: "utf8", cwd: ROOT });
|
||||
const json = JSON.parse(out.trim().split("\n").pop());
|
||||
const m = json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
try {
|
||||
const res = await fetch(m[1] + "/app.css", { headers: { cookie: cookieFor(m[1], m[2]) } });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), asset("app.css").body.toString("utf8"));
|
||||
} finally {
|
||||
execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid], { env: ENV, cwd: ROOT });
|
||||
}
|
||||
});
|
||||
@@ -24,9 +24,6 @@ import {
|
||||
noteReplyLines,
|
||||
staleLaunchFeedback,
|
||||
REVIEW_REPLY,
|
||||
SKILL_CATALOG,
|
||||
START_POSES,
|
||||
startPose,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
threadText,
|
||||
@@ -38,13 +35,9 @@ import { ACCENTS, CARD_WIDTHS, SOUND_EVENTS, soundKey, soundPrefs } from "../src
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js";
|
||||
import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js";
|
||||
import { REMOTE_FOLD } from "../src/web-console/public/git-board.js";
|
||||
import {
|
||||
applyPatch,
|
||||
readLedger,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sweepUploads,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
@@ -475,8 +468,7 @@ test("the way home follows Stop's turn rules and hides where it has no job", ()
|
||||
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");
|
||||
const css = joinedCss();
|
||||
assert.ok(html.indexOf('id="btn-home"') < html.indexOf('id="btn-stop"'), "the triangle sits left of Stop session");
|
||||
assert.match(html, /id="btn-home"[\s\S]{0,200}aria-label="Back to the dashboard"/, "the icon button has a name");
|
||||
for (const id of ["home-modal", "home-blurb", "home-warn", "home-cancel", "home-go"]) {
|
||||
@@ -484,8 +476,6 @@ test("the page carries the way home: the triangle, its confirm, and the wiring",
|
||||
}
|
||||
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", () => {
|
||||
@@ -523,9 +513,12 @@ test("console-launches.md and the dashboard prompt teach the handoff pick-up and
|
||||
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"))) {
|
||||
// The modules beside app.js and the screens under screens/, each import
|
||||
// resolved from the file that makes it (a screen's "../state.js" is state.js).
|
||||
const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...fs.readdirSync(path.join(dir, "screens")).map((f) => `screens/${f}`)];
|
||||
for (const f of files) {
|
||||
const src = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
for (const m of src.matchAll(/^\s*import\b[^"']*["']\.\/([^"']+)["']/gm)) wanted.add(m[1]);
|
||||
for (const m of src.matchAll(/^\s*import\b[^"']*["'](\.\.?\/[^"']+)["']/gm)) wanted.add(path.posix.join(path.posix.dirname(f), m[1]));
|
||||
}
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
for (const m of html.matchAll(/<link rel="modulepreload" href="\/([^"]+)"/g)) wanted.add(m[1]);
|
||||
@@ -613,28 +606,6 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
|
||||
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(/<template id="start-poses">([\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 */
|
||||
|
||||
|
||||
@@ -798,9 +769,9 @@ const helpFacts = () => ({
|
||||
maxDocMb: MAX_DOC_BYTES / 1024 / 1024,
|
||||
imageEdge: IMAGE_LONG_EDGE,
|
||||
cleanupDays: SESSION_MAX_AGE_MS / 86400000,
|
||||
goneSeconds: sourceConst("public/app.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
|
||||
adriftMinutes: sourceConst("public/app.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
|
||||
maxUploadMb: sourceConst("public/app.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
|
||||
goneSeconds: sourceConst("public/screens/core.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
|
||||
adriftMinutes: sourceConst("public/selectors.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
|
||||
maxUploadMb: sourceConst("public/uploads.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
|
||||
idleMinutes: sourceConst("server.mjs", /const IDLE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "IDLE_MS") / 60000,
|
||||
maxLifeHours: sourceConst("server.mjs", /const MAX_LIFE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "MAX_LIFE_MS") / 3600000,
|
||||
closedTabMinutes: sourceConst("server.mjs", /\(IDLE_MS - ([^)]+)\)/, "the closed-tab shutdown") / 60000,
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// Web console tests, the shape of the source: no console file grows past
|
||||
// 3,000 lines, and the files lib.mjs split into stand on their own.
|
||||
// Run with: node --test scripts/test-web-console-shape.mjs
|
||||
|
||||
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 { spawnSync } from "node:child_process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
|
||||
const MAX_LINES = 3000;
|
||||
|
||||
// Every .mjs, .js and .css file under `dir` (vendored code aside), as paths
|
||||
// relative to it with forward slashes.
|
||||
function sourceFiles(dir, rel = "") {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
||||
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "public/vendor") out.push(...sourceFiles(dir, p));
|
||||
} else if (/\.(mjs|js|css)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// A file's line count, as `wc -l` gives it for a file ending in a newline.
|
||||
function lineCount(text) {
|
||||
return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
||||
}
|
||||
|
||||
// The lines that name each file over the limit.
|
||||
function oversized(dir) {
|
||||
return sourceFiles(dir)
|
||||
.map((p) => [p, lineCount(fs.readFileSync(path.join(dir, p), "utf8"))])
|
||||
.filter(([p, n]) => n > MAX_LINES)
|
||||
.map(([p, n]) => `${p} is ${n} lines, over the ${MAX_LINES}-line limit: split it by job`);
|
||||
}
|
||||
|
||||
test("shape: no console file is over 3,000 lines", () => {
|
||||
assert.deepEqual(oversized(CONSOLE_DIR), []);
|
||||
});
|
||||
|
||||
test("shape: the size check names the file that is too big", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "public", "vendor"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "big.mjs"), "x\n".repeat(MAX_LINES + 1));
|
||||
fs.writeFileSync(path.join(dir, "edge.css"), "x\n".repeat(MAX_LINES));
|
||||
fs.writeFileSync(path.join(dir, "small.js"), "x\n");
|
||||
fs.writeFileSync(path.join(dir, "public", "vendor", "huge.js"), "x\n".repeat(MAX_LINES * 2));
|
||||
assert.deepEqual(oversized(dir), [`big.mjs is ${MAX_LINES + 1} lines, over the ${MAX_LINES}-line limit: split it by job`]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("shape: files.mjs still finds the console's own folder", async () => {
|
||||
const { HERE, PUBLIC_DIR } = await import("../src/web-console/files.mjs");
|
||||
assert.equal(path.basename(HERE), "web-console");
|
||||
assert.equal(PUBLIC_DIR, path.join(HERE, "public"));
|
||||
});
|
||||
|
||||
test("shape: lib.mjs is gone, and every file it split into is there", () => {
|
||||
assert.equal(fs.existsSync(path.join(CONSOLE_DIR, "lib.mjs")), false, "src/web-console/lib.mjs still exists");
|
||||
for (const f of SPLIT_FILES) {
|
||||
const text = fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8");
|
||||
assert.match(text, /^\/\/ Plan2Code Web Console - \S.*\.\n/, `${f} opens with a one-line job comment`);
|
||||
}
|
||||
});
|
||||
|
||||
// Every page file but the entry (app.js) only defines things, so each one
|
||||
// loads under plain Node with no page around it. Imported alone in a fresh
|
||||
// process: one that reaches for `document` or `window` at load, or runs
|
||||
// anything else that throws, is named with its first error line. One that
|
||||
// starts a timer or a listener throws nothing but never exits: it is named too.
|
||||
const LOAD_TIMEOUT_MS = 5000;
|
||||
function pageLoadFailures(pub) {
|
||||
return sourceFiles(pub)
|
||||
.filter((p) => p.endsWith(".js") && p !== "app.js" && (!p.includes("/") || p.startsWith("screens/")))
|
||||
.flatMap((p) => {
|
||||
const url = pathToFileURL(path.join(pub, p)).href;
|
||||
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], {
|
||||
encoding: "utf8",
|
||||
timeout: LOAD_TIMEOUT_MS,
|
||||
});
|
||||
if (r.error && r.error.code === "ETIMEDOUT") return [`${p} does not load on its own: still running after load (a timer or listener started at module scope)`];
|
||||
if (r.status === 0) return [];
|
||||
const line = r.stderr.split("\n").find((l) => /Error/.test(l)) || r.stderr.trim().split("\n")[0];
|
||||
return [`${p} does not load on its own: ${line.trim()}`];
|
||||
});
|
||||
}
|
||||
|
||||
test("shape: every page file but app.js only defines things, and loads under plain Node", () => {
|
||||
assert.deepEqual(pageLoadFailures(path.join(CONSOLE_DIR, "public")), []);
|
||||
});
|
||||
|
||||
test("shape: the define-only check names a page file that touches the page at load", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-define-only-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "screens"));
|
||||
fs.mkdirSync(path.join(dir, "vendor"));
|
||||
fs.writeFileSync(path.join(dir, "package.json"), '{ "type": "module" }\n');
|
||||
fs.writeFileSync(path.join(dir, "app.js"), "document.title = 'the entry may';\n");
|
||||
fs.writeFileSync(path.join(dir, "fine.js"), "export const title = () => document.title;\n");
|
||||
fs.writeFileSync(path.join(dir, "screens", "eager.js"), "export const title = document.title;\n");
|
||||
fs.writeFileSync(path.join(dir, "screens", "ticks.js"), "setInterval(() => {}, 1000);\n");
|
||||
fs.writeFileSync(path.join(dir, "vendor", "lib.js"), "window.x = 1;\n");
|
||||
const failures = pageLoadFailures(dir);
|
||||
assert.equal(failures.length, 2, failures.join("\n"));
|
||||
assert.match(failures.find((f) => f.startsWith("screens/eager.js")), /does not load on its own: ReferenceError: document is not defined/);
|
||||
assert.match(failures.find((f) => f.startsWith("screens/ticks.js")), /does not load on its own: still running after load/);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// A screen reaches the rest of the page through ../state.js and the pure
|
||||
// modules beside it, never through another screen: only core.js (the render
|
||||
// loop, which draws every screen) imports screens, and only app.js (the
|
||||
// entry) imports core.js. Each import that breaks that is named.
|
||||
function pageImportProblems(pub) {
|
||||
const problems = [];
|
||||
for (const p of sourceFiles(pub).filter((f) => f.endsWith(".js") && (!f.includes("/") || f.startsWith("screens/")))) {
|
||||
const text = fs.readFileSync(path.join(pub, p), "utf8");
|
||||
for (const m of text.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']\s*\)|^\s*import\s*["']([^"']+)["']/gm)) {
|
||||
const spec = m[1] || m[2] || m[3];
|
||||
if (!spec.startsWith(".")) continue;
|
||||
const target = path.posix.join(path.posix.dirname(p), spec);
|
||||
if (target === "screens/core.js" && p !== "app.js") problems.push(`${p} imports ${spec}: only app.js imports core.js`);
|
||||
else if (p.startsWith("screens/") && p !== "screens/core.js" && target.startsWith("screens/"))
|
||||
problems.push(`${p} imports ${spec}: a screen imports ../state.js and the modules beside it, never another screen`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
test("shape: a screen never imports another screen, and only app.js imports core.js", () => {
|
||||
assert.deepEqual(pageImportProblems(path.join(CONSOLE_DIR, "public")), []);
|
||||
});
|
||||
|
||||
test("shape: the import check names a screen that imports another, and any file but app.js importing core.js", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-imports-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "screens"));
|
||||
const put = (rel, text) => fs.writeFileSync(path.join(dir, rel), text);
|
||||
put("app.js", 'import { render } from "./screens/core.js";\n');
|
||||
put("state.js", "export const page = {};\n");
|
||||
put("render.js", "export const el = () => null;\n");
|
||||
put("screens/core.js", 'import { a } from "./a.js";\nimport { page } from "../state.js";\n');
|
||||
put("screens/a.js", 'import { b } from "./b.js";\nimport { page } from "../state.js";\nimport { el } from "../render.js";\n');
|
||||
put("screens/b.js", 'import { page } from "../state.js";\n');
|
||||
put("screens/c.js", 'import { render } from "./core.js";\n');
|
||||
put("helper.js", 'import { render } from "./screens/core.js";\n');
|
||||
put("screens/d.js", 'import "./b.js";\n');
|
||||
assert.deepEqual(pageImportProblems(dir).sort(), [
|
||||
"helper.js imports ./screens/core.js: only app.js imports core.js",
|
||||
"screens/a.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
|
||||
"screens/c.js imports ./core.js: only app.js imports core.js",
|
||||
"screens/d.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
|
||||
]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The page's CSP refuses style attributes, so one set from script is dropped
|
||||
// on the floor in the browser. Every page module, wherever a split moves the
|
||||
// code that draws.
|
||||
test("shape: no page module sets a style attribute from script", () => {
|
||||
const pub = path.join(CONSOLE_DIR, "public");
|
||||
const offenders = sourceFiles(pub)
|
||||
.filter((p) => p.endsWith(".js"))
|
||||
.filter((p) => /setAttribute\(\s*["']style["']/.test(fs.readFileSync(path.join(pub, p), "utf8")));
|
||||
assert.deepEqual(offenders, []);
|
||||
});
|
||||
|
||||
// Every URL the server's old `if` chain matched, in its order, so a route lost
|
||||
// or moved in routes.mjs fails here by name: several match by prefix, and the
|
||||
// token gate sits after the first two. SERVABLE stands for the page's own files
|
||||
// and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has
|
||||
// no routes of its own: its buttons are sends (`__git`), through /submit.
|
||||
const ROUTE_ORDER = [
|
||||
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
|
||||
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
|
||||
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
|
||||
];
|
||||
|
||||
test("shape: routes.mjs lists every URL the server answers, in order", () => {
|
||||
const routes = fs.readFileSync(path.join(CONSOLE_DIR, "routes.mjs"), "utf8");
|
||||
const start = routes.indexOf("const ROUTES = [");
|
||||
const list = routes.slice(start, routes.indexOf("\n];", start));
|
||||
const entries = list
|
||||
.split("\n")
|
||||
.filter((line) => /^\s*\{/.test(line))
|
||||
.map((line) => (line.match(/path: "([^"]*)"|startsWith\("([^"]*)"\)|\b(SERVABLE|WORKSPACE_EDITS)\b/) || []).slice(1).find(Boolean));
|
||||
assert.deepEqual(entries, ROUTE_ORDER);
|
||||
const edits = routes.match(/const WORKSPACE_EDITS = \{([^}]*)\}/)[1];
|
||||
for (const p of ["/workspace/add", "/workspace/edit", "/workspace/remove"]) assert.ok(edits.includes(`"${p}"`), `${p} is a workspace edit`);
|
||||
});
|
||||
|
||||
// Each file split out of lib.mjs, imported first and alone in a fresh
|
||||
// process: a module-scope read of a value from a file still loading (an
|
||||
// import cycle) throws here, naming the file, before it reaches a real run.
|
||||
const SPLIT_FILES = ["files.mjs", "sessions.mjs", "scan.mjs", "patches.mjs", "inbox.mjs", "workspace.mjs", "settings.mjs"];
|
||||
|
||||
test("shape: every file split out of lib.mjs loads first and alone", () => {
|
||||
for (const f of SPLIT_FILES) {
|
||||
const url = pathToFileURL(path.join(CONSOLE_DIR, f)).href;
|
||||
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], { encoding: "utf8" });
|
||||
assert.equal(r.status, 0, `${f} does not load on its own: ${r.stderr.trim().split("\n").find((l) => /Error/.test(l)) || r.stderr}`);
|
||||
}
|
||||
});
|
||||
|
||||
// app.js is the entry and nothing else, so no test may read it as text: what a
|
||||
// screen does is tested by driving the page, and what a screen file holds is
|
||||
// read from that screen. A statement that both reads a file and names app.js
|
||||
// is a read (a fetch of /app.js, or a fixture file called app.js, is not).
|
||||
const SCRIPTS_DIR = path.join(ROOT, "scripts");
|
||||
|
||||
// parse-check.mjs only parses the entry, so it may name it.
|
||||
const MAY_NAME_APP_JS = new Set(["parse-check.mjs"]);
|
||||
|
||||
// One statement that reads and names app.js, or a read helper handed it
|
||||
// (`web("app.js")`, `publicSource("public/app.js")`), or a path to it
|
||||
// under public/, in any file that also reads files.
|
||||
function appJsReaders(dir) {
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((f) => f.endsWith(".mjs") && f !== "test-web-console-shape.mjs" && !MAY_NAME_APP_JS.has(f))
|
||||
.filter((f) => {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
const oneStatement = text
|
||||
.split(";")
|
||||
.some((statement) => /\b(readFileSync|readFile|publicSource)\s*\(/.test(statement) && /["'/]app\.js["']/.test(statement));
|
||||
const handedToAHelper = /\w\(\s*["'](?:(?:src\/web-console\/)?public\/)?app\.js["']\s*\)/.test(text);
|
||||
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
|
||||
return oneStatement || handedToAHelper || publicPath;
|
||||
})
|
||||
.map((f) => `${f} reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it`);
|
||||
}
|
||||
|
||||
test("shape: no test in scripts/ reads public/app.js as text", () => {
|
||||
assert.deepEqual(appJsReaders(SCRIPTS_DIR), []);
|
||||
});
|
||||
|
||||
test("shape: the app.js check names the test file that reads it", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "test-fine.mjs"), 'const r = await fetch(base + "/app.js");\nfs.appendFileSync(path.join(d, "src", "app.js"), "x");\n');
|
||||
assert.deepEqual(appJsReaders(dir), []);
|
||||
fs.writeFileSync(path.join(dir, "test-reads-it.mjs"), 'const app = fs.readFileSync(path.join(ROOT, "public", "app.js"), "utf8");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-reads-it.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
fs.rmSync(path.join(dir, "test-reads-it.mjs"));
|
||||
fs.writeFileSync(path.join(dir, "test-alias.mjs"), 'const web = (f) => fs.readFileSync(path.join(ROOT, "public", f), "utf8");\nconst app = web("app.js");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-alias.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The stylesheet is many files under public/styles/, joined by the server into
|
||||
// the one /app.css the page asks for. CSS_ORDER is the one place the cascade
|
||||
// order is stated: every file in it exists, each once, and no file in the folder
|
||||
// is left out of it or served on its own.
|
||||
test("shape: CSS_ORDER names every file in public/styles/ once, and none is served on its own", async () => {
|
||||
const { CSS_ORDER, SERVABLE } = await import("../src/web-console/static.mjs");
|
||||
const dir = path.join(CONSOLE_DIR, "public", "styles");
|
||||
assert.ok(CSS_ORDER.length > 0, "CSS_ORDER lists files");
|
||||
assert.equal(new Set(CSS_ORDER).size, CSS_ORDER.length, "no file is listed twice");
|
||||
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(dir, f)), `CSS_ORDER lists ${f}, which is not in public/styles/`);
|
||||
const onDisk = fs.readdirSync(dir).filter((f) => f.endsWith(".css")).sort();
|
||||
assert.deepEqual([...CSS_ORDER].sort(), onDisk, "public/styles/ holds exactly the files CSS_ORDER lists");
|
||||
for (const rel of SERVABLE) assert.ok(!rel.startsWith("styles/") && !CSS_ORDER.includes(rel), `${rel} must not be served on its own`);
|
||||
});
|
||||
|
||||
// The files table in AGENTS-architecture.md gives every console file a row,
|
||||
// so a contributor finds where a job lives without searching. A row's first
|
||||
// cell names the file by its path under src/web-console/ (backticked; one cell
|
||||
// may name several files, joined by "·").
|
||||
const ARCHITECTURE_DOC = path.join(ROOT, ".agents-docs", "AGENTS-architecture.md");
|
||||
|
||||
// The paths the files table names, from the first cell of each table row.
|
||||
function tableFiles(markdown) {
|
||||
const named = new Set();
|
||||
for (const line of markdown.split("\n")) {
|
||||
if (!line.startsWith("|")) continue;
|
||||
const cell = line.split("|")[1] || "";
|
||||
for (const m of cell.matchAll(/`([^`]+)`/g)) named.add(m[1]);
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
// One line per console file with no row in the table.
|
||||
function undocumented(dir, markdown) {
|
||||
const named = tableFiles(markdown);
|
||||
return sourceFiles(dir)
|
||||
.filter((p) => !named.has(p))
|
||||
.map((p) => `${p} has no row in the files table of AGENTS-architecture.md: add one with its one-line job`);
|
||||
}
|
||||
|
||||
test("shape: every console file has a row in the files table of AGENTS-architecture.md", () => {
|
||||
const problems = undocumented(CONSOLE_DIR, fs.readFileSync(ARCHITECTURE_DOC, "utf8"));
|
||||
assert.deepEqual(problems, []);
|
||||
});
|
||||
|
||||
test("shape: the docs-table check names a file with no row, and passes one that has it", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-docs-table-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "public"));
|
||||
fs.writeFileSync(path.join(dir, "a.mjs"), "");
|
||||
fs.writeFileSync(path.join(dir, "public", "b.js"), "");
|
||||
const table = "| File | Role |\n|---|---|\n| `a.mjs` | the first |\n";
|
||||
assert.deepEqual(undocumented(dir, table), [
|
||||
"public/b.js has no row in the files table of AGENTS-architecture.md: add one with its one-line job",
|
||||
]);
|
||||
assert.deepEqual(undocumented(dir, `${table}| \`public/b.js\` · \`x.js\` | the second |\n`), []);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
// Web console tests, the skill list: public/skills.js holds every per-skill
|
||||
// fact the console uses, and the older tables are lookups on it.
|
||||
// Run with: node --test scripts/test-web-console-skills.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
SKILLS,
|
||||
skillFor,
|
||||
skillByName,
|
||||
isBuild,
|
||||
isPhased,
|
||||
isMetered,
|
||||
subagentsFor,
|
||||
takesTemplates,
|
||||
labelFor,
|
||||
} from "../src/web-console/public/skills.js";
|
||||
import { CONSOLE_WORKFLOWS, SKILL_CATALOG, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
|
||||
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
|
||||
import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js";
|
||||
import { helpTabFor } from "../src/web-console/public/help.js";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { ROOT, cli, poseTemplate } from "./web-console-test-helpers.mjs";
|
||||
import { SUBAGENT_WORKFLOWS } from "../src/web-console/public/subagents.js";
|
||||
import { TEMPLATE_WORKFLOWS } from "../src/web-console/public/starters.js";
|
||||
|
||||
// meter.js keeps its answers-row names private: what they were when the list
|
||||
// moved, written out. A skill added since has no row here, and only has to
|
||||
// have a name.
|
||||
const NAMES_AT_THE_MOVE = {
|
||||
dashboard: "the dashboard",
|
||||
pathfinder: "Pathfinder",
|
||||
plan: "Plan",
|
||||
"revise-plan": "Revise plan",
|
||||
document: "Document",
|
||||
implement: "Implement",
|
||||
"implement-review": "Implement + Review",
|
||||
review: "Review",
|
||||
"quick-task": "Quick task",
|
||||
init: "Init",
|
||||
"init-update": "Init update",
|
||||
finalize: "Finalize",
|
||||
handoff: "Handoff",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
xray: "X-ray",
|
||||
diagnose: "Diagnose",
|
||||
};
|
||||
|
||||
const CARD_FIELDS = ["group", "chip", "title", "blurb", "about", "spec"];
|
||||
|
||||
test("every skill the console knows has one entry, the dashboard included", () => {
|
||||
const workflows = SKILLS.map((s) => s.workflow);
|
||||
assert.deepEqual([...workflows].sort(), Object.keys(WORKFLOW_LABEL).sort());
|
||||
assert.equal(new Set(workflows).size, workflows.length, "one entry per workflow");
|
||||
assert.deepEqual(SKILLS.map((s) => s.command).sort(), [...CONSOLE_WORKFLOWS].sort());
|
||||
// The cards come first, in the dashboard's order.
|
||||
const carded = SKILLS.filter((s) => s.card);
|
||||
assert.deepEqual(carded.map((s) => s.skill), SKILL_CATALOG.map((e) => e.skill));
|
||||
assert.equal(skillFor("dashboard").skill, "plan2code");
|
||||
assert.equal(skillFor("dashboard").card, null, "the dashboard is the hub, not a card");
|
||||
});
|
||||
|
||||
// The older exports (WORKFLOW_LABEL, SKILL_CATALOG, LAUNCH_COUNTED and the
|
||||
// rest) are now built from SKILLS, so this checks the wiring: each one still
|
||||
// says what its entry says. It proved the move when the tables were still
|
||||
// written by hand; the meter names and the build flags, which have no
|
||||
// importable twin, are held to their values at the move.
|
||||
test("the derived exports agree with each entry", () => {
|
||||
for (const s of SKILLS) {
|
||||
const w = s.workflow;
|
||||
for (const f of ["skill", "workflow", "label", "name"]) assert.ok(typeof s[f] === "string" && s[f].trim(), `${w}: ${f} must be filled in`);
|
||||
assert.equal(s.command, "/" + s.skill, `${w}: command`);
|
||||
assert.equal(s.label, WORKFLOW_LABEL[w], `${w}: label`);
|
||||
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) assert.equal(s.name, NAMES_AT_THE_MOVE[w], `${w}: name`);
|
||||
assert.equal(s.pose, startPose(w), `${w}: pose`);
|
||||
assert.equal(s.metered, LAUNCH_COUNTED.has(w), `${w}: metered`);
|
||||
assert.equal(s.subagents, SUBAGENT_WORKFLOWS[w] ? SUBAGENT_WORKFLOWS[w].instruction : null, `${w}: subagents`);
|
||||
assert.equal(s.templates, TEMPLATE_WORKFLOWS.includes(w), `${w}: templates`);
|
||||
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) {
|
||||
assert.equal(s.builds, ["implement", "implement-review", "quick-task"].includes(w), `${w}: builds`);
|
||||
assert.equal(s.phased, ["implement", "implement-review"].includes(w), `${w}: phased`);
|
||||
}
|
||||
const entry = SKILL_CATALOG.find((e) => e.workflow === w);
|
||||
if (!entry) {
|
||||
assert.equal(s.card, null, `${w}: no card`);
|
||||
continue;
|
||||
}
|
||||
assert.equal(entry.skill, s.skill, `${w}: skill`);
|
||||
assert.equal(entry.command, s.command, `${w}: card command`);
|
||||
for (const f of CARD_FIELDS) assert.equal(s.card[f], entry[f], `${w}: card.${f}`);
|
||||
}
|
||||
// Every pose in the page's list belongs to an entry.
|
||||
for (const pose of START_POSES) assert.ok(SKILLS.some((s) => s.pose === pose), `${pose} belongs to a skill`);
|
||||
for (const w of PROGRESS_WORKFLOWS) assert.ok(isPhased(w), `${w} counts its tasks`);
|
||||
});
|
||||
|
||||
test("the entries are frozen data", () => {
|
||||
assert.ok(Object.isFrozen(SKILLS));
|
||||
for (const s of SKILLS) {
|
||||
assert.ok(Object.isFrozen(s), `${s.workflow} is frozen`);
|
||||
if (s.card) assert.ok(Object.isFrozen(s.card), `${s.workflow}.card is frozen`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the lookups answer by workflow or skill name, and say nothing for an unknown one", () => {
|
||||
assert.equal(skillFor("implement-review").skill, "plan2code-3-implement-review");
|
||||
assert.equal(skillByName("plan2code-git").workflow, "git");
|
||||
assert.equal(skillByName("plan2code").workflow, "dashboard");
|
||||
assert.equal(labelFor("xray"), "X-ray");
|
||||
assert.equal(subagentsFor("review"), SUBAGENT_WORKFLOWS.review.instruction);
|
||||
for (const unknown of ["nope", undefined, null, "", "constructor", "__proto__"]) {
|
||||
assert.equal(skillFor(unknown), null);
|
||||
assert.equal(skillByName(unknown), null);
|
||||
assert.equal(labelFor(unknown), null);
|
||||
assert.equal(subagentsFor(unknown), null);
|
||||
for (const is of [isBuild, isPhased, isMetered, takesTemplates]) assert.equal(is(unknown), false);
|
||||
}
|
||||
});
|
||||
|
||||
// Which workflows labels.js and help.js count as builds, as they stood when the
|
||||
// sets moved onto skills.js: labels.js leaves Quick Task out, help.js keeps it.
|
||||
test("the two build sets hold what they held before", () => {
|
||||
assert.deepEqual([...BUILD_WORKFLOWS].sort(), ["implement", "implement-review"]);
|
||||
assert.deepEqual(SKILLS.filter((s) => isBuild(s.workflow)).map((s) => s.workflow).sort(), ["implement", "implement-review", "quick-task"]);
|
||||
// help.js keeps its set private: Help opens on its Building tab for exactly these.
|
||||
const onBuild = SKILLS.map((s) => s.workflow).filter((workflow) => helpTabFor({ workflow }) === "build");
|
||||
assert.deepEqual(onBuild.sort(), ["implement", "implement-review", "quick-task"]);
|
||||
assert.equal(helpTabFor({ workflow: "nope" }), "about");
|
||||
});
|
||||
|
||||
/* ------------------------------------------- tests that name what was missed */
|
||||
|
||||
// Each check below is a pure function of a skill list, so a test can hand it a
|
||||
// copy with one thing wrong and see the message name the skill.
|
||||
|
||||
// Each skill's starting screen clones its pose from index.html. A pose with no
|
||||
// drawing silently falls back to the flight, and a drawing no skill uses is
|
||||
// dead markup.
|
||||
function poseProblems(skills, drawn) {
|
||||
const problems = [];
|
||||
for (const s of skills) {
|
||||
if (s.card && !s.pose) problems.push(`${s.skill} has a card but no pose`);
|
||||
if (s.pose && !drawn.includes(s.pose)) problems.push(`${s.skill} names pose "${s.pose}", which index.html does not draw`);
|
||||
}
|
||||
for (const pose of drawn) {
|
||||
if (!skills.some((s) => s.pose === pose)) problems.push(`index.html draws pose "${pose}", which belongs to no skill`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// Every workflow the console can open has its notes behind `console.mjs help`.
|
||||
function helpProblems(skills, topics) {
|
||||
return skills.filter((s) => !Object.hasOwn(topics, s.workflow)).map((s) => `${s.skill} (${s.workflow}) has no help topic in console.mjs`);
|
||||
}
|
||||
|
||||
// The skills with a card, plus the dashboard, are exactly what install.js builds.
|
||||
function installProblems(skills, installed) {
|
||||
const named = skills.filter((s) => s.card || s.workflow === "dashboard").map((s) => s.skill);
|
||||
return [
|
||||
...named.filter((n) => !installed.includes(n)).map((n) => `${n} is in skills.js but not in install.js SOURCE_PROMPTS`),
|
||||
...installed.filter((n) => !named.includes(n)).map((n) => `${n} is in install.js SOURCE_PROMPTS but has no card in skills.js`),
|
||||
];
|
||||
}
|
||||
|
||||
const drawnPoses = () => [...poseTemplate().matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
|
||||
const helpTopics = () => cli(["help", "topics"]).json.topics;
|
||||
|
||||
// install.js reads the home directory at load: point it at a temp one, as the
|
||||
// install tests do. Requiring it never runs its CLI (that waits on require.main).
|
||||
function installedSkills() {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-skills-"));
|
||||
const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
|
||||
process.env.HOME = home;
|
||||
process.env.USERPROFILE = home;
|
||||
try {
|
||||
const { SOURCE_PROMPTS, generateSkillName } = createRequire(import.meta.url)(path.join(ROOT, "install.js"));
|
||||
return SOURCE_PROMPTS.map(generateSkillName);
|
||||
} finally {
|
||||
for (const [k, v] of Object.entries(saved)) v === undefined ? delete process.env[k] : (process.env[k] = v);
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("every skill's pose is drawn in the page, and every drawn pose belongs to a skill", () => {
|
||||
const drawn = drawnPoses();
|
||||
assert.deepEqual(poseProblems(SKILLS, drawn), []);
|
||||
assert.doesNotMatch(poseTemplate(), /\sstyle=/, "a style attribute would be refused by the CSP");
|
||||
// Variants borrow their pose; the dashboard keeps the flight.
|
||||
assert.equal(startPose("implement-review"), "implement");
|
||||
assert.equal(startPose("revise-plan"), "plan");
|
||||
assert.equal(startPose("init-update"), "init");
|
||||
assert.equal(startPose("dashboard"), null);
|
||||
assert.equal(startPose(undefined), null);
|
||||
|
||||
const broken = SKILLS.map((s) => (s.workflow === "xray" ? { ...s, pose: "x-ray-glasses" } : s));
|
||||
assert.deepEqual(poseProblems(broken, drawn), [
|
||||
'plan2code-xray names pose "x-ray-glasses", which index.html does not draw',
|
||||
'index.html draws pose "xray", which belongs to no skill',
|
||||
]);
|
||||
const poseless = SKILLS.map((s) => (s.workflow === "git" ? { ...s, pose: null } : s));
|
||||
assert.deepEqual(poseProblems(poseless, drawn), ["plan2code-git has a card but no pose", 'index.html draws pose "git", which belongs to no skill']);
|
||||
});
|
||||
|
||||
test("every workflow in the skill list has a help topic", () => {
|
||||
const topics = helpTopics();
|
||||
assert.deepEqual(helpProblems(SKILLS, topics), []);
|
||||
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up" }];
|
||||
assert.deepEqual(helpProblems(extra, topics), ["plan2code-made-up (made-up) has no help topic in console.mjs"]);
|
||||
});
|
||||
|
||||
test("the skill list and install.js agree on which skills exist", () => {
|
||||
const installed = installedSkills();
|
||||
assert.ok(installed.includes("plan2code"), "read SOURCE_PROMPTS");
|
||||
assert.deepEqual(installProblems(SKILLS, installed), []);
|
||||
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up", card: {} }];
|
||||
assert.deepEqual(installProblems(extra, installed), ["plan2code-made-up is in skills.js but not in install.js SOURCE_PROMPTS"]);
|
||||
assert.deepEqual(installProblems(SKILLS, [...installed, "plan2code-orphan"]), ["plan2code-orphan is in install.js SOURCE_PROMPTS but has no card in skills.js"]);
|
||||
});
|
||||
|
||||
test("dashboard note: the agent's note shows only on the spec the picker opened on", () => {
|
||||
const a = { dir: "specs/a" };
|
||||
const b = { dir: "specs/b" };
|
||||
assert.equal(onInitialPick(a, a), true);
|
||||
assert.equal(onInitialPick(a, b), false);
|
||||
assert.equal(onInitialPick(a, null), false);
|
||||
assert.equal(onInitialPick(null, null), true, "no spec at all: scratch is the opening pick");
|
||||
assert.equal(onInitialPick(null, a), false);
|
||||
});
|
||||
|
||||
test("dashboard note: the agent's note, the looking-over line and the neutral line", () => {
|
||||
const menu = { note: "Phase 2 is next." };
|
||||
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: true, working: false }), "agent");
|
||||
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: false, working: false }), "neutral", "another pick, another line");
|
||||
assert.equal(dashNoteKind({ menu: { note: " " }, hasMenu: true, onInitial: true, working: true }), "neutral", "a blank note is no note");
|
||||
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: true }), "looking");
|
||||
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: false }), "neutral");
|
||||
});
|
||||
|
||||
test("starting screen: the hint stays calm for ninety seconds, then points at the terminal", () => {
|
||||
assert.match(startingHint(0), /fills in by itself/);
|
||||
assert.match(startingHint(90000), /fills in by itself/, "ninety seconds is still calm");
|
||||
assert.match(startingHint(90001), /terminal has the play-by-play/);
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import path from "node:path";
|
||||
// (it touches `document` at module scope and starts a session on import), which
|
||||
// is exactly why this lives in its own file.
|
||||
import { cardAvailability, SKILL_CATALOG } from "../src/web-console/public/answers.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
|
||||
import {
|
||||
@@ -24,8 +25,9 @@ import {
|
||||
latestTag,
|
||||
} from "../src/web-console/update-check.mjs";
|
||||
import { runHint } from "../src/web-console/public/render.js";
|
||||
import { applyPatch } from "../src/web-console/lib.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { ROOT, cli, helpTemplate, sessionUrl } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
test("favicon: the dot follows the status line -- busy, ready, attention, plain", () => {
|
||||
// Anything with the spinning ring is busy, even a finished screen opening the dashboard.
|
||||
@@ -82,7 +84,7 @@ test("runHint: command words (git included) get the hint, the rest nothing", ()
|
||||
});
|
||||
|
||||
test("a reused item id does not inherit the previous answer's submitted record", async () => {
|
||||
const { applyPatch } = await import("../src/web-console/lib.mjs");
|
||||
const { applyPatch } = await import("../src/web-console/patches.mjs");
|
||||
const before = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "open", submitted: { at: "t", text: "old answer" } }] };
|
||||
const reworded = applyPatch(before, { items: [{ id: "q7", kind: "choice", title: "B", body: "new", status: "open" }] });
|
||||
assert.equal(reworded.items[0].submitted, undefined);
|
||||
@@ -100,7 +102,7 @@ test("a reused item id does not inherit the previous answer's submitted record",
|
||||
});
|
||||
|
||||
test("unansweredChat lists delivered Quick questions that still have no reply", async () => {
|
||||
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/lib.mjs");
|
||||
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/inbox.mjs");
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-chat-"));
|
||||
appendChat(dir, { kind: "reset", conversation: 1, workflow: "dashboard", reason: "start" });
|
||||
appendChat(dir, { kind: "message", conversation: 1, text: "run it" });
|
||||
@@ -251,8 +253,7 @@ test("update check: the frame carries update only when a newer release is cached
|
||||
test("stop modal: handoff choice first, plain stop second, Keep going last, styled and wired", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const html = web("index.html");
|
||||
const app = web("app.js");
|
||||
const css = web("app.css");
|
||||
const css = joinedCss();
|
||||
const dialog = html.match(/<dialog class="modal" id="stop-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "index.html has the stop modal");
|
||||
const body = dialog[1];
|
||||
@@ -262,39 +263,17 @@ test("stop modal: handoff choice first, plain stop second, Keep going last, styl
|
||||
assert.doesNotMatch(body, /\sstyle=|<script/i);
|
||||
assert.match(css, /\.stop-choice/, "app.css styles the choices");
|
||||
assert.match(css, /\.stop-choice:focus-visible/, "and gives them a focus outline");
|
||||
const open = app.slice(app.indexOf("function openStopConfirm()"), app.indexOf("async function stopSession("));
|
||||
assert.ok(open.includes("stop-handoff") && open.includes("isDashboard()"), "openStopConfirm hides the handoff on the dashboard");
|
||||
assert.ok(app.includes("stopSession(true)") && app.includes("STOP_HANDOFF_REPLY") && app.includes("stopAction"), "app.js wires the handoff stop");
|
||||
const help = helpTemplate().match(/<section class="help-panel" data-tab="finishing">([\s\S]*?)<\/section>/);
|
||||
assert.ok(help && help[1].includes("Stop with a handoff") && help[1].includes("Just stop and save") && help[1].includes("~/.plan2code/handoffs/"), "Help names both choices and where handoffs land");
|
||||
});
|
||||
|
||||
// The dashboard's handoff chips, preview and their four actions.
|
||||
test("dashboard handoffs: dashed chips, a preview with four buttons, and the cards give way", () => {
|
||||
// The dashboard's handoff chips, preview and their four actions. What they
|
||||
// do on the page is held by the page tests in test-web-console-page-dashboard.mjs;
|
||||
// this keeps the style, the modal markup and the Help.
|
||||
test("dashboard handoffs: the style, the read dialog and the delete warning ship, and Help explains the chips", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const app = web("app.js");
|
||||
const css = web("app.css");
|
||||
const css = joinedCss();
|
||||
const html = web("index.html");
|
||||
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
|
||||
|
||||
const picker = fn("renderSpecPicker", "\nfunction ");
|
||||
assert.ok(picker.includes("is-handoff") && picker.includes('"Handoff"'), "renderSpecPicker builds handoff chips");
|
||||
assert.ok(picker.includes('"handoff:"'), "a handoff is picked as handoff:<id>");
|
||||
const dash = fn("renderDashboard", "\n/* -----");
|
||||
assert.ok(dash.includes("handoffList()"), "renderDashboard shows the picker for handoffs alone");
|
||||
const early = dash.indexOf("renderHandoffPreview(");
|
||||
assert.ok(early > 0 && early < dash.indexOf("hideUnavailableToggle()"), "the preview returns before the toggle and the card groups");
|
||||
assert.match(app, /const selHandoff = \(\) =>/);
|
||||
assert.match(app, /startsWith\("handoff:"\)/);
|
||||
|
||||
const preview = fn("renderHandoffPreview", "\nasync function ");
|
||||
for (const label of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
|
||||
assert.ok(preview.includes(`"${label}"`), `the preview names ${label}`);
|
||||
}
|
||||
assert.ok(app.includes("pickupAction(") && app.includes('"/submit"'), "Pick it up here posts a __pickup to /submit");
|
||||
assert.ok(app.includes('"/handoff?id="'), "Read it all fetches /handoff?id=");
|
||||
assert.ok(app.includes("handoffCopyText("), "Copy puts the ready prompt on the clipboard");
|
||||
assert.ok(app.includes("deleteHandoffAction(") && app.includes("function openHandoffDelete("), "Delete reuses the confirm dialog");
|
||||
|
||||
assert.match(css, /\.spec-chip\.is-handoff/, "app.css styles handoff chips");
|
||||
assert.match(css, /\.handoff-preview\b/, "and the preview panel");
|
||||
@@ -318,41 +297,25 @@ test("sign-off: approve leads show, and the approve button wears the accent", ()
|
||||
const show = text.indexOf('{ "id": "show", "label": "Show me it working" }');
|
||||
assert.ok(approve > 0 && show > approve, `${f} lists Approve this phase before Show me it working`);
|
||||
}
|
||||
const app = doc("public/app.js");
|
||||
assert.match(app, /const forward = v\.id === "approve" \|\| v\.id === "yes";/, "approve and yes are the forward verdicts");
|
||||
assert.match(app, /forward \? " is-approve"/, "an unpicked forward verdict gets is-approve");
|
||||
assert.match(doc("public/app.css"), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
|
||||
assert.match(joinedCss(), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
|
||||
});
|
||||
|
||||
// A fixed bug's chip: a visible Delete, one confirm, and "bug fixed" said once.
|
||||
test("bug fixed delete: a promoted Delete on the chip and a one-step confirm", () => {
|
||||
// What the fixed bug's chip and Delete do on the page is held by the page tests
|
||||
// in test-web-console-page-dashboard.mjs; this keeps the style and the Help.
|
||||
test("bug fixed delete: the Delete button is styled and Help explains the one confirm", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const app = web("app.js");
|
||||
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
|
||||
|
||||
const picker = fn("renderSpecPicker", "\nfunction ");
|
||||
assert.ok(picker.includes('"spec-chip-del-label"') && picker.includes('"Delete"'), "renderSpecPicker builds a Delete button for a fixed bug");
|
||||
assert.ok(picker.includes("chipDetail("), "the chip's detail line comes from chipDetail");
|
||||
assert.doesNotMatch(picker, /spec\.detail\b/, "never the scan's detail directly");
|
||||
|
||||
const css = web("app.css");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.spec-chip-del-label\s*\{/, "app.css styles the Delete button");
|
||||
assert.match(css, /\.spec-chip-del-label:focus-visible/, "and gives it a focus outline");
|
||||
|
||||
const step = fn("deleteStep", "\nasync function ");
|
||||
const fixedAt = step.indexOf('state === "fixed"');
|
||||
const revealAt = step.indexOf('$("delete-confirm").hidden = false');
|
||||
assert.ok(fixedAt > 0 && revealAt > 0 && fixedAt < revealAt, "deleteStep sends a fixed bug's delete before it would reveal the name step");
|
||||
const open = fn("openDeleteConfirm", "\nfunction ");
|
||||
assert.ok(open.includes('state === "fixed"') && open.includes("so this only clears the write-up"), "openDeleteConfirm sets up one step and the fixed warning");
|
||||
|
||||
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
|
||||
assert.ok(panel && /fixed\s+bug[\s\S]*?Delete[\s\S]*?one\s+confirm/i.test(panel[1]), "Help says a fixed bug has its own Delete and needs one confirm");
|
||||
});
|
||||
|
||||
test("update banner: the modal is in the page, with the exact command and no inline styles or scripts", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
|
||||
const dialog = html.match(/<dialog class="modal" id="update-modal" aria-labelledby="update-title">([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "index.html has the update modal");
|
||||
assert.doesNotMatch(dialog[1], /\sstyle=/);
|
||||
@@ -362,33 +325,26 @@ test("update banner: the modal is in the page, with the exact command and no inl
|
||||
assert.match(panel[1], /UPDATE AVAILABLE/, "the dashboard topic explains the banner");
|
||||
assert.doesNotMatch(panel[1], /\sstyle=/);
|
||||
assert.doesNotMatch(panel[1], /<script/i);
|
||||
assert.ok(app.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "app.js copies the exact command");
|
||||
assert.ok(dash.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "the dashboard copies the exact command");
|
||||
});
|
||||
|
||||
test("update banner: built only on the dashboard, dismissed per session, and Help's version links to Releases", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const start = app.indexOf("function renderDashboard(main) {");
|
||||
assert.ok(start >= 0, "app.js has renderDashboard");
|
||||
const end = app.indexOf("\n}\n", start);
|
||||
const body = app.slice(start, end);
|
||||
assert.match(body, /"dash-nudge update-banner"/, "renderDashboard builds the banner");
|
||||
const outside = app.slice(0, start) + app.slice(end);
|
||||
assert.doesNotMatch(outside, /update-banner/, "no other code builds it");
|
||||
assert.match(app, /"p2c-update-dismissed:" \+ S\.sid/, "the dismissal is keyed by the session id");
|
||||
assert.match(app, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
|
||||
assert.match(app, /\.rel = "noopener noreferrer";/);
|
||||
const help = app.match(/async function renderHelpVersion\(\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(help, "app.js has renderHelpVersion");
|
||||
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
|
||||
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
|
||||
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
|
||||
assert.match(dash, /"p2c-update-dismissed:" \+ page\.S\.sid/, "the dismissal is keyed by the session id");
|
||||
assert.match(render, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
|
||||
assert.match(render, /\.rel = "noopener noreferrer";/);
|
||||
});
|
||||
|
||||
// The Changelog card sits left of Git, which sits left of Handoff, the last
|
||||
// card. It is always clickable, and a launch from it resumes the session under
|
||||
// its own workflow.
|
||||
test("the Changelog card comes just before Git, Handoff is last, and Changelog is always on", () => {
|
||||
const skills = SKILL_CATALOG.map((e) => e.skill);
|
||||
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"));
|
||||
assert.deepEqual(skills.slice(-3), ["plan2code-changelog", "plan2code-git", "plan2code-handoff"]);
|
||||
// The card order is skills.js's order.
|
||||
const skills = SKILLS.filter((s) => s.card).map((s) => s.skill);
|
||||
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"), "Changelog sits just before Git");
|
||||
assert.equal(skills.indexOf("plan2code-git") + 1, skills.indexOf("plan2code-handoff"), "Git sits just before Handoff");
|
||||
assert.equal(skills.at(-1), "plan2code-handoff", "Handoff is last");
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
|
||||
assert.equal(entry.workflow, "changelog");
|
||||
assert.equal(entry.command, "/plan2code-changelog");
|
||||
@@ -434,93 +390,17 @@ test("help: privacy names the handoffs folder and preferences says Cleanup never
|
||||
assert.match(cleanup, /never\s+offered/, "the Cleanup text says the handoffs folder is never offered for removal");
|
||||
});
|
||||
|
||||
// Every say(...) call in a source slice, as its top-level arguments (raw
|
||||
// source text). String-aware, so commas and brackets inside a line are text.
|
||||
function sayCalls(source) {
|
||||
const calls = [];
|
||||
let at = 0;
|
||||
while ((at = source.indexOf("say(", at)) !== -1) {
|
||||
if (/[\w.]/.test(source[at - 1] || "")) {
|
||||
at += 4;
|
||||
continue;
|
||||
}
|
||||
const args = [];
|
||||
let depth = 0;
|
||||
let quote = null;
|
||||
let start = at + 4;
|
||||
let i = start;
|
||||
for (; i < source.length; i++) {
|
||||
const ch = source[i];
|
||||
if (quote) {
|
||||
if (ch === "\\") i++;
|
||||
else if (ch === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
||||
else if ("([{".includes(ch)) depth++;
|
||||
else if (")]}".includes(ch)) {
|
||||
if (depth === 0) break;
|
||||
depth--;
|
||||
} else if (ch === "," && depth === 0) {
|
||||
args.push(source.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
const last = source.slice(start, i).trim();
|
||||
if (last) args.push(last);
|
||||
calls.push(args);
|
||||
at = i;
|
||||
}
|
||||
return calls;
|
||||
}
|
||||
|
||||
test("status line: the quiet, Not running and Not connected lines offer What to check, opening Help on the stuck tab", () => {
|
||||
const app = publicSource("app.js");
|
||||
test("help: the stuck tab is second, and openHelpOn only opens a tab that exists", () => {
|
||||
const app = publicSource("screens/help-dialog.js");
|
||||
assert.equal(HELP_TABS.findIndex((t) => t.id === "stuck"), 1, "the stuck tab is second");
|
||||
const opener = app.match(/function openHelpOn\(id\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(opener, "app.js has openHelpOn");
|
||||
assert.ok(opener, "help-dialog.js has openHelpOn");
|
||||
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
|
||||
const render = app.slice(app.indexOf("function renderStatus()"), app.indexOf("/* ---------------------------------------------------------------- brief */"));
|
||||
const sayDef = render.slice(render.indexOf("const say = ("), render.indexOf("text.replaceChildren("));
|
||||
assert.match(sayDef, /help\.textContent = "What to check"/);
|
||||
assert.match(sayDef, /help\.addEventListener\("click", \(\) => openHelpOn\("stuck"\)\)/, "the button opens Help on the stuck tab");
|
||||
const calls = sayCalls(render.slice(render.indexOf("text.replaceChildren(")));
|
||||
const checked = calls.filter((args) => args[4] && args[4] !== "false");
|
||||
for (const needle of ["Not connected. Your answers are saved.", "Still working on it.", "is not running. Your answers are saved", "is not running right now."]) {
|
||||
assert.ok(checked.some((args) => args.join(",").includes(needle)), `"${needle}" carries What to check`);
|
||||
}
|
||||
assert.ok(checked.some((args) => args[4] === "Boolean(hint)"), "the approval hint carries What to check");
|
||||
// Nothing else does: the finished, working and adrift lines stay plain.
|
||||
assert.equal(checked.length, 4, `four calls pass check, got: ${checked.map((a) => a[1]).join(" | ")}`);
|
||||
});
|
||||
|
||||
test("finished screen: Before you close this waits while a hand-off they asked for is starting", () => {
|
||||
const app = publicSource("app.js");
|
||||
const handoff = app.slice(app.indexOf("function renderHandoff("));
|
||||
const body = handoff.slice(0, handoff.indexOf("\n}\n"));
|
||||
assert.match(body, /if \(!closeGuideHeld\(\)\) card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
|
||||
const held = app.match(/function closeGuideHeld\(\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(held, "app.js has closeGuideHeld");
|
||||
const run = (gone, afterBuild, pending) =>
|
||||
new Function("gone", "local", "reviewPending", held[1])(gone, { afterBuild }, () => pending);
|
||||
for (const kind of ["review", "commit", "dashboard"]) {
|
||||
assert.equal(run(false, kind, null), true, `held while ${kind} is starting`);
|
||||
}
|
||||
assert.equal(run(false, null, "asked"), true, "held while a review is asked");
|
||||
assert.equal(run(false, null, "open"), false, "shown while the review is only on offer");
|
||||
assert.equal(run(false, null, null), false, "shown on a plain finish");
|
||||
assert.equal(run(false, "done", null), false, "shown once they said they are done");
|
||||
assert.equal(run(true, "review", null), false, "shown once the server is gone: nothing is starting");
|
||||
// The press re-renders the page, and so does the finish going away, so the
|
||||
// panel follows the state.
|
||||
const send = app.slice(app.indexOf("async function sendAfterBuild("), app.indexOf("/* ------------------------------------------------------------- dashboard */"));
|
||||
assert.match(send, /local\.afterBuild = kind;[\s\S]*finally \{\s*render\(\);/);
|
||||
assert.match(app, /if \(!finish\(\) && local\.afterBuild\) \{\s*local\.afterBuild = null;/);
|
||||
});
|
||||
|
||||
test("models: Codex is a model CLI on the server and the page, with its own tab", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const app = publicSource("app.js");
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
const app = publicSource("screens/looks.js");
|
||||
const html = publicSource("index.html");
|
||||
const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]);
|
||||
assert.deepEqual(list(server), ["claude", "devin", "codex"]);
|
||||
@@ -534,52 +414,9 @@ test("models: Codex is a model CLI on the server and the page, with its own tab"
|
||||
for (const cli of list(server)) assert.ok(Array.isArray(shipped[cli]), `the launcher's models.json has ${cli}`);
|
||||
});
|
||||
|
||||
test("finished screen: every shape shows Before you close this, with three rows", () => {
|
||||
const app = publicSource("app.js");
|
||||
const handoff = app.slice(app.indexOf("function renderHandoff("));
|
||||
assert.match(handoff.slice(0, handoff.indexOf("\n}\n")), /card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
|
||||
const guide = app.slice(app.indexOf("function renderCloseGuide("), app.indexOf("function renderHandoff("));
|
||||
for (const label of ["Safe to close", "Start fresh", "Carry on", "Before you close this"]) {
|
||||
assert.ok(guide.includes(label), `the guide says "${label}"`);
|
||||
}
|
||||
assert.match(guide, /shape === "paused"/, "a pause changes the Start fresh sentence");
|
||||
assert.match(guide, /resume command/);
|
||||
});
|
||||
|
||||
test("getting started: the new help, status and finished-screen strings carry no em dash", () => {
|
||||
const app = publicSource("app.js");
|
||||
const guide = app.slice(app.indexOf("const GUIDE_ICONS"), app.indexOf("function renderHandoff("));
|
||||
assert.ok(!guide.includes(EM), "the close guide has no em dash");
|
||||
const tpl = helpTemplate();
|
||||
const stuck = tpl.match(/<section class="help-panel" data-tab="stuck">([\s\S]*?)<\/section>/)[1];
|
||||
const fresh = stuck.slice(0, stuck.indexOf("<h4>Not running, or not connected?</h4>"));
|
||||
assert.ok(!fresh.includes(EM), "the callout and rows have no em dash");
|
||||
});
|
||||
|
||||
test("a redraw keeps the place of whatever scrolls: question card, finished screen, doc column", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = app.slice(app.indexOf("function withFocus("), app.indexOf("// Scroll memory across tab switches."));
|
||||
assert.ok(fn.includes("const place = mainPlace();") && fn.includes("restoreMainPlace(place);"), "withFocus saves and restores the main column's place");
|
||||
assert.ok(!fn.includes('querySelector(".card.question")'), "not only a question card");
|
||||
const scrollers = app.match(/const MAIN_SCROLLERS = "([^"]+)"/);
|
||||
assert.ok(scrollers, "MAIN_SCROLLERS lists the column's scrolling children");
|
||||
for (const s of [".card", ".dash", ".waiting-pane"]) assert.ok(scrollers[1].includes(":scope > " + s), `${s} keeps its place`);
|
||||
const place = app.slice(app.indexOf("function mainPlace("), app.indexOf("function withFocus("));
|
||||
assert.match(place, /if \(drawnView === place\.key\) main\.scrollTop = place\.top;/, "the doc column comes back only on the same tab");
|
||||
assert.match(place, /scrollerKey\(inner\) === place\.key/, "a card comes back only while it shows the same thing");
|
||||
assert.match(place, /:scope > \.git-board/, "the git board keeps its own per-tab place");
|
||||
});
|
||||
|
||||
test("Skip this one is a small accent button, like a comment box's quick answer", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.match(app, /const skip = el\("button", "btn tiny", skipped \? "Do not skip" : "Skip this one"\);/, "the skip button is btn tiny");
|
||||
assert.match(app, /quick = el\("button", "btn tiny"/, "the quick answer it matches is btn tiny");
|
||||
});
|
||||
|
||||
test("a confirm's yes and a recap's yes are outlined in the accent, a dangerous yes stays red", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const confirm = app.slice(app.indexOf("function buildConfirm("), app.indexOf("row.appendChild(mk(noLabel"));
|
||||
assert.match(confirm, /\(yes && !danger && !on \? " is-approve" : ""\)/, "an unpicked, safe yes gets is-approve");
|
||||
assert.match(confirm, /\(danger && !on \? " danger" : ""\)/, "a dangerous yes stays red");
|
||||
assert.match(app, /const ok = el\("button", "btn" \+ \(okOn \? " primary" : " is-approve"\)/, "the recap's yes gets is-approve");
|
||||
});
|
||||
@@ -0,0 +1,408 @@
|
||||
// Web console tests, the spec states: public/spec-states.js defines every
|
||||
// state the dashboard scan can report, and the labels, next steps and card
|
||||
// rules are lookups on it.
|
||||
// Run with: node --test scripts/test-web-console-spec-states.mjs
|
||||
|
||||
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 { SPEC_STATES as TABLE, stateFor } from "../src/web-console/public/spec-states.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { SKILL_CATALOG, cardAvailability, defaultSpec } from "../src/web-console/public/answers.js";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
|
||||
// What the picker labels each state and which card each state lights, as
|
||||
// answers.js's SPEC_STATE_LABELS and NEXT_FOR_STATE said before the table.
|
||||
const LABELS = {
|
||||
diagnosed: "Bug diagnosed",
|
||||
fixed: "Bug fixed",
|
||||
exploring: "Exploring",
|
||||
mapped: "Ready to plan",
|
||||
planned: "Ready to document",
|
||||
documented: "Ready to build",
|
||||
building: "Building",
|
||||
built: "Ready to finalize",
|
||||
unrecognized: "Files on disk",
|
||||
};
|
||||
const NEXT = {
|
||||
diagnosed: "plan2code-quick-task",
|
||||
fixed: null,
|
||||
exploring: "plan2code-0-pathfinder",
|
||||
mapped: "plan2code-1-plan",
|
||||
planned: "plan2code-2-document",
|
||||
documented: "plan2code-3-implement",
|
||||
building: "plan2code-3-implement",
|
||||
built: "plan2code-4-finalize",
|
||||
unrecognized: null,
|
||||
};
|
||||
|
||||
test("spec states: each state keeps its label and next step, and only fixed is finished", () => {
|
||||
assert.deepEqual(Object.keys(TABLE), Object.keys(LABELS), "the states, in the scan's order");
|
||||
for (const [name, label] of Object.entries(LABELS)) {
|
||||
const s = stateFor(name);
|
||||
assert.ok(s, `${name} is in the table`);
|
||||
assert.equal(s.label, label, `${name}'s label`);
|
||||
assert.equal(s.next, NEXT[name], `${name}'s next step`);
|
||||
assert.equal(s.finished, name === "fixed", `${name}'s finished flag`);
|
||||
}
|
||||
assert.equal(stateFor("made-up"), null, "an unknown state is null");
|
||||
assert.ok(Object.isFrozen(TABLE) && Object.values(TABLE).every(Object.isFrozen), "the table is frozen");
|
||||
});
|
||||
|
||||
// Every card's answer for every picker selection, as cardAvailability() gave
|
||||
// them before the card rules moved onto skills.js: generated once from that
|
||||
// code and written out here, so the move is proven to change nothing. "none"
|
||||
// is "start from scratch" (no spec picked). The scan is a set-up git project
|
||||
// with nothing to commit; SCAN_CASES covers the three cards that read it.
|
||||
const SCAN = { hasAgents: true, isGit: true, pending: 0 };
|
||||
const CARDS = {
|
||||
"plan2code-init": {
|
||||
"none": { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
diagnosed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
fixed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
exploring: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
mapped: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
planned: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
documented: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
building: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
built: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
unrecognized: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
},
|
||||
"plan2code-init-update": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-0-pathfinder": {
|
||||
"none": { on: true, next: true },
|
||||
diagnosed: { on: false, reason: "The cause is found. Fix it in a quick task, or plan it." },
|
||||
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
|
||||
exploring: { on: true, next: true },
|
||||
mapped: { on: false, reason: "This spec is already past the questions" },
|
||||
planned: { on: false, reason: "This spec is already past the questions" },
|
||||
documented: { on: false, reason: "This spec is already past the questions" },
|
||||
building: { on: false, reason: "This spec is already past the questions" },
|
||||
built: { on: false, reason: "This spec is already past the questions" },
|
||||
unrecognized: { on: true, next: false },
|
||||
},
|
||||
"plan2code-1-plan": {
|
||||
"none": { on: true, next: false },
|
||||
diagnosed: { on: true, next: false },
|
||||
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
|
||||
exploring: { on: false, reason: "Pathfinder is not finished with this spec yet" },
|
||||
mapped: { on: true, next: true },
|
||||
planned: { on: true, next: false },
|
||||
documented: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
building: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
built: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
unrecognized: { on: true, next: false },
|
||||
},
|
||||
"plan2code-1b-revise-plan": {
|
||||
"none": { on: false, reason: "Needs a spec that is already written up" },
|
||||
diagnosed: { on: false, reason: "Needs a spec that is already written up" },
|
||||
fixed: { on: false, reason: "Needs a spec that is already written up" },
|
||||
exploring: { on: false, reason: "Needs a spec that is already written up" },
|
||||
mapped: { on: false, reason: "Needs a spec that is already written up" },
|
||||
planned: { on: false, reason: "Needs a spec that is already written up" },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: false, reason: "The spec is fully built" },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is already written up" },
|
||||
},
|
||||
"plan2code-2-document": {
|
||||
"none": { on: false, reason: "Needs a drafted plan first" },
|
||||
diagnosed: { on: false, reason: "Needs a drafted plan first" },
|
||||
fixed: { on: false, reason: "Needs a drafted plan first" },
|
||||
exploring: { on: false, reason: "Needs a drafted plan first" },
|
||||
mapped: { on: false, reason: "Needs a drafted plan first" },
|
||||
planned: { on: true, next: true },
|
||||
documented: { on: false, reason: "The phases are already written up" },
|
||||
building: { on: false, reason: "The phases are already written up" },
|
||||
built: { on: false, reason: "The phases are already written up" },
|
||||
unrecognized: { on: false, reason: "Needs a drafted plan first" },
|
||||
},
|
||||
"plan2code-3-implement": {
|
||||
"none": { on: false, reason: "Needs the phase checklists written up first" },
|
||||
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
fixed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
exploring: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
mapped: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
planned: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
documented: { on: true, next: true },
|
||||
building: { on: true, next: true },
|
||||
built: { on: false, reason: "All tasks are already done" },
|
||||
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
},
|
||||
"plan2code-3-implement-review": {
|
||||
"none": { on: false, reason: "Needs the phase checklists written up first" },
|
||||
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
fixed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
exploring: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
mapped: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
planned: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
documented: { on: true, next: false },
|
||||
building: { on: true, next: false },
|
||||
built: { on: false, reason: "All tasks are already done" },
|
||||
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
},
|
||||
"plan2code-4-finalize": {
|
||||
"none": { on: false, reason: "Needs a spec that is fully built" },
|
||||
diagnosed: { on: false, reason: "Needs a spec that is fully built" },
|
||||
fixed: { on: false, reason: "Needs a spec that is fully built" },
|
||||
exploring: { on: false, reason: "Needs a spec that is fully built" },
|
||||
mapped: { on: false, reason: "Needs a spec that is fully built" },
|
||||
planned: { on: false, reason: "Needs a spec that is fully built" },
|
||||
documented: { on: false, reason: "Needs a spec that is fully built" },
|
||||
building: { on: false, reason: "Needs a spec that is fully built" },
|
||||
built: { on: true, next: true },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is fully built" },
|
||||
},
|
||||
"plan2code-quick-task": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true, next: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-review": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-xray": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-diagnose": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-changelog": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-git": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-handoff": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
};
|
||||
|
||||
const SCAN_CASES = [
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init", { on: true }],
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init-update", { on: false, reason: "Needs an AGENTS.md. Set the project up first." }],
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-git", { on: true, note: "Not a git repository yet: it offers to start one" }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init-update", { on: true }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-git", { on: true, note: "3 files to commit" }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init-update", { on: true }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-git", { on: true, note: "1 file to commit" }],
|
||||
];
|
||||
|
||||
test("card rules: every card gives the same answer for every spec state as before", () => {
|
||||
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), Object.keys(CARDS), "one row per card, in card order");
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
for (const [sel, want] of Object.entries(CARDS[entry.skill])) {
|
||||
const spec = sel === "none" ? null : { dir: "specs/x", name: "x", state: sel };
|
||||
assert.deepEqual(cardAvailability(entry, SCAN, spec), want, `${entry.skill} with ${sel}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("card rules: a state the table does not know is treated like files on disk", () => {
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
const weird = cardAvailability(entry, SCAN, { dir: "specs/x", name: "x", state: "made-up" });
|
||||
assert.deepEqual(weird, CARDS[entry.skill].unrecognized, `${entry.skill} with an unknown state`);
|
||||
}
|
||||
});
|
||||
|
||||
test("card rules: Init, Init update and Git read the scan, not the spec", () => {
|
||||
for (const [scan, skill, want] of SCAN_CASES) {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
assert.deepEqual(cardAvailability(entry, scan, null), want, `${skill} with ${JSON.stringify(scan)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("finished: any finished state is never the picker's default, not only fixed", () => {
|
||||
// The test's own copy of the table, with a made-up second finished state.
|
||||
const table = { ...TABLE, archived: { label: "Archived", next: null, finished: true } };
|
||||
const lookup = (name) => (Object.hasOwn(table, name) ? table[name] : null);
|
||||
const specs = [
|
||||
{ dir: "specs/a", name: "a", state: "archived" },
|
||||
{ dir: "specs/b", name: "b", state: "fixed" },
|
||||
{ dir: "specs/c", name: "c", state: "planned" },
|
||||
];
|
||||
assert.equal(defaultSpec(specs, lookup)?.dir, "specs/c", "the newest spec still in play");
|
||||
assert.equal(defaultSpec(specs.slice(0, 2), lookup), null, "only finished specs: start from scratch");
|
||||
assert.equal(defaultSpec(specs)?.dir, "specs/a", "the real table does not know archived, so it is in play");
|
||||
|
||||
// The cards greyed for a fixed bug give a made-up finished state the same reason.
|
||||
const archived = { dir: "specs/a", name: "a", state: "archived" };
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
const fixed = cardAvailability(entry, SCAN, { dir: "specs/b", name: "b", state: "fixed" });
|
||||
assert.deepEqual(cardAvailability(entry, SCAN, archived, lookup), fixed, `${entry.skill} treats archived as it treats fixed`);
|
||||
}
|
||||
});
|
||||
|
||||
// One spec folder per state, in the shapes classifySpec() reads.
|
||||
const PHASE = (ticks) => "# Phase 1\n\n" + ticks.map((x, i) => `- [${x ? "x" : " "}] **Task 1.${i + 1}:** Step ${i + 1}\n`).join("");
|
||||
const FIXTURES = {
|
||||
diagnosed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Diagnosed\n" },
|
||||
fixed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Fixed\n" },
|
||||
exploring: { "pathfinder/map.md": "# Map\n\nStatus: Working\n" },
|
||||
mapped: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n" },
|
||||
planned: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Draft\n" },
|
||||
documented: { "overview.md": "# Overview\n", "phase-1.md": PHASE([false, false]) },
|
||||
building: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, false]) },
|
||||
built: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, true]) },
|
||||
unrecognized: { "notes.md": "Some loose notes.\n" },
|
||||
};
|
||||
|
||||
// The states a scan of these fixtures reports, against the table's: the
|
||||
// lines that name what does not match, empty when they agree.
|
||||
function scanProblems(fixtures, table) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-states-"));
|
||||
try {
|
||||
for (const [name, files] of Object.entries(fixtures))
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
const file = path.join(root, "specs", name, rel);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, text);
|
||||
}
|
||||
const scan = scanProject(root);
|
||||
const problems = scan.specs.filter((sp) => sp.state !== sp.name).map((sp) => `the ${sp.name} fixture scans as ${sp.state}`);
|
||||
const seen = new Set(scan.specs.map((sp) => sp.state));
|
||||
for (const state of seen) if (!Object.hasOwn(table, state)) problems.push(`the scan returns ${state}, which spec-states.js lacks`);
|
||||
for (const state of Object.keys(table)) if (!seen.has(state)) problems.push(`no fixture reaches ${state}: add one, or drop it from spec-states.js`);
|
||||
return problems;
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("the scan: every state it can return is in the table, and a fixture reaches every state in it", () => {
|
||||
assert.deepEqual(scanProblems(FIXTURES, TABLE), []);
|
||||
// The check names what is missing.
|
||||
const { built, ...short } = FIXTURES;
|
||||
assert.deepEqual(scanProblems(short, TABLE), ["no fixture reaches built: add one, or drop it from spec-states.js"]);
|
||||
const { unrecognized, ...known } = TABLE;
|
||||
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
|
||||
});
|
||||
|
||||
// The states no card names in its `states` list: a card that is on for "any"
|
||||
// spec does not count, since it would take a state nobody thought about. A
|
||||
// finished state is taken by no card on purpose.
|
||||
function untakenStates(skills, table) {
|
||||
const taken = new Set(skills.flatMap((sk) => (Array.isArray(sk.states) ? sk.states : [])));
|
||||
return Object.entries(table)
|
||||
.filter(([name, s]) => !s.finished && !taken.has(name))
|
||||
.map(([name]) => `no card's states take ${name}: add it to the skills.js entries whose card it lights`);
|
||||
}
|
||||
|
||||
test("card rules: every state still in play is taken by at least one card", () => {
|
||||
assert.deepEqual(untakenStates(SKILLS, TABLE), []);
|
||||
// The check names the state: Document and Plan are the cards that take planned.
|
||||
const without = SKILLS.map((sk) =>
|
||||
Array.isArray(sk.states) && (sk.skill === "plan2code-2-document" || sk.skill === "plan2code-1-plan")
|
||||
? { ...sk, states: sk.states.filter((st) => st !== "planned") }
|
||||
: sk
|
||||
);
|
||||
assert.deepEqual(untakenStates(without, TABLE), ["no card's states take planned: add it to the skills.js entries whose card it lights"]);
|
||||
});
|
||||
|
||||
test("card rules: a card's states and greyed reasons name only real states", () => {
|
||||
const known = new Set([...Object.keys(TABLE), "none"]);
|
||||
for (const sk of SKILLS) {
|
||||
if (Array.isArray(sk.states)) for (const st of sk.states) assert.ok(known.has(st), `${sk.skill} takes ${st}, which is no state`);
|
||||
for (const key of Object.keys(sk.greyed || {})) assert.ok(key === "default" || key === "finished" || known.has(key), `${sk.skill}'s greyed names ${key}, which is no state`);
|
||||
if (Array.isArray(sk.states) && sk.card) assert.ok(sk.greyed && sk.greyed.default, `${sk.skill} has a default greyed reason`);
|
||||
}
|
||||
});
|
||||
|
||||
// The states the dashboard skill's prose (src/plan2code.md) never mentions,
|
||||
// by name in backticks (`planned`) or by label in quotes ("Ready to
|
||||
// document"). The agent reads that prose to choose its recommendation, so
|
||||
// every state needs a word there; a bare word ("reading or exploring", a file
|
||||
// named building-habits.md) is not one.
|
||||
function unmentionedStates(prose, table) {
|
||||
const lower = prose.toLowerCase();
|
||||
return Object.entries(table)
|
||||
.filter(([name, s]) => !prose.includes("`" + name + "`") && !lower.includes(`"${s.label.toLowerCase()}"`))
|
||||
.map(([name, s]) => `src/plan2code.md mentions neither \`${name}\` nor "${s.label}"`);
|
||||
}
|
||||
|
||||
test("the dashboard skill: its prose names every spec state", () => {
|
||||
const prose = fs.readFileSync(path.join(import.meta.dirname, "..", "src", "plan2code.md"), "utf8");
|
||||
assert.deepEqual(unmentionedStates(prose, TABLE), []);
|
||||
const sample = 'Only `planned` and "Ready to build", while building and exploring are bare words.';
|
||||
const some = { planned: TABLE.planned, documented: TABLE.documented, building: TABLE.building, exploring: TABLE.exploring };
|
||||
assert.deepEqual(unmentionedStates(sample, some), [
|
||||
'src/plan2code.md mentions neither `building` nor "Building"',
|
||||
'src/plan2code.md mentions neither `exploring` nor "Exploring"',
|
||||
]);
|
||||
});
|
||||
@@ -15,7 +15,9 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { applyPatch, scanProject } from "../src/web-console/lib.mjs";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -615,13 +617,6 @@ test("a wait with nothing open leaves a working agent working", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the git board lets go of a working agent that went adrift", () => {
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const at = js.indexOf("const gitMode = ");
|
||||
const line = js.slice(at, js.indexOf(";", at));
|
||||
assert.ok(line.includes("(agentWorking() && !agentAdrift())"), line);
|
||||
});
|
||||
|
||||
test("post --file - reads the patch from stdin, UTF-8 and a BOM included", () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
@@ -715,16 +710,13 @@ test("a finish ends the working stretch, and resuming a pause starts a fresh one
|
||||
});
|
||||
|
||||
test("a card with a note box over the git board flows at its own height, never shrunk under the board", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const rule = css.slice(css.indexOf(".git-cards > .card,"), css.indexOf("{", css.indexOf(".git-cards > .card,")));
|
||||
assert.ok(rule.includes(".git-cards > .card.is-primary.has-grow"), "the board's natural-height rule outranks .has-grow");
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function markGrowBox("), js.indexOf("function naturalHeight("));
|
||||
assert.ok(fn.includes("isGitBoard()"), "no box grows over the board");
|
||||
});
|
||||
|
||||
test("a card and its pager in the git board's card slot fill the board's width, never shrink to their content", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
// .card and .pager centre with auto inline margins; in the slot's grid those
|
||||
// would shrink a short confirm, and the pager under it, to fit their content.
|
||||
assert.match(css, /\.card\s*\{[^}]*margin:\s*0 auto/, "the base card still centres outside the board");
|
||||
@@ -733,7 +725,7 @@ test("a card and its pager in the git board's card slot fill the board's width,
|
||||
});
|
||||
|
||||
test("long task lines, long words, a narrow board and a narrow Ask pane never widen the page", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const rule = (sel) => {
|
||||
const at = css.indexOf("\n" + sel + " {");
|
||||
assert.ok(at > -1, `${sel} has a rule`);
|
||||
@@ -750,12 +742,10 @@ test("long task lines, long words, a narrow board and a narrow Ask pane never wi
|
||||
});
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.git-cards > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const fn = view.slice(view.indexOf("export function drawGitBoard("), view.indexOf("function header("));
|
||||
assert.ok(fn.includes("ctx.hasCard"), "the note checks for a card first");
|
||||
assert.ok(fn.includes("will ask what to do here in a moment"));
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.match(js, /hasCard: Boolean\(card\)/, "the host says whether a card is in the slot");
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
// Web console tests, the page's shared state: public/state.js holds what
|
||||
// every screen reads (`page`) and the hooks a screen calls instead of the
|
||||
// render loop and the draft's save. It only defines, so it imports here under
|
||||
// plain Node, page or no page.
|
||||
// Run with: node --test scripts/test-web-console-state.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { page, redraw, onRedraw, saveNow, onSave, fresh, freshChat, hooks, useHooks, stage, setDraft, bootData } from "../src/web-console/public/state.js";
|
||||
|
||||
test("state: page starts as app.js always started it", () => {
|
||||
assert.equal(page.S, null, "no server state before the first frame");
|
||||
assert.equal(page.selected, null, "no question picked");
|
||||
assert.equal(page.view, "questions", "the questions tab");
|
||||
assert.deepEqual(page.local, {
|
||||
staged: {},
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
launching: null,
|
||||
deleting: null,
|
||||
retract: {},
|
||||
chat: { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null },
|
||||
});
|
||||
});
|
||||
|
||||
test("state: the rest of the shared state starts as app.js always started it", () => {
|
||||
const { S, local, selected, view, ...rest } = page;
|
||||
assert.deepEqual(rest, {
|
||||
agentLastSeen: null,
|
||||
pendingResult: false,
|
||||
pendingStop: false,
|
||||
pendingBannerUp: false,
|
||||
gone: false,
|
||||
chatFrame: null,
|
||||
chatDot: false,
|
||||
chatError: "",
|
||||
askRowCount: 0,
|
||||
docInView: null,
|
||||
wsFrame: null,
|
||||
meterFrame: null,
|
||||
updateFrame: null,
|
||||
subagentsFrame: null,
|
||||
overview: { key: null, text: null },
|
||||
wake: null,
|
||||
dashPick: null,
|
||||
mentionPop: null,
|
||||
heldPose: null,
|
||||
scopeMine: null,
|
||||
launchScoping: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("state: fresh() and freshChat() hand out a new empty draft each time", () => {
|
||||
assert.deepEqual(fresh(), page.local);
|
||||
assert.notEqual(fresh(), fresh(), "two calls share one object");
|
||||
assert.notEqual(fresh().chat, fresh().chat, "two drafts share one chat");
|
||||
assert.deepEqual(freshChat(), page.local.chat);
|
||||
});
|
||||
|
||||
for (const [name, call, on] of [
|
||||
["redraw", redraw, onRedraw],
|
||||
["saveNow", saveNow, onSave],
|
||||
]) {
|
||||
test(`state: ${name}() does nothing until a hook is set, then calls the latest one once per call`, () => {
|
||||
assert.doesNotThrow(() => call(), `${name}() throws with no hook`);
|
||||
let first = 0;
|
||||
let second = 0;
|
||||
on(() => first++);
|
||||
call();
|
||||
call();
|
||||
assert.equal(first, 2, "each call runs the hook once");
|
||||
on(() => second++);
|
||||
call();
|
||||
assert.deepEqual([first, second], [2, 1], "a second hook replaces the first");
|
||||
});
|
||||
}
|
||||
|
||||
test("state: a hook a screen calls throws by name until start-up sets it, then runs the one set", () => {
|
||||
assert.throws(() => hooks.banner("x"), /hooks\.banner was called before start-up set it/);
|
||||
const seen = [];
|
||||
useHooks({ banner: (text) => seen.push(text) });
|
||||
hooks.banner("hello");
|
||||
assert.deepEqual(seen, ["hello"]);
|
||||
useHooks({ banner: (text) => seen.push(text + "!") });
|
||||
hooks.banner("again");
|
||||
assert.deepEqual(seen, ["hello", "again!"], "a second set replaces the first");
|
||||
assert.throws(() => hooks.unknown(), /hooks\.unknown was called/);
|
||||
});
|
||||
|
||||
test("state: stage() stages or takes back an answer, then saves and redraws; setDraft() only saves", () => {
|
||||
let saved = 0;
|
||||
let drawn = 0;
|
||||
onSave(() => saved++);
|
||||
onRedraw(() => drawn++);
|
||||
stage("q1", { k: "A" });
|
||||
assert.deepEqual(page.local.staged, { q1: { k: "A" } });
|
||||
assert.deepEqual([saved, drawn], [1, 1]);
|
||||
stage("q1", null);
|
||||
assert.deepEqual(page.local.staged, {}, "null takes the answer back");
|
||||
assert.deepEqual([saved, drawn], [2, 2]);
|
||||
setDraft("note-q1", "typed");
|
||||
assert.equal(page.local.drafts["note-q1"], "typed");
|
||||
assert.deepEqual([saved, drawn], [3, 2], "a draft is kept without a redraw");
|
||||
delete page.local.drafts["note-q1"];
|
||||
});
|
||||
|
||||
test("state: bootData() is null without a page, and asked again it says the same", () => {
|
||||
assert.equal(bootData(), null);
|
||||
assert.equal(bootData(), null);
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultInstruction, offered } from "../src/web-console/public/subagents.js";
|
||||
import { readSubagentCursor } from "../src/web-console/lib.mjs";
|
||||
import { readSubagentCursor } from "../src/web-console/settings.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
|
||||
@@ -12,7 +12,8 @@ import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { defaultName } from "../src/web-console/public/workspace.js";
|
||||
import { meterView } from "../src/web-console/public/meter.js";
|
||||
import { readLedger, readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
|
||||
import { readLedger } from "../src/web-console/sessions.mjs";
|
||||
import { readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -21,7 +21,7 @@ import path from "node:path";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import http from "node:http";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readChat } from "../src/web-console/lib.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
|
||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -179,6 +179,14 @@ export const helpTemplate = () => {
|
||||
return tpl[1];
|
||||
};
|
||||
|
||||
// The Planny poses each skill's starting screen clones, from index.html.
|
||||
export const poseTemplate = () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
|
||||
assert.ok(tpl, "index.html has the start-poses template");
|
||||
return tpl[1];
|
||||
};
|
||||
|
||||
// The server checks magic bytes only, so a JPEG header and some padding will do.
|
||||
export const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(400, 7), Buffer.from([0xff, 0xd9])]);
|
||||
|
||||
|
||||
Reference in new issue
Block a user