// 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 canceled 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/inbox.mjs"; export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url))); export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs"); // Canonicalized the same way server.mjs canonicalizes a session dir (DIR, // server.mjs): on a machine whose %TEMP% itself resolves through an 8.3 // short name (seen in the wild on Windows), a server started later writes // `state.worktree` in its realpath'd form, while anything in a test that // builds a path under HOME without this would use the short one. Two // spellings of the same folder hash to two different keys wherever a test // writes through a path-keyed store (notepads.mjs, workspace.mjs, // settings.mjs) ahead of the server itself touching that path, so the // server's own later read finds nothing there. Resolving it once, here, // keeps every path this file hands out consistent with what the server // will compute. const rawHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-")); export const HOME = (() => { for (const real of [fs.realpathSync.native, fs.realpathSync]) { try { return real(rawHome); } catch {} } return rawHome; })(); 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; // Learning's store on this machine (~/.plan2code/learning) likewise, set for // this process too so a test importing learning.mjs never reaches the real one. export const LEARNING_DIR = path.join(HOME, "learning"); process.env.PLAN2CODE_LEARNING_DIR = LEARNING_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. 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_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NOTEPADS_DIR: NOTEPADS_DIR, PLAN2CODE_LEARNING_DIR: LEARNING_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; } } // One wait slice of a session, parsed: { code, out } where out is the last // stdout line as JSON (null when it is not). Exit 10 and 20 are results here, // not failures. export function waitOnce(sid, seconds = 5, opts) { const res = cli(["wait", "--session", sid, "--seconds", String(seconds)], opts); return { code: res.status, out: res.json, stdout: res.stdout, stderr: res.stderr }; } // The last non-empty line of a command's stdout: `post --wait` prints the // post's line, then the wait's. export const lastLine = (stdout) => String(stdout).trim().split("\n").filter(Boolean).pop() ?? ""; // End one session the way an agent must: a finish first, then stop. A test // that only wants a session gone for cleanup may pass --force to stop instead. export function stopSession(sid, opts) { postFinish(sid, opts); return cli(["stop", "--session", sid], opts); } function postFinish(sid, opts) { cli(["post", "--session", sid, "--file", payload(`finish-${sid}.json`, { finish: { headline: "Test done" } })], opts); } 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(/