Add the web console Notepad and shared skill tables, release v2.10.0

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-19 15:56:52 -07:00
1 parent 124beb46db
commit f8b54ef708
59 files changed
+12549 -321

No files matched your search

+26 -1
View File
@@ -245,6 +245,29 @@ test("specs: open tasks under approved phases are a checkoff, and tick checks th
assert.equal(S("tick", "lunch-vote", "--task", "nope").code, 2);
});
test("specs: numbered task lines are tasks, counted by status and ticked by tick", () => {
const root = specFixture();
// phase() writes "- [m]" lines; renumber phase 1 as a numbered list.
write(root, "specs/lunch-vote/phase-1.md", phase(1, "In Progress", [["x", "1.1"], [" ", "1.2"]]).replace("- [x] **Task 1.1:**", "1. [x] **Task 1.1:**").replace("- [ ] **Task 1.2:**", "2. [ ] **Task 1.2:**"));
assert.match(read(root, "specs/lunch-vote/phase-1.md"), /^1\. \[x\] \*\*Task 1\.1:\*\* Do 1\.1\n2\. \[ \] \*\*Task 1\.2:\*\* Do 1\.2$/m);
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
const st = S("status", "lunch-vote");
assert.equal(st.code, 0, st.stderr);
const p1 = st.json.phases.find((p) => p.number === 1);
assert.equal(p1.tasks.total, 2);
assert.equal(p1.tasks.complete, 1);
assert.deepEqual(p1.openTasks, ["1.2"]);
assert.ok(!st.json.checks.some((c) => c.code === "uncounted-task" && /phase-1/.test(c.message)), JSON.stringify(st.json.checks));
const t = S("tick", "lunch-vote", "--task", "1.2");
assert.equal(t.code, 0, t.stderr);
assert.equal(t.json.changed, true);
assert.match(read(root, "specs/lunch-vote/phase-1.md"), /^2\. \[x\] \*\*Task 1\.2:\*\* Do 1\.2\n > Confirmed done by the user on \d{4}-\d{2}-\d{2}\.$/m);
const after = S("status", "lunch-vote").json.phases.find((p) => p.number === 1);
assert.equal(after.tasks.complete, 2);
assert.deepEqual(after.openTasks, []);
});
test("specs status: drift between the checklist and the phase files is an error", () => {
const root = specFixture();
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [x] [Phase 2"));
@@ -516,7 +539,9 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1", "--set", "total_tasks=99", "--root", root]).code, 2);
write(root, "specs/lunch-vote/phase-2.md", read(root, "specs/lunch-vote/phase-2.md") + "- [ ] **Task 2.4A:** odd\n1. [ ] **Task 2.5:** numbered\n");
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 2);
// Task 2.4A is flagged; a numbered task line is counted like any other (spec-files.mjs).
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 1);
assert.ok(j.phases.find((p) => p.number === 2).openTasks.includes("2.5"));
write(root, "specs/lunch-vote/overview.md", "");
const e = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
assert.equal(e.overview, "overview.md");
+7
View File
@@ -339,6 +339,13 @@ test("handoff new refuses bad usage with 2 and a bad value with 3", () => {
assert.equal(run(["handoff", "new", "--skill", "plan2code-quick-task"]).status, 2);
assert.equal(run(["handoff", "list"]).status, 2);
assert.equal(run(["handoff"]).status, 2);
// A name newHandoff() would take (lowercase and dashes) but no workflow
// the console knows: refused as usage before anything is written (FR-5).
const before = fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR).sort() : [];
const unknown = run(["handoff", "new", "--workflow", "x-ray", "--skill", "plan2code-xray"]);
assert.equal(unknown.status, 2, unknown.stderr);
assert.match(unknown.stderr, /unknown workflow "x-ray"; one of: .*, xray, /);
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR).sort() : [], before, "no new file in the handoffs folder");
const bad = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "../x"]);
assert.equal(bad.status, 3);
assert.equal(bad.json.ok, false);
+33
View File
@@ -22,6 +22,7 @@ import {
noteAwaiting,
suggestionFrom,
} from "../src/web-console/public/answers.js";
import { WORKFLOWS } from "../src/web-console/public/skills.js";
import {
HOME,
MODELS_DIR,
@@ -214,6 +215,38 @@ test("open --resume restates workflow, title and spec on the live session", () =
fs.writeFileSync(stateFile, snapshot);
});
// A workflow name the console does not know (x-ray for xray) is refused as bad
// usage before anything is made: no session folder for a fresh open, and no
// write over the resumed session's good name (FR-5).
test("open refuses an unknown --workflow and makes no session folder", () => {
const sessionsDir = path.join(HOME, "sessions");
const before = fs.readdirSync(sessionsDir).sort();
const res = cli(["open", "--no-open", "--workflow", "x-ray"], { expectFail: true });
assert.equal(res.status, 2, res.stderr);
assert.match(res.stderr, /unknown workflow "x-ray"/);
for (const name of WORKFLOWS) assert.ok(res.stderr.includes(name), `stderr lists ${name}`);
assert.deepEqual(fs.readdirSync(sessionsDir).sort(), before, "no session folder was created");
});
test("open --resume refuses an unknown --workflow and leaves the state alone", () => {
const stateFile = path.join(session, "state.json");
const bytes = fs.readFileSync(stateFile);
const res = cli(["open", "--resume", sid, "--no-open", "--workflow", "x-ray"], { expectFail: true });
assert.equal(res.status, 2, res.stderr);
assert.match(res.stderr, /unknown workflow "x-ray"/);
assert.ok(fs.readFileSync(stateFile).equals(bytes), "state.json is byte for byte the same");
});
test("open with no --workflow still opens a Pathfinder session", () => {
const res = cli(["open", "--no-open"]);
try {
assert.equal(res.json.ok, true);
assert.equal(readState(res.json.session).workflow, "pathfinder");
} finally {
cli(["stop", "--session", res.json.sid]);
}
});
// Plan -> Back to the dashboard -> Document used to show Plan's questions,
// sections and doc tabs under Document's name: the resume only renamed the
// workflow. A switch through the dashboard is a fresh start, so it is blank.
+63 -1
View File
@@ -66,6 +66,7 @@ import {
pendingNote,
reviewOffer,
SKILL_CATALOG,
launchVariant,
SPEC_STATE_LABELS,
STALE_MS,
STOP_REPLY,
@@ -118,6 +119,8 @@ import {
runPoints,
tooltipFor,
WEIGHTS,
LAUNCH_LABELS,
RUN_LABELS,
} from "../src/web-console/public/meter.js";
import {
blockFor,
@@ -156,6 +159,7 @@ import {
} 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 { startsClean } from "../src/web-console/public/hops.js";
import { chatReplyLines } from "../src/web-console/inbox.mjs";
import {
initialWorkspace,
@@ -329,6 +333,34 @@ test("the page's own resume command is built only from what the session says", (
assert.equal(resumeCommand({ workflow: "handoff" }), "/plan2code-handoff");
});
// resumeCommand() reads the entry's `resume`: one case per kind.
test("the resume command follows the entry's resume kind, and an unknown workflow resumes as Pathfinder", () => {
// "overview"
assert.equal(resumeCommand({ workflow: "document", specDir: "specs/lunch-vote" }), "/plan2code-2-document specs/lunch-vote/overview.md");
assert.equal(resumeCommand({ workflow: "document" }), "/plan2code-2-document");
// "folder"
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
assert.equal(resumeCommand({ workflow: "pathfinder" }), "/plan2code-0-pathfinder");
// null: a spec is ignored
assert.equal(resumeCommand({ workflow: "review", specDir: "specs/lunch-vote" }), "/plan2code-review");
// An old session's workflow the console no longer knows
assert.equal(resumeCommand({ workflow: "made-up", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
assert.equal(resumeCommand({}), "/plan2code-0-pathfinder");
});
test("a hop starts the page clean to or from the dashboard and into Git, and nowhere else", () => {
assert.equal(startsClean("implement", "dashboard"), true);
assert.equal(startsClean("dashboard", "plan"), true);
assert.equal(startsClean("changelog", "git"), true);
assert.equal(startsClean("finalize", "git"), true);
assert.equal(startsClean("git", "changelog"), false);
assert.equal(startsClean("implement", "review"), false);
assert.equal(startsClean("git", "git"), false);
assert.equal(startsClean("dashboard", "dashboard"), false);
assert.equal(startsClean(undefined, "git"), false);
assert.equal(startsClean("plan", undefined), false);
});
test("the review offer is read from true or a label, and absent otherwise", () => {
assert.equal(reviewOffer({ command: "/x" }), null);
assert.equal(reviewOffer({ command: "/x", review: false }), null);
@@ -1017,7 +1049,10 @@ test("a verdict's button text never renders blank", () => {
test("the dashboard matrix lights only the cards a spec state allows", () => {
const scan = { hasAgents: true };
const sel = (state) => ({ dir: "specs/x", name: "x", state });
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
const entry = (skill) => {
const own = SKILL_CATALOG.find((e) => e.skill === skill);
return own || launchVariant(SKILL_CATALOG.find((e) => e.review === skill), true);
};
const on = (skill, sc, s) => cardAvailability(entry(skill), sc, s).on;
// AGENTS.md gates the setup pair, whatever the picker holds.
@@ -2142,3 +2177,30 @@ test("initialWorkspace names the original folder after itself and marks it origi
assert.deepEqual(ws.folders[0], { id: "f0", path: path.join("C:", "git", "My Repo"), name: "my-repo", description: "", original: true });
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
});
// The meter's tables are built from skills.js plus the events that are not a
// skill's own. Held to their values when they were written by hand.
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
assert.deepEqual({ ...WEIGHTS }, {
"pathfinder-chart": 2, "pathfinder-question": 0, "pathfinder-research": 1,
plan: 2, "revise-plan": 1, document: 2, "implement-phase": 2, "implement-review-phase": 3,
review: 2, "quick-task": 1, init: 2, "init-update": 2, finalize: 1, handoff: 0, git: 1,
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1,
});
assert.deepEqual({ ...LAUNCH_LABELS }, {
plan: "Plan started", "revise-plan": "Revise plan started", document: "Document started",
review: "Review started", "quick-task": "Quick task started", init: "Init started",
"init-update": "Init update started", finalize: "Finalize started", git: "Git started",
changelog: "Changelog started", xray: "X-ray started", diagnose: "Diagnose started",
});
assert.deepEqual({ ...RUN_LABELS }, {
"pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled",
"pathfinder-research": "Pathfinder research done", plan: "Plan drafted", "revise-plan": "Plan revised",
document: "Spec documented", "implement-phase": "Implement phase built",
"implement-review-phase": "Implement + Review phase built", review: "Code review run",
"quick-task": "Quick task built", init: "Init run", "init-update": "Init update run",
finalize: "Finalize run", handoff: "Handoff written", git: "Git run", "git-commits": "Commits in Git",
"git-conflict": "Git conflict help", changelog: "Changelog run", xray: "X-ray run", diagnose: "Diagnose run",
});
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
});
+728
View File
@@ -0,0 +1,728 @@
// Web console tests, the notepad: the store in notepads.mjs (names, reads,
// saves, pictures, path checks), its /notepad routes, that nothing in a
// notepad ever reaches the agent, how Cleanup treats the folder, and the
// page's pure rules in public/notepad.js (saving, status words, errors).
// Run with: node --test scripts/test-web-console-notepad.mjs
//
// Shared setup (a per-process console home, the CLI runner, fixtures) lives in
// web-console-test-helpers.mjs; see the comment at its top. Every notepad here
// lands in its throwaway NOTEPADS_DIR, never the real home folder.
import test from "node:test";
import assert from "node:assert/strict";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { DAY_MS, HOME, JPEG, NOTEPADS_DIR, ROOT, backdate, cli, openSession, sleep } from "./web-console-test-helpers.mjs";
const store = await import("../src/web-console/notepads.mjs");
const rules = await import("../src/web-console/public/notepad.js");
const { cleanupFindings, removeCleanup } = await import("../src/web-console/sessions.mjs");
const {
IMAGE_ID_RE,
NOTE_MAX_BYTES,
NOTEPAD_KEY_RE,
NOTEPAD_MAX_IMAGES,
addImage,
addThumb,
imagePath,
notepadFolder,
notepadKey,
notepadsDir,
readNotepad,
removeImage,
removeNotepad,
saveNote,
staleNotepads,
} = store;
const FOLD_CASE = process.platform === "win32" || process.platform === "darwin";
let folders = 0;
// A project folder of its own per test, so no two tests share a notepad.
const freshFolder = (name = "proj") => path.join(HOME, "projects", `${name}-${++folders}`);
const refusal = (fn, code) =>
assert.throws(fn, (e) => e instanceof store.NotepadError && e.code === code, `expected ${code}`);
/* ----------------------------------------------------------------- store */
test("notepadsDir follows PLAN2CODE_NOTEPADS_DIR at call time", () => {
assert.equal(notepadsDir(), NOTEPADS_DIR);
});
test("notepadKey is the folder name and a hash, folded where the file system ignores case", () => {
const key = notepadKey(path.join(HOME, "My Project"));
assert.match(key, NOTEPAD_KEY_RE);
assert.ok(key.startsWith("my-project-"), key);
const upper = notepadKey(path.join(HOME.toUpperCase(), "MY PROJECT"));
if (FOLD_CASE) assert.equal(upper, key);
else assert.notEqual(upper, key);
// Two worktrees, two notepads.
assert.notEqual(notepadKey(path.join(HOME, "repo")), notepadKey(path.join(HOME, "repo-feature")));
// Nothing usable in the name still gives a key the pattern accepts.
assert.match(notepadKey(path.join(HOME, "ÄÖÜ")), /^folder-[0-9a-f]{12}$/);
assert.match(notepadKey(path.join(HOME, "a-".repeat(40))), NOTEPAD_KEY_RE);
});
test("reading a folder with no notepad creates nothing", () => {
const folder = freshFolder();
assert.deepEqual(readNotepad(folder), { text: "", savedAt: null, images: [] });
assert.equal(fs.existsSync(notepadFolder(folder)), false);
});
test("saveNote round-trips text atomically, with meta.json written once", () => {
const folder = freshFolder();
const { savedAt } = saveNote(folder, "# Ideas\n\n- one ✓\n");
assert.ok(!Number.isNaN(Date.parse(savedAt)));
const read = readNotepad(folder);
assert.equal(read.text, "# Ideas\n\n- one ✓\n");
assert.equal(read.savedAt, savedAt);
const dir = notepadFolder(folder);
const meta = JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8"));
assert.equal(meta.v, 1);
assert.equal(meta.folder, path.resolve(folder));
saveNote(folder, "second");
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")), meta);
assert.deepEqual(fs.readdirSync(dir).sort(), ["images", "meta.json", "note.md"]);
});
test("saveNote refuses a non-string and a note one byte over the cap", () => {
const folder = freshFolder();
refusal(() => saveNote(folder, 5), "bad");
refusal(() => saveNote(folder, null), "bad");
refusal(() => saveNote(folder, "x".repeat(NOTE_MAX_BYTES + 1)), "too-long");
// Bytes, not characters: a multi-byte character counts for its bytes.
refusal(() => saveNote(folder, "é".repeat(NOTE_MAX_BYTES / 2 + 1)), "too-long");
assert.ok(saveNote(folder, "x".repeat(NOTE_MAX_BYTES)).savedAt);
});
test("reading a notepad leaves every file time alone", () => {
const folder = freshFolder();
saveNote(folder, "text");
const { id } = addImage(folder, JPEG);
const dir = notepadFolder(folder);
const files = [path.join(dir, "note.md"), path.join(dir, "meta.json"), path.join(dir, "images", id + ".jpg")];
const old = new Date(Date.now() - 40 * DAY_MS);
for (const f of files) fs.utimesSync(f, old, old);
readNotepad(folder);
imagePath(folder, id, false);
for (const f of files) assert.equal(Math.round(fs.statSync(f).mtimeMs), old.getTime(), f);
});
test("pictures: JPEG only, listed oldest first, with thumbnails when sent", () => {
const folder = freshFolder();
refusal(() => addImage(folder, Buffer.from("not a jpeg")), "not-jpeg");
refusal(() => addImage(folder, "string"), "not-jpeg");
const first = addImage(folder, JPEG);
const second = addImage(folder, JPEG);
assert.match(first.id, IMAGE_ID_RE);
assert.equal(first.url, `/notepad/images/${first.id}.jpg`);
const dir = notepadFolder(folder);
// Make the order unambiguous: the first is older.
const older = new Date(Date.now() - 60_000);
fs.utimesSync(path.join(dir, "images", first.id + ".jpg"), older, older);
addThumb(folder, second.id, JPEG);
assert.deepEqual(readNotepad(folder).images, [
{ id: first.id, url: first.url, thumb: null },
{ id: second.id, url: second.url, thumb: `/notepad/images/${second.id}.thumb.jpg` },
]);
});
test("addThumb and removeImage refuse bad and unknown ids", () => {
const folder = freshFolder();
const { id } = addImage(folder, JPEG);
for (const bad of ["../x", "", null, 7, "00000000-0000-0000-0000-000000000000"]) {
refusal(() => addThumb(folder, bad, JPEG), "not-found");
refusal(() => removeImage(folder, bad), "not-found");
}
refusal(() => addThumb(folder, id, Buffer.from("png")), "not-jpeg");
addThumb(folder, id, JPEG);
removeImage(folder, id);
assert.deepEqual(readNotepad(folder).images, []);
assert.deepEqual(fs.readdirSync(path.join(notepadFolder(folder), "images")), []);
});
test("a refused delete or thumb on a folder with no notepad creates nothing", () => {
const folder = freshFolder();
refusal(() => removeImage(folder, "00000000-0000-0000-0000-000000000000"), "not-found");
refusal(() => addThumb(folder, "00000000-0000-0000-0000-000000000000", JPEG), "not-found");
assert.equal(fs.existsSync(notepadFolder(folder)), false);
});
test("a thumbnail replaced again leaves the newest bytes and no temp file", () => {
const folder = freshFolder();
const { id } = addImage(folder, JPEG);
addThumb(folder, id, JPEG);
const second = Buffer.concat([JPEG, Buffer.from("second")]);
addThumb(folder, id, second);
const images = path.join(notepadFolder(folder), "images");
assert.deepEqual(fs.readFileSync(path.join(images, id + ".thumb.jpg")), second);
assert.deepEqual(fs.readdirSync(images).filter((n) => n.endsWith(".tmp")), []);
});
test("the image cap refuses one past NOTEPAD_MAX_IMAGES", () => {
const folder = freshFolder();
const images = path.join(notepadFolder(folder), "images");
addImage(folder, JPEG);
// Fill the rest directly: 200 real round trips would only slow the suite.
for (let i = 1; i < NOTEPAD_MAX_IMAGES; i++) fs.writeFileSync(path.join(images, crypto.randomUUID() + ".jpg"), JPEG);
refusal(() => addImage(folder, JPEG), "too-many");
});
test("imagePath refuses anything but this notepad's own regular files", (t) => {
const folder = freshFolder();
const { id } = addImage(folder, JPEG);
assert.equal(imagePath(folder, id, false), fs.realpathSync(path.join(notepadFolder(folder), "images", id + ".jpg")));
assert.equal(imagePath(folder, id, true), null, "no thumb yet");
assert.equal(imagePath(folder, "../meta", false), null);
assert.equal(imagePath(folder, "00000000-0000-0000-0000-000000000000", false), null);
// A planted link is refused even under a valid name.
const outside = path.join(HOME, "outside.jpg");
fs.writeFileSync(outside, JPEG);
const linkId = crypto.randomUUID();
try {
fs.symlinkSync(outside, path.join(notepadFolder(folder), "images", linkId + ".jpg"));
} catch (e) {
if (["EPERM", "EACCES"].includes(e.code)) return t.skip("symlinks need extra rights here");
throw e;
}
assert.equal(imagePath(folder, linkId, false), null);
});
test("no lock or temp file is left behind after writes", () => {
const folder = freshFolder();
saveNote(folder, "a");
const { id } = addImage(folder, JPEG);
addThumb(folder, id, JPEG);
addThumb(folder, id, JPEG);
const dir = notepadFolder(folder);
const all = [...fs.readdirSync(dir), ...fs.readdirSync(path.join(dir, "images"))];
assert.equal(all.filter((n) => n.endsWith(".lock") || n.endsWith(".tmp")).length, 0, all.join(", "));
});
/* ---------------------------------------------------------------- routes */
const getJson = async (s, pathname) => {
const res = await fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } });
return { status: res.status, body: await res.json(), headers: res.headers };
};
const postJpeg = (s, pathname, buf, extra = {}) =>
fetch(`${s.base}${pathname}`, {
method: "POST",
headers: { "content-type": "image/jpeg", cookie: s.cookie, connection: "close", ...extra },
body: buf,
});
test("GET /notepad answers an empty notepad, then the saved text", async () => {
const s = openSession();
// The session's folder is this repo; start from a clean notepad for it.
fs.rmSync(NOTEPADS_DIR, { recursive: true, force: true });
const empty = await getJson(s, "/notepad");
assert.equal(empty.status, 200);
assert.deepEqual(empty.body, { text: "", savedAt: null, images: [] });
const saved = await s.send("/notepad/text", { text: "# Route note" });
assert.equal(saved.status, 200);
const body = await saved.json();
assert.equal(body.ok, true);
const read = await getJson(s, "/notepad");
assert.equal(read.body.text, "# Route note");
assert.equal(read.body.savedAt, body.savedAt);
});
test("POST /notepad/text refuses a non-string, an oversized note and bad JSON", async () => {
const s = openSession();
const bad = await s.send("/notepad/text", { text: 7 });
assert.equal(bad.status, 400);
assert.deepEqual(await bad.json(), { error: "bad" });
const long = await s.send("/notepad/text", { text: "x".repeat(NOTE_MAX_BYTES + 1) });
assert.equal(long.status, 413);
assert.deepEqual(await long.json(), { error: "too-long" });
const notJson = await fetch(`${s.base}/notepad/text`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
body: "{nope",
});
assert.equal(notJson.status, 400);
});
test("notepad writes need the session cookie and refuse a foreign origin", async () => {
const s = openSession();
const noCookie = await fetch(`${s.base}/notepad/text`, {
method: "POST",
headers: { "content-type": "application/json", connection: "close" },
body: JSON.stringify({ text: "x" }),
});
assert.equal(noCookie.status, 403);
const foreign = await fetch(`${s.base}/notepad/text`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, origin: "http://evil.example", connection: "close" },
body: JSON.stringify({ text: "x" }),
});
assert.equal(foreign.status, 403);
const foreignImage = await postJpeg(s, "/notepad/image", JPEG, { origin: "http://evil.example" });
assert.equal(foreignImage.status, 403);
const noCookieRead = await fetch(`${s.base}/notepad`, { headers: { connection: "close" } });
assert.equal(noCookieRead.status, 403);
});
test("pictures through the routes: upload, thumb, fetch, delete and every refusal", async () => {
const s = openSession();
const wrongType = await fetch(`${s.base}/notepad/image`, {
method: "POST",
headers: { "content-type": "image/png", cookie: s.cookie, connection: "close" },
body: JPEG,
});
assert.equal(wrongType.status, 415);
assert.deepEqual(await wrongType.json(), { error: "not-jpeg" });
const notJpeg = await postJpeg(s, "/notepad/image", Buffer.from("plain text"));
assert.equal(notJpeg.status, 415);
const tooLarge = await postJpeg(s, "/notepad/image", Buffer.concat([JPEG, Buffer.alloc(4 * 1024 * 1024)]));
assert.equal(tooLarge.status, 413);
assert.deepEqual(await tooLarge.json(), { error: "too-large" });
const up = await postJpeg(s, "/notepad/image", JPEG);
assert.equal(up.status, 200);
const { id, url } = await up.json();
assert.match(id, IMAGE_ID_RE);
const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG);
assert.equal(unknownThumb.status, 404);
assert.deepEqual(await unknownThumb.json(), { error: "not-found" });
const thumbNotJpeg = await postJpeg(s, `/notepad/thumb?id=${id}`, Buffer.from("png"));
assert.equal(thumbNotJpeg.status, 415);
assert.deepEqual(await thumbNotJpeg.json(), { error: "not-jpeg" });
const thumbTooLarge = await postJpeg(s, `/notepad/thumb?id=${id}`, Buffer.concat([JPEG, Buffer.alloc(4 * 1024 * 1024)]));
assert.equal(thumbTooLarge.status, 413);
assert.deepEqual(await thumbTooLarge.json(), { error: "too-large" });
assert.equal((await postJpeg(s, `/notepad/thumb?id=${id}`, JPEG)).status, 200);
const img = await fetch(`${s.base}${url}`, { headers: { cookie: s.cookie, connection: "close" } });
assert.equal(img.status, 200);
assert.equal(img.headers.get("content-type"), "image/jpeg");
assert.equal(img.headers.get("cache-control"), "no-store");
assert.equal(img.headers.get("x-content-type-options"), "nosniff");
assert.deepEqual(Buffer.from(await img.arrayBuffer()), JPEG);
const thumb = await fetch(`${s.base}/notepad/images/${id}.thumb.jpg`, { headers: { cookie: s.cookie, connection: "close" } });
assert.equal(thumb.status, 200);
for (const bad of ["/notepad/images/../meta.json", "/notepad/images/nope.jpg", `/notepad/images/${id}.png`, "/notepad/images/%2e%2e%2fmeta.json"]) {
const res = await fetch(`${s.base}${bad}`, { headers: { cookie: s.cookie, connection: "close" } });
assert.equal(res.status, 404, bad);
}
const gone = await s.send("/notepad/image/delete", { id: "00000000-0000-0000-0000-000000000000" });
assert.equal(gone.status, 404);
const del = await s.send("/notepad/image/delete", { id });
assert.equal(del.status, 200);
const after = await fetch(`${s.base}${url}`, { headers: { cookie: s.cookie, connection: "close" } });
assert.equal(after.status, 404);
});
test("POST /notepad/image refuses one past the cap with 409", async (t) => {
const s = openSession();
// The session runs in this repo, so its notepad is the one for ROOT. Fill it
// directly (200 round trips would only slow the suite), and empty it after
// so the tests below start from a notepad with room.
const images = path.join(notepadFolder(ROOT), "images");
t.after(() => fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true }));
assert.equal((await postJpeg(s, "/notepad/image", JPEG)).status, 200);
const have = fs.readdirSync(images).filter((n) => !n.endsWith(".thumb.jpg")).length;
for (let i = have; i < NOTEPAD_MAX_IMAGES; i++) fs.writeFileSync(path.join(images, crypto.randomUUID() + ".jpg"), JPEG);
const full = await postJpeg(s, "/notepad/image", JPEG);
assert.equal(full.status, 409);
assert.deepEqual(await full.json(), { error: "too-many" });
});
test("two folders get two notepads through their own sessions", async (t) => {
const a = path.join(os.tmpdir(), `p2c-notepad-a-${process.pid}`);
const b = path.join(os.tmpdir(), `p2c-notepad-b-${process.pid}`);
for (const d of [a, b]) fs.mkdirSync(d, { recursive: true });
const { cliIn, payload, BASE, sessionUrl, until } = await import("./web-console-test-helpers.mjs");
const sids = [];
// Each server runs in its folder, and Windows will not remove a folder a
// live process sits in: stop both, and wait until neither answers, before
// cleaning up (stop returns before the process has gone).
t.after(async () => {
for (const [cwd, sid] of sids) cliIn(cwd, ["stop", "--session", sid]);
const gone = async ({ base }) => {
try {
await fetch(`${base}/health`, { signal: AbortSignal.timeout(1000) });
return false;
} catch {
return true;
}
};
for (const [, , s] of sids) await until(() => gone(s), 5000);
for (const d of [a, b]) fs.rmSync(d, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
});
const open = (cwd) => {
const res = cliIn(cwd, ["open", "--file", payload(`np-${path.basename(cwd)}.json`, BASE), "--no-open"]);
const s = sessionUrl(res.json.url);
sids.push([cwd, res.json.sid, s]);
return s;
};
const sa = open(a);
const sb = open(b);
const save = (s, text) =>
fetch(`${s.base}/notepad/text`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
body: JSON.stringify({ text }),
});
assert.equal((await save(sa, "from a")).status, 200);
assert.equal((await save(sb, "from b")).status, 200);
assert.equal((await getJson(sa, "/notepad")).body.text, "from a");
assert.equal((await getJson(sb, "/notepad")).body.text, "from b");
assert.notEqual(notepadFolder(a), notepadFolder(b));
});
/* -------------------------------------------- never to the agent, Cleanup */
test("nothing in a notepad reaches the session folder or the agent's wait", async () => {
const s = openSession();
const marker = `NOTEPAD-MARKER-${process.pid}-${Date.now()}`;
assert.equal((await s.send("/notepad/text", { text: `secret ${marker}` })).status, 200);
const picture = Buffer.concat([JPEG, Buffer.from(marker)]);
assert.equal((await postJpeg(s, "/notepad/image", picture)).status, 200);
const seen = [];
const walk = (dir) => {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) walk(p);
else seen.push(p);
}
};
walk(s.session);
for (const file of seen) {
assert.ok(!fs.readFileSync(file).includes(marker), `${path.relative(s.session, file)} carries notepad content`);
}
assert.equal(fs.existsSync(path.join(s.session, "uploads")) && fs.readdirSync(path.join(s.session, "uploads")).length > 0, false);
const waited = cli(["wait", "--session", s.sid, "--seconds", "1"]);
assert.ok(!waited.stdout.includes(marker));
const status = cli(["status"]);
assert.ok(!status.stdout.includes(marker));
});
test("Cleanup never lists the notepads folder as a stray, fresh or old", async () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-notepad-cleanup-"));
const consoleDir = path.join(root, "console");
fs.mkdirSync(path.join(consoleDir, "sessions"), { recursive: true });
const note = path.join(root, "notepads", "proj-0123456789ab", "note.md");
fs.mkdirSync(path.dirname(note), { recursive: true });
fs.writeFileSync(note, "x");
const ids = async (now) => (await cleanupFindings({ consoleDir, plan2codeDir: root, now })).items.map((i) => i.id);
assert.ok(!(await ids(Date.now())).includes("root:notepads"));
// Two hours on: past the stray grace, so only the kept list protects it.
assert.ok(!(await ids(Date.now() + 2 * 60 * 60 * 1000)).includes("root:notepads"));
// A real stray beside it is still listed, so the scan did run.
const stray = path.join(root, "leftover.txt");
fs.writeFileSync(stray, "x");
assert.ok((await ids(Date.now() + 2 * 60 * 60 * 1000)).includes("root:leftover.txt"));
fs.rmSync(root, { recursive: true, force: true });
});
// Every file and folder under `dir`, and `dir` itself, moved `days` back.
function backdateAll(dir, days) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) backdateAll(p, days);
else backdate(p, days);
}
backdate(dir, days);
}
// Cleanup's scan with no console or ~/.plan2code strays in the way: only the
// notepads folder (the file's NOTEPADS_DIR) has anything to find.
function quietCleanup() {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-notepad-stale-"));
fs.mkdirSync(path.join(root, "console", "sessions"), { recursive: true });
const opts = { consoleDir: path.join(root, "console"), plan2codeDir: root };
return { opts, done: () => fs.rmSync(root, { recursive: true, force: true }) };
}
test("Cleanup lists a notepad only once its newest file is a month old, as one item that removes the whole folder", async () => {
const q = quietCleanup();
// Old text, but a picture added today: still in use.
const mixed = freshFolder("mixed");
saveNote(mixed, "old words");
backdateAll(notepadFolder(mixed), 31);
addImage(mixed, JPEG);
// Every file a month old.
const old = freshFolder("old");
saveNote(old, "forgotten");
addImage(old, JPEG);
backdateAll(notepadFolder(old), 31);
// Written today.
const fresh = freshFolder("fresh");
saveNote(fresh, "today");
const { items } = await cleanupFindings(q.opts);
const notepads = items.filter((i) => i.where === "notepad");
assert.deepEqual(
notepads.map((i) => i.id),
["notepad:" + notepadKey(old)],
);
assert.equal(notepads[0].name, notepadKey(old));
assert.equal(notepads[0].kind, "folder");
assert.equal(notepads[0].folder, path.resolve(old));
assert.ok(notepads[0].bytes > JPEG.length, "the item counts the whole folder");
assert.deepEqual(
staleNotepads(Date.now(), 30 * DAY_MS).map((n) => n.key),
[notepadKey(old)],
);
const done = await removeCleanup(["notepad:" + notepadKey(old), "notepad:" + notepadKey(fresh)], q.opts);
assert.deepEqual(done.removed, ["notepad:" + notepadKey(old)], "only what the fresh scan still finds is removed");
assert.equal(fs.existsSync(notepadFolder(old)), false, "the whole folder went");
assert.equal(readNotepad(fresh).text, "today");
assert.equal(readNotepad(mixed).images.length, 1);
q.done();
});
test("a notepad with no meta.json is listed by its key alone", async () => {
const q = quietCleanup();
const folder = freshFolder("nometa");
saveNote(folder, "x");
fs.rmSync(path.join(notepadFolder(folder), "meta.json"));
backdateAll(notepadFolder(folder), 31);
const item = (await cleanupFindings(q.opts)).items.find((i) => i.id === "notepad:" + notepadKey(folder));
assert.ok(item, "still listed");
assert.equal(item.folder, null);
removeNotepad(notepadKey(folder));
q.done();
});
test("removeNotepad refuses a bad key and a linked folder, and staleNotepads skips both", (t) => {
for (const key of ["", "../proj-0123456789ab", "Proj-0123456789ab", "proj-0123456789a", "proj", "proj-0123456789ab/..", 7, null]) {
refusal(() => removeNotepad(key), "bad");
}
refusal(() => removeNotepad("gone-0123456789ab"), "not-found");
// A link under a valid key, pointing at a folder that must survive.
const target = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-notepad-target-"));
fs.writeFileSync(path.join(target, "keep.md"), "mine");
backdateAll(target, 60);
const key = "linked-" + crypto.randomBytes(6).toString("hex");
const link = path.join(notepadsDir(), key);
fs.mkdirSync(notepadsDir(), { recursive: true });
try {
fs.symlinkSync(target, link, process.platform === "win32" ? "junction" : "dir");
} catch (e) {
fs.rmSync(target, { recursive: true, force: true });
if (["EPERM", "EACCES"].includes(e.code)) return t.skip("links need extra rights here");
throw e;
}
try {
assert.ok(!staleNotepads(Date.now(), 30 * DAY_MS).some((n) => n.key === key), "a link is never listed");
refusal(() => removeNotepad(key), "bad");
assert.equal(fs.readFileSync(path.join(target, "keep.md"), "utf8"), "mine");
} finally {
// The link alone: a Windows junction goes with rmdir, a symlink with unlink.
try {
fs.unlinkSync(link);
} catch {
fs.rmdirSync(link);
}
fs.rmSync(target, { recursive: true, force: true });
}
// A plain file under a valid key is no notepad either.
const file = path.join(notepadsDir(), "file-" + crypto.randomBytes(6).toString("hex"));
fs.writeFileSync(file, "x");
backdate(file, 60);
assert.ok(!staleNotepads(Date.now(), 30 * DAY_MS).some((n) => n.path === file));
refusal(() => removeNotepad(path.basename(file)), "bad");
fs.rmSync(file);
});
test("the sweeps at open leave a 60-day-old notepad untouched", async () => {
const folder = freshFolder("sixty");
saveNote(folder, "kept for months");
addImage(folder, JPEG);
backdateAll(notepadFolder(folder), 60);
const before = fs.statSync(path.join(notepadFolder(folder), "note.md")).mtimeMs;
const s = openSession();
// The sweeps run after open prints; give them their moment.
await sleep(500);
assert.equal(readNotepad(folder).text, "kept for months");
assert.equal(readNotepad(folder).images.length, 1);
assert.equal(fs.statSync(path.join(notepadFolder(folder), "note.md")).mtimeMs, before, "not even touched");
cli(["stop", "--session", s.sid]);
removeNotepad(notepadKey(folder));
});
/* ------------------------------------------------------------ page rules */
// Drives nextSave() through a list of events from a start state, returning
// every step's status, attempt and timer.
function run(events, from = rules.SAVE_START) {
let state = from;
return events.map((event) => {
const next = rules.nextSave(state, event);
state = next.state;
return [state.status, state.attempt, next.timer];
});
}
test("page rules: the caps equal the server's", () => {
assert.equal(rules.NOTE_MAX_BYTES, NOTE_MAX_BYTES);
assert.equal(rules.NOTEPAD_MAX_IMAGES, NOTEPAD_MAX_IMAGES);
assert.equal(String(rules.IMAGE_ID_RE), String(IMAGE_ID_RE));
assert.equal(rules.SAVE_DEBOUNCE_MS, 800);
assert.deepEqual([...rules.RETRY_STEPS_MS], [1000, 2000, 4000, 8000, 16000, 30000]);
});
test("page rules: noteBytes counts UTF-8 bytes, and a non-string as nothing", () => {
assert.equal(rules.noteBytes("abc"), 3);
assert.equal(rules.noteBytes("é"), 2);
assert.equal(rules.noteBytes("😀"), 4);
assert.equal(rules.noteBytes(null), 0);
});
test("page rules: typing arms the debounce, then due, sent and ok land saved", () => {
assert.deepEqual(run([{ type: "typed", bytes: 5 }, "due", "sent", "ok"]), [
["pending", 0, rules.SAVE_DEBOUNCE_MS],
["saving", 0, null],
["saving", 0, null],
["saved", 0, null],
]);
// Typing again from saved starts over.
assert.deepEqual(run([{ type: "typed", bytes: 1 }], { status: "saved", attempt: 0 }), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
});
test("page rules: failures back off step by step, hold at the last step, and reset on typed or ok", () => {
const events = [{ type: "typed", bytes: 1 }, "due"];
for (let i = 0; i < 8; i++) events.push({ type: "error", code: "bad" }, "retry");
const steps = run(events).filter(([status]) => status === "failed").map(([, , timer]) => timer);
assert.deepEqual(steps, [1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000]);
const failed = { status: "failed", attempt: 4 };
assert.deepEqual(run([{ type: "typed", bytes: 1 }], failed), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
assert.deepEqual(run(["retry", "ok", { type: "error" }], failed), [
["saving", 4, null],
["saved", 0, null],
["failed", 1, 1000],
]);
// A flush (due) on a failed save sends now, keeping the count.
assert.deepEqual(run(["due"], failed), [["saving", 4, null]]);
});
test("page rules: a note past the cap never sends, and a server too-long stops retrying", () => {
assert.deepEqual(run([{ type: "typed", bytes: NOTE_MAX_BYTES + 1 }, "due", "retry"]), [
["too-long", 0, null],
["too-long", 0, null],
["too-long", 0, null],
]);
assert.deepEqual(run([{ type: "typed", bytes: NOTE_MAX_BYTES }]), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
assert.deepEqual(run([{ type: "error", code: "too-long" }], { status: "saving", attempt: 2 }), [["too-long", 0, null]]);
// Typing it back under the cap saves again.
assert.deepEqual(run([{ type: "typed", bytes: 10 }], { status: "too-long", attempt: 0 }), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
});
test("page rules: due and retry do nothing where there is nothing to send, and bad input changes nothing", () => {
for (const status of ["idle", "saving", "saved", "too-long"]) {
const state = { status, attempt: 0 };
assert.equal(rules.nextSave(state, "due").state, state, `due from ${status}`);
assert.equal(rules.nextSave(state, "due").timer, null);
}
for (const status of ["idle", "pending", "saving", "saved", "too-long"]) {
const state = { status, attempt: 0 };
assert.equal(rules.nextSave(state, "retry").state, state, `retry from ${status}`);
}
const state = { status: "pending", attempt: 0 };
assert.equal(rules.nextSave(state, "nonsense").state, state);
assert.equal(rules.nextSave({ status: "weird" }, "typed").state.status, "weird");
// Never mutates its input.
const frozen = Object.freeze({ status: "failed", attempt: 1 });
rules.nextSave(frozen, { type: "error" });
assert.deepEqual(frozen, { status: "failed", attempt: 1 });
});
test("page rules: saveStatus words and unsaved()", () => {
const words = {
idle: "",
pending: "Saving",
saving: "Saving",
saved: "Saved",
failed: "Not saved (retrying)",
"too-long": "Too long to save (over 1 MB)",
};
for (const [status, text] of Object.entries(words)) {
assert.equal(rules.saveStatus({ status, attempt: 0 }), text);
assert.equal(rules.saveStatus(status), text);
}
assert.equal(rules.saveStatus(undefined), "");
assert.deepEqual(
Object.keys(words).filter((status) => rules.unsaved({ status })),
["pending", "saving", "failed"],
);
});
test("page rules: keepsText holds unsaved and too-long text against a reload", () => {
const statuses = ["idle", "pending", "saving", "saved", "failed", "too-long"];
assert.deepEqual(
statuses.filter((status) => rules.keepsText({ status })),
["pending", "saving", "failed", "too-long"],
);
assert.match(rules.NOT_LOADED, /^[A-Z].*\.$/);
});
test("page rules: errorSentence covers every server code, and anything else is a lost connection", () => {
// Every code the store can raise.
const raised = new Set();
for (const m of fs.readFileSync(path.join(ROOT, "src", "web-console", "notepads.mjs"), "utf8").matchAll(/new NotepadError\("([a-z-]+)"/g)) raised.add(m[1]);
// The routes add too-large for an oversized picture.
raised.add("too-large");
assert.deepEqual([...raised].sort(), [...rules.ERROR_CODES].sort());
const lost = rules.errorSentence(null);
const seen = new Set([lost]);
for (const code of rules.ERROR_CODES) {
const sentence = rules.errorSentence(code);
assert.match(sentence, /^[A-Z].*\.$/, code);
assert.ok(!seen.has(sentence), `${code} has a sentence of its own`);
seen.add(sentence);
}
assert.equal(rules.errorSentence("teapot"), lost);
assert.equal(rules.errorSentence(undefined), lost);
assert.match(rules.errorSentence("too-many"), new RegExp(String(NOTEPAD_MAX_IMAGES)));
});
test("page rules: step wraps at both ends, and an empty list has nowhere to go", () => {
assert.equal(rules.step(0, 1, 3), 1);
assert.equal(rules.step(2, 1, 3), 0);
assert.equal(rules.step(0, -1, 3), 2);
assert.equal(rules.step(1, -1, 3), 0);
assert.equal(rules.step(0, 1, 1), 0);
assert.equal(rules.step(0, 1, 0), -1);
assert.equal(rules.step(0, -1, 0), -1);
});
test("page rules: withoutStyleAttrs moves a link's anchor name to data-anchor and drops any other style", () => {
assert.equal(
rules.withoutStyleAttrs('<div><a href="x" style="anchor-name: --link-3"><span class="syntax-marker">[</span>a</a></div>'),
'<div><a href="x" data-anchor="--link-3"><span class="syntax-marker">[</span>a</a></div>',
);
assert.equal(rules.withoutStyleAttrs('<span style="display: flex; gap: 6px;"><svg style="flex-shrink: 0;"></svg></span>'), "<span><svg></svg></span>");
// Typed text reaches it with its quotes escaped, so it is never touched.
const typed = "<div>&lt;b style=&quot;color: red&quot;&gt;</div>";
assert.equal(rules.withoutStyleAttrs(typed), typed);
});
test("page rules: topLevelParts cuts the HTML into its top-level elements, or says it cannot", () => {
const parts = ["<div><h1><span class=\"syntax-marker\"># </span>Hi</h1></div>", "<ul><li class=\"bullet-list\">a</li><li class=\"bullet-list\">b</li></ul>", "<div>&nbsp;</div>", "<div>a<br>b<img src=\"x\"></div>", "<div><span/></div>"];
assert.deepEqual(rules.topLevelParts(parts.join("")), parts);
assert.deepEqual(rules.topLevelParts(""), []);
assert.equal(rules.topLevelParts("<div>open"), null, "unbalanced");
assert.equal(rules.topLevelParts("<div>a</div></div>"), null, "closes more than it opens");
assert.equal(rules.topLevelParts("text<div>a</div>"), null, "text at the top level");
assert.equal(rules.topLevelParts("<div>a</div>trailing"), null);
});
test("page rules: changedRange finds the unchanged head and tail, never overlapping", () => {
assert.deepEqual(rules.changedRange(["a", "b", "c"], ["a", "x", "c"]), { head: 1, tail: 1 });
assert.deepEqual(rules.changedRange(["a", "b", "c"], ["a", "b", "c"]), { head: 3, tail: 0 });
assert.deepEqual(rules.changedRange(["a", "b"], ["a", "b", "b"]), { head: 2, tail: 0 });
assert.deepEqual(rules.changedRange(["a", "a"], ["a"]), { head: 1, tail: 0 });
assert.deepEqual(rules.changedRange([], ["a"]), { head: 0, tail: 0 });
assert.deepEqual(rules.changedRange(["x", "a", "b"], ["a", "b"]), { head: 0, tail: 2 });
});
+45
View File
@@ -14,6 +14,7 @@ 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";
import { CATALOG_GROUPS, SKILL_CATALOG } from "../src/web-console/public/answers.js";
const suite = pageSuite(test);
@@ -204,6 +205,50 @@ test("the Welcome stays away when the person has seen it, and off the dashboard"
assert.equal(await plan.page.locator("#welcome-modal").isVisible(), false, "the Welcome showed on a workflow page");
});
test("Help's dashboard topic lists every card once, grouped and in the dashboard's order, by its Help line or blurb", async (t) => {
savedLooks(t, { welcomeSeen: true });
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
await toTheDashboard(s);
await openHelp(s);
await tabButton(s, "dashboard").click();
const panel = s.page.locator("#help-panel-dashboard");
await panel.waitFor();
// Read back as drawn: each group's heading, then its list's title and line.
const drawnGroups = await panel.locator(".help-cards").evaluate((box) => {
const out = [];
for (const node of box.children) {
if (node.tagName === "P") out.push({ title: node.textContent, cards: [] });
else
out.at(-1).cards.push(
...[...node.children].map((li) => ({
title: li.firstElementChild.textContent,
line: li.textContent.slice(li.firstElementChild.textContent.length),
}))
);
}
return out;
});
const expected = CATALOG_GROUPS.map((g) => ({
title: g.title,
cards: SKILL_CATALOG.filter((e) => e.group === g.id).map((e) => ({ title: e.title + ".", line: " " + (e.help || e.blurb) })),
}));
assert.deepEqual(drawnGroups, expected);
// Each card's title and line appear exactly once in the whole topic.
const text = await panel.evaluate((n) => n.textContent);
const titles = await panel.locator(".help-cards li > strong").allTextContents();
for (const e of SKILL_CATALOG) {
assert.equal(titles.filter((x) => x === e.title + ".").length, 1, `${e.title} is listed once`);
assert.equal(text.split(e.help || e.blurb).length - 1, 1, `${e.title}'s line appears once`);
}
// Built once: a second open adds no second list.
await s.page.keyboard.press("Escape");
await helpModal(s).waitFor({ state: "hidden" });
await openHelp(s);
assert.equal(await panel.locator(".help-cards li").count(), SKILL_CATALOG.length);
});
// 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.
+754
View File
@@ -0,0 +1,754 @@
// Page tests for the Notepad: the top bar icon on every screen, the styled
// editor, autosave and what survives a reload or a restart, one notepad per
// folder, the page's content-security policy with the editor open, hostile
// Markdown, typing speed on a long note, the editor's two layers lining up,
// both themes, and the pictures: adding, deleting, the preview and the cap.
// Run with:
// node --test scripts/test-web-console-page-notepad.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. Notes land in the file's throwaway NOTEPADS_DIR.
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, drawn } from "./page-test-helpers.mjs";
import { backdate, cli, until } from "./web-console-test-helpers.mjs";
import {
NOTEPAD_MAX_IMAGES,
NOTE_MAX_BYTES,
addImage,
notepadFolder,
notepadKey,
readNotepad,
removeImage,
saveNote,
} from "../src/web-console/notepads.mjs";
import { NOT_LOADED, SAVE_DEBOUNCE_MS, errorSentence } from "../src/web-console/public/notepad.js";
const suite = pageSuite(test);
// A plan session on the person's turn.
const PLAN_QUESTION = {
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
agent: { status: "waiting" },
};
const input = (s) => s.page.locator("#notepad-editor .overtype-input");
// Opens the notepad and, unless told the note cannot load, waits until it has:
// the editor is read-only until then.
async function openNotepad(s, { loads = true } = {}) {
await s.page.click("#btn-notepad");
await s.page.locator("#notepad-modal[open]").waitFor();
await input(s).waitFor();
if (loads) await s.page.waitForFunction(() => !document.querySelector("#notepad-editor .overtype-input").readOnly);
}
async function closeNotepad(s) {
await s.page.click("#notepad-close");
await s.page.waitForFunction(() => !document.getElementById("notepad-modal").open);
}
// The editor's text once the page has read the note in: opening reads it from
// the server, so the first value can still be the empty editor.
async function shows(s, text) {
await s.page.waitForFunction((want) => document.querySelector("#notepad-editor .overtype-input").value === want, text, { timeout: 5000 });
return input(s).inputValue();
}
// The note on disk for the session's folder, as the store reads it.
const onDisk = (s) => readNotepad(s.project).text;
async function iconUsable(s, where) {
const btn = s.page.locator("#btn-notepad");
assert.ok(await btn.isVisible(), `the icon shows on ${where}`);
assert.ok(await btn.isEnabled(), `the icon is usable on ${where}`);
assert.equal(await btn.getAttribute("aria-label"), "Notepad");
assert.equal(await btn.getAttribute("title"), "Notepad");
}
test("the notepad icon shows on the dashboard, a skill session and a finished screen", async (t) => {
const dash = await openSession(await suite.browser(), { t, workflow: "dashboard" });
await iconUsable(dash, "the dashboard");
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await iconUsable(s, "a skill session");
// Right of Stop session and Subagents, in the same row.
const order = await s.page.evaluate(() =>
[...document.querySelectorAll(".topbar-row.second .row-left > button")].map((b) => b.id),
);
assert.ok(order.indexOf("btn-notepad") > order.indexOf("btn-stop"), order.join(", "));
assert.equal(order.indexOf("btn-notepad"), order.indexOf("btn-subagents") + 1, order.join(", "));
s.post({ settle: true, finish: { headline: "The plan is done", body: "All written down." } });
await s.page.locator(".handoff, .end-pane, #main").first().waitFor();
await s.page.waitForFunction(() => document.getElementById("btn-stop").hidden);
await iconUsable(s, "the finished screen");
await openNotepad(s);
});
test("typing Markdown styles it in place, saves within two seconds, and survives close, reload and a restart", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
assert.equal(await input(s).getAttribute("aria-label"), "Notepad text");
await input(s).focus();
await s.page.keyboard.type("# Shopping list\n\nSome **bold** text");
const typedAt = Date.now();
// Styled in place: the preview layer under the textarea holds a heading.
await s.page.locator("#notepad-editor .overtype-preview h1").waitFor();
assert.match(await s.page.locator("#notepad-editor .overtype-preview h1").innerText(), /Shopping list/);
assert.equal(await s.page.locator("#notepad-editor .overtype-preview strong").count(), 1);
await until(() => onDisk(s) === "# Shopping list\n\nSome **bold** text", 4000);
assert.ok(Date.now() - typedAt < 2000, `saved ${Date.now() - typedAt} ms after the last key`);
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent === "Saved");
// Close flushes at once, without waiting out the debounce.
await s.page.keyboard.type("\nmore");
await s.page.click("#notepad-close");
const closedAt = Date.now();
await until(() => onDisk(s).endsWith("\nmore"), 4000);
assert.ok(Date.now() - closedAt < SAVE_DEBOUNCE_MS, `flushed ${Date.now() - closedAt} ms after close`);
assert.equal(await s.page.evaluate(() => document.activeElement && document.activeElement.id), "btn-notepad");
const expected = "# Shopping list\n\nSome **bold** text\nmore";
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await openNotepad(s);
assert.equal(await shows(s, expected), expected, "a reload shows the saved note");
// A server restart (the agent's open --resume) keeps it too.
cli(["stop", "--session", s.sid], { cwd: s.project });
await until(async () => !(await s.answers()), 5000);
const resumed = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "plan"], { cwd: s.project }).json;
s.url = resumed.url;
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
await drawn(s.page);
await openNotepad(s);
assert.equal(await shows(s, expected), expected, "a restarted server shows the saved note");
});
test("two sessions in two folders keep two separate notepads", async (t) => {
const a = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const b = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(a);
await input(a).fill("Folder A's note");
await until(() => onDisk(a) === "Folder A's note", 4000);
await openNotepad(b);
assert.equal(await input(b).inputValue(), "", "the second folder starts empty");
await input(b).fill("Folder B's note");
await until(() => onDisk(b) === "Folder B's note", 4000);
assert.equal(onDisk(a), "Folder A's note");
// Reopening each shows its own.
await closeNotepad(a);
await openNotepad(a);
assert.equal(await shows(a, "Folder A's note"), "Folder A's note");
});
test("the editor breaks no content-security rule, and hostile Markdown runs nothing", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const consoleErrors = [];
s.page.on("console", (m) => {
if (m.type() === "error") consoleErrors.push(m.text());
});
await s.context.addInitScript(() => {
window.__violations = [];
document.addEventListener("securitypolicyviolation", (e) =>
window.__violations.push(`${e.violatedDirective} ${e.blockedURI} ${e.sourceFile}:${e.lineNumber} ${e.sample}`),
);
});
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await openNotepad(s);
await input(s).focus();
await s.page.keyboard.type(
"# Title\n\n- a list with `code` and [a link](https://example.com)\n> quoted\n\n" +
'<img src=x onerror="window.__pwned = 1">\n<script>window.__pwned2 = 1</script>\n' +
'<a href="javascript:window.__pwned3 = 1">click</a>\n',
);
await until(() => onDisk(s).includes("__pwned3"), 4000);
await s.page.waitForTimeout(300);
const result = await s.page.evaluate(() => ({
violations: window.__violations,
pwned: [window.__pwned, window.__pwned2, window.__pwned3],
imgs: document.querySelectorAll("#notepad-editor .overtype-preview img").length,
scripts: document.querySelectorAll("#notepad-editor script").length,
styleTag: Boolean(document.querySelector("style.overtype-styles")),
}));
assert.deepEqual(result.violations, [], "no content-security violations with the notepad open");
assert.deepEqual(result.pwned, [undefined, undefined, undefined], "nothing typed ran");
assert.equal(result.imgs, 0, "typed HTML stays text");
assert.equal(result.scripts, 0);
assert.equal(result.styleTag, false, "OverType injected no <style>");
assert.deepEqual(consoleErrors.filter((e) => /Content.Security.Policy|Refused to/i.test(e)), []);
// The heading is styled from the stylesheet the page ships.
const h1 = await s.page.locator("#notepad-editor .overtype-preview h1").evaluate((el) => getComputedStyle(el).fontWeight);
assert.ok(Number(h1) >= 600 || h1 === "bold", `the heading is bold (${h1})`);
});
// The editor redraws only the lines that changed (patchPreview in
// screens/notepad.js): about 90 ms a key at 200 KB on a quiet machine, against
// about 310 ms when every key redrew the whole note. The bar is higher than
// that because `npm test` runs every test file at once, which alone adds 50 ms
// or more; it still catches a slide back toward whole-note redraws.
const KEY_BUDGET_MS = 200;
test("typing into a 200 KB note keeps input-to-paint under the key budget on average", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const block = "## Heading\n\nSome **bold** text with `code` and a [link](https://example.com).\n\n- an item\n- another\n\n";
saveNote(s.project, block.repeat(Math.ceil((200 * 1024) / block.length)));
await openNotepad(s);
await s.page.waitForFunction(() => document.querySelector("#notepad-editor .overtype-input").value.length > 200000);
await s.page.evaluate(() => {
window.__lags = [];
window.addEventListener(
"keydown",
() => {
const t0 = performance.now();
requestAnimationFrame(() => requestAnimationFrame(() => window.__lags.push(performance.now() - t0)));
},
{ capture: true },
);
const ta = document.querySelector("#notepad-editor .overtype-input");
ta.focus();
ta.setSelectionRange(ta.value.length, ta.value.length);
});
// `npm test` runs every test file at once, and a round that lands in another
// file's busiest moment measures the machine rather than the editor: the
// best of up to three rounds is the editor's number.
const averages = [];
for (let round = 0; round < 3; round++) {
await s.page.evaluate(() => (window.__lags = []));
await s.page.keyboard.type("typing at the end of a long note", { delay: 60 });
await s.page.waitForTimeout(200);
const lags = await s.page.evaluate(() => window.__lags);
assert.ok(lags.length >= 20, `measured ${lags.length} keys`);
averages.push(lags.reduce((a, b) => a + b, 0) / lags.length);
if (averages.at(-1) < KEY_BUDGET_MS) break;
}
const best = Math.min(...averages);
assert.ok(best < KEY_BUDGET_MS, `average input-to-paint ${averages.map((a) => a.toFixed(1)).join(", ")} ms`);
});
test("the textarea and the styled layer line up, line for line", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
await input(s).fill(
"# A heading\n## A smaller one\nPlain text with **bold**, *em* and `code`.\n> a quote\n- a list item\n\n" +
"A long line that wraps: " + "word ".repeat(80) + "\nThe last line",
);
const m = await s.page.evaluate(() => {
const ta = document.querySelector("#notepad-editor .overtype-input");
const pv = document.querySelector("#notepad-editor .overtype-preview");
const cs = (el) => getComputedStyle(el);
const lineHeight = parseFloat(cs(ta).lineHeight);
const lines = [...pv.children];
const top0 = lines[0].getBoundingClientRect().top;
return {
lineHeight,
count: lines.length,
offsets: lines.map((el) => (el.getBoundingClientRect().top - top0) / lineHeight),
heights: [ta.scrollHeight, pv.scrollHeight],
fonts: [ta, pv, pv.querySelector("h1"), pv.querySelector("h2"), pv.querySelector("strong"), pv.querySelector("code")].map(
(el) => `${cs(el).fontFamily} ${cs(el).fontSize}`,
),
padding: [cs(ta).paddingTop, cs(pv).paddingTop, cs(ta).paddingLeft, cs(pv).paddingLeft],
};
});
assert.equal(m.count, 8, "one preview line per text line");
for (const [i, offset] of m.offsets.entries()) {
assert.ok(Math.abs(offset - Math.round(offset)) < 0.05, `line ${i + 1} sits on the grid (${offset})`);
}
assert.ok(Math.abs(m.heights[0] - m.heights[1]) <= 1, `same height: ${m.heights.join(" vs ")}`);
assert.equal(new Set(m.fonts).size, 1, `one font and size everywhere: ${[...new Set(m.fonts)].join(" | ")}`);
assert.equal(m.padding[0], m.padding[1]);
assert.equal(m.padding[2], m.padding[3]);
});
test("the editor follows the console's light and dark themes", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
await input(s).fill("# Heading\n\nText");
const colours = (theme) =>
s.page.evaluate((th) => {
document.documentElement.setAttribute("data-theme", th);
const root = getComputedStyle(document.documentElement);
const probe = (value, prop = "color") => {
const el = document.createElement("span");
el.style[prop] = value;
document.body.appendChild(el);
const out = getComputedStyle(el)[prop];
el.remove();
return out;
};
const ta = document.querySelector("#notepad-editor .overtype-input");
const pv = document.querySelector("#notepad-editor .overtype-preview");
return {
ink: probe(root.getPropertyValue("--ink")),
accent: probe(root.getPropertyValue("--accent")),
panel: probe(root.getPropertyValue("--panel"), "backgroundColor"),
text: getComputedStyle(pv).color,
heading: getComputedStyle(pv.querySelector("h1")).color,
caret: getComputedStyle(ta).caretColor,
background: getComputedStyle(document.querySelector("#notepad-editor .overtype-wrapper")).backgroundColor,
};
}, theme);
const light = await colours("light");
const dark = await colours("dark");
for (const [name, c] of Object.entries({ light, dark })) {
assert.equal(c.text, c.ink, `${name}: text in the console's ink`);
assert.equal(c.heading, c.accent, `${name}: headings in the highlight colour`);
assert.equal(c.caret, c.accent, `${name}: the caret in the highlight colour`);
assert.equal(c.background, c.panel, `${name}: the editor on the panel colour`);
}
assert.notEqual(light.text, dark.text, "the two themes differ");
assert.notEqual(light.background, dark.background);
});
test("after edits anywhere, the styled layer matches a full redraw", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const block = "## Heading\n\nSome **bold** and a [link](https://example.com).\n\n- an item\n- another\n1. first\n2. second\n\n```js\nconst x = 1;\n```\n> quote\n";
saveNote(s.project, block.repeat(40));
await openNotepad(s);
await s.page.waitForFunction(() => document.querySelector("#notepad-editor .overtype-input").value.length > 1000);
// The layer on the page against one drawn from scratch from the same text.
const matches = () =>
s.page.evaluate(async () => {
const { withoutStyleAttrs } = await import("/notepad.js");
const ta = document.querySelector("#notepad-editor .overtype-input");
const pv = document.querySelector("#notepad-editor .overtype-preview");
const parser = ta.closest(".overtype-wrapper")._instance.constructor.MarkdownParser;
const fresh = document.createElement("div");
fresh.className = "overtype-preview";
// Parsed into an inert template, so nothing in it reaches the page.
const tpl = document.createElement("template");
tpl.innerHTML = withoutStyleAttrs(parser.parse(ta.value, -1, false, undefined, false));
fresh.append(tpl.content);
// OverType shades code fences in pairs, in order, after drawing
// (_applyCodeBlockBackgrounds): the fresh copy gets the same, so a stale
// mark left on the page shows as a difference.
const fences = fresh.querySelectorAll(".code-fence");
for (let i = 0; i < fences.length - 1; i += 2) {
for (const f of [fences[i], fences[i + 1]]) {
f.parentElement.classList.add("code-block-line");
f.style.display = "block";
}
}
// An emptied style or class attribute looks exactly like none.
const plain = (html) => html.replace(/ (style|class)=""/g, "");
return plain(pv.innerHTML) === plain(fresh.innerHTML);
});
const at = (pos) =>
s.page.evaluate((p) => {
const ta = document.querySelector("#notepad-editor .overtype-input");
const i = p < 0 ? ta.value.length + p : p;
ta.focus();
ta.setSelectionRange(i, i);
}, pos);
await at(0);
await s.page.keyboard.type("# A new first line\n");
assert.ok(await matches(), "typing at the top");
await at(600);
await s.page.keyboard.type("\n- a list item added in the middle\n[another link](https://example.org) ");
assert.ok(await matches(), "typing in the middle, adding a link before others");
await at(900);
for (let i = 0; i < 30; i++) await s.page.keyboard.press("Backspace");
assert.ok(await matches(), "deleting across lines");
await at(-5);
await s.page.keyboard.type("\n```\nopen fence at the end");
assert.ok(await matches(), "an unclosed fence at the end");
await s.page.keyboard.press("Control+a");
await s.page.keyboard.press("Backspace");
assert.ok(await matches(), "clearing it all");
await s.page.keyboard.type("# Back again");
assert.ok(await matches(), "typing into the empty note");
// Four fences, two shaded blocks; deleting the first fence leaves three, and
// the last one, kept from the drawing before, is no longer paired.
// Ending on the last fence, so its line is the one kept unchanged.
await s.page.keyboard.type("\n```\ncode\n```\ntext\n```\nmore\n```");
assert.ok(await matches(), "two fenced blocks");
const firstFence = await s.page.evaluate(() => document.querySelector("#notepad-editor .overtype-input").value.indexOf("```"));
await at(firstFence + 4);
for (let i = 0; i < 4; i++) await s.page.keyboard.press("Backspace");
assert.ok(await matches(), "the first fence deleted, unpairing the last");
});
test("a note that cannot be read leaves the editor read-only, and nothing typed reaches the stored note", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
saveNote(s.project, "The real note");
await s.page.route("**/notepad", (route) => (route.request().method() === "GET" ? route.abort() : route.continue()));
await openNotepad(s, { loads: false });
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent === want, NOT_LOADED);
assert.equal(await input(s).evaluate((el) => el.readOnly), true);
await input(s).focus();
await s.page.keyboard.type("typed into the empty editor");
assert.equal(await input(s).inputValue(), "", "nothing could be typed");
await s.page.waitForTimeout(SAVE_DEBOUNCE_MS + 400);
assert.equal(onDisk(s), "The real note");
// Once it can be read, reopening loads it and the editor opens up.
await s.page.unroute("**/notepad");
await closeNotepad(s);
await openNotepad(s);
assert.equal(await shows(s, "The real note"), "The real note");
});
test("a note too long to save keeps its text when the notepad is closed and opened again", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
saveNote(s.project, "Saved earlier");
await openNotepad(s);
await shows(s, "Saved earlier");
const long = "x".repeat(NOTE_MAX_BYTES) + " and some more";
await input(s).fill(long);
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent.startsWith("Too long to save"));
await closeNotepad(s);
await openNotepad(s);
await s.page.waitForTimeout(300);
assert.equal((await input(s).inputValue()).length, long.length, "the long text is still in the editor");
assert.equal(onDisk(s), "Saved earlier", "and nothing over the cap was saved");
});
/* ------------------------------------------------------------ pictures */
// The stored pictures for the session's folder, and whether each of a
// picture's two files is on disk.
const stored = (s) => readNotepad(s.project).images;
const filesOf = (s, id) => {
const dir = path.join(notepadFolder(s.project), "images");
return [fs.existsSync(path.join(dir, id + ".jpg")), fs.existsSync(path.join(dir, id + ".thumb.jpg"))];
};
const thumbs = (s) => s.page.locator("#notepad-strip > li");
const readyCount = (s, n) =>
s.page.waitForFunction((want) => document.querySelectorAll("#notepad-strip > li.is-ready").length === want, n, { timeout: 5000 });
// A small PNG drawn in the page, as base64: a real picture for reencode() to
// decode, one colour per call so the pictures differ.
const pngBase64 = (s, colour) =>
s.page.evaluate(async (fill) => {
const c = document.createElement("canvas");
c.width = 320;
c.height = 200;
const ctx = c.getContext("2d");
ctx.fillStyle = fill;
ctx.fillRect(0, 0, 320, 200);
const blob = await new Promise((resolve) => c.toBlob(resolve, "image/png"));
let bin = "";
for (const b of new Uint8Array(await blob.arrayBuffer())) bin += String.fromCharCode(b);
return btoa(bin);
}, colour);
const pngFile = async (s, colour, name = "shot.png") => ({ name, mimeType: "image/png", buffer: Buffer.from(await pngBase64(s, colour), "base64") });
async function addViaButton(s, colour) {
const before = stored(s).length;
await s.page.setInputFiles("#notepad-file", await pngFile(s, colour));
await until(() => stored(s).length === before + 1 && filesOf(s, stored(s).at(-1).id).every(Boolean), 5000);
await readyCount(s, before + 1);
}
// A synthetic paste or drop of one PNG, sent to the editor, where a person's
// would land. A paste answers whether the page took it from the editor, a
// drop whether the dialog lit up while it was dragged over.
const sendPicture = (s, kind, colour) =>
s.page.evaluate(
async ({ kind, fill }) => {
const c = document.createElement("canvas");
c.width = 240;
c.height = 160;
const ctx = c.getContext("2d");
ctx.fillStyle = fill;
ctx.fillRect(0, 0, 240, 160);
const blob = await new Promise((resolve) => c.toBlob(resolve, "image/png"));
const dt = new DataTransfer();
dt.items.add(new File([blob], "pasted.png", { type: "image/png" }));
const ta = document.querySelector("#notepad-editor .overtype-input");
if (kind === "paste") return !ta.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true }));
ta.dispatchEvent(new DragEvent("dragover", { dataTransfer: dt, bubbles: true, cancelable: true }));
const lit = document.getElementById("notepad-modal").classList.contains("is-drop");
ta.dispatchEvent(new DragEvent("drop", { dataTransfer: dt, bubbles: true, cancelable: true }));
return lit;
},
{ kind, fill: colour },
);
test("Add image, paste and drop each add a thumbnail whose files are on disk and which survives closing", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
assert.equal(await thumbs(s).count(), 0);
await addViaButton(s, "#c33");
assert.equal(await sendPicture(s, "paste", "#3c3"), true, "the paste was taken from the editor");
await until(() => stored(s).length === 2 && filesOf(s, stored(s)[1].id).every(Boolean), 5000);
assert.equal(await sendPicture(s, "drop", "#33c"), true, "the dialog lit up while a picture was dragged over it");
await until(() => stored(s).length === 3 && filesOf(s, stored(s)[2].id).every(Boolean), 5000);
await readyCount(s, 3);
assert.equal(await s.page.locator("#notepad-modal.is-drop").count(), 0, "the highlight is gone after the drop");
assert.equal(await input(s).inputValue(), "", "no picture landed in the text");
const alts = await s.page.locator("#notepad-strip img").evaluateAll((imgs) => imgs.map((i) => i.alt));
assert.deepEqual(alts, ["Notepad image 1", "Notepad image 2", "Notepad image 3"]);
const xs = await s.page.locator("#notepad-strip .notepad-thumb-delete").evaluateAll((b) => b.map((x) => x.getAttribute("aria-label")));
assert.deepEqual(xs, ["Delete image 1", "Delete image 2", "Delete image 3"]);
// Closed and opened again, the strip is drawn from the stored pictures,
// oldest first, each from its stored thumbnail.
const ids = stored(s).map((img) => img.id);
await closeNotepad(s);
await openNotepad(s);
// Until the re-read lands, the strip still shows the thumbnails made here.
await s.page.waitForFunction(() => {
const imgs = [...document.querySelectorAll("#notepad-strip img")];
return imgs.length === 3 && imgs.every((i) => new URL(i.src).pathname.startsWith("/notepad/images/"));
});
const srcs = await s.page.locator("#notepad-strip img").evaluateAll((imgs) => imgs.map((i) => new URL(i.src).pathname));
assert.deepEqual(srcs, ids.map((id) => `/notepad/images/${id}.thumb.jpg`));
await s.page.waitForFunction(() => [...document.querySelectorAll("#notepad-strip img")].every((i) => i.complete && i.naturalWidth > 0));
});
test("a pasted text snippet still lands in the editor", 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 });
await openNotepad(s);
await s.page.evaluate(() => navigator.clipboard.writeText("a pasted snippet"));
await input(s).focus();
await s.page.keyboard.press("Control+V");
await shows(s, "a pasted snippet");
await until(() => onDisk(s) === "a pasted snippet", 4000);
assert.equal(stored(s).length, 0, "no picture was added");
assert.equal(await thumbs(s).count(), 0);
});
test("the X asks first: Keep keeps the picture, Delete removes both its files", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
await addViaButton(s, "#c33");
await addViaButton(s, "#3c3");
const [first, second] = stored(s).map((img) => img.id);
await s.page.click("#notepad-strip li:nth-child(1) .notepad-thumb-delete");
await s.page.locator(".notepad-ask").waitFor();
assert.match(await s.page.locator(".notepad-ask").innerText(), /Delete this image\?/);
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Keep", "Keep has the focus");
assert.deepEqual(filesOf(s, first), [true, true], "one click deleted nothing");
// Enter on the focused button keeps it.
await s.page.keyboard.press("Enter");
await s.page.waitForFunction(() => !document.querySelector(".notepad-ask"));
await readyCount(s, 2);
assert.deepEqual(filesOf(s, first), [true, true]);
await s.page.click("#notepad-strip li:nth-child(1) .notepad-thumb-delete");
await s.page.click(".notepad-ask-delete");
await until(() => !filesOf(s, first).some(Boolean), 4000);
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
assert.deepEqual(stored(s).map((img) => img.id), [second]);
assert.equal(await s.page.locator("#notepad-strip img").getAttribute("alt"), "Notepad image 1");
});
test("the preview opens at the clicked picture, steps and wraps, and Esc closes it before the Notepad", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
for (const colour of ["#c33", "#3c3", "#33c"]) await addViaButton(s, colour);
const urls = stored(s).map((img) => img.url);
const shown = () =>
s.page.evaluate(() => ({
src: new URL(document.getElementById("notepad-preview-img").src).pathname,
count: document.getElementById("notepad-preview-count").textContent,
}));
await s.page.click("#notepad-strip li:nth-child(2) .notepad-thumb-open");
await s.page.locator("#notepad-preview[open]").waitFor();
assert.deepEqual(await shown(), { src: urls[1], count: "2 of 3" });
await s.page.waitForFunction(() => {
const i = document.getElementById("notepad-preview-img");
return i.complete && i.naturalWidth > 0;
});
await s.page.keyboard.press("ArrowRight");
assert.deepEqual(await shown(), { src: urls[2], count: "3 of 3" });
await s.page.keyboard.press("ArrowRight");
assert.deepEqual(await shown(), { src: urls[0], count: "1 of 3" }, "Next wraps to the first");
await s.page.keyboard.press("ArrowLeft");
assert.deepEqual(await shown(), { src: urls[2], count: "3 of 3" }, "Previous wraps to the last");
await s.page.click("#notepad-preview-prev");
assert.deepEqual(await shown(), { src: urls[1], count: "2 of 3" });
await s.page.click("#notepad-preview-next");
assert.deepEqual(await shown(), { src: urls[2], count: "3 of 3" });
await s.page.keyboard.press("Escape");
await s.page.waitForFunction(() => !document.getElementById("notepad-preview").open);
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-modal").open), true, "the Notepad stays open");
assert.equal(
await s.page.evaluate(() => document.activeElement.closest("li") === document.querySelector("#notepad-strip li:nth-child(2)")),
true,
"the focus is back on the thumbnail it opened from",
);
await s.page.keyboard.press("Escape");
await s.page.waitForFunction(() => !document.getElementById("notepad-modal").open);
// One picture: nothing to step to.
for (const id of stored(s).slice(1).map((img) => img.id)) removeImage(s.project, id);
await openNotepad(s);
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
await s.page.click("#notepad-strip .notepad-thumb-open");
await s.page.locator("#notepad-preview[open]").waitFor();
assert.equal(await s.page.locator("#notepad-preview-prev").isVisible(), false);
assert.equal(await s.page.locator("#notepad-preview-next").isVisible(), false);
assert.equal(await s.page.locator("#notepad-preview-count").innerText(), "1 of 1");
});
test("past the cap, what fits is added and the cap sentence stays up; the 201st alone is refused", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
// The store checks only the JPEG signature, so a stub stands in for 199.
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 0xff, 0xd9]);
for (let i = 0; i < NOTEPAD_MAX_IMAGES - 1; i++) addImage(s.project, jpeg);
await openNotepad(s);
await s.page.waitForFunction((n) => document.querySelectorAll("#notepad-strip > li").length === n, NOTEPAD_MAX_IMAGES - 1);
const status = () => s.page.locator("#notepad-status").textContent();
// Two for one place: the first lands, and the sentence outlives its upload.
await s.page.setInputFiles("#notepad-file", [await pngFile(s, "#c33", "fits.png"), await pngFile(s, "#3c3", "too-many.png")]);
await until(() => stored(s).length === NOTEPAD_MAX_IMAGES && filesOf(s, stored(s).at(-1).id).every(Boolean), 5000);
await s.page.waitForFunction((n) => document.querySelectorAll("#notepad-strip > li.is-ready").length === n, NOTEPAD_MAX_IMAGES);
assert.ok((await status()).includes(errorSentence("too-many")), `still says the cap: "${await status()}"`);
await s.page.setInputFiles("#notepad-file", await pngFile(s, "#33c", "one-more.png"));
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence("too-many"));
assert.equal(await thumbs(s).count(), NOTEPAD_MAX_IMAGES);
assert.equal(stored(s).length, NOTEPAD_MAX_IMAGES);
});
const isPath = (want) => (url) => url.pathname === want;
test("a failed upload shows Retry, which sends only what did not land and keeps the focus on the thumbnail", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
// The picture lands, its thumbnail does not.
await s.page.route(isPath("/notepad/thumb"), (route) => route.abort(), { times: 1 });
await s.page.setInputFiles("#notepad-file", await pngFile(s, "#c33"));
await s.page.locator("#notepad-strip li.is-failed .notepad-retry").waitFor();
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence(null));
assert.equal(stored(s).length, 1);
const { id } = stored(s)[0];
assert.deepEqual(filesOf(s, id), [true, false]);
await s.page.locator(".notepad-retry").focus();
await s.page.keyboard.press("Enter");
await readyCount(s, 1);
await until(() => filesOf(s, id).every(Boolean), 4000);
assert.deepEqual(stored(s).map((img) => img.id), [id], "Retry did not store the picture twice");
assert.equal(await s.page.evaluate(() => Boolean(document.activeElement.closest("#notepad-strip li"))), true, "the focus stayed on the thumbnail");
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent === "", null, { timeout: 4000 });
// A picture the server turned away for good is taken off, with why.
await s.page.route(isPath("/notepad/image"), (route) => route.fulfill({ status: 413, contentType: "application/json", body: '{"error":"too-large"}' }), { times: 1 });
await s.page.setInputFiles("#notepad-file", await pngFile(s, "#3c3"));
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence("too-large"));
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
assert.equal(stored(s).length, 1);
});
test("a delete that fails keeps the thumbnail and says why", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openNotepad(s);
await addViaButton(s, "#c33");
const { id } = stored(s)[0];
await s.page.route(isPath("/notepad/image/delete"), (route) => route.abort(), { times: 1 });
await s.page.click("#notepad-strip .notepad-thumb-delete");
await s.page.click(".notepad-ask-delete");
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence(null));
await s.page.waitForFunction(() => !document.querySelector(".notepad-ask"));
assert.equal(await thumbs(s).count(), 1);
assert.deepEqual(filesOf(s, id), [true, true]);
assert.equal(await s.page.evaluate(() => document.activeElement.getAttribute("aria-label")), "Delete image 1", "the focus is back on the X");
});
/* ------------------------------------------------- Cleanup, phone, Help */
// Every file and folder under `dir`, and `dir` itself, moved `days` back.
function backdateAll(dir, days) {
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
const p = path.join(dir, e.name);
if (e.isDirectory()) backdateAll(p, days);
else backdate(p, days);
}
backdate(dir, days);
}
test("User Preferences, Cleanup offers a month-old notepad by its folder and removes it", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
saveNote(s.project, "an old idea");
backdateAll(notepadFolder(s.project), 31);
// Here the notepads folder sits in the console home (NOTEPADS_DIR), where
// Cleanup would list it as a stray once everything in it is old; a notepad
// written today keeps it in use, as the real ~/.plan2code/notepads is never
// inside the console folder.
const other = path.join(s.project, "elsewhere");
saveNote(other, "today");
t.after(() => fs.rmSync(notepadFolder(other), { recursive: true, force: true }));
await s.page.click("#btn-looks");
await s.page.click("#cleanup-scan");
const list = s.page.locator("#cleanup-list");
const row = list.locator(".cleanup-row").filter({ hasText: "Notepad for" });
await row.waitFor();
assert.equal(await row.count(), 1, "one item for the whole notepad");
assert.equal((await row.locator("span").first().innerText()).trim(), "Notepad for " + path.resolve(s.project));
assert.ok((await list.locator(".cleanup-summary").innerText()).includes("1 old notepad"), "the summary counts it as a notepad");
assert.equal(await list.locator(".cleanup-row").filter({ hasText: "notepads/" }).count(), 0, "the notepads folder is no stray");
assert.equal(fs.existsSync(notepadFolder(s.project)), true, "a scan only looks");
await s.page.click("#cleanup-delete");
await s.page.waitForFunction(() => /^Deleted /.test(document.getElementById("cleanup-status").textContent));
assert.equal(fs.existsSync(notepadFolder(s.project)), false, "the whole notepad folder went");
assert.equal(readNotepad(s.project).text, "");
assert.ok(!fs.readdirSync(path.dirname(notepadFolder(s.project))).includes(notepadKey(s.project)));
});
test("the notepad works at phone width: full screen, nothing wider than the window, fingertip-sized controls", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.setViewportSize({ width: 390, height: 844 });
const noSideScroll = async (where) => {
const { sw, iw } = await s.page.evaluate(() => ({ sw: document.documentElement.scrollWidth, iw: window.innerWidth }));
assert.ok(sw <= iw, `${where}: the page is ${sw}px wide in a ${iw}px window`);
};
const box = (sel) => s.page.locator(sel).first().boundingBox();
await noSideScroll("the session");
assert.ok((await box("#btn-notepad")).width >= 44, "the icon is a fingertip wide");
await openNotepad(s);
await addViaButton(s, "#c33");
await noSideScroll("the notepad");
const modal = await box("#notepad-modal");
assert.deepEqual([modal.x, modal.y, modal.width, modal.height], [0, 0, 390, 844], "the notepad fills the screen");
const inner = await s.page.$eval("#notepad-modal", (m) => ({ sw: m.scrollWidth, cw: m.clientWidth }));
assert.ok(inner.sw <= inner.cw, `the dialog scrolls sideways: ${inner.sw} > ${inner.cw}`);
for (const sel of ["#notepad-add", "#notepad-close"]) assert.ok((await box(sel)).height >= 44, `${sel} is a fingertip tall`);
const x = await box(".notepad-thumb-delete");
assert.ok(x.width >= 30 && x.height >= 30, "the X is big enough to tap");
const strip = await box("#notepad-strip");
assert.ok(strip.width > 300, "the pictures get the full width under Add image");
await s.page.click(".notepad-thumb-open");
await s.page.locator("#notepad-preview[open]").waitFor();
await noSideScroll("the preview");
const img = await box("#notepad-preview-img");
assert.ok(img.x >= 0 && img.x + img.width <= 390, "the picture fits the window");
assert.ok((await box("#notepad-preview-close")).height >= 44);
});
test("Help's Getting around panel describes the notepad", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.click("#btn-about");
await s.page.locator("#help-modal").waitFor();
await s.page.click("#help-tab-around");
const panel = s.page.locator("#help-panel-around");
await panel.getByRole("heading", { name: "Your notepad" }).waitFor();
const text = await panel.innerText();
for (const words of ["Notepad", "never sent to Plan2Code", "last save wins", "Cleanup"]) {
assert.ok(text.includes(words), `the panel mentions ${words}`);
}
});
+44
View File
@@ -485,6 +485,50 @@ test("the top bar's back triangle asks first, then sends __dashboard with the ty
await s.page.waitForFunction(() => document.getElementById("btn-home").disabled);
});
// What a person sees break: Commit it now, or Changelog's commit offer, hops
// into Git without the dashboard, and the board opens over the last skill's
// staged answer, its selected question and its open tab.
test("a hop into Git from another skill starts the page clean: nothing staged, nothing selected, the questions view", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "changelog",
payload: {
items: [{ id: "q1", kind: "choice", title: "Which version", body: "The next version number.",
options: [{ k: "A", text: "A patch release" }, { k: "B", text: "A minor release" }] }],
docs: [{ id: "notes", title: "Release notes", blocks: [{ id: "b1", md: "## Draft\n\nTwo fixes." }] }],
agent: { status: "waiting" },
},
});
// The page's own state, from the module app.js loaded (same URL, same instance).
const local = () =>
s.page.evaluate(async () => {
const { page } = await import("/state.js");
return { workflow: page.S.workflow, staged: page.local.staged, selected: page.selected, view: page.view };
});
await itemCard(s.page, "q1").getByText("A minor release").click();
await s.page.locator(".view-tab", { hasText: "Release notes" }).click();
const before = await local();
assert.deepEqual(Object.keys(before.staged), ["q1"], "the answer was never staged");
assert.equal(before.selected, "q1");
assert.notEqual(before.view, "questions", "the Release notes tab never opened");
const draftFile = path.join(s.session, "draft.json");
assert.ok(await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes('"q1"'), 5000), "the staged answer never reached the draft");
// What Commit it now and Changelog's commit offer run.
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "git"], { cwd: s.project });
await s.page.waitForFunction(async () => (await import("/state.js")).page.S.workflow === "git", null, { timeout: 10000 });
// Long enough for the page's draft push (600 ms after a save) to have run.
await new Promise((r) => setTimeout(r, 1500));
const after = await local();
assert.deepEqual(after.staged, {}, `the page kept the last skill's staged answer: ${JSON.stringify(after.staged)}`);
assert.equal(after.selected, null, `the page kept the last skill's selection: ${after.selected}`);
assert.equal(after.view, "questions", `the page kept the last skill's tab: ${after.view}`);
const stored = await s.page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "{}").staged || {}, `p2c-console:${s.sid}`);
assert.deepEqual(stored, {}, "the browser's copy kept the staged answer");
const draft = fs.existsSync(draftFile) ? JSON.parse(fs.readFileSync(draftFile, "utf8")) : {};
assert.deepEqual(draft.staged || {}, {}, "the server's draft kept the staged answer");
});
// 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 });
+1
View File
@@ -186,6 +186,7 @@ test("shape: no page module sets a style attribute from script", () => {
const ROUTE_ORDER = [
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/images/",
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
];
+137 -2
View File
@@ -14,8 +14,10 @@ import {
subagentsFor,
takesTemplates,
labelFor,
WORKFLOWS,
isWorkflow,
} 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 { CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, 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";
@@ -106,6 +108,27 @@ test("the entries are frozen data", () => {
}
});
test("the meter, resume and Help fields are well formed on every entry", () => {
const label = (v) => v === null || (typeof v === "string" && v.trim() !== "");
for (const s of SKILLS) {
const w = s.workflow;
assert.ok(Object.hasOwn(s, "weight") && (s.weight === null || (typeof s.weight === "number" && s.weight >= 0)), `${w}: weight is a number >= 0, or null`);
assert.ok(Object.hasOwn(s, "started") && label(s.started), `${w}: started is a label, or null`);
assert.ok(Object.hasOwn(s, "ran") && label(s.ran), `${w}: ran is a label, or null`);
assert.ok(Object.hasOwn(s, "resume") && ["overview", "folder", null].includes(s.resume), `${w}: resume is "overview", "folder" or null`);
if (s.card && Object.hasOwn(s.card, "help")) assert.ok(typeof s.card.help === "string" && s.card.help.trim(), `${w}: card.help is a line, or absent`);
if (s.metered) assert.ok(typeof s.weight === "number" && s.started, `${w}: a metered launch has a weight and a started label`);
}
});
test("WORKFLOWS lists every entry once, in order, and isWorkflow() knows only those", () => {
assert.deepEqual(WORKFLOWS, SKILLS.map((s) => s.workflow));
assert.equal(new Set(WORKFLOWS).size, WORKFLOWS.length);
assert.ok(Object.isFrozen(WORKFLOWS));
for (const w of WORKFLOWS) assert.equal(isWorkflow(w), true, w);
for (const bad of ["x-ray", "", undefined, null, 3, "Plan"]) assert.equal(isWorkflow(bad), false, String(bad));
});
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");
@@ -159,7 +182,8 @@ function helpProblems(skills, topics) {
// 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);
const reviews = skills.map((s) => s.review).filter(Boolean);
const named = skills.filter((s) => s.card || s.workflow === "dashboard" || reviews.includes(s.skill)).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`),
@@ -245,3 +269,114 @@ test("starting screen: the hint stays calm for ninety seconds, then points at th
assert.match(startingHint(90000), /fills in by itself/, "ninety seconds is still calm");
assert.match(startingHint(90001), /terminal has the play-by-play/);
});
/* ---------------------------------------------- the docs held to the list */
// What one prose list says against what it should say: the lines naming the
// missing and the extra names, empty when they agree.
function listProblems(file, said, want) {
const have = new Set(said);
const should = new Set(want);
return [
...[...should].filter((n) => !have.has(n)).map((n) => `${file} is missing ${n}`),
...[...have].filter((n) => !should.has(n)).map((n) => `${file} names ${n}, which is not in skills.js`),
];
}
const readSrc = (...parts) => fs.readFileSync(path.join(ROOT, "src", ...parts), "utf8");
// A markdown section's text: from its heading to the next heading of the same level.
function sectionOf(text, heading) {
const at = text.indexOf(heading);
assert.ok(at >= 0, `no "${heading}" heading`);
const level = heading.match(/^#+/)[0];
const rest = text.slice(at + heading.length);
const next = rest.search(new RegExp(`\\n${level} `));
return next < 0 ? rest : rest.slice(0, next);
}
test("docs: console.md's open step names every workflow", () => {
const text = readSrc("web-console", "console.md");
const m = text.match(/where `<w>` is one of ([\s\S]*?)\. Get it right/);
assert.ok(m, "console.md: the open step's `<w>` sentence is not where the test looks");
const said = [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]);
assert.deepEqual(listProblems("src/web-console/console.md", said, WORKFLOWS), []);
});
test("docs: the dashboard skill's launch table maps every skill to its workflow", () => {
const section = sectionOf(readSrc("plan2code.md"), "## A pick arrives");
const pairs = [];
for (const line of section.split(/\r?\n/)) {
if (!/^\|\s*plan2code-/.test(line)) continue;
const cells = line.split("|").map((c) => c.trim()).filter(Boolean);
for (let i = 0; i + 1 < cells.length; i += 2) pairs.push(`${cells[i]} -> ${cells[i + 1]}`);
}
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => `${s.skill} -> ${s.workflow}`);
assert.deepEqual(listProblems("src/plan2code.md (A pick arrives)", pairs, want), []);
});
test("docs: the dashboard skill's reads-and-writes table has a row for every skill", () => {
const section = sectionOf(readSrc("plan2code.md"), "## What each skill reads and writes");
const said = [];
for (const line of section.split(/\r?\n/)) {
const m = line.match(/^\|\s*([a-z0-9()-]+)\s*\|/);
if (!m || m[1] === "skill" || /^-+$/.test(m[1])) continue;
// `3-implement(-review)` stands for both build skills.
if (m[1] === "3-implement(-review)") said.push("3-implement", "3-implement-review");
else said.push(m[1]);
}
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => s.skill.replace(/^plan2code-/, ""));
assert.deepEqual(listProblems("src/plan2code.md (What each skill reads and writes)", said, want), []);
});
test("docs: `console.mjs help` lists every workflow, in order", () => {
const out = cli(["help"]).stdout;
const m = out.match(/workflows: ([\s\S]*?)\n\s*\n/);
assert.ok(m, "console.mjs help prints no workflows: list");
const said = m[1].split(/[·\s]+/).filter(Boolean);
assert.deepEqual(listProblems("console.mjs help", said, WORKFLOWS), []);
assert.deepEqual(said, [...WORKFLOWS], "console.mjs help: the workflows are in skills.js order");
});
// A count goes stale the day a skill is added; the docs say "every skill".
// Matched over the whole file, since the docs are hard-wrapped and a count can
// sit on one line with "skills" on the next; the line is where the match starts.
const SKILL_COUNT_RE = /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\s+skills\b/gi;
function skillCounts(files) {
return files.flatMap(([file, text]) =>
[...text.matchAll(SKILL_COUNT_RE)].map((m) => `${file}:${text.slice(0, m.index).split("\n").length} states a skill count: ${m[0].replace(/\s+/g, " ")}`)
);
}
test("docs: no console doc states how many skills there are", () => {
const dir = path.join(ROOT, "src", "web-console");
const files = [];
const walk = (d) => {
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
const p = path.join(d, e.name);
if (e.isDirectory()) walk(p);
else if (e.name.endsWith(".md")) files.push([path.relative(ROOT, p).replace(/\\/g, "/"), fs.readFileSync(p, "utf8")]);
}
};
walk(dir);
assert.ok(files.some(([f]) => f.endsWith("notes/implement.md")), "the walk reaches notes/");
assert.deepEqual(skillCounts(files), []);
// The check names the line, and catches a count wrapped across two lines.
assert.deepEqual(skillCounts([["x.md", "Intro\nthe dashboard and all twelve skills behind it\n"]]), ["x.md:2 states a skill count: twelve skills"]);
assert.deepEqual(skillCounts([["y.md", "Intro\nthe dashboard and all twelve\nskills behind it\n"]]), ["y.md:2 states a skill count: twelve skills"]);
});
test("Implement's card launches Implement + Review when Review is ticked", () => {
const card = SKILL_CATALOG.find((e) => e.skill === "plan2code-3-implement");
assert.equal(card.title, "Implement");
assert.equal(SKILL_CATALOG.some((e) => e.skill === "plan2code-3-implement-review"), false, "no card of its own");
assert.equal(launchVariant(card, false), card);
const reviewed = launchVariant(card, true);
assert.equal(reviewed.skill, "plan2code-3-implement-review");
assert.equal(reviewed.workflow, "implement-review");
assert.equal(reviewed.command, "/plan2code-3-implement-review");
assert.equal(reviewed.spec, true, "still takes the picked spec");
assert.equal(catalogEntry("plan2code-3-implement-review").skill, "plan2code-3-implement", "handoffs and recommendations resolve to the card");
const quick = SKILL_CATALOG.find((e) => e.skill === "plan2code-quick-task");
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
});
+93 -5
View File
@@ -10,8 +10,69 @@ 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 { SKILL_CATALOG, cardAvailability, defaultSpec, launchVariant } from "../src/web-console/public/answers.js";
import { scanProject } from "../src/web-console/scan.mjs";
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks } from "../src/web-console/spec-files.mjs";
// The task pattern specs.mjs used before spec-files.mjs: TASK_ID_RE must take
// a `-` task line apart into the same groups.
const OLD_TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
test("spec files: every marker names its state, and the table is frozen", () => {
assert.deepEqual(MARKERS, { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" });
assert.ok(Object.isFrozen(MARKERS));
});
test("spec files: -, * and numbered task lines all match, and TASK_ID_RE keeps the old groups", () => {
for (const line of ["- [ ] **Task 1.2:** Do it", "* [x] **Task 1.2:** Do it", "1. [/] **Task 1.2:** Do it", " 12. [?] **Task 3.4:** Do it"]) {
assert.ok(TASK_LINE_RE.test(line), `TASK_LINE_RE matches ${line}`);
assert.ok(TASK_ID_RE.test(line), `TASK_ID_RE matches ${line}`);
assert.ok(CHECKBOX_RE.test(line), `CHECKBOX_RE matches ${line}`);
}
assert.ok(!TASK_LINE_RE.test("- [ ] Acceptance: it works"), "a plain checkbox is no task line");
// A line TASK_ID_RE cannot take apart is no task line for the scan either.
for (const line of ["- [x] **task 1.1:** Lowercase", "- [x] **Task 1.1:** Two spaces"]) {
assert.ok(!TASK_ID_RE.test(line) && !TASK_LINE_RE.test(line), `neither pattern takes ${line}`);
}
assert.ok(CHECKBOX_RE.test("- [ ] Acceptance: it works"), "but it is a checkbox");
for (const line of ["- [x] **Task 2.3:** Build it", "- [ ] **Task 1.B:** Name it", "- [/] **Task 4.2a:** Split it"]) {
assert.deepEqual([...line.match(TASK_ID_RE)], [...line.match(OLD_TASK_RE)], `the same groups for ${line}`);
}
assert.deepEqual("1. [x] **Task 2.3:** Build it".match(TASK_ID_RE).slice(1), ["x", "2", "3", ""], "a numbered line's groups");
});
test("spec files: statusOf() reads every Status form, LF or CRLF, and is null without one", () => {
const forms = { "**Status:** Complete": "Complete", "**Status**: In Progress": "In Progress", "Status: Not Started": "Not Started" };
for (const [line, value] of Object.entries(forms)) {
for (const eol of ["\n", "\r\n"]) {
const text = `# Phase 1${eol}${eol}${line}${eol}**Estimated Tasks:** 3${eol}`;
assert.equal(statusOf(text), value, `${line} with ${eol === "\n" ? "LF" : "CRLF"}`);
assert.equal(text.match(STATUS_RE)[1] + text.match(STATUS_RE)[2], line, "the prefix and value rebuild the line");
}
}
assert.equal(statusOf("# Phase 1\n\nNo status here.\n"), null);
assert.equal(statusOf(""), null);
assert.equal(statusOf(undefined), null);
});
test("spec files: countTasks() counts task lines only when there are any, every checkbox otherwise", () => {
const phase = [
"# Phase 1",
"- [x] **Task 1.1:** One",
"* [?] **Task 1.2:** Two",
"1. [ ] **Task 1.3:** Three",
"- [/] **Task 1.4:** Four",
"- [!] **Task 1.5:** Five",
"- [~] **Task 1.6:** An unknown marker",
"## Acceptance Criteria",
"- [ ] It works",
"- [x] It is fast",
].join("\r\n");
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, total: 5 });
const older = "# Phase 1\n\n- [x] Make it\n- [ ] Ship it\n- [?] Check it\n";
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, total: 3 });
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, total: 0 });
});
// 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.
@@ -252,6 +313,9 @@ const CARDS = {
},
};
// Implement's card also launches Implement + Review, which has the same rules.
const CARD_ENTRIES = SKILL_CATALOG.flatMap((e) => (e.review ? [e, launchVariant(e, true)] : [e]));
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." }],
@@ -265,8 +329,8 @@ const SCAN_CASES = [
];
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) {
assert.deepEqual(CARD_ENTRIES.map((e) => e.skill), Object.keys(CARDS), "one row per card, in card order");
for (const entry of CARD_ENTRIES) {
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}`);
@@ -275,7 +339,7 @@ test("card rules: every card gives the same answer for every spec state as befor
});
test("card rules: a state the table does not know is treated like files on disk", () => {
for (const entry of SKILL_CATALOG) {
for (const entry of CARD_ENTRIES) {
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`);
}
@@ -303,7 +367,7 @@ test("finished: any finished state is never the picker's default, not only fixed
// 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) {
for (const entry of CARD_ENTRIES) {
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`);
}
@@ -354,6 +418,30 @@ test("the scan: every state it can return is in the table, and a fixture reaches
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
});
test("the scan: an assumed task counts as done and is named, and numbered task lines count", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-assumed-"));
const specs = {
mixed: "- [x] **Task 1.1:** One\n- [x] **Task 1.2:** Two\n- [?] **Task 1.3:** Three\n- [ ] **Task 1.4:** Four\n",
assumed: "- [?] **Task 1.1:** One\n- [?] **Task 1.2:** Two\n",
numbered: "1. [x] **Task 1.1:** One\n2. [ ] **Task 1.2:** Two\n3. [ ] **Task 1.3:** Three\n",
plain: "- [x] **Task 1.1:** One\n- [x] **Task 1.2:** Two\n",
};
try {
for (const [name, phase] of Object.entries(specs)) {
fs.mkdirSync(path.join(root, "specs", name), { recursive: true });
fs.writeFileSync(path.join(root, "specs", name, "overview.md"), "# Overview\n");
fs.writeFileSync(path.join(root, "specs", name, "phase-1.md"), "# Phase 1\n\n" + phase + "\n## Acceptance Criteria\n\n- [ ] It works\n");
}
const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp]));
assert.deepEqual([by.mixed.state, by.mixed.detail], ["building", "3 of 4 tasks done, 1 assumed"]);
assert.deepEqual([by.assumed.state, by.assumed.detail], ["built", "all tasks done, 2 assumed"]);
assert.deepEqual([by.numbered.state, by.numbered.detail], ["building", "1 of 3 tasks done"]);
assert.deepEqual([by.plain.state, by.plain.detail], ["built", "all tasks done"], "no assumed tasks, no \", 0 assumed\"");
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
// 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.
+90
View File
@@ -0,0 +1,90 @@
#!/usr/bin/env node
// Captures the CSS the vendored OverType would inject, as a real stylesheet.
// Dev-only: lives in scripts/ so it never ships inside a skill.
//
// node scripts/vendor-overtype.mjs
//
// The console's content-security policy (`style-src 'self'`) blocks the
// <style> OverType adds to the page, so the notepad sets
// `OverType.stylesInjected = true` and ships the same rules in
// src/web-console/public/styles/notepad.css instead. This script loads
// public/vendor/overtype.esm.js in a blank page, calls
// `OverType.injectStyles(true)` and writes what landed in
// `style.overtype-styles` between the header and the end marker below. The
// notepad's own rules, after the marker, are kept as they are. Run it again
// after upgrading the vendored file.
//
// Needs playwright-core (a root devDependency) and a local Chrome or Edge,
// launched through scripts/browser.mjs.
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { launchBrowser } from "./browser.mjs";
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const PUBLIC = path.join(ROOT, "src", "web-console", "public");
const VENDOR = path.join(PUBLIC, "vendor", "overtype.esm.js");
const OUT = path.join(PUBLIC, "styles", "notepad.css");
export const HEADER = "/* OverType 2.6.1 generated CSS: regenerate with node scripts/vendor-overtype.mjs */";
export const END_MARKER = "/* end OverType */";
// A made-up origin served from here, so the module loads as it does on the
// page: as a module, from a URL, with nothing else around it.
const ORIGIN = "http://overtype.invalid";
async function capture() {
const browser = await launchBrowser();
try {
const page = await browser.newPage();
await page.route(`${ORIGIN}/**`, (route) => {
const url = new URL(route.request().url());
if (url.pathname === "/overtype.esm.js") {
return route.fulfill({ contentType: "text/javascript", body: fs.readFileSync(VENDOR) });
}
return route.fulfill({ contentType: "text/html", body: "<!doctype html><title>OverType CSS</title>" });
});
await page.goto(`${ORIGIN}/`);
return await page.evaluate(async (src) => {
const { OverType } = await import(src);
OverType.injectStyles(true);
const style = document.querySelector("style.overtype-styles");
return style ? style.textContent : null;
}, `${ORIGIN}/overtype.esm.js`);
} finally {
await browser.close();
}
}
// The generated block, then whatever followed the marker before (the
// notepad's own rules), or nothing on a first run. A stylesheet with rules but
// no marker is refused: rewriting it would delete them.
export function assemble(css, existing) {
const at = existing.indexOf(END_MARKER);
if (at === -1 && existing.trim()) {
throw new Error(`notepad.css has no "${END_MARKER}" marker, so its own rules cannot be told apart: put the marker back, then run this again.`);
}
const own = at === -1 ? "" : existing.slice(at + END_MARKER.length);
const body = css.trim().split("\n").map((line) => line.replace(/\s+$/, "")).join("\n");
return `${HEADER}\n${body}\n${END_MARKER}${own || "\n"}`;
}
const css = await capture().catch((e) => {
console.error(e.browserProblem ? e.message : `Could not capture OverType's CSS: ${e.message}`);
process.exit(1);
});
if (!css) {
console.error("OverType injected no style.overtype-styles element.");
process.exit(1);
}
const existing = fs.existsSync(OUT) ? fs.readFileSync(OUT, "utf8") : "";
let out;
try {
out = assemble(css, existing);
} catch (e) {
console.error(e.message);
process.exit(1);
}
fs.writeFileSync(OUT, out);
console.log(`Wrote ${path.relative(ROOT, OUT)} (${css.length} characters of OverType CSS).`);
+6 -1
View File
@@ -31,6 +31,11 @@ export const MODELS_DIR = path.join(HOME, "plan2code");
// Handoffs are written outside every repo, under ~/.plan2code/handoffs, so
// each test file gets its own throwaway folder for them too.
export const HANDOFFS_DIR = path.join(HOME, "handoffs");
// Notepads likewise live under ~/.plan2code/notepads. Set here for this
// process too, so a test importing notepads.mjs directly never reaches the
// real folder (notepadsDir() reads the variable on every call).
export const NOTEPADS_DIR = path.join(HOME, "notepads");
process.env.PLAN2CODE_NOTEPADS_DIR = NOTEPADS_DIR;
// A spawned console server or CLI must not inherit relocation vars (an
// exported GIT_DIR would redirect the board's reads), SSH markers (they set
// `remote` in open output) or leftover PLAN2CODE_* knobs.
@@ -54,7 +59,7 @@ for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
// cannot open. An empty file is the portable "no global config".
const EMPTY_GITCONFIG = path.join(HOME, "empty-gitconfig");
fs.writeFileSync(EMPTY_GITCONFIG, "");
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NOTEPADS_DIR: NOTEPADS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
// Every server these tests start runs the release check at boot. A fresh
// cached failure keeps the whole suite off the network and bannerless.
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));