// Shared setup for the web console tests (scripts/test-web-console-*.mjs). // // Lives in scripts/ rather than src/web-console/ on purpose: everything under // src/web-console/ is copied verbatim into two skills, and tests should not ship. // // node --test runs each test file in its own process, and this module is // evaluated once per process, so every file gets its own console home: the // remembered workspaces, subagent switches, looks and sessions of one file // never reach another file running beside it. Importing it also registers the // cleanup that stops every server the file started and removes that home. // // PLAN2CODE_PICKER_ECHO (tests only, beside PLAN2CODE_NO_BROWSER): when set // in the server's environment, /workspace/browse returns it as the picked // folder instead of opening a picker, and "-" as a cancelled one. import test from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { execFileSync, spawnSync } from "node:child_process"; import http from "node:http"; import { fileURLToPath } from "node:url"; import { readChat } from "../src/web-console/lib.mjs"; export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs"); export const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-")); export const MODELS_DIR = path.join(HOME, "plan2code"); // 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. const AMBIENT_ENV_KEYS = [ "GIT_DIR", "GIT_WORK_TREE", "GIT_INDEX_FILE", "GIT_COMMON_DIR", "GIT_OBJECT_DIRECTORY", "GIT_CONFIG", "GIT_CONFIG_GLOBAL", "GIT_CONFIG_SYSTEM", "GIT_CONFIG_NOSYSTEM", "SSH_CONNECTION", "PLAN2CODE_PICKER_ECHO", "PLAN2CODE_NOW", ]; const scrubbed = { ...process.env }; for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k]; // GIT_CONFIG_GLOBAL wants a real path: os.devNull is `\\.\nul` here, which git // 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_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 })); // The session cookie is named for the server's port: browsers ignore the port // when they scope a cookie, so one shared name let each session's server // overwrite the one before it. export const cookieFor = (base, tok) => `p2c_console_${new URL(base).port}=${tok}`; export function cli(args, { expectFail = false, env, cwd = ROOT } = {}) { const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: env ? { ...ENV, ...env } : ENV, encoding: "utf8", cwd, }); if (!expectFail && res.status !== 0 && res.status !== 10 && res.status !== 20 && res.status !== 30) { throw new Error(`console ${args.join(" ")} failed (${res.status}): ${res.stderr}`); } return { ...res, json: safeJson(res.stdout) }; } export function safeJson(s) { const line = String(s).trim().split("\n").filter(Boolean).pop(); try { return JSON.parse(line); } catch { return null; } } export function payload(file, obj) { const p = path.join(HOME, file); fs.writeFileSync(p, JSON.stringify(obj)); return p; } // HTTP to a session a file keeps in its own variables: `get()` returns its // current { baseUrl, token }, read on every call. export function clientFor(get) { async function post(pathname, body) { const { baseUrl, token } = get(); for (let attempt = 0; attempt < 3; attempt++) { try { return await fetch(baseUrl + pathname, { method: "POST", headers: { "content-type": "application/json", cookie: cookieFor(baseUrl, token), connection: "close" }, body: JSON.stringify(body ?? {}), }); } catch (err) { if (attempt === 2) throw err; } } } // Over a raw socket, like rawGet in -session: fetch() folds `..` out of a URL // before it leaves, which would make every traversal test assert nothing. function raw(method, pathname, body, headers = {}) { const { baseUrl, token } = get(); const port = Number(new URL(baseUrl).port); return new Promise((resolve, reject) => { const req = http.request( { host: "127.0.0.1", port, path: pathname, method, headers: { cookie: cookieFor(baseUrl, token), origin: baseUrl, connection: "close", ...headers }, }, (res) => { const chunks = []; res.on("data", (c) => chunks.push(c)); res.on("end", () => { const buf = Buffer.concat(chunks); resolve({ status: res.statusCode, headers: res.headers, body: buf, json: safeJson(buf.toString("utf8")) }); }); } ); req.on("error", reject); req.end(body); }); } return { post, raw }; } export const BASE = { workflow: "pathfinder", title: "Test session", items: [ { id: "q1", kind: "choice", title: "Export format", body: "Pick one.", options: [ { k: "A", text: "CSV", recommended: true }, { k: "B", text: "Excel" }, ], token: { A: "a", B: "b" }, }, ], agent: { status: "waiting" }, }; // The console's agent contract: console.md and every topic file it indexes // (console-*.md, building*.md, notes/*.md), as one text. A rule an agent must // learn has to be written somewhere in here; which file it lives in is the // index's business. export const WEB_CONSOLE_DIR = path.join(ROOT, "src", "web-console"); export function consoleDocFiles() { const top = fs.readdirSync(WEB_CONSOLE_DIR).filter((f) => f.endsWith(".md")); const notes = fs.readdirSync(path.join(WEB_CONSOLE_DIR, "notes")).filter((f) => f.endsWith(".md")).map((f) => `notes/${f}`); return [...top, ...notes].sort(); } export const consoleDoc = (name) => fs.readFileSync(path.join(WEB_CONSOLE_DIR, name), "utf8"); export const consoleDocs = () => consoleDocFiles().map(consoleDoc).join("\n\n"); export const helpTemplate = () => { const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8"); const tpl = html.match(/