mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 20:45:33 -08:00
Sync upstream v2.4.0 into v2.4.1: welcome dialog, bug/idea button with issue templates, version in Help, gear preferences and ocean default accent, plus web console screenshots, new landing page and web-console-first docs
AI Assisted
This commit is contained in:
1 parent
0d7c2e140b
commit
cb86034de9
288 files changed
+25222
-4767
No files matched your search
@@ -0,0 +1,368 @@
|
||||
#!/usr/bin/env node
|
||||
// Screenshots of the web console for the docs. Dev-only: lives in scripts/ so
|
||||
// it never ships inside a skill.
|
||||
//
|
||||
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
|
||||
// [--out <dir>]
|
||||
//
|
||||
// Every shot is staged with no agent: a throwaway sample project called
|
||||
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
|
||||
// `console.mjs open` and `post` with the payloads in scripts/screenshots/.
|
||||
// Each screen is saved light and dark, at 1280x800 and twice the pixel
|
||||
// density, as `<out>/<shot>-light.webp` and `<out>/<shot>-dark.webp`.
|
||||
// The shots use the console's Ocean highlight rather than its default orange:
|
||||
// it is the console's nearest to the Plan2Code blue the site and README use.
|
||||
//
|
||||
// Shots: dashboard, question, doc, build, signoff, finish, ask.
|
||||
//
|
||||
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
|
||||
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
|
||||
// folders and --out.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
const PAYLOADS = path.join(ROOT, "scripts", "screenshots");
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
|
||||
}
|
||||
const OUT = path.resolve(args.out || path.join(ROOT, "docs", "screenshots"));
|
||||
const QUALITY = 85;
|
||||
const WARN_KB = 300;
|
||||
const THEMES = ["light", "dark"];
|
||||
|
||||
// Which workflow each shot opens under, which payloads it posts in order,
|
||||
// which tab it is captured on (by the tab's label; none means the first tab),
|
||||
// and where to scroll first: `scrollTo` is put at the top of the view and
|
||||
// `mustShow` has to end up wholly inside it (none means the top).
|
||||
const SHOTS = {
|
||||
// The suggested card sits below the fold at 1280x800, and it is the point of
|
||||
// the shot. Starting at the "Hide unavailable" switch keeps the spec picker's
|
||||
// cut out of frame and the card in it.
|
||||
dashboard: {
|
||||
workflow: "dashboard",
|
||||
posts: ["dashboard"],
|
||||
scrollTo: ".dash-toggle",
|
||||
mustShow: ".dash-card:has(.pill.suggested)",
|
||||
},
|
||||
question: { workflow: "plan", posts: ["question"] },
|
||||
doc: { workflow: "plan", posts: ["doc"], tab: "What we've agreed" },
|
||||
build: { workflow: "implement", posts: ["build"], tab: "Phase 3 tasks" },
|
||||
signoff: { workflow: "implement", posts: ["signoff"] },
|
||||
finish: { workflow: "implement", posts: ["signoff", "finish"] },
|
||||
ask: { workflow: "plan", posts: ["question"], ask: "Where are tasks paged?" },
|
||||
};
|
||||
|
||||
// On Windows the temp dir sits under the user's profile, and the page can
|
||||
// show the project's path, so the sample project goes at the drive root
|
||||
// instead. Elsewhere the temp dir carries no username. Each run makes its own
|
||||
// folder there (p2c-shots-XXXXXX), so it never deletes anything it did not
|
||||
// create and two runs never share one.
|
||||
const SCRATCH_ROOT = process.platform === "win32" ? path.parse(os.tmpdir()).root : os.tmpdir();
|
||||
let SCRATCH = null;
|
||||
let HOME = null;
|
||||
let ENV = null;
|
||||
|
||||
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
||||
|
||||
function fail(message) {
|
||||
console.error(message);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
function phaseFile(n, name, tasks, done) {
|
||||
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
|
||||
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
|
||||
}
|
||||
|
||||
// A neutral project the console scans as mid-build: Phases 1 and 2 done,
|
||||
// Phases 3 and 4 still to do.
|
||||
function makeSampleProject() {
|
||||
const project = path.join(SCRATCH, "task-api");
|
||||
const spec = path.join(project, "specs", "task-api");
|
||||
fs.mkdirSync(spec, { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(project, "AGENTS.md"),
|
||||
"# AGENTS.md\n\nA REST API for a team's tasks, on Fastify, Postgres and Zod.\n\n## Development Commands\n\n- `npm start` runs the API\n- `npm test` runs the tests\n"
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(spec, "overview.md"),
|
||||
[
|
||||
"# Task API",
|
||||
"",
|
||||
"**Status:** In Progress",
|
||||
"",
|
||||
"## Summary",
|
||||
"",
|
||||
"A REST API for a team's tasks: create, list, update and delete them, with filters by status and assignee and cursor paging.",
|
||||
"",
|
||||
"## Phase Checklist",
|
||||
"",
|
||||
"- [x] Phase 1: Project setup ([phase-1.md](./phase-1.md))",
|
||||
"- [x] Phase 2: Data model ([phase-2.md](./phase-2.md))",
|
||||
"- [ ] Phase 3: API endpoints ([phase-3.md](./phase-3.md))",
|
||||
"- [ ] Phase 4: Authentication ([phase-4.md](./phase-4.md))",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
// The file the Ask shot's answer points at.
|
||||
fs.mkdirSync(path.join(project, "src", "tasks"), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(project, "src", "tasks", "paginate.js"),
|
||||
[
|
||||
"// Cursor paging for GET /tasks: up to 50 tasks a page, oldest first.",
|
||||
"export function paginate(tasks, cursor, limit = 50) {",
|
||||
" const start = cursor ? tasks.findIndex((t) => t.id === cursor) + 1 : 0;",
|
||||
" const page = tasks.slice(start, start + limit);",
|
||||
" return { tasks: page, nextCursor: page.length === limit ? page[page.length - 1].id : null };",
|
||||
"}",
|
||||
"",
|
||||
].join("\n")
|
||||
);
|
||||
fs.writeFileSync(path.join(spec, "phase-1.md"), phaseFile(1, "Project setup", ["Scaffold the Fastify app", "Add the Postgres connection", "Add the test runner"], true));
|
||||
fs.writeFileSync(
|
||||
path.join(spec, "phase-2.md"),
|
||||
phaseFile(2, "Data model", ["Add the tasks table and its migration", "Add the task model", "Add status and assignee indexes", "Seed sample tasks"], true)
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(spec, "phase-3.md"),
|
||||
phaseFile(3, "API endpoints", ["Add GET /tasks with cursor paging", "Add POST /tasks", "Add PATCH /tasks/:id", "Add DELETE /tasks/:id"], false)
|
||||
);
|
||||
fs.writeFileSync(
|
||||
path.join(spec, "phase-4.md"),
|
||||
phaseFile(4, "Authentication", ["Add API keys", "Require a key on every route", "Scope tasks to the key's team"], false)
|
||||
);
|
||||
return project;
|
||||
}
|
||||
|
||||
function cli(cwd, ...cliArgs) {
|
||||
const r = spawnSync(process.execPath, [CONSOLE_CLI, ...cliArgs], { cwd, env: ENV, encoding: "utf8" });
|
||||
const line = (r.stdout || "").trim().split("\n").pop() || "";
|
||||
let out = null;
|
||||
try {
|
||||
out = JSON.parse(line);
|
||||
} catch {}
|
||||
return { code: r.status, out, err: r.stderr };
|
||||
}
|
||||
|
||||
function post(project, sid, name) {
|
||||
const r = cli(project, "post", "--session", sid, "--file", path.join(PAYLOADS, name + ".json"));
|
||||
if (r.code !== 0) throw new Error(`post ${name}.json failed (${r.code}): ${r.err.trim()}`);
|
||||
}
|
||||
|
||||
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
|
||||
function stage(project, shot) {
|
||||
const spec = SHOTS[shot];
|
||||
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
|
||||
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
|
||||
for (const name of spec.posts) post(project, r.out.sid, name);
|
||||
return { sid: r.out.sid, url: r.out.url };
|
||||
}
|
||||
|
||||
// Waits for the page to draw real state, then lets the animations finish
|
||||
// (the dashboard's wake-up is the longest).
|
||||
async function settle(page) {
|
||||
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(3500);
|
||||
}
|
||||
|
||||
async function openTab(page, label) {
|
||||
await page.evaluate((text) => {
|
||||
const tab = [...document.querySelectorAll("#views .view-tab")].find((b) => b.firstChild && b.firstChild.textContent.trim() === text);
|
||||
if (tab) tab.click();
|
||||
}, label);
|
||||
await sleep(600);
|
||||
}
|
||||
|
||||
async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const problem = await page.evaluate(
|
||||
(topSel, showSel) => {
|
||||
const node = document.querySelector(topSel);
|
||||
if (!node) return `nothing matched ${topSel}, captured from the top`;
|
||||
node.scrollIntoView({ block: "start", behavior: "instant" });
|
||||
if (!showSel) return null;
|
||||
const show = document.querySelector(showSel);
|
||||
if (!show) return `nothing matched ${showSel}`;
|
||||
const r = show.getBoundingClientRect();
|
||||
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
|
||||
},
|
||||
top,
|
||||
mustShow || null
|
||||
);
|
||||
if (problem) console.log(` warning: ${problem}`);
|
||||
await sleep(300);
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const written = [];
|
||||
for (const theme of THEMES) {
|
||||
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
|
||||
// The theme is applied at load, so reload rather than trust a live switch.
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
if (page.__tab) await openTab(page, page.__tab);
|
||||
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
|
||||
const file = path.join(OUT, `${name}-${theme}.webp`);
|
||||
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
|
||||
const kb = Math.round(fs.statSync(file).size / 1024);
|
||||
console.log(`${path.basename(file)} ${kb} KB`);
|
||||
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
|
||||
written.push(file);
|
||||
}
|
||||
return written;
|
||||
}
|
||||
|
||||
// Opens the page for a staged session and saves both themes.
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
page.__tab = tab || null;
|
||||
page.__scroll = { scrollTo: top, mustShow };
|
||||
return await shoot(page, name);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
}
|
||||
}
|
||||
|
||||
// The Ask shot: a question typed and sent on the page, collected with `chat`
|
||||
// the way an agent would, and answered with a posted reply.
|
||||
async function captureAsk(browser, project, sid, url, question) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
await openTab(page, "Ask");
|
||||
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
|
||||
await page.type("#ask-input", question);
|
||||
await page.evaluate(() => {
|
||||
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
|
||||
if (send) send.click();
|
||||
});
|
||||
|
||||
let entry = null;
|
||||
for (let i = 0; i < 40 && !entry; i++) {
|
||||
const r = cli(project, "chat", "--session", sid);
|
||||
if (r.code === 0 && r.out && r.out.chat) entry = r.out.chat.find((c) => c.kind === "message");
|
||||
if (!entry) await sleep(250);
|
||||
}
|
||||
if (!entry) throw new Error("the Ask question never reached the console");
|
||||
|
||||
const reply = path.join(HOME, "ask-reply.json");
|
||||
fs.writeFileSync(
|
||||
reply,
|
||||
JSON.stringify({
|
||||
chat: {
|
||||
replies: [
|
||||
{
|
||||
id: "r" + entry.seq,
|
||||
re: entry.seq,
|
||||
conversation: entry.conversation,
|
||||
md: "Paging is in `src/tasks/paginate.js`. It reads the `cursor` query parameter, returns up to 50 tasks and a `nextCursor`, and `GET /tasks` calls it on every request.",
|
||||
},
|
||||
],
|
||||
},
|
||||
agent: { status: "waiting" },
|
||||
})
|
||||
);
|
||||
const r = cli(project, "post", "--session", sid, "--file", reply);
|
||||
if (r.code !== 0) throw new Error(`posting the Ask reply failed (${r.code}): ${r.err.trim()}`);
|
||||
await sleep(1000);
|
||||
page.__tab = "Ask";
|
||||
return await shoot(page, "ask");
|
||||
} finally {
|
||||
await ctx.close();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const names = args.only ? [args.only] : Object.keys(SHOTS);
|
||||
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
|
||||
|
||||
let puppeteer;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
|
||||
}
|
||||
const browserPath = findBrowser();
|
||||
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
|
||||
|
||||
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
|
||||
HOME = path.join(SCRATCH, "console-home");
|
||||
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||
fs.mkdirSync(HOME, { recursive: true });
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
let browser = null;
|
||||
let project = null;
|
||||
try {
|
||||
project = makeSampleProject();
|
||||
// A saved role keeps the dashboard's "pick your role" banner out of shot,
|
||||
// and the Ocean highlight is the console's nearest to the Plan2Code blue
|
||||
// the landing page uses.
|
||||
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean" } }));
|
||||
browser = await puppeteer.launch({
|
||||
executablePath: browserPath,
|
||||
headless: true,
|
||||
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
|
||||
});
|
||||
for (const name of names) {
|
||||
const { sid, url } = stage(project, name);
|
||||
try {
|
||||
if (SHOTS[name].ask) await captureAsk(browser, project, sid, url, SHOTS[name].ask);
|
||||
else await capture(browser, url, name, SHOTS[name]);
|
||||
} finally {
|
||||
cli(project, "stop", "--session", sid);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (project) cli(project, "stop", "--all");
|
||||
removeScratch();
|
||||
}
|
||||
}
|
||||
|
||||
// `stop` signals the server and returns without waiting for it to exit, and
|
||||
// on Windows a server still closing holds its log open. Retry the delete, and
|
||||
// never let a failed cleanup replace the run's own result or error.
|
||||
function removeScratch() {
|
||||
try {
|
||||
fs.rmSync(SCRATCH, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
|
||||
} catch (e) {
|
||||
console.log(`warning: could not remove ${SCRATCH} (${e.code || e.message}); delete it by hand`);
|
||||
}
|
||||
}
|
||||
|
||||
main().catch((e) => {
|
||||
console.error(e && e.message ? e.message : e);
|
||||
process.exit(1);
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
# Screenshot payloads
|
||||
|
||||
Each JSON file here stages one web console screen for the docs, with no agent
|
||||
involved. `node scripts/capture-screenshots.mjs` opens a console session in a
|
||||
throwaway sample project, posts these files, and saves the screens as light
|
||||
and dark WebP images in `docs/screenshots/`.
|
||||
|
||||
| File | Stages |
|
||||
| --- | --- |
|
||||
| `dashboard.json` | The dashboard menu, suggesting the next build phase |
|
||||
| `question.json` | A Plan session with three questions open (also the base of the Ask shot) |
|
||||
| `doc.json` | A living document with settled, assumed and draft sections, and its review card |
|
||||
| `build.json` | A phase being built: the progress bar, the task list and the current task |
|
||||
| `signoff.json` | The completion report and the sign-off card |
|
||||
| `finish.json` | The finished screen after sign-off (posted after `signoff.json`) |
|
||||
|
||||
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
|
||||
`--only <shot>`.
|
||||
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"workflow": "implement",
|
||||
"title": "task-api: Phase 3",
|
||||
"headline": {
|
||||
"stage": "Phase 3: API endpoints",
|
||||
"cleared": 5,
|
||||
"total": 11
|
||||
},
|
||||
"docs": [
|
||||
{
|
||||
"id": "phase",
|
||||
"title": "Phase 3 tasks",
|
||||
"version": 6,
|
||||
"blocks": [
|
||||
{
|
||||
"id": "tasks",
|
||||
"state": "settled",
|
||||
"md": "- [x] **Task 3.1:** Register the /tasks routes plugin\n- [x] **Task 3.2:** Add GET /tasks with cursor paging\n- [x] **Task 3.3:** Add GET /tasks/:id\n- [x] **Task 3.4:** Add POST /tasks with a Zod schema\n- [x] **Task 3.5:** Add PATCH /tasks/:id for status and fields\n- [ ] **Task 3.6:** Add DELETE /tasks/:id as a soft delete\n- [ ] **Task 3.7:** Filter GET /tasks by status and assignee\n- [ ] **Task 3.8:** Return one error shape for 400, 404 and 409\n- [ ] **Task 3.9:** Document the endpoints in openapi.yaml\n- [ ] **Task 3.10:** Write tests for paging, filters and validation\n- [ ] **Task 3.11:** Run the test suite and record the results"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "phasefile",
|
||||
"title": "phase-3.md",
|
||||
"version": 6,
|
||||
"blocks": [
|
||||
{
|
||||
"id": "body",
|
||||
"state": "settled",
|
||||
"md": "# Phase 3: API endpoints\n\n**Status:** In Progress\n**Estimated Tasks:** 11\n\n## Overview\n\nThe /tasks endpoints: list with paging and filters, read, create, update and soft delete, with one error shape for every failure.\n\n## Prerequisites\n\n- Phase 2 complete (the tasks table and model exist) VERIFIED\n- Postgres runs locally VERIFIED\n\n## Tasks\n\n- [x] **Task 3.1:** Register the /tasks routes plugin\n- [x] **Task 3.2:** Add GET /tasks with cursor paging\n- [x] **Task 3.3:** Add GET /tasks/:id\n- [x] **Task 3.4:** Add POST /tasks with a Zod schema\n- [x] **Task 3.5:** Add PATCH /tasks/:id for status and fields\n- [ ] **Task 3.6:** Add DELETE /tasks/:id as a soft delete\n- [ ] **Task 3.7:** Filter GET /tasks by status and assignee\n- [ ] **Task 3.8:** Return one error shape for 400, 404 and 409\n- [ ] **Task 3.9:** Document the endpoints in openapi.yaml\n- [ ] **Task 3.10:** Write tests for paging, filters and validation\n- [ ] **Task 3.11:** Run the test suite and record the results\n\n## Acceptance Criteria\n\n- Every endpoint validates its input and answers errors in one shape\n- Paging stays stable while tasks are added and removed\n"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "working",
|
||||
"activity": "Task 6 of 11: deleting a task",
|
||||
"quietMinutes": 15
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"menu": {
|
||||
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
|
||||
"recommend": "plan2code-3-implement",
|
||||
"details": {
|
||||
"plan2code-3-implement": "Phase 3 of 4 is next"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: What we've agreed",
|
||||
"cleared": 4,
|
||||
"total": 7,
|
||||
"confidence": "Most of it is settled. Paging is assumed for now."
|
||||
},
|
||||
"docs": [
|
||||
{
|
||||
"id": "map",
|
||||
"title": "What we've agreed",
|
||||
"version": 2,
|
||||
"note": "Added paging",
|
||||
"blocks": [
|
||||
{
|
||||
"id": "b1",
|
||||
"state": "settled",
|
||||
"md": "## Where we're headed\n\nA REST API for a team's tasks: create, list, update and delete them, with filters by status and assignee. Built on Fastify, Postgres and Zod."
|
||||
},
|
||||
{
|
||||
"id": "b2",
|
||||
"state": "assumed",
|
||||
"md": "### Paging\n\nAssuming cursor paging, 50 tasks per page. Still open: the web app may want page numbers."
|
||||
},
|
||||
{
|
||||
"id": "b3",
|
||||
"state": "draft",
|
||||
"md": "### Still to work out\n\n- How clients sign in\n- Whether a deleted task can be restored"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "agree",
|
||||
"kind": "review",
|
||||
"title": "Check the plan so far",
|
||||
"doc": "map",
|
||||
"body": "Read what we've agreed, then approve it or say what to change. Paging is marked as assumed.",
|
||||
"verdicts": [
|
||||
{
|
||||
"id": "approve",
|
||||
"label": "Looks right"
|
||||
},
|
||||
{
|
||||
"id": "changes",
|
||||
"label": "I want changes"
|
||||
}
|
||||
],
|
||||
"token": {
|
||||
"approve": "yes",
|
||||
"changes": "needs changes"
|
||||
},
|
||||
"nothingYet": "Nothing is written to disk until you approve.",
|
||||
"fallbackText": "Does what we've agreed look right? Reply yes, or describe what to change."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "signoff",
|
||||
"status": "answered",
|
||||
"answer": {
|
||||
"verdict": "approve"
|
||||
}
|
||||
}
|
||||
],
|
||||
"finish": {
|
||||
"headline": "Phase 3 is built",
|
||||
"body": "11 of 11 tasks, all on disk. Phase 4 (authentication) is next.",
|
||||
"command": "/plan2code-3-implement specs/task-api/overview.md",
|
||||
"doc": "report",
|
||||
"dashboard": true
|
||||
},
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 1 of 7: What we're building",
|
||||
"cleared": 1,
|
||||
"total": 7,
|
||||
"confidence": "A clear idea so far. Who calls the API and how it signs in are still open."
|
||||
},
|
||||
"topics": [
|
||||
{
|
||||
"id": "t1",
|
||||
"title": "What we're building",
|
||||
"status": "current"
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "q2",
|
||||
"topic": "t1",
|
||||
"kind": "choice",
|
||||
"title": "How tasks are paged",
|
||||
"body": "A team can have thousands of tasks. How should the list endpoint hand them back?",
|
||||
"options": [
|
||||
{
|
||||
"k": "A",
|
||||
"text": "Cursor paging",
|
||||
"detail": "Stable while tasks are added and removed. No jumping to page 7.",
|
||||
"recommended": true
|
||||
},
|
||||
{
|
||||
"k": "B",
|
||||
"text": "Page numbers",
|
||||
"detail": "Familiar and easy to link to, but rows shift when tasks change mid-scroll."
|
||||
},
|
||||
{
|
||||
"k": "C",
|
||||
"text": "Everything at once",
|
||||
"detail": "Simplest to build; slow and heavy once a team has a few thousand tasks."
|
||||
}
|
||||
],
|
||||
"token": {
|
||||
"A": "a",
|
||||
"B": "b",
|
||||
"C": "c"
|
||||
},
|
||||
"fallbackText": "How tasks are paged: a) cursor paging b) page numbers c) everything at once. My guess: a."
|
||||
},
|
||||
{
|
||||
"id": "q3",
|
||||
"topic": "t1",
|
||||
"kind": "multi",
|
||||
"title": "Day one endpoints",
|
||||
"body": "Which of these should be there on the first day? Anything left unticked waits for a later version.",
|
||||
"options": [
|
||||
{
|
||||
"k": "1",
|
||||
"text": "List and read tasks",
|
||||
"detail": "GET /tasks and GET /tasks/:id, with filters by status and assignee."
|
||||
},
|
||||
{
|
||||
"k": "2",
|
||||
"text": "Create and update tasks",
|
||||
"detail": "POST /tasks and PATCH /tasks/:id, validated."
|
||||
},
|
||||
{
|
||||
"k": "3",
|
||||
"text": "Delete tasks",
|
||||
"detail": "A soft delete, so a task can come back."
|
||||
},
|
||||
{
|
||||
"k": "4",
|
||||
"text": "Comments on a task",
|
||||
"detail": "A thread under each task. Doubles the data model."
|
||||
}
|
||||
],
|
||||
"presets": [
|
||||
{
|
||||
"label": "The essentials",
|
||||
"ks": [
|
||||
"1",
|
||||
"2"
|
||||
]
|
||||
},
|
||||
{
|
||||
"label": "Everything",
|
||||
"ks": [
|
||||
"1",
|
||||
"2",
|
||||
"3",
|
||||
"4"
|
||||
]
|
||||
}
|
||||
],
|
||||
"token": {
|
||||
"1": "1",
|
||||
"2": "2",
|
||||
"3": "3",
|
||||
"4": "4"
|
||||
},
|
||||
"fallbackText": "Day one endpoints (pick any): 1) list and read 2) create and update 3) delete 4) comments on a task."
|
||||
},
|
||||
{
|
||||
"id": "q4",
|
||||
"topic": "t1",
|
||||
"kind": "text",
|
||||
"title": "Who calls it",
|
||||
"body": "Which apps will call this API, and roughly how many people use them?",
|
||||
"placeholder": "For example: our web app and a mobile app, about 2,000 people across 40 teams.",
|
||||
"token": {},
|
||||
"fallbackText": "Who calls it: which apps will call this API, and roughly how many people use them?"
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
{
|
||||
"workflow": "implement",
|
||||
"title": "task-api: Phase 3",
|
||||
"headline": {
|
||||
"stage": "Phase 3: API endpoints",
|
||||
"cleared": 11,
|
||||
"total": 11
|
||||
},
|
||||
"docs": [
|
||||
{
|
||||
"id": "phase",
|
||||
"title": "Phase 3 tasks",
|
||||
"version": 12,
|
||||
"blocks": [
|
||||
{
|
||||
"id": "tasks",
|
||||
"state": "settled",
|
||||
"md": "- [x] **Task 3.1:** Register the /tasks routes plugin\n- [x] **Task 3.2:** Add GET /tasks with cursor paging\n- [x] **Task 3.3:** Add GET /tasks/:id\n- [x] **Task 3.4:** Add POST /tasks with a Zod schema\n- [x] **Task 3.5:** Add PATCH /tasks/:id for status and fields\n- [x] **Task 3.6:** Add DELETE /tasks/:id as a soft delete\n- [x] **Task 3.7:** Filter GET /tasks by status and assignee\n- [x] **Task 3.8:** Return one error shape for 400, 404 and 409\n- [x] **Task 3.9:** Document the endpoints in openapi.yaml\n- [x] **Task 3.10:** Write tests for paging, filters and validation\n- [x] **Task 3.11:** Run the test suite and record the results"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": "report",
|
||||
"title": "Completion report",
|
||||
"version": 1,
|
||||
"blocks": [
|
||||
{
|
||||
"id": "summary",
|
||||
"state": "settled",
|
||||
"md": "## Summary\n\nThe /tasks endpoints work end to end. Clients can list tasks with cursor paging and filters, read one, create, update and soft delete, and every failure comes back in the same error shape.\n\n**Tasks:** 11 of 11 done, none blocked."
|
||||
},
|
||||
{
|
||||
"id": "tests",
|
||||
"state": "settled",
|
||||
"md": "## Tests\n\n| Suite | Passed | Failed |\n| --- | --- | --- |\n| tasks | 31 | 0 |\n| paging | 8 | 0 |"
|
||||
},
|
||||
{
|
||||
"id": "files",
|
||||
"state": "settled",
|
||||
"md": "## Files\n\n**Created:** `src/tasks/routes.js`, `src/tasks/schema.js`, `src/tasks/paginate.js`, `test/tasks.test.js`\n\n**Modified:** `src/app.js`, `openapi.yaml`"
|
||||
},
|
||||
{
|
||||
"id": "verify",
|
||||
"state": "settled",
|
||||
"md": "## How to check it\n\n1. Run `npm test`: 39 passing.\n2. Create two tasks, then call `GET /tasks?limit=1`: one task and a `nextCursor`.\n3. `PATCH /tasks/:id` with an unknown status answers 400 in the shared error shape."
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "signoff",
|
||||
"kind": "review",
|
||||
"title": "Approve this phase",
|
||||
"doc": "report",
|
||||
"body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, or say what to change.",
|
||||
"verdicts": [
|
||||
{
|
||||
"id": "review",
|
||||
"label": "Review the code first"
|
||||
},
|
||||
{
|
||||
"id": "approve",
|
||||
"label": "Approve this phase"
|
||||
},
|
||||
{
|
||||
"id": "changes",
|
||||
"label": "I want changes"
|
||||
}
|
||||
],
|
||||
"token": {
|
||||
"review": "review",
|
||||
"approve": "approved",
|
||||
"changes": "needs changes"
|
||||
},
|
||||
"nothingYet": "Nothing is marked complete until you approve.",
|
||||
"gate": {
|
||||
"id": "signoff",
|
||||
"authoritative": true
|
||||
},
|
||||
"fallbackText": "Reply \"approved\" to mark this phase complete, \"review\" to run the code review first, or describe any issues."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting",
|
||||
"quietMinutes": null
|
||||
}
|
||||
}
|
||||
@@ -11,8 +11,10 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
@@ -126,6 +128,28 @@ test("launcher: an unknown --cli exits 2, a missing CLI 127, and nothing is star
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: mergeModels keeps the shipped list first and drops user duplicates", () => {
|
||||
const { mergeModels, modelEntries } = require(LAUNCHER);
|
||||
const shipped = [{ id: "a", label: "A" }, { id: "b", label: "B" }];
|
||||
const user = [{ id: "b", label: "B old" }, { id: "c", label: "C" }, { id: "c", label: "C again" }];
|
||||
assert.deepEqual(mergeModels(shipped, user), [...shipped, { id: "c", label: "C" }]);
|
||||
assert.deepEqual(mergeModels(shipped, []), shipped);
|
||||
// A missing or corrupt user file yields no additions rather than an error.
|
||||
assert.deepEqual(modelEntries(null, "devin"), []);
|
||||
assert.deepEqual(modelEntries({ devin: "nope" }, "devin"), []);
|
||||
assert.deepEqual(modelEntries({ devin: [{ id: 1 }, null, { id: "ok", label: "Ok" }] }, "devin"), [{ id: "ok", label: "Ok" }]);
|
||||
});
|
||||
|
||||
test("launcher: the shipped models.json is curated Devin at low/medium/high only", () => {
|
||||
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
|
||||
assert.ok(shipped.claude.length > 0);
|
||||
assert.ok(shipped.devin.length > 0 && shipped.devin.length <= 30);
|
||||
for (const { id, label } of shipped.devin) {
|
||||
assert.ok(id && label);
|
||||
assert.doesNotMatch(id, /(xhigh|max|fast|priority)$/);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: with neither CLI installed it exits 127 naming both", (t) => {
|
||||
const box = sandbox([]);
|
||||
t.after(box.cleanup);
|
||||
|
||||
+515
-17
@@ -75,6 +75,7 @@ import {
|
||||
STOP_REPLY,
|
||||
sentAnswer,
|
||||
submittedAwaiting,
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
turnGate,
|
||||
verdictLabel,
|
||||
@@ -136,6 +137,7 @@ import {
|
||||
} from "../src/web-console/public/workspace.js";
|
||||
import {
|
||||
levelFor,
|
||||
breakdownFrom,
|
||||
meterView,
|
||||
pointsFrom,
|
||||
RED_AT,
|
||||
@@ -146,6 +148,7 @@ import {
|
||||
} from "../src/web-console/public/meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "../src/web-console/public/mentions.js";
|
||||
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
|
||||
import { runHint } from "../src/web-console/public/render.js";
|
||||
import { pickerCommand, pickFolder, WINDOWS_PICKER_SOURCE, WORKSPACE_PICKER_PROMPT } from "../src/web-console/picker.mjs";
|
||||
import {
|
||||
appendLedger,
|
||||
@@ -153,6 +156,7 @@ import {
|
||||
bindLoopback,
|
||||
chatReplyLines,
|
||||
checkDocument,
|
||||
cwdHash,
|
||||
handOff,
|
||||
initialWorkspace,
|
||||
parseArgs,
|
||||
@@ -170,6 +174,7 @@ import {
|
||||
SPEC_STATES,
|
||||
staleScratch,
|
||||
staleSessions,
|
||||
STATE_LOCK_FILE,
|
||||
sweepUploads,
|
||||
terminalLine,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
@@ -182,7 +187,12 @@ const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
|
||||
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
|
||||
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||
const MODELS_DIR = path.join(HOME, "plan2code");
|
||||
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1" };
|
||||
|
||||
// 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.
|
||||
|
||||
function cli(args, { expectFail = false, env, cwd = ROOT } = {}) {
|
||||
const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], {
|
||||
@@ -1228,10 +1238,36 @@ test("a document that is the wrong type, lies about its type, or is too large is
|
||||
assert.equal((await uploadDoc("a.md", MD, { origin: "http://evil.example.com" })).status, 403);
|
||||
});
|
||||
|
||||
test("a document is never served back, and deleting it removes its file", async () => {
|
||||
test("a document is served back inline under a fixed type, and deleting it removes its file", async () => {
|
||||
const { id, path: file } = (await uploadDoc("spec.pdf", PDF)).json;
|
||||
const url = `/uploads/${id}.pdf`;
|
||||
assert.equal((await raw("GET", url)).status, 404);
|
||||
const pdf = await raw("GET", url);
|
||||
assert.equal(pdf.status, 200);
|
||||
assert.equal(pdf.headers["content-type"], "application/pdf");
|
||||
assert.equal(pdf.headers["x-content-type-options"], "nosniff");
|
||||
assert.equal(pdf.headers["content-security-policy"], undefined, "a sandboxed PDF cannot open in the viewer");
|
||||
assert.deepEqual(pdf.body, PDF);
|
||||
for (const [name, buf, type] of [
|
||||
["page.html", Buffer.from("<script>fetch('/submit')</script>"), "text/plain; charset=utf-8"],
|
||||
["logo.svg", MD, null],
|
||||
["notes.md", MD, "text/plain; charset=utf-8"],
|
||||
]) {
|
||||
const up = await uploadDoc(name, buf);
|
||||
if (!type) {
|
||||
assert.equal(up.status, 415, "an svg is not an allowed document");
|
||||
continue;
|
||||
}
|
||||
const text = await raw("GET", `/uploads/${up.json.id}.${name.split(".").pop()}`);
|
||||
assert.equal(text.status, 200, name);
|
||||
assert.equal(text.headers["content-type"], type, "text and code are never served as html");
|
||||
assert.equal(text.headers["content-security-policy"], "sandbox");
|
||||
assert.deepEqual(text.body, buf);
|
||||
assert.equal((await raw("DELETE", `/uploads/${up.json.id}.${name.split(".").pop()}`)).status, 204);
|
||||
}
|
||||
assert.equal((await raw("GET", url, undefined, { cookie: "" })).status, 403);
|
||||
for (const p of ["/uploads/../state.json.md", "/uploads/%2e%2e/x.pdf", "/uploads/not-a-uuid.md"]) {
|
||||
assert.equal((await raw("GET", p)).status, 404, p);
|
||||
}
|
||||
for (const p of ["/uploads/../state.json.md", "/uploads/%2e%2e/x.pdf", "/uploads/not-a-uuid.md"]) {
|
||||
assert.equal((await raw("DELETE", p)).status, 404, p);
|
||||
}
|
||||
@@ -1296,6 +1332,46 @@ test("a result is consumed only once", () => {
|
||||
assert.equal(res.status, 10, "an already-consumed result must not be handed over twice");
|
||||
});
|
||||
|
||||
test("a send records its note and attachments on the item, so the page can show them after a reload", async () => {
|
||||
const readState = () => JSON.parse(fs.readFileSync(path.join(HOME, "sessions", sid, "state.json"), "utf8"));
|
||||
const j = (await uploadJpeg("shot.png")).json;
|
||||
const d = (await uploadDoc("spec.pdf", PDF)).json;
|
||||
const atts = [
|
||||
{ path: j.path, name: j.name, kind: "image" },
|
||||
{ path: d.path, name: d.name, kind: "file" },
|
||||
];
|
||||
const ok = await post("/submit", {
|
||||
actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }, noteAction("q1", "see these", atts)],
|
||||
reply: "x",
|
||||
});
|
||||
assert.equal(ok.status, 200);
|
||||
const q1 = readState().items.find((i) => i.id === "q1");
|
||||
assert.equal(q1.submitted.k, "B");
|
||||
assert.equal(q1.submitted.images, undefined, "the answer record stays the answer");
|
||||
assert.ok(q1.sentNote.at);
|
||||
assert.equal(q1.sentNote.at, q1.submitted.at, "one send, one clock reading");
|
||||
assert.equal(q1.sentNote.text, "see these");
|
||||
assert.deepEqual(q1.sentNote.images, [{ path: j.path, name: j.name }]);
|
||||
assert.deepEqual(q1.sentNote.files, [{ path: d.path, name: d.name }]);
|
||||
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
|
||||
|
||||
const only = await post("/submit", { actions: [noteAction("q1", "just a note", [])], reply: "y" });
|
||||
assert.equal(only.status, 200);
|
||||
const after = readState().items.find((i) => i.id === "q1");
|
||||
assert.equal(after.sentNote.text, "just a note");
|
||||
assert.deepEqual(after.sentNote.images ?? [], []);
|
||||
assert.equal(cli(["wait", "--session", sid, "--seconds", "10"]).status, 0);
|
||||
});
|
||||
|
||||
test("what the person attached is not scanned for markers either", () => {
|
||||
const statePath = path.join(HOME, "sessions", sid, "state.json");
|
||||
const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
||||
state.items.find((i) => i.id === "q1").sentNote = { at: new Date().toISOString(), text: "TASK_COMPLETE Risk 3" };
|
||||
fs.writeFileSync(statePath, JSON.stringify(state, null, 2));
|
||||
const res = cli(["post", "--session", sid, "--file", payload("after2.json", { headline: { stage: "Working" } })]);
|
||||
assert.equal(res.status, 0);
|
||||
});
|
||||
|
||||
test("cancel surfaces as exit 30", async () => {
|
||||
await post("/cancel", {});
|
||||
const res = cli(["wait", "--session", sid, "--seconds", "5"]);
|
||||
@@ -1344,6 +1420,27 @@ test("rejects a review verdict with no label", () => {
|
||||
assert.doesNotMatch(res.stderr, /verdict "changes"/);
|
||||
});
|
||||
|
||||
test("rejects a choice option with no text", () => {
|
||||
const p = {
|
||||
items: [
|
||||
{
|
||||
id: "o1",
|
||||
kind: "choice",
|
||||
title: "Where should we go next",
|
||||
options: [
|
||||
{ k: "A", label: "Reproduce first", desc: "Run it" },
|
||||
{ k: "B", text: "Plan the fixes", detail: "Write a plan" },
|
||||
],
|
||||
required: false,
|
||||
},
|
||||
],
|
||||
};
|
||||
const res = cli(["post", "--session", sid, "--file", payload("option.json", p)], { expectFail: true });
|
||||
assert.equal(res.status, 3);
|
||||
assert.match(res.stderr, /option "A" needs "text"/);
|
||||
assert.doesNotMatch(res.stderr, /option "B"/);
|
||||
});
|
||||
|
||||
test("rejects loop completion markers and metrics-scraper bait", () => {
|
||||
const p = {
|
||||
items: [{ id: "j2", kind: "text", title: "Coverage", body: "Requirements 22 of 25. TASK_COMPLETE", required: false }],
|
||||
@@ -1770,6 +1867,45 @@ test("looks round-trip through the server, and junk never reaches the file", asy
|
||||
);
|
||||
});
|
||||
|
||||
test("a partial looks write merges onto the saved file, so a stale tab cannot undo another tab's change", async () => {
|
||||
const get = async () => (await (await fetch(baseUrl + "/looks", { headers: { cookie: consoleCookie(baseUrl, token) } })).json()).looks;
|
||||
assert.equal((await post("/looks", { set: { sound: false } })).status, 200);
|
||||
assert.deepEqual(await get(), { theme: "dark", accent: "cobalt", sound: false });
|
||||
assert.equal((await post("/looks", { set: { accent: "sky" } })).status, 200);
|
||||
assert.deepEqual(await get(), { theme: "dark", accent: "sky", sound: false }, "keys this write did not name stay put");
|
||||
assert.equal((await post("/looks", { set: { deep: { nested: true } } })).status, 400);
|
||||
assert.deepEqual(await get(), { theme: "dark", accent: "sky", sound: false });
|
||||
assert.equal((await post("/looks", { looks: { theme: "dark", accent: "cobalt" } })).status, 200);
|
||||
});
|
||||
|
||||
test("the tab title carries the session's short id, so tabs from different agents can be told apart", async () => {
|
||||
const html = await (await fetch(baseUrl + "/", { headers: { cookie: consoleCookie(baseUrl, token) } })).text();
|
||||
assert.match(html, new RegExp(`<title>[^<]* · #${sid.slice(-6)} · Plan2Code</title>`));
|
||||
});
|
||||
|
||||
test("models: the user's additions round-trip, XHigh and Max are refused, and the shipped list is read-only", async () => {
|
||||
fs.mkdirSync(path.join(MODELS_DIR, "bin"), { recursive: true });
|
||||
fs.writeFileSync(path.join(MODELS_DIR, "bin", "models.json"), JSON.stringify({ claude: [{ id: "opus", label: "Opus" }], devin: [{ id: "adaptive", label: "Adaptive" }] }));
|
||||
const get = async () => (await fetch(baseUrl + "/models", { headers: { cookie: consoleCookie(baseUrl, token) } })).json();
|
||||
|
||||
assert.deepEqual((await get()).shipped.devin, [{ id: "adaptive", label: "Adaptive" }]);
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [] });
|
||||
|
||||
const saved = await post("/models", { models: { devin: [{ id: " new-model-medium ", label: "" }, { id: "new-model-medium" }, { id: "" }] } });
|
||||
assert.equal(saved.status, 200);
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [{ id: "new-model-medium", label: "new-model-medium" }] });
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(MODELS_DIR, "models.json"), "utf8")).devin.length, 1, "the launcher reads this file");
|
||||
|
||||
for (const id of ["some-model-xhigh", "some-model-MAX", "bad id!"]) {
|
||||
assert.equal((await post("/models", { models: { devin: [{ id }] } })).status, 400, id);
|
||||
}
|
||||
assert.equal((await post("/models", { nope: true })).status, 400);
|
||||
assert.equal((await get()).user.devin.length, 1, "a refused write must not touch what is saved");
|
||||
|
||||
assert.equal((await post("/models", { models: {} })).status, 200, "reset to default");
|
||||
assert.deepEqual((await get()).user, { claude: [], devin: [] });
|
||||
});
|
||||
|
||||
test("stop leaves a process it cannot identify as ours alone", () => {
|
||||
// A handle file can outlive a reboot in the system temp dir and its pid can
|
||||
// be reused. Killing on the strength of a number alone can hit anything.
|
||||
@@ -2051,6 +2187,18 @@ test("a send the agent never settled is still a send in flight", () => {
|
||||
assert.equal(submittedAwaiting({ submitted: sub, thread: [{ who: "agent", text: "No time on me." }] }), null);
|
||||
});
|
||||
|
||||
test("a note the agent has not answered yet is still on its way", () => {
|
||||
const note = { at: "2026-09-23T03:00:00Z", text: "look at this" };
|
||||
assert.equal(noteAwaiting({}), null);
|
||||
assert.equal(noteAwaiting(null), null);
|
||||
assert.equal(noteAwaiting({ sentNote: "nope" }), null);
|
||||
assert.equal(noteAwaiting({ sentNote: note }), note);
|
||||
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Earlier.", at: "2026-09-23T02:00:00Z" }] }), note);
|
||||
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "Seen.", at: "2026-09-23T03:01:00Z" }] }), null);
|
||||
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "user", text: "look at this", at: "2026-09-23T03:00:00Z" }] }), null);
|
||||
assert.equal(noteAwaiting({ sentNote: note, thread: [{ who: "agent", text: "No clock." }] }), null);
|
||||
});
|
||||
|
||||
// --- the session's ending ------------------------------------------------
|
||||
//
|
||||
// Everything else the page shows is a pause. `finish` is the one signal that
|
||||
@@ -2943,26 +3091,26 @@ test("open without --title names the session after the project folder", () => {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
});
|
||||
|
||||
// A saved dark theme and accent used to flash the default light rust for as
|
||||
// A saved dark theme and accent used to flash the default light accent for as
|
||||
// long as it took the script to fetch /looks. The server paints them now.
|
||||
test("saved looks are painted by the server before any script runs", async () => {
|
||||
const looksFile = path.join(HOME, "looks.json");
|
||||
const before = fs.existsSync(looksFile) ? fs.readFileSync(looksFile) : null;
|
||||
fs.writeFileSync(
|
||||
looksFile,
|
||||
JSON.stringify({ looks: { theme: "dark", accent: "ocean", sound: true, width: "wide" } })
|
||||
JSON.stringify({ looks: { theme: "dark", accent: "violet", sound: true, width: "wide" } })
|
||||
);
|
||||
try {
|
||||
const res = cli(["open", "--workflow", "plan", "--no-open"]);
|
||||
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
const cookie = consoleCookie(m[1], m[2]);
|
||||
const html = await (await fetch(m[1] + "/", { headers: { cookie } })).text();
|
||||
assert.match(html, /<html lang="en" data-theme="dark" data-looks-accent="ocean" data-width="wide">/);
|
||||
assert.match(html, /<html lang="en" data-theme="dark" data-looks-accent="violet" data-width="wide">/);
|
||||
const css = await (await fetch(m[1] + "/app.css", { headers: { cookie } })).text();
|
||||
assert.ok(css.includes(`:root[data-looks-accent="ocean"][data-theme="dark"]{--accent:${ACCENTS.ocean.dark[0]}`));
|
||||
assert.ok(css.includes(`:root[data-looks-accent="violet"][data-theme="dark"]{--accent:${ACCENTS.violet.dark[0]}`));
|
||||
assert.ok(!css.includes(`data-looks-accent="${DEFAULT_ACCENT}"`), "the default needs no rule");
|
||||
const boot = JSON.parse(html.match(/id="boot">([\s\S]*?)<\/script>/)[1]);
|
||||
assert.equal(boot.looks.accent, "ocean");
|
||||
assert.equal(boot.looks.accent, "violet");
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
} finally {
|
||||
if (before) fs.writeFileSync(looksFile, before);
|
||||
@@ -3373,6 +3521,7 @@ test("post and wait hand back the terminal line; the collected result on disk do
|
||||
const waiting = cli(["wait", "--session", res.json.sid, "--seconds", "5"]);
|
||||
assert.equal(waiting.status, 10);
|
||||
assert.equal(waiting.json.message, "Waiting on your answer in the web console");
|
||||
assert.match(waiting.json.next, /run this same wait command again/);
|
||||
assert.equal(waiting.json.terminalLine, terminalLine(res.json.url));
|
||||
|
||||
const sent = await fetch(`${s.base}/submit`, {
|
||||
@@ -3396,6 +3545,21 @@ test("post and wait hand back the terminal line; the collected result on disk do
|
||||
}
|
||||
});
|
||||
|
||||
test("building.md gives a quick-task build its own Build progress tab", () => {
|
||||
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "building.md"), "utf8");
|
||||
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
|
||||
assert.ok(section.includes('"title": "Build progress"'));
|
||||
assert.match(section, /post after every step/i);
|
||||
});
|
||||
|
||||
test("building.md has the finished quick task offer Back to the dashboard as well as the review", () => {
|
||||
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "building.md"), "utf8");
|
||||
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
|
||||
const bullet = section.slice(section.indexOf("**The finish after the build:**"), section.indexOf("**Escalated / aborted:**"));
|
||||
assert.ok(bullet.includes('"dashboard": true'));
|
||||
assert.ok(bullet.includes("Review it now"));
|
||||
});
|
||||
|
||||
/* ------------------------------------------- quick question: the contract */
|
||||
|
||||
// Every outcome `wait` had before the chat channel existed, pinned by exit
|
||||
@@ -3411,7 +3575,7 @@ const pinKeys = (obj, expected, what) =>
|
||||
`${what}: top-level keys changed`
|
||||
);
|
||||
const RESULT_KEYS = ["type", "at", "sid", "rev", "actions", "reply", "consumedAt", "terminalLine"];
|
||||
const WAITING_KEYS = ["status", "sid", "elapsed", "answered", "total", "staged", "url", "message", "terminalLine"];
|
||||
const WAITING_KEYS = ["status", "sid", "elapsed", "answered", "total", "staged", "url", "message", "next", "terminalLine"];
|
||||
|
||||
function openSession(extra = {}) {
|
||||
const res = cli(["open", "--file", payload(`pin-${Date.now()}.json`, { ...BASE, ...extra }), "--no-open"]);
|
||||
@@ -3756,15 +3920,14 @@ test("typed text never starts a reply line of its own, so it cannot pass for a d
|
||||
}
|
||||
});
|
||||
|
||||
test("a finished session refuses a question as offline", async () => {
|
||||
test("a finished session whose agent is still listening still takes a question", async () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
postPatch(s, { finish: { headline: "The map is written" } });
|
||||
await until(async () => (await chatFrame(s)).offline);
|
||||
await until(async () => !(await chatFrame(s)).offline);
|
||||
const res = await ask(s, "Anyone there?");
|
||||
assert.equal(res.status, 409);
|
||||
assert.equal(res.body.error, "offline");
|
||||
assert.equal((await s.send("/chat", { reset: true, conversation: 1 })).status, 409);
|
||||
assert.equal(res.status, 200, JSON.stringify(res.body));
|
||||
assert.equal(res.body.ok, true);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
@@ -4064,8 +4227,9 @@ test("unreadDot and shouldChime: one chime per new reply, never while on Ask, ne
|
||||
test("chatOffline: finished, paused, a stale working agent (with quietMinutes), an adrift waiting agent, a live one", () => {
|
||||
const now = 10 * 60 * 60 * 1000;
|
||||
const ago = (ms) => ({ agentLastSeenMs: now - ms, now });
|
||||
assert.equal(chatOffline({ finish: { headline: "Done" }, agent: { status: "waiting" }, ...ago(0) }), true);
|
||||
assert.equal(chatOffline({ finish: { headline: "Paused — saved" }, agent: { status: "working" }, ...ago(0) }), true);
|
||||
assert.equal(chatOffline({ finish: { headline: "Done" }, agent: { status: "waiting" }, ...ago(0) }), false, "a live agent through the finish wait is online");
|
||||
assert.equal(chatOffline({ finish: { headline: "Done" }, agent: { status: "waiting" }, ...ago(3 * 60 * 1000 + 1000) }), true, "offline once it goes quiet");
|
||||
assert.equal(chatOffline({ finish: { headline: "Paused — saved" }, agent: { status: "working" }, ...ago(STALE_MS + 1000) }), true);
|
||||
assert.equal(chatOffline({ agent: { status: "working" }, ...ago(STALE_MS + 1000) }), true);
|
||||
assert.equal(chatOffline({ agent: { status: "working" }, ...ago(STALE_MS - 1000) }), false);
|
||||
assert.equal(chatOffline({ agent: { status: "working", quietMinutes: 20 }, ...ago(15 * 60 * 1000) }), false, "a long task is not offline");
|
||||
@@ -4420,9 +4584,27 @@ test("meter: levels, ring, fold and tooltip wording", () => {
|
||||
fraction: 0.25,
|
||||
words: "Session: fresh",
|
||||
tooltip: "This session is fresh (2 points).",
|
||||
items: [{ label: "Document started", points: 2 }],
|
||||
});
|
||||
});
|
||||
|
||||
test("meter: the breakdown lists each scoring entry once and sums to the total", () => {
|
||||
const entries = [
|
||||
{ kind: "launch", id: "L1", workflow: "dashboard" },
|
||||
{ kind: "launch", id: "L2", workflow: "quick-task" },
|
||||
{ kind: "run", id: "L2:phase-2", event: "implement-phase" },
|
||||
{ kind: "run", id: "L2:phase-2", event: "implement-phase" },
|
||||
{ kind: "run", id: "L2:handoff", event: "handoff" },
|
||||
{ kind: "folder-issue", id: "L2:api", name: "api", reason: "denied" },
|
||||
];
|
||||
assert.deepEqual(breakdownFrom(entries), [
|
||||
{ label: "Quick task started", points: 1 },
|
||||
{ label: "Implement phase built: phase-2", points: 2 },
|
||||
]);
|
||||
assert.equal(pointsFrom(entries), breakdownFrom(entries).reduce((n, r) => n + r.points, 0));
|
||||
assert.deepEqual(breakdownFrom(null), []);
|
||||
});
|
||||
|
||||
test("workspace: default names, name rules and the free-name suggestion", () => {
|
||||
assert.equal(defaultName("C:\\git\\My Repo_v2"), "my-repo-v2");
|
||||
assert.equal(defaultName("/home/sam/api/"), "api");
|
||||
@@ -4531,6 +4713,7 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
"meter-fill",
|
||||
"meter-words",
|
||||
"meter-pop",
|
||||
"meter-list",
|
||||
"meter-help",
|
||||
]) {
|
||||
assert.ok(html.includes(`id="${id}"`), `index.html must carry #${id}`);
|
||||
@@ -5010,6 +5193,274 @@ test("meter: a folder issue shows in the frame's workspace.issues until the next
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------- review fixes: two writers, one page */
|
||||
|
||||
// Browsers scope a cookie by host and ignore the port. With one shared name,
|
||||
// the second session's link overwrote the first session's token, and the
|
||||
// first tab got nothing but 403s from then on.
|
||||
test("two sessions keep their own cookies: each server reads only the one named for its port", async () => {
|
||||
const a = openSession();
|
||||
const b = openSession();
|
||||
try {
|
||||
for (const s of [a, b]) {
|
||||
const token = s.url.match(/\/s\/([^/]+)\//)[1];
|
||||
const res = await fetch(s.url, { redirect: "manual" });
|
||||
assert.ok(res.headers.get("set-cookie").startsWith(`${consoleCookie(s.base, token)};`));
|
||||
}
|
||||
// What a browser holding both sends to either server.
|
||||
const both = `${a.cookie}; ${b.cookie}`;
|
||||
for (const s of [a, b]) {
|
||||
assert.equal((await fetch(`${s.base}/state`, { headers: { cookie: both, connection: "close" } })).status, 200);
|
||||
}
|
||||
// The old shared name is no longer a key to anything.
|
||||
const aToken = a.url.match(/\/s\/([^/]+)\//)[1];
|
||||
const shared = await fetch(`${a.base}/state`, { headers: { cookie: `p2c_console=${aToken}`, connection: "close" } });
|
||||
assert.equal(shared.status, 403);
|
||||
// Another session's cookie opens nothing here either.
|
||||
const crossed = b.cookie.replace(/^p2c_console_\d+/, `p2c_console_${new URL(a.base).port}`);
|
||||
assert.equal((await fetch(`${a.base}/state`, { headers: { cookie: crossed, connection: "close" } })).status, 403);
|
||||
} finally {
|
||||
cli(["stop", "--session", a.sid]);
|
||||
cli(["stop", "--session", b.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// state.json has two writers, `post` and the server's /submit. Both are held
|
||||
// at the lock here until each has read nothing yet, then let go together:
|
||||
// whichever writes second must be building on the first one's write.
|
||||
test("a post and a submit that overlap both survive: the state lock serialises them", async () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
const lock = path.join(s.session, STATE_LOCK_FILE);
|
||||
fs.writeFileSync(lock, String(process.pid));
|
||||
const patchFile = payload(`overlap-${Date.now()}.json`, {
|
||||
items: [{ id: "q2", kind: "text", title: "Team name", required: false }],
|
||||
agent: { status: "waiting", activity: "Asking about the team" },
|
||||
});
|
||||
const posting = new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, [CONSOLE_CLI, "post", "--session", s.sid, "--file", patchFile], { env: ENV, cwd: ROOT });
|
||||
let err = "";
|
||||
child.stderr.on("data", (c) => (err += c));
|
||||
child.on("exit", (code) => resolve({ code, err }));
|
||||
});
|
||||
const submitting = s.send("/submit", EXPORT_A);
|
||||
await sleep(400);
|
||||
assert.ok(fs.existsSync(lock), "nobody broke a live, young lock");
|
||||
fs.rmSync(lock);
|
||||
const [posted, submitted] = await Promise.all([posting, submitting]);
|
||||
assert.equal(posted.code, 0, posted.err);
|
||||
assert.equal(submitted.status, 200);
|
||||
|
||||
const state = readState(s.session);
|
||||
const q1 = state.items.find((i) => i.id === "q1");
|
||||
assert.ok(state.items.some((i) => i.id === "q2"), "the post's new question is kept");
|
||||
assert.equal(state.agent.activity, "Asking about the team");
|
||||
assert.equal(q1.submitted && q1.submitted.k, "A", "the send's record is kept");
|
||||
assert.equal(state.phase, "submitted");
|
||||
assert.equal(fs.existsSync(lock), false, "and the lock is let go");
|
||||
assert.equal(cli(["wait", "--session", s.sid, "--seconds", "5"]).status, 0);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
test("a lock left by a writer that died is broken rather than waited on for good", () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
const lock = path.join(s.session, STATE_LOCK_FILE);
|
||||
// A pid no process has: the holder is gone.
|
||||
fs.writeFileSync(lock, "999999999");
|
||||
const res = postPatch(s, { agent: { status: "working" } });
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
assert.equal(readState(s.session).agent.status, "working");
|
||||
assert.equal(fs.existsSync(lock), false);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// A young handle and a live pid are what a server that died a minute ago
|
||||
// leaves behind for any process to inherit. Only /health is proof.
|
||||
test("stop never kills a live process that does not answer /health as ours", () => {
|
||||
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
const sidForged = "20000101-000000-beef01";
|
||||
// Under the test home, as the CLI sees it: this process has no override of
|
||||
// its own, and lib.mjs would name the real runtime dir.
|
||||
const dir = path.join(HOME, "runtime", cwdHash(repoRoots(ROOT).project));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const forged = path.join(dir, `${sidForged}.json`);
|
||||
try {
|
||||
fs.writeFileSync(
|
||||
forged,
|
||||
JSON.stringify({ v: 1, sid: sidForged, pid: bystander.pid, port: 1, url: "http://127.0.0.1:1/", startedAt: new Date().toISOString() })
|
||||
);
|
||||
const res = cli(["stop", "--session", sidForged]);
|
||||
assert.equal(res.json.stopped, 0);
|
||||
assert.equal(res.json.skippedStaleHandles, 1);
|
||||
assert.equal(fs.existsSync(forged), false, "the handle goes");
|
||||
assert.doesNotThrow(() => process.kill(bystander.pid, 0), "the process stays");
|
||||
} finally {
|
||||
bystander.kill();
|
||||
fs.rmSync(forged, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// A fresh `open` starts the server before it writes the state. The server used
|
||||
// to seed workspace.json at boot from the folder holding .git, which for a
|
||||
// linked worktree is the main checkout.
|
||||
test("open from a linked worktree seeds the workspace with the worktree, not the main checkout", () => {
|
||||
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-wt-"));
|
||||
const repo = path.join(base, "repo");
|
||||
const wt = path.join(base, "wt");
|
||||
fs.mkdirSync(repo);
|
||||
const git = (cwd, ...a) => execFileSync("git", a, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"] });
|
||||
git(repo, "init", "-q");
|
||||
git(repo, "-c", "user.email=t@t", "-c", "user.name=t", "commit", "-q", "--allow-empty", "-m", "x");
|
||||
git(repo, "worktree", "add", "-q", wt);
|
||||
const { worktree, project } = repoRoots(wt);
|
||||
assert.notEqual(worktree, project);
|
||||
let sidOpened = null;
|
||||
try {
|
||||
const res = cliIn(wt, ["open", "--workflow", "plan", "--no-open"]);
|
||||
sidOpened = res.json.sid;
|
||||
assert.deepEqual(res.json.workspace.folders.map((f) => f.path), [worktree]);
|
||||
const onDisk = JSON.parse(fs.readFileSync(path.join(res.json.session, WORKSPACE_FILE), "utf8"));
|
||||
assert.deepEqual(onDisk.folders.map((f) => f.path), [worktree], "workspace.json names the worktree");
|
||||
} finally {
|
||||
if (sidOpened) cliIn(wt, ["stop", "--session", sidOpened]);
|
||||
fs.rmSync(base, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------- review fixes: the CLI's edges */
|
||||
|
||||
test("validate refuses a text pattern that does not compile, and post exits 3 on it", () => {
|
||||
const item = (pattern) => ({ items: [{ id: "t1", kind: "text", title: "Ticket number", pattern }] });
|
||||
assert.deepEqual(validate(item("^[A-Z]+-\\d+$")), []);
|
||||
assert.match(validate(item("([")).join("\n"), /"pattern" is not a valid JavaScript regular expression/);
|
||||
assert.match(validate(item(7)).join("\n"), /"pattern" must be a string/);
|
||||
|
||||
const s = openSession();
|
||||
try {
|
||||
const before = fs.readFileSync(path.join(s.session, "state.json"), "utf8");
|
||||
const bad = postPatch(s, { items: [{ id: "t1", kind: "text", title: "Ticket number", pattern: "([", required: false }] }, { expectFail: true });
|
||||
assert.equal(bad.status, 3);
|
||||
assert.match(bad.stderr, /pattern/);
|
||||
assert.equal(fs.readFileSync(path.join(s.session, "state.json"), "utf8"), before, "nothing was written");
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
test("a flag that needs a value and has none is bad usage, exit 2, never a crash", () => {
|
||||
for (const argv of [
|
||||
["open", "--resume"],
|
||||
["open", "--session", "--no-open"],
|
||||
["wait", "--session"],
|
||||
["post", "--session", sid, "--file"],
|
||||
["keep", "--session", sid, "--upload", "x", "--name", "--spec", "specs/x"],
|
||||
["status", "--session"],
|
||||
["stop", "--session"],
|
||||
]) {
|
||||
const res = cli(argv, { expectFail: true });
|
||||
assert.equal(res.status, 2, argv.join(" "));
|
||||
assert.match(res.stderr, /needs a value/, argv.join(" "));
|
||||
assert.doesNotMatch(res.stderr, /TypeError|at .*\.mjs/, argv.join(" "));
|
||||
}
|
||||
});
|
||||
|
||||
test("wait reads --seconds 6s as six seconds, not as nothing", () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
const t0 = Date.now();
|
||||
const res = cli(["wait", "--session", s.sid, "--seconds", "6s"]);
|
||||
assert.equal(res.status, 10);
|
||||
assert.ok(Date.now() - t0 >= 5000, "the slice ran its length");
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
test("only open leaves the console-dir pointer; status, help and a bad command do not", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pointer-"));
|
||||
const env = { PLAN2CODE_CONSOLE_HOME: home, PLAN2CODE_MODELS_DIR: path.join(home, "plan2code") };
|
||||
const pointer = path.join(home, "console-dir");
|
||||
try {
|
||||
cli(["status"], { env });
|
||||
cli(["help"], { env });
|
||||
const usage = cli(["nope"], { env, expectFail: true });
|
||||
assert.match(usage.stderr, /keep/, "the usage line names every command");
|
||||
assert.equal(fs.existsSync(pointer), false);
|
||||
const opened = cli(["open", "--no-open"], { env });
|
||||
assert.equal(fs.readFileSync(pointer, "utf8").trim(), path.join(ROOT, "src", "web-console"));
|
||||
cli(["stop", "--session", opened.json.sid], { env });
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
/* ------------------------------------------- review fixes: the Origin guard */
|
||||
|
||||
// Every route that changes something refuses a foreign Origin before it reads
|
||||
// a byte of the body. /workspace/browse is the one that could open a native
|
||||
// dialog; the echo stands in for it, so a guard that failed would answer 200
|
||||
// here rather than put a picker on the screen.
|
||||
test("every state-changing route refuses a foreign Origin, and nothing changes", async () => {
|
||||
const picked = tempFolder();
|
||||
const s = consoleSession(["--workflow", "plan", "--file", payload(`origin-${Date.now()}.json`, BASE)], {
|
||||
env: { PLAN2CODE_PICKER_ECHO: picked },
|
||||
});
|
||||
const files = ["state.json", "result.json", "draft.json", WORKSPACE_FILE, "chat.ndjson"];
|
||||
const snapshot = () =>
|
||||
Object.fromEntries(
|
||||
[...files.map((f) => path.join(s.session, f)), path.join(HOME, "looks.json")].map((f) => [
|
||||
f,
|
||||
fs.existsSync(f) ? fs.readFileSync(f, "utf8") : null,
|
||||
])
|
||||
);
|
||||
const routes = [
|
||||
["POST", "/submit", EXPORT_A],
|
||||
["POST", "/cancel", {}],
|
||||
["POST", "/chat", { text: "Why CSV?", conversation: 1 }],
|
||||
["POST", "/chat/decision", { re: "r1", decision: "approve", conversation: 1 }],
|
||||
["POST", "/draft", { staged: { q1: { k: "B" } } }],
|
||||
["POST", "/looks", { looks: { theme: "light" } }],
|
||||
["POST", "/models", { models: { devin: [{ id: "x" }] } }],
|
||||
["POST", "/workspace/add", { path: picked }],
|
||||
["POST", "/workspace/edit", { id: "f0", name: "renamed" }],
|
||||
["POST", "/workspace/remove", { id: "f0" }],
|
||||
["POST", "/workspace/browse", {}],
|
||||
["POST", "/bye", {}],
|
||||
["POST", "/upload", null],
|
||||
["DELETE", "/uploads/00000000-0000-0000-0000-000000000000.jpg", null],
|
||||
];
|
||||
try {
|
||||
await s.get("/workspace");
|
||||
const before = snapshot();
|
||||
for (const [method, route, body] of routes) {
|
||||
const res = await fetch(`${s.base}${route}`, {
|
||||
method,
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, origin: "http://evil.example.com", connection: "close" },
|
||||
body: body === null ? undefined : JSON.stringify(body),
|
||||
});
|
||||
assert.equal(res.status, 403, `${method} ${route}`);
|
||||
}
|
||||
assert.deepEqual(snapshot(), before, "no file moved");
|
||||
// And the same requests from the page's own origin do get through, so the
|
||||
// 403s above are the guard and not something else.
|
||||
const own = await fetch(`${s.base}/workspace/browse`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, origin: s.base, connection: "close" },
|
||||
body: "{}",
|
||||
});
|
||||
assert.equal(own.status, 200);
|
||||
assert.deepEqual(await own.json(), { path: picked });
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
fs.rmSync(picked, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test.after(() => {
|
||||
try {
|
||||
execFileSync(process.execPath, [CONSOLE_CLI, "stop", "--all"], { env: ENV, cwd: ROOT });
|
||||
@@ -5158,7 +5609,7 @@ test("validate rejects an item pattern that is not a valid regular expression",
|
||||
for (const bad of ["([a-z", "*oops", 42]) {
|
||||
const problems = validate({ items: [item(bad)] });
|
||||
assert.equal(problems.length, 1, JSON.stringify(bad));
|
||||
assert.match(problems[0], /item "slug" "pattern" must be a string holding a valid JavaScript regular expression/);
|
||||
assert.match(problems[0], /item "slug" "pattern" (must be a string holding a JavaScript regular expression|is not a valid JavaScript regular expression)/);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -5167,3 +5618,50 @@ test("the usage line names every command", () => {
|
||||
assert.equal(res.status, 2);
|
||||
assert.match(res.stderr, /<open\|post\|wait\|chat\|keep\|status\|stop\|help>/);
|
||||
});
|
||||
|
||||
test("runHint: git blocks get Run it, command words get the hint, the rest nothing", () => {
|
||||
assert.equal(runHint("git add -A && git commit -m \"x\""), "run");
|
||||
assert.equal(runHint("\n\ngit status\n"), "run");
|
||||
assert.equal(runHint("git"), "run");
|
||||
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 runs.
|
||||
assert.equal(runHint(" \ngit commit -m \"x\"\n"), "run");
|
||||
});
|
||||
|
||||
test("a reused item id does not inherit the previous answer's submitted record", async () => {
|
||||
const { applyPatch } = await import("../src/web-console/lib.mjs");
|
||||
const 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/lib.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" }] } }), []);
|
||||
});
|
||||
Reference in new issue
Block a user