// Web console tests, favicon, update check, help and page-source pins. // Run with: node --test scripts/test-web-console-source.mjs // // Shared setup (a per-process console home, the CLI runner, fixtures) lives in // web-console-test-helpers.mjs; see the comment at its top. import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; // The page's pure answer-shaping logic. app.js itself cannot be imported here // (it touches `document` at module scope and starts a session on import), which // is exactly why this lives in its own file. import { cardAvailability, SKILL_CATALOG } from "../src/web-console/public/answers.js"; import { SKILLS } from "../src/web-console/public/skills.js"; import { HELP_TABS } from "../src/web-console/public/help.js"; import { PREFS_TABS } from "../src/web-console/public/prefs.js"; import { SERVABLE } from "../src/web-console/static.mjs"; import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js"; import { CACHE_MS, RELEASES_URL, REPO_URL, checkForUpdate, compareVersions, latestTag, } from "../src/web-console/update-check.mjs"; import { runHint } from "../src/web-console/public/render.js"; import { applyPatch } from "../src/web-console/patches.mjs"; import { ROOT, cli, helpTemplate, sessionUrl } from "./web-console-test-helpers.mjs"; import { joinedCss } from "./css-helpers.mjs"; test("favicon: the dot follows the status line -- busy, ready, attention, plain", () => { // Anything with the spinning ring is busy, even a finished screen opening the dashboard. assert.equal(faviconState({ mood: "work", spin: true }), "busy"); // Pointing is the person's move, a finished screen with a press on offer too. assert.equal(faviconState({ mood: "point" }), "ready"); // A working mood without the ring is the stale line; adrift (a finished // screen's stranded press among them) and gone need a look too. assert.equal(faviconState({ mood: "work" }), "attention"); assert.equal(faviconState({ mood: "adrift" }), "attention"); assert.equal(faviconState({ mood: "gone" }), "attention"); assert.equal(faviconState({ mood: "happy" }), "plain"); // All done or paused, nothing left to press. assert.equal(faviconState({ mood: "done" }), "plain"); assert.equal(faviconState(), "plain"); }); test("favicon: every variant is the served Planny plus a bottom bar, busy dashed and the rest solid", () => { const served = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "favicon.svg"), "utf8"); const squash = (s) => s.replace(/\s+/g, " ").trim(); assert.ok(squash(served).includes(squash(FAVICON_BODY)), "FAVICON_BODY is the drawing in public/favicon.svg"); assert.equal(squash(faviconSvg("plain")), squash(served), "plain is the served file"); for (const [state, color] of Object.entries(FAVICON_COLORS)) { const svg = faviconSvg(state); assert.ok(squash(svg).includes(squash(FAVICON_BODY)), state); assert.ok(svg.includes('y="27"'), `${state} has the bottom bar`); if (state === "busy") { // Dashed, not solid: pattern carries the difference as well as color. assert.ok(svg.includes(`stroke="${color}"`) && svg.includes("stroke-dasharray"), "busy is a dashed bar"); assert.ok(!svg.includes(`fill="${color}"`), "busy is never a solid bar"); } else { assert.ok(svg.includes(`fill="${color}"`), `${state} bar is solid ${color}`); assert.ok(!svg.includes("stroke-dasharray"), `${state} is not dashed`); } } assert.equal(new Set(Object.values(FAVICON_COLORS)).size, 3, "three distinct colors"); }); test("runHint: command words (git included) get the hint, the rest nothing", () => { assert.equal(runHint("git add -A && git commit -m \"x\""), "hint"); assert.equal(runHint("\n\ngit status\n"), "hint"); assert.equal(runHint("git"), "hint"); assert.equal(runHint("node install.js --build-skills"), "hint"); assert.equal(runHint("docker compose up"), "hint"); assert.equal(runHint("#!/bin/bash\necho hi"), "hint"); assert.equal(runHint("pws run.ps1"), null); assert.equal(runHint("/plan2code-3-implement specs/x/overview.md"), null); assert.equal(runHint("/plan2code"), null); assert.equal(runHint('{"a": 1}'), null); assert.equal(runHint("some prose, not a command"), null); assert.equal(runHint(""), null); assert.equal(runHint(null), null); // The first non-empty line decides: a git line after a blank one hints. assert.equal(runHint(" \ngit commit -m \"x\"\n"), "hint"); }); test("a reused item id does not inherit the previous answer's submitted record", async () => { const { applyPatch } = await import("../src/web-console/patches.mjs"); const before = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "open", submitted: { at: "t", text: "old answer" } }] }; const reworded = applyPatch(before, { items: [{ id: "q7", kind: "choice", title: "B", body: "new", status: "open" }] }); assert.equal(reworded.items[0].submitted, undefined); assert.equal(reworded.items[0].status, "open"); // Settling or threading the same question keeps the record. assert.ok(applyPatch(before, { items: [{ id: "q7", status: "answered", answer: { k: "A" } }] }).items[0].submitted); // A settled question with a typo fixed stays settled. const settled = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "answered", answer: { k: "A" }, submitted: { at: "t", k: "A" } }] }; const edited = applyPatch(settled, { items: [{ id: "q7", body: "old, fixed" }] }).items[0]; assert.deepEqual([edited.status, edited.answer, !!edited.submitted], ["answered", { k: "A" }, true]); assert.ok(applyPatch(before, { items: [{ id: "q7", thread: [{ who: "agent", text: "hi" }] }] }).items[0].submitted); // A settled id reused for a different kind of question opens as a new one, even with no status in the patch. const swapped = applyPatch(settled, { items: [{ id: "q7", kind: "confirm", title: "C", body: "new" }] }).items[0]; assert.deepEqual([swapped.status, swapped.answer, swapped.submitted], ["open", undefined, undefined]); }); test("unansweredChat lists delivered Quick questions that still have no reply", async () => { const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/inbox.mjs"); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-chat-")); appendChat(dir, { kind: "reset", conversation: 1, workflow: "dashboard", reason: "start" }); appendChat(dir, { kind: "message", conversation: 1, text: "run it" }); assert.deepEqual(unansweredChat(dir, {}), [], "not handed over yet, so not owed"); writeCursor(dir, 2); assert.deepEqual(unansweredChat(dir, {}), [2]); assert.deepEqual(unansweredChat(dir, { chat: { replies: [{ id: "r2", re: 2, conversation: 1, md: "done" }] } }), []); }); /* ------------------------------------------------------- update check */ const REPO_VERSION = JSON.parse(fs.readFileSync(path.join(ROOT, "version.json"), "utf8")).version; test("update check: compareVersions orders X.Y.Z numerically and refuses anything else", () => { assert.equal(compareVersions("2.4.3", "2.4.3"), 0); assert.equal(compareVersions("2.4.3", "2.5.0"), -1); assert.equal(compareVersions("3.0.0", "2.99.99"), 1); assert.equal(compareVersions("2.10.0", "2.9.9"), 1, "numeric, not string, order"); for (const bad of ["2.4", "v2.4.3", "", undefined, "2.4.3-rc1"]) { assert.equal(compareVersions(bad, "2.4.3"), null, String(bad)); assert.equal(compareVersions("2.4.3", bad), null, String(bad)); } }); test("update check: latestTag picks the highest vX.Y.Z, skipping peeled and non-release tags", () => { const out = [ "aaa\trefs/tags/v2.4.3", "bbb\trefs/tags/v2.4.3^{}", "ccc\trefs/tags/v2.10.0", "ddd\trefs/tags/v2.10.0^{}", "eee\trefs/tags/v2.9.9", "fff\trefs/tags/v3.0.0-rc1", "ggg\trefs/tags/release-4", "hhh\trefs/tags/v9.0.0^{}", ].join("\n"); assert.equal(latestTag(out), "2.10.0"); assert.equal(latestTag(out.replace(/\n/g, "\r\n")), "2.10.0", "CRLF output"); assert.equal(latestTag("fff\trefs/tags/v3.0.0-rc1\nggg\trefs/tags/release-4"), null); assert.equal(latestTag(""), null); assert.equal(latestTag(null), null); assert.equal(latestTag(42), null); }); test("update check: the cache is reused for an hour, failures included, and rebuilt when stale or corrupt", async () => { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-update-")); const cacheFile = path.join(dir, "nested", "update-check.json"); const now = 1_800_000_000_000; let calls = 0; const tags = (v) => async () => { calls++; return `abc\trefs/tags/v${v}\n`; }; const read = () => JSON.parse(fs.readFileSync(cacheFile, "utf8")); try { // No cache: asks, and writes what it found. assert.deepEqual(await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: tags("2.5.0") }), { installed: "2.4.3", latest: "2.5.0", updateAvailable: true, }); assert.equal(calls, 1); assert.deepEqual(read(), { checkedAt: now, latest: "2.5.0" }); // Fresh: the runner is not called. const fresh = await checkForUpdate({ installed: "2.4.3", cacheFile, now: now + CACHE_MS - 1, run: tags("9.9.9") }); assert.equal(fresh.latest, "2.5.0"); assert.equal(calls, 1); // Equal or newer installed: no update. assert.equal((await checkForUpdate({ installed: "2.5.0", cacheFile, now, run: tags("9.9.9") })).updateAvailable, false); assert.equal((await checkForUpdate({ installed: "2.6.0", cacheFile, now, run: tags("9.9.9") })).updateAvailable, false); assert.equal(calls, 1); // Stale: asks again and rewrites. const stale = await checkForUpdate({ installed: "2.4.3", cacheFile, now: now + CACHE_MS, run: tags("2.6.0") }); assert.equal(stale.latest, "2.6.0"); assert.equal(calls, 2); assert.equal(read().checkedAt, now + CACHE_MS); // Corrupt: treated as stale. fs.writeFileSync(cacheFile, "{not json"); assert.equal((await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: tags("2.7.0") })).latest, "2.7.0"); assert.equal(calls, 3); // A failed lookup is cached as null, and not retried within the hour. fs.rmSync(cacheFile); const failed = async () => { calls++; return null; }; assert.equal(await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: failed }), null); assert.equal(calls, 4); assert.deepEqual(read(), { checkedAt: now, latest: null }); assert.equal(await checkForUpdate({ installed: "2.4.3", cacheFile, now: now + 1000, run: tags("9.9.9") }), null); assert.equal(calls, 4, "the cached failure is reused"); // A runner that throws, or an unknown installed version, is null, never a throw. fs.rmSync(cacheFile); const boom = async () => { throw new Error("boom"); }; assert.equal(await checkForUpdate({ installed: "2.4.3", cacheFile, now, run: boom }), null); assert.equal(await checkForUpdate({ installed: "dev", cacheFile, now: now + CACHE_MS * 2, run: tags("2.5.0") }), null); } finally { fs.rmSync(dir, { recursive: true, force: true }); } }); test("update check: the repo and Releases URLs are the plan2code repo's", () => { assert.equal(REPO_URL, "https://github.com/jparkerweb/plan2code.git"); assert.equal(RELEASES_URL, "https://github.com/jparkerweb/plan2code/releases/"); }); test("update check: the frame carries update only when a newer release is cached, and /version names latest", async () => { const newer = `${Number(REPO_VERSION.split(".")[0]) + 1}.0.0`; for (const [latest, expectUpdate] of [ [newer, true], [REPO_VERSION, false], ]) { const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-update-frame-")); const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") }; fs.writeFileSync(path.join(home, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest })); const res = cli(["open", "--no-open", "--workflow", "dashboard"], { env }); const s = sessionUrl(res.json.url); const get = async (pathname) => (await fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } })).json(); try { // The check answers just after boot; give it a moment either way. let frame; for (let i = 0; i < 20; i++) { frame = await get("/state"); if (frame.update) break; await new Promise((r) => setTimeout(r, 100)); } if (expectUpdate) { assert.deepEqual(frame.update, { installed: REPO_VERSION, latest: newer }); } else { assert.equal("update" in frame, false, "no update key when the installed version is current"); } assert.deepEqual(await get("/version"), { version: REPO_VERSION, latest }); } finally { cli(["stop", "--session", res.json.sid, "--force"], { env }); fs.rmSync(home, { recursive: true, force: true }); } } }); test("stop modal: handoff choice first, plain stop second, Keep going last, styled and wired", () => { const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8"); const html = web("index.html"); const css = joinedCss(); const dialog = html.match(/]*>([\s\S]*?)<\/dialog>/); assert.ok(dialog, "index.html has the stop modal"); const body = dialog[1]; const at = (id) => body.indexOf(`id="${id}"`); assert.ok(at("stop-handoff") >= 0 && at("stop-handoff") < at("stop-go") && at("stop-go") < at("stop-cancel"), "handoff, plain stop, Keep going, in that order"); assert.ok(body.includes("Stop with a handoff") && body.includes("Just stop and save")); assert.doesNotMatch(body, /\sstyle=|