Add Stop with a handoff, handoff chips on the dashboard, and a one-step delete for fixed bugs

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-17 12:35:29 -07:00
1 parent 33a0dbd34a
commit 36843e4bc9
34 files changed
+1926 -267

No files matched your search

-55
View File
@@ -1,55 +0,0 @@
// Tests for plan2code-handoff's scripts/handoff-path.mjs.
//
// See skill-script-helpers.mjs for how these run.
import { test } from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { ROOT, SKILLS, NOW, runScript, tmp, write, read, gitInit, phase } from "./skill-script-helpers.mjs";
/* =========================================================== handoff-path.mjs */
test("handoff-path: timestamped name, no overwrite, git ignore check", () => {
const repo = tmp("handoff");
gitInit(repo);
const H = (...a) => runScript("plan2code-handoff", "handoff-path.mjs", a, { cwd: repo });
const first = H("--dir", "handoffs");
assert.equal(first.code, 0, first.stderr);
assert.equal(path.basename(first.json.path), "2026-08-03-1405-handoff.md");
assert.equal(first.json.created, true);
assert.equal(first.json.git.inRepo, true);
assert.equal(first.json.git.ignored, false);
assert.match(first.json.warning, /handoffs\//);
fs.writeFileSync(first.json.path, "x");
assert.equal(path.basename(H("--dir", "handoffs").json.path), "2026-08-03-1405-2-handoff.md");
write(repo, ".gitignore", "handoffs/\n");
assert.equal(H("--dir", "handoffs").json.git.ignored, true);
const temp = H();
assert.equal(temp.json.git.inRepo, false);
assert.equal(temp.json.git.ignored, null);
const dry = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "later", "--dry-run"], { cwd: repo });
assert.equal(dry.json.created, false);
assert.ok(!fs.existsSync(path.join(repo, "later")));
});
/* ================================================= verification regressions */
test("handoff-path: the repo root itself is never the line to ignore", () => {
const repo = tmp("handoff2");
gitInit(repo);
const j = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "."], { cwd: repo }).json;
assert.equal(j.git.inRepo, true);
assert.equal(j.git.ignoreLine, "*-handoff.md");
});
test("handoff-path: --dir naming an existing file is refused", () => {
const repo = tmp("handoff3");
write(repo, "notes.txt", "x");
const r = runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt"], { cwd: repo });
assert.equal(r.code, 5);
assert.equal(r.json.ok, false);
assert.equal(r.json.error, "not-a-folder");
assert.match(r.json.next, /--dir temp/);
assert.equal(runScript("plan2code-handoff", "handoff-path.mjs", ["--dir", "notes.txt", "--dry-run"], { cwd: repo }).code, 5, "dry-run refuses it too");
});
+11
View File
@@ -29,6 +29,17 @@ test("every skill with scripts ships common.mjs and version.json; dashboard ship
assert.equal(JSON.parse(fs.readFileSync(path.join(SKILLS, "plan2code-4-finalize", "scripts", "version.json"), "utf8")).version, v);
});
test("the Handoff skill writes through the console's handoff new, with no folder or gitignore step", () => {
const skill = fs.readFileSync(path.join(SKILLS, "plan2code-handoff", "SKILL.md"), "utf8");
assert.match(skill, /console\.mjs" handoff new/);
assert.doesNotMatch(skill, /handoff-path\.mjs/);
assert.doesNotMatch(skill, /--dir temp/);
assert.doesNotMatch(skill, /\.gitignore/);
// handoff-path.mjs is retired: the build ships only the shared specs.mjs.
assert.ok(!fs.existsSync(path.join(SKILLS, "plan2code-handoff", "scripts", "handoff-path.mjs")), "handoff-path.mjs is not shipped");
assert.ok(fs.existsSync(path.join(SKILLS, "plan2code-handoff", "scripts", "specs.mjs")), "specs.mjs still is");
});
test("every script a SKILL.md (or a reference it ships) runs exists beside it, and answers --help", () => {
for (const skill of fs.readdirSync(SKILLS)) {
const dir = path.join(SKILLS, skill);
+503
View File
@@ -0,0 +1,503 @@
// Web console tests, the handoff store: ids, writing, listing, marking,
// removing and sweeping ~/.plan2code/handoffs/, and the console commands
// built on it.
// Run with: node --test scripts/test-web-console-handoffs.mjs
//
// Shared setup (a per-process console home, the CLI runner, fixtures) lives in
// web-console-test-helpers.mjs; see the comment at its top. Every handoff here
// lands in its throwaway HANDOFFS_DIR, never the real home folder.
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 { spawnSync } from "node:child_process";
import { CONSOLE_CLI, ENV, HANDOFFS_DIR, cli, safeJson, sessionUrl } from "./web-console-test-helpers.mjs";
process.env.PLAN2CODE_HANDOFFS_DIR = HANDOFFS_DIR;
const store = await import("../src/web-console/handoffs.mjs");
const { HANDOFF_ID, handoffsDir, isHandoffId } = store;
test("isHandoffId takes only a bare handoff id", () => {
assert.ok(isHandoffId("2026-10-17-1152-handoff"));
assert.ok(isHandoffId("2026-10-17-1152-handoff-3"));
for (const bad of ["../x", "2026-10-17-1152-handoff.md", "a/2026-10-17-1152-handoff", "", null, undefined, 7, {}]) {
assert.equal(isHandoffId(bad), false, String(bad));
}
assert.ok(HANDOFF_ID.test("2026-10-17-1152-handoff"));
});
test("handoffsDir follows PLAN2CODE_HANDOFFS_DIR at call time", () => {
assert.equal(handoffsDir(), HANDOFFS_DIR);
const saved = process.env.PLAN2CODE_HANDOFFS_DIR;
try {
process.env.PLAN2CODE_HANDOFFS_DIR = path.join(HANDOFFS_DIR, "elsewhere");
assert.equal(handoffsDir(), path.join(HANDOFFS_DIR, "elsewhere"));
} finally {
process.env.PLAN2CODE_HANDOFFS_DIR = saved;
}
});
// A link at `at`: a file symlink to `file` where the machine allows one, else
// a junction to the folder `dir`, which needs no privilege on Windows and
// which lstat reports as a link all the same. False when neither can be made.
function link(file, dir, at) {
try {
fs.symlinkSync(file, at, "file");
return true;
} catch (err) {
if (err.code !== "EPERM") throw err;
}
try {
fs.symlinkSync(dir, at, "junction");
return true;
} catch {
return false;
}
}
// A clean folder per test that writes handoffs, and the pinned clock it asks for.
function fresh(nowPinned) {
fs.rmSync(HANDOFFS_DIR, { recursive: true, force: true });
if (nowPinned === undefined) delete process.env.PLAN2CODE_NOW;
else process.env.PLAN2CODE_NOW = nowPinned;
}
const WORKTREE = path.join(HANDOFFS_DIR, "..", "repo");
const REC = {
worktree: WORKTREE,
project: WORKTREE,
spec: "specs/lunch-vote",
workflow: "quick-task",
skill: "plan2code-quick-task",
title: "Lunch vote",
fromStop: true,
};
test("newHandoff claims the next free id for the minute and writes only the .json", () => {
fresh("2026-10-17 11:52");
try {
const a = store.newHandoff(REC);
const b = store.newHandoff({ ...REC, spec: undefined, fromStop: false });
assert.equal(a.id, "2026-10-17-1152-handoff");
assert.equal(b.id, "2026-10-17-1152-handoff-2");
assert.equal(a.path, path.join(HANDOFFS_DIR, a.id + ".md"));
assert.equal(fs.existsSync(a.path), false, "the agent writes the .md");
const meta = JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, a.id + ".json"), "utf8"));
assert.deepEqual(Object.keys(meta), ["v", "id", "title", "worktree", "project", "spec", "workflow", "skill", "written", "fromStop", "usedAt"]);
assert.deepEqual(
{ ...meta, written: undefined },
{ v: 1, id: a.id, title: "Lunch vote", worktree: WORKTREE, project: WORKTREE, spec: "specs/lunch-vote", workflow: "quick-task", skill: "plan2code-quick-task", written: undefined, fromStop: true, usedAt: null }
);
assert.ok(!Number.isNaN(Date.parse(meta.written)));
assert.deepEqual(a.meta, meta);
assert.equal(b.meta.spec, null);
assert.equal(b.meta.fromStop, false);
} finally {
fresh();
}
});
test("newHandoff refuses a bad workflow, skill or spec and leaves no file", () => {
fresh("2026-10-17 11:52");
try {
for (const [field, value] of [["workflow", "Quick Task"], ["workflow", undefined], ["skill", "../x"], ["spec", "../x"], ["spec", "specs/a/b"]]) {
assert.throws(() => store.newHandoff({ ...REC, [field]: value }), new RegExp(field));
}
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR) : [], []);
} finally {
fresh();
}
});
test("readHandoffMeta round-trips, markHandoffUsed stamps usedAt and leaves the .md alone", () => {
fresh("2026-10-17 11:52");
try {
const { id, path: md, meta } = store.newHandoff(REC);
fs.writeFileSync(md, "# Handoff: Lunch vote\n");
const before = fs.readFileSync(md);
assert.deepEqual(store.readHandoffMeta(id), meta);
const used = store.markHandoffUsed(id, new Date("2026-10-18T09:00:00Z"));
assert.equal(used.usedAt, "2026-10-18T09:00:00.000Z");
assert.deepEqual(store.readHandoffMeta(id), used);
assert.deepEqual(fs.readFileSync(md), before);
assert.equal(store.readHandoffMeta("../x"), null);
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-9"), null);
assert.equal(store.markHandoffUsed("2026-10-17-1152-handoff-9"), null);
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-17-1152-handoff-7.json"), "not json");
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-7"), null);
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-17-1152-handoff-8.json"), JSON.stringify({ ...meta, v: 2 }));
assert.equal(store.readHandoffMeta("2026-10-17-1152-handoff-8"), null);
} finally {
fresh();
}
});
test("readHandoffMeta refuses a linked .json", (t) => {
fresh("2026-10-17 11:52");
try {
const { meta } = store.newHandoff(REC);
const linkId = "2026-10-17-1152-handoff-5";
const outside = path.join(HANDOFFS_DIR, "..", "outside-dir");
fs.mkdirSync(outside, { recursive: true });
if (!link(path.join(HANDOFFS_DIR, meta.id + ".json"), outside, path.join(HANDOFFS_DIR, linkId + ".json"))) {
t.skip("this machine can make neither a symlink nor a junction");
return;
}
assert.equal(store.readHandoffMeta(linkId), null);
} finally {
fresh();
}
});
// A handoff with a document, as the agent would leave it.
function written(rec, md, when) {
const h = store.newHandoff(rec, when);
if (md !== null) fs.writeFileSync(h.path, md);
return h;
}
const DOC = `# Handoff: Lunch vote
## Context
Some context.
## Next task
Wire the vote button
to the tally, then test it.
## Notes
x
`;
test("listHandoffs lists only this checkout's unused handoffs that have both files, newest first", () => {
fresh();
try {
const mine = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
const newer = written({ ...REC, title: "Second" }, "# Handoff - Second try\n\n## Next task\n\n" + "word ".repeat(80) + "\n", new Date("2026-10-17T12:00:00Z"));
written({ ...REC, worktree: path.join(HANDOFFS_DIR, "..", "other") }, DOC, new Date("2026-10-17T10:01:00Z"));
const used = written(REC, DOC, new Date("2026-10-17T10:02:00Z"));
store.markHandoffUsed(used.id);
// A .json with no .md, and a .md with no .json.
written(REC, null, new Date("2026-10-17T10:03:00Z"));
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-01-0900-handoff.md"), DOC);
const list = store.listHandoffs(WORKTREE);
assert.deepEqual(list.map((h) => h.id), [newer.id, mine.id]);
assert.deepEqual(list[1], {
id: mine.id,
title: "Lunch vote",
next: "Wire the vote button to the tally, then test it.",
written: mine.meta.written,
spec: "specs/lunch-vote",
skill: "plan2code-quick-task",
workflow: "quick-task",
});
assert.equal(list[0].title, "Second try");
assert.equal(list[0].next.length, 280);
assert.ok(list[0].next.endsWith("…"));
} finally {
fresh();
}
});
test("listHandoffs falls back to the stored title and lists nothing for a missing folder", () => {
fresh();
try {
assert.deepEqual(store.listHandoffs(WORKTREE), []);
const h = written(REC, "No heading here.\n", new Date("2026-10-17T10:00:00Z"));
assert.deepEqual(store.listHandoffs(WORKTREE).map((x) => [x.id, x.title, x.next]), [[h.id, "Lunch vote", ""]]);
// Only the word "Handoff" is a prefix: "Handoffs" is part of the title.
const plural = written(REC, "# Handoffs page redesign\n", new Date("2026-10-17T09:00:00Z"));
assert.equal(store.listHandoffs(WORKTREE).find((x) => x.id === plural.id).title, "Handoffs page redesign");
} finally {
fresh();
}
});
test("listHandoffs matches the worktree whatever its case on win32 and darwin", { skip: process.platform !== "win32" && process.platform !== "darwin" }, () => {
fresh();
try {
const h = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
assert.deepEqual(store.listHandoffs(WORKTREE.toUpperCase()).map((x) => x.id), [h.id]);
} finally {
fresh();
}
});
test("removeHandoff removes both files, or a lone one, and refuses anything else", () => {
fresh();
try {
const both = written(REC, DOC, new Date("2026-10-17T10:00:00Z"));
assert.deepEqual(store.removeHandoff(both.id), { ok: true, removed: [both.id + ".md", both.id + ".json"] });
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR), []);
fs.writeFileSync(path.join(HANDOFFS_DIR, "2026-10-01-0900-handoff.md"), DOC);
assert.deepEqual(store.removeHandoff("2026-10-01-0900-handoff").removed, ["2026-10-01-0900-handoff.md"]);
const lone = written(REC, null, new Date("2026-10-17T10:01:00Z"));
assert.deepEqual(store.removeHandoff(lone.id).removed, [lone.id + ".json"]);
assert.throws(() => store.removeHandoff("../evil"), /not a handoff id: \.\.\/evil/);
assert.throws(() => store.removeHandoff("2026-10-01-0900-handoff"), /there is no handoff 2026-10-01-0900-handoff/);
} finally {
fresh();
}
});
test("removeHandoff refuses a linked .md and leaves everything in place", (t) => {
fresh();
try {
const h = written(REC, null, new Date("2026-10-17T10:00:00Z"));
const outside = path.join(HANDOFFS_DIR, "..", "outside.md");
const outsideDir = path.join(HANDOFFS_DIR, "..", "outside-dir");
fs.writeFileSync(outside, "keep me");
fs.mkdirSync(outsideDir, { recursive: true });
fs.writeFileSync(path.join(outsideDir, "keep.txt"), "keep me too");
if (!link(outside, outsideDir, h.path)) {
t.skip("this machine can make neither a symlink nor a junction");
return;
}
assert.throws(() => store.removeHandoff(h.id), /link/);
assert.ok(fs.existsSync(path.join(HANDOFFS_DIR, h.id + ".json")));
assert.ok(fs.lstatSync(h.path).isSymbolicLink(), "the link itself stays");
assert.equal(fs.readFileSync(outside, "utf8"), "keep me");
assert.equal(fs.readFileSync(path.join(outsideDir, "keep.txt"), "utf8"), "keep me too");
} finally {
fresh();
}
});
test("staleHandoffs lists only month-old handoffs and removeHandoffs takes both files", async () => {
fresh();
try {
const old = written(REC, DOC, new Date("2026-09-01T10:00:00Z"));
const recent = written(REC, DOC, new Date("2026-10-16T10:00:00Z"));
const oldMdOnly = "2026-08-01-0900-handoff";
fs.writeFileSync(path.join(HANDOFFS_DIR, oldMdOnly + ".md"), DOC);
fs.writeFileSync(path.join(HANDOFFS_DIR, "notes.txt"), "not mine");
const DAY = 24 * 60 * 60 * 1000;
const age = (file, days) => {
const t = (Date.now() - days * DAY) / 1000;
fs.utimesSync(file, t, t);
};
age(path.join(HANDOFFS_DIR, old.id + ".json"), 31);
age(old.path, 31);
age(path.join(HANDOFFS_DIR, recent.id + ".json"), 1);
age(path.join(HANDOFFS_DIR, oldMdOnly + ".md"), 40);
age(path.join(HANDOFFS_DIR, "notes.txt"), 90);
const stale = store.staleHandoffs(Date.now(), 30 * DAY);
assert.deepEqual(stale.sort(), [oldMdOnly, old.id].sort());
assert.deepEqual((await store.removeHandoffs([...stale, "../evil", "notes.txt"])).sort(), [oldMdOnly, old.id].sort());
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR).sort(), [recent.id + ".json", recent.id + ".md", "notes.txt"].sort());
} finally {
fresh();
}
});
/* ------------------------------------------------------- console commands */
// A throwaway git checkout to run the CLI in, so repoRoots() names it.
const REPO = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-handoff-repo-"));
spawnSync("git", ["init", "-q", REPO], { env: ENV });
const REPO_REAL = fs.realpathSync.native(REPO);
function run(args) {
const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", cwd: REPO });
return { status: res.status, stderr: res.stderr, json: safeJson(res.stdout) };
}
test("handoff new claims a handoff for this checkout and prints where to write it", () => {
fresh();
try {
const res = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "specs/lunch-vote", "--title", "Lunch vote", "--from-stop"]);
assert.equal(res.status, 0, res.stderr);
assert.equal(res.json.ok, true);
assert.ok(store.isHandoffId(res.json.id));
assert.equal(path.dirname(res.json.path), HANDOFFS_DIR);
assert.ok(res.json.path.endsWith(".md"));
assert.equal(fs.existsSync(res.json.path), false);
const meta = JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, res.json.id + ".json"), "utf8"));
assert.equal(meta.worktree, REPO_REAL);
assert.equal(meta.project, REPO_REAL);
assert.equal(meta.spec, "specs/lunch-vote");
assert.equal(meta.fromStop, true);
assert.deepEqual(res.json.meta, meta);
} finally {
fresh();
}
});
test("handoff new refuses bad usage with 2 and a bad value with 3", () => {
fresh();
try {
assert.equal(run(["handoff", "new", "--workflow", "quick-task"]).status, 2);
assert.equal(run(["handoff", "new", "--skill", "plan2code-quick-task"]).status, 2);
assert.equal(run(["handoff", "list"]).status, 2);
assert.equal(run(["handoff"]).status, 2);
const bad = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "../x"]);
assert.equal(bad.status, 3);
assert.equal(bad.json.ok, false);
assert.match(bad.json.message, /spec/);
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR) : [], []);
} finally {
fresh();
}
});
test("delete-handoff removes both files and refuses a bad id or no flag", () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(made.path, DOC);
const done = run(["delete-handoff", "--handoff", made.id]);
assert.equal(done.status, 0, done.stderr);
assert.deepEqual(done.json, { ok: true, removed: [made.id + ".md", made.id + ".json"] });
assert.deepEqual(fs.readdirSync(HANDOFFS_DIR), []);
const bad = run(["delete-handoff", "--handoff", "../evil"]);
assert.equal(bad.status, 3);
assert.equal(bad.json.ok, false);
assert.match(bad.json.message, /not a handoff id/);
assert.equal(run(["delete-handoff"]).status, 2);
assert.equal(run(["delete-handoff", "--handoff"]).status, 2);
} finally {
fresh();
}
});
/* ------------------------------------------------- the dashboard's scan */
// Open a dashboard in REPO (and stop it after), returning its state and a getter for pages.
async function withDashboard(fn) {
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
assert.equal(opened.status, 0, opened.stderr);
const s = sessionUrl(opened.json.url);
const get = (pathname) => fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } });
try {
return await fn({ sid: opened.json.sid, session: opened.json.session, get });
} finally {
run(["stop", "--session", opened.json.sid]);
}
}
const readStateOf = (session) => JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8"));
test("a dashboard open scans this checkout's handoffs and the folder; other workflows do not", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
fs.writeFileSync(made.path, DOC);
await withDashboard(({ session }) => {
const scan = readStateOf(session).scan;
assert.equal(scan.handoffs.length, 1);
assert.equal(scan.handoffs[0].id, made.id);
assert.equal(scan.handoffs[0].title, "Lunch vote");
assert.equal(scan.handoffs[0].next, "Wire the vote button to the tally, then test it.");
assert.equal(scan.handoffsDir, HANDOFFS_DIR);
});
const quick = run(["open", "--no-open", "--workflow", "quick-task"]);
try {
assert.equal(readStateOf(quick.json.session).scan, undefined, "no scan, so no handoffs, off the dashboard");
} finally {
run(["stop", "--session", quick.json.sid]);
}
} finally {
fresh();
}
});
test("GET /handoff serves a scanned handoff's document and nothing else", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
fs.writeFileSync(made.path, DOC);
const unscanned = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(unscanned.path, DOC);
await withDashboard(async ({ get }) => {
// The two above were both on disk when the dashboard opened, so use a third made afterwards as "unscanned".
const later = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(later.path, DOC);
const ok = await get(`/handoff?id=${made.id}`);
assert.equal(ok.status, 200);
assert.match(ok.headers.get("content-type"), /^text\/markdown/);
assert.equal(ok.headers.get("cache-control"), "no-store");
assert.equal(await ok.text(), DOC);
assert.equal((await get(`/handoff?id=${later.id}`)).status, 404, "valid but not scanned");
assert.equal((await get("/handoff?id=../x")).status, 404);
assert.equal((await get("/handoff")).status, 404);
});
// A used handoff drops out of the next scan, so it is no longer served.
store.markHandoffUsed(made.id);
await withDashboard(async ({ get }) => {
assert.equal((await get(`/handoff?id=${made.id}`)).status, 404, "used");
});
} finally {
fresh();
}
});
test("a __pickup round trip prints the hop, marks the handoff used, and the next dashboard scan drops it", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"]).json;
fs.writeFileSync(made.path, DOC);
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
const s = sessionUrl(opened.json.url);
try {
const res = await fetch(`${s.base}/submit`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
body: JSON.stringify({ actions: [{ i: "__pickup", type: "pickup", handoff: made.id }], reply: "pick up" }),
});
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]);
assert.equal(got.status, 0, got.stderr);
assert.match(got.json.resume, /--workflow quick-task$/);
assert.equal(got.json.handoffFile, made.path);
assert.ok(JSON.parse(fs.readFileSync(path.join(HANDOFFS_DIR, made.id + ".json"), "utf8")).usedAt, "the .json now has usedAt");
assert.ok(fs.existsSync(made.path), "the document stays until the sweep");
const back = run(["open", "--resume", opened.json.sid, "--no-open", "--workflow", "dashboard"]);
assert.equal(back.status, 0, back.stderr);
assert.deepEqual(readStateOf(opened.json.session).scan.handoffs, [], "a used handoff is no longer listed");
} finally {
run(["stop", "--session", opened.json.sid]);
}
} finally {
fresh();
}
});
test("a __delete with a handoff round-trips like a spec delete: no resume, no skillFile", async () => {
fresh();
try {
const made = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task"]).json;
fs.writeFileSync(made.path, DOC);
const opened = run(["open", "--no-open", "--workflow", "dashboard"]);
const s = sessionUrl(opened.json.url);
try {
const res = await fetch(`${s.base}/submit`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
body: JSON.stringify({ actions: [{ i: "__delete", type: "delete", handoff: made.id }], reply: "delete it" }),
});
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]);
assert.equal(got.status, 0, got.stderr);
assert.equal(got.json.actions[0].handoff, made.id);
assert.equal(got.json.resume, undefined);
assert.equal(got.json.skillFile, undefined);
assert.equal(got.json.handoffFile, undefined);
} finally {
run(["stop", "--session", opened.json.sid]);
}
} finally {
fresh();
}
});
test.after(() => fs.rmSync(REPO, { recursive: true, force: true }));
+58
View File
@@ -50,7 +50,9 @@ import {
launchTarget,
deleteAction,
deleteReply,
chipDetail,
deleteSummary,
FIXED_REASON,
isDeletableSpecDir,
MAX_NOTE_IMAGES,
noteAction,
@@ -67,6 +69,14 @@ import {
SPEC_STATE_LABELS,
STALE_MS,
STOP_REPLY,
STOP_HANDOFF_REPLY,
stopAction,
pickupAction,
pickupReply,
deleteHandoffAction,
deleteHandoffReply,
handoffCopyText,
handoffAge,
verdictLabel,
verdictText,
lastOpenCard,
@@ -580,6 +590,42 @@ test("the stop request cannot be mistaken for a brief request", () => {
assert.doesNotMatch(STOP_REPLY, /\b(brief|recap|minutes)\b/i);
});
test("handoff helpers: actions carry only the id, replies and copy text are plain, ages round at the boundaries", () => {
const h = { id: "2026-10-17-1152-handoff", title: "Lunch vote" };
assert.deepEqual(pickupAction(h), { i: "__pickup", type: "pickup", handoff: h.id });
assert.deepEqual(deleteHandoffAction(h), { i: "__delete", type: "delete", handoff: h.id });
assert.equal(pickupReply(h), 'Pick up the handoff "Lunch vote" right here in this session.');
assert.equal(deleteHandoffReply(h), 'Delete the handoff "Lunch vote" for good, right here in this session.');
const file = "/home/sam/.plan2code/handoffs/2026-10-17-1152-handoff.md";
assert.equal(handoffCopyText(file), `Read the handoff at ${file} and carry on with its Next task.`);
for (const line of [pickupReply(h), deleteHandoffReply(h), handoffCopyText(file)]) {
assert.ok(!line.includes("—"), "no em dash");
assert.doesNotMatch(line, /(brief|recap|minutes)/i);
}
const now = Date.parse("2026-10-17T12:00:00Z");
const ago = (ms) => handoffAge(new Date(now - ms).toISOString(), now);
assert.equal(ago(0), "just now");
assert.equal(ago(59 * 1000), "just now");
assert.equal(ago(60 * 1000), "1 min ago");
assert.equal(ago(59 * 60 * 1000), "59 min ago");
assert.equal(ago(60 * 60 * 1000), "1 h ago");
assert.equal(ago(23 * 3600 * 1000), "23 h ago");
assert.equal(ago(24 * 3600 * 1000), "1 day ago");
assert.equal(ago(3 * 24 * 3600 * 1000), "3 days ago");
assert.equal(handoffAge("not a date", now), "");
});
test("the stop-with-a-handoff request is its own plain line, and stopAction sets the flag only when asked", () => {
assert.notEqual(STOP_HANDOFF_REPLY, STOP_REPLY);
assert.match(STOP_HANDOFF_REPLY, /handoff/i);
assert.doesNotMatch(STOP_HANDOFF_REPLY, /\b(brief|recap|minutes)\b/i);
assert.ok(!STOP_HANDOFF_REPLY.includes("—"), "no em dash in a line that rides to the agent");
assert.ok(!("handoff" in stopAction({})), "a plain stop carries no handoff key");
assert.deepEqual(stopAction({}), { i: "__stop", type: "stop" });
assert.equal(stopAction({ handoff: true }).handoff, true);
assert.equal(stopAction({ handoff: true }).type, "stop");
});
// Nineteen highlight colors, four shades each, two themes: far too many to
// trust to eyeballing, and a failure here is a label nobody can read.
const hexLum = (h) => {
@@ -775,6 +821,18 @@ test("a delete is a session action naming the folder, and its reply says it is f
assert.equal(deleteSummary({ ...spec, detail: "" }).stage, SPEC_STATE_LABELS.building);
});
test("a fixed bug says so once: on its chip, in the delete dialog and on its greyed cards", () => {
const fixed = { dir: "specs/old-bug", name: "old-bug", state: "fixed", detail: "bug fixed", files: 1, touched: 1 };
assert.equal(deleteSummary(fixed).stage, "Bug fixed");
const building = { dir: "specs/lunch-vote", name: "lunch-vote", state: "building", detail: "1 of 2 tasks done" };
assert.equal(deleteSummary(building).stage, `${SPEC_STATE_LABELS.building}: 1 of 2 tasks done`);
assert.equal(chipDetail(fixed), "");
assert.equal(chipDetail(building), "1 of 2 tasks done");
assert.equal(chipDetail({ ...building, detail: undefined }), "");
assert.match(FIXED_REASON, /Delete button/);
assert.doesNotMatch(FIXED_REASON, /✕/);
});
test("scanProject counts each spec's files", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-scan-files-"));
try {
+19
View File
@@ -38,6 +38,7 @@ import {
} from "../src/web-console/lib.mjs";
import {
ROOT,
HANDOFFS_DIR,
HOME,
ENV,
cookieFor,
@@ -434,6 +435,9 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
backdate(path.join(plan2code, "busy"));
kept.push(busy);
stray(path.join(plan2code, "notes.txt"));
// Handoffs are Plan2Code's own, however old: swept by age on open, never offered here.
backdate(put(path.join(plan2code, "handoffs", "2025-01-01-0900-handoff.md")));
backdate(path.join(plan2code, "handoffs"));
// In use right now: a held lock and a temp between its write and rename.
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
kept.push(...live);
@@ -448,6 +452,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
"root:notes.txt",
"session:20250801-101010-aaaaaa",
]);
assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray");
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
@@ -659,6 +664,20 @@ test("open reports a month-old session under swept and removes it after printing
assert.equal(fs.existsSync(oldDir), false);
});
test("open reports a month-old handoff under swept.handoffs and removes both its files", async () => {
const id = "2025-01-01-0900-handoff";
fs.mkdirSync(HANDOFFS_DIR, { recursive: true });
const files = [path.join(HANDOFFS_DIR, id + ".md"), path.join(HANDOFFS_DIR, id + ".json")];
fs.writeFileSync(files[0], "# Handoff: old\n");
fs.writeFileSync(files[1], "{}");
for (const f of files) backdate(f);
const res = cli(["open", "--workflow", "plan", "--no-open"]);
cli(["stop", "--session", res.json.sid]);
assert.deepEqual(res.json.swept.handoffs, [id]);
for (let i = 0; i < 20 && files.some((f) => fs.existsSync(f)); i++) await new Promise((r) => setTimeout(r, 100));
assert.deepEqual(files.filter((f) => fs.existsSync(f)), []);
});
test("post and wait hand back the terminal line; the collected result on disk does not carry it", async () => {
const res = cli(["open", "--file", payload("tl.json", BASE), "--no-open"]);
const s = sessionUrl(res.json.url);
+33 -1
View File
@@ -28,6 +28,7 @@ import {
START_POSES,
startPose,
STOP_REPLY,
STOP_HANDOFF_REPLY,
threadText,
threadWho,
turnGate,
@@ -388,6 +389,24 @@ test("a stop request carries the staged answers, reaches the agent as a send, an
assert.equal((await ping()).pendingStop, false);
});
// "Stop with a handoff" is the same send with `handoff: true` on the action.
// The source tree has no built Handoff skill beside it, so no handoffSkill.
test("a handoff stop keeps its flag, reports as a stop until collected, and names no skill file in the source tree", async () => {
const ping = async () => (await post("/ping", {})).json();
const before = await ping();
await post("/submit", {
rev: before.rev,
actions: [{ i: "__stop", type: "stop", handoff: true }],
reply: STOP_HANDOFF_REPLY,
});
assert.equal((await ping()).pendingStop, true, "an uncollected handoff stop shows on the heartbeat");
const res = cli(["wait", "--session", sid, "--seconds", "5"]);
assert.equal(res.status, 0);
assert.equal(res.json.actions[0].handoff, true, "the flag reaches the agent");
assert.equal(res.json.handoffSkill, undefined, "no built skill beside the source tree");
assert.equal((await ping()).pendingStop, false);
});
// The top bar's triangle is a stop that lands on the menu: the staged answers
// and `__dashboard` go as one send with no finish on the page, the agent gets
// both at once, and the resume through the dashboard blanks the skill's page.
@@ -479,11 +498,24 @@ test("console-stop.md, building.md and the dashboard prompt teach the mid-workfl
assert.ok(stopMd.includes("## Back to the dashboard, mid-workflow"));
assert.ok(stopMd.includes(HOME_REPLY), "console-stop.md quotes the reply line the agent will see");
assert.match(stopMd, /No `finish` and no `stop` in between/);
assert.match(read("src", "web-console", "console.md"), /`__stop`, `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a mid-workflow __dashboard there");
assert.ok(stopMd.includes("## Stop with a handoff"));
for (const word of ["handoff new", "--from-stop", "handoffSkill"]) assert.ok(stopMd.includes(word), `console-stop.md names ${word}`);
assert.match(read("src", "web-console", "console.md"), /`__stop` \(plain, or with `handoff: true`\), `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a handoff stop and a mid-workflow __dashboard there");
assert.ok(read("src", "web-console", "building.md").includes("mid-build `__dashboard`"));
assert.ok(read("src", "plan2code.md").includes("mid-workflow from the top bar's triangle"));
});
test("console-launches.md and the dashboard prompt teach the handoff pick-up and delete", () => {
const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8");
const launches = read("src", "web-console", "console-launches.md");
for (const word of ["__pickup", "handoffFile", "delete-handoff", "handoffsDir", "fallback"]) {
assert.ok(launches.includes(word), `console-launches.md names ${word}`);
}
assert.ok(launches.includes("handoffs, handoffsDir"), "console-launches.md lists the scan fields");
const prompt = read("src", "plan2code.md");
for (const word of ["__pickup", "delete-handoff"]) assert.ok(prompt.includes(word), `src/plan2code.md names ${word}`);
});
// The server serves a hardcoded allow-list, so a new module that nobody adds
// to it 404s, the import fails, and the page never starts: a blank console
// with the default title and one line in the browser's console. Every module
+122 -4
View File
@@ -248,6 +248,107 @@ test("update check: the frame carries update only when a newer release is cached
}
});
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 app = web("app.js");
const css = web("app.css");
const dialog = html.match(/<dialog class="modal" id="stop-modal"[^>]*>([\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=|<script/i);
assert.match(css, /\.stop-choice/, "app.css styles the choices");
assert.match(css, /\.stop-choice:focus-visible/, "and gives them a focus outline");
const open = app.slice(app.indexOf("function openStopConfirm()"), app.indexOf("async function stopSession("));
assert.ok(open.includes("stop-handoff") && open.includes("isDashboard()"), "openStopConfirm hides the handoff on the dashboard");
assert.ok(app.includes("stopSession(true)") && app.includes("STOP_HANDOFF_REPLY") && app.includes("stopAction"), "app.js wires the handoff stop");
const help = helpTemplate().match(/<section class="help-panel" data-tab="finishing">([\s\S]*?)<\/section>/);
assert.ok(help && help[1].includes("Stop with a handoff") && help[1].includes("Just stop and save") && help[1].includes("~/.plan2code/handoffs/"), "Help names both choices and where handoffs land");
});
// The dashboard's handoff chips, preview and their four actions.
test("dashboard handoffs: dashed chips, a preview with four buttons, and the cards give way", () => {
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
const app = web("app.js");
const css = web("app.css");
const html = web("index.html");
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
const picker = fn("renderSpecPicker", "\nfunction ");
assert.ok(picker.includes("is-handoff") && picker.includes('"Handoff"'), "renderSpecPicker builds handoff chips");
assert.ok(picker.includes('"handoff:"'), "a handoff is picked as handoff:<id>");
const dash = fn("renderDashboard", "\n/* -----");
assert.ok(dash.includes("handoffList()"), "renderDashboard shows the picker for handoffs alone");
const early = dash.indexOf("renderHandoffPreview(");
assert.ok(early > 0 && early < dash.indexOf("hideUnavailableToggle()"), "the preview returns before the toggle and the card groups");
assert.match(app, /const selHandoff = \(\) =>/);
assert.match(app, /startsWith\("handoff:"\)/);
const preview = fn("renderHandoffPreview", "\nasync function ");
for (const label of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
assert.ok(preview.includes(`"${label}"`), `the preview names ${label}`);
}
assert.ok(app.includes("pickupAction(") && app.includes('"/submit"'), "Pick it up here posts a __pickup to /submit");
assert.ok(app.includes('"/handoff?id="'), "Read it all fetches /handoff?id=");
assert.ok(app.includes("handoffCopyText("), "Copy puts the ready prompt on the clipboard");
assert.ok(app.includes("deleteHandoffAction(") && app.includes("function openHandoffDelete("), "Delete reuses the confirm dialog");
assert.match(css, /\.spec-chip\.is-handoff/, "app.css styles handoff chips");
assert.match(css, /\.handoff-preview\b/, "and the preview panel");
const modal = html.match(/<dialog class="modal handoff-read" id="handoff-modal"[^>]*>([\s\S]*?)<\/dialog>/);
assert.ok(modal, "index.html has #handoff-modal");
assert.doesNotMatch(modal[1], /\sstyle=|<script/i);
assert.ok(html.includes('id="delete-warn-handoff"'), "the delete dialog carries the handoff warning");
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
assert.ok(panel && panel[1].includes("Pick it up here") && panel[1].includes("30-day sweep"), "Help explains handoff chips");
});
// The sign-off card: Approve comes before Show me it working, and an unpicked
// approve verdict is outlined in the accent.
test("sign-off: approve leads show, and the approve button wears the accent", () => {
const doc = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", f), "utf8");
for (const f of ["notes/implement.md", "building-review.md"]) {
const text = doc(f);
const approve = text.indexOf('{ "id": "approve", "label": "Approve this phase" }');
const show = text.indexOf('{ "id": "show", "label": "Show me it working" }');
assert.ok(approve > 0 && show > approve, `${f} lists Approve this phase before Show me it working`);
}
const app = doc("public/app.js");
assert.match(app, /v\.id === "approve" \? " is-approve"/, "an unpicked approve verdict gets is-approve");
assert.match(doc("public/app.css"), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
});
// A fixed bug's chip: a visible Delete, one confirm, and "bug fixed" said once.
test("bug fixed delete: a promoted Delete on the chip and a one-step confirm", () => {
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
const app = web("app.js");
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
const picker = fn("renderSpecPicker", "\nfunction ");
assert.ok(picker.includes('"spec-chip-del-label"') && picker.includes('"Delete"'), "renderSpecPicker builds a Delete button for a fixed bug");
assert.ok(picker.includes("chipDetail("), "the chip's detail line comes from chipDetail");
assert.doesNotMatch(picker, /spec\.detail\b/, "never the scan's detail directly");
const css = web("app.css");
assert.match(css, /\.spec-chip-del-label\s*\{/, "app.css styles the Delete button");
assert.match(css, /\.spec-chip-del-label:focus-visible/, "and gives it a focus outline");
const step = fn("deleteStep", "\nasync function ");
const fixedAt = step.indexOf('state === "fixed"');
const revealAt = step.indexOf('$("delete-confirm").hidden = false');
assert.ok(fixedAt > 0 && revealAt > 0 && fixedAt < revealAt, "deleteStep sends a fixed bug's delete before it would reveal the name step");
const open = fn("openDeleteConfirm", "\nfunction ");
assert.ok(open.includes('state === "fixed"') && open.includes("so this only clears the write-up"), "openDeleteConfirm sets up one step and the fixed warning");
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
assert.ok(panel && /fixed\s+bug[\s\S]*?Delete[\s\S]*?one\s+confirm/i.test(panel[1]), "Help says a fixed bug has its own Delete and needs one confirm");
});
test("update banner: the modal is in the page, with the exact command and no inline styles or scripts", () => {
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
@@ -280,12 +381,13 @@ test("update banner: built only on the dashboard, dismissed per session, and Hel
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
});
// The Changelog card sits left of Git, the last card. It is always clickable,
// and a launch from it resumes the session under its own workflow.
test("the Changelog card comes just before Git, Git is last, and Changelog is always on", () => {
// The Changelog card sits left of Git, which sits left of Handoff, the last
// card. It is always clickable, and a launch from it resumes the session under
// its own workflow.
test("the Changelog card comes just before Git, Handoff is last, and Changelog is always on", () => {
const skills = SKILL_CATALOG.map((e) => e.skill);
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"));
assert.equal(skills[skills.length - 1], "plan2code-git");
assert.deepEqual(skills.slice(-3), ["plan2code-changelog", "plan2code-git", "plan2code-handoff"]);
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
assert.equal(entry.workflow, "changelog");
assert.equal(entry.command, "/plan2code-changelog");
@@ -315,6 +417,22 @@ test("help: the stuck tab is second, with a callout and four symptom rows before
assert.match(panel, /<svg class="help-callout-icon"[^>]*aria-hidden="true"/, "the icon is decoration");
});
test("help: privacy names the handoffs folder and preferences says Cleanup never offers it", () => {
const tpl = helpTemplate();
const privacy = tpl.match(/<section class="help-panel" data-tab="privacy">([\s\S]*?)<\/section>/)[1];
const kept = privacy.slice(privacy.indexOf("<h4>What is kept, and where</h4>"));
assert.match(kept, /(<code>)?~\/\.plan2code\/handoffs\/(<\/code>)?/, "privacy lists ~/.plan2code/handoffs/");
assert.doesNotMatch(
kept,
/Everything lives under\s+<code>~\/\.plan2code\/console\/<\/code>/,
"the lead no longer says everything lives under the console folder"
);
const prefs = tpl.match(/<section class="help-panel" data-tab="prefs">([\s\S]*?)<\/section>/)[1];
const cleanup = prefs.slice(prefs.indexOf("<strong>Cleanup</strong>"), prefs.indexOf("<strong>Back to default</strong>"));
assert.match(cleanup, /handoffs/, "the Cleanup text names the handoffs folder");
assert.match(cleanup, /never\s+offered/, "the Cleanup text says the handoffs folder is never offered for removal");
});
// Every say(...) call in a source slice, as its top-level arguments (raw
// source text). String-aware, so commas and brackets inside a line are text.
function sayCalls(source) {
+66
View File
@@ -31,6 +31,7 @@ import {
WEB_CONSOLE_DIR,
consoleDoc,
consoleDocFiles,
HANDOFFS_DIR,
} from "./web-console-test-helpers.mjs";
const choice = (id, extra = {}) => ({
@@ -321,6 +322,62 @@ test("settle and a defaulted reply id go through post end to end", async () => {
/* ------------------------------------------------------------ session hops */
// A pick-up hops into the stored workflow and spec; the page sends only the
// id. A missing spec folder, a workflow that is not a workflow name, or the
// Handoff skill's own handoff falls back to Quick Task, flagged. (No skills sit beside the source tree, so the
// stored skill name stands there.)
test("a pick-up comes with the stored skill's resume command, handoffFile, and falls back to Quick Task", async () => {
process.env.PLAN2CODE_HANDOFFS_DIR = HANDOFFS_DIR;
const store = await import("../src/web-console/handoffs.mjs");
const worktree = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-pickup-"));
fs.mkdirSync(path.join(worktree, "specs", "lunch-vote"), { recursive: true });
const make = (rec) => {
const h = store.newHandoff({ worktree, project: worktree, workflow: "implement", skill: "plan2code-3-implement", title: "T", ...rec }, new Date(2026, 9, 17, 10, 0 + make.n++));
fs.writeFileSync(h.path, "# Handoff: T\n");
return h;
};
make.n = 0;
const s = consoleSession(["--workflow", "dashboard"]);
const resumeOf = (workflow, spec = "") =>
`node "${path.join(ROOT, "src", "web-console", "console.mjs")}" open --resume ${s.sid} --no-open --workflow ${workflow}${spec}`;
try {
const good = make({ spec: "specs/lunch-vote" });
const goneSpec = make({ spec: "specs/deleted" });
const badMeta = make({ spec: null });
const metaFile = path.join(HANDOFFS_DIR, badMeta.id + ".json");
fs.writeFileSync(metaFile, fs.readFileSync(metaFile, "utf8").replace('"workflow": "implement"', '"workflow": "Not A Workflow"'));
const cases = [
[good, resumeOf("implement", " --spec specs/lunch-vote"), undefined],
[goneSpec, resumeOf("quick-task"), true],
[badMeta, resumeOf("quick-task"), true],
// The Handoff skill's own handoff carries on in Quick Task, never in another handoff.
[make({ workflow: "handoff", skill: "plan2code-handoff" }), resumeOf("quick-task"), true],
];
for (const [h, resume, fallback] of cases) {
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: h.id }], reply: "pick up" })).status, 200);
const res = waitFor(s);
assert.equal(res.status, 0);
assert.equal(res.json.resume, resume);
assert.equal(res.json.handoffFile, h.path);
assert.equal(res.json.fallback, fallback);
}
// A stored spec with shell characters never reaches `resume`: Quick Task, flagged.
const hostile = make({ spec: "specs/x;touch pwned" });
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: hostile.id }], reply: "pick up" })).status, 200);
const hot = waitFor(s).json;
assert.equal(hot.resume, resumeOf("quick-task"));
assert.equal(hot.fallback, true);
// An id that is not a handoff id gets the fallback and no handoffFile.
assert.equal((await s.send("/submit", { actions: [{ i: "__pickup", type: "pickup", handoff: "../x" }], reply: "pick up" })).status, 200);
const bad = waitFor(s).json;
assert.equal(bad.handoffFile, undefined);
assert.equal(bad.fallback, true);
} finally {
cli(["stop", "--session", s.sid]);
fs.rmSync(worktree, { recursive: true, force: true });
}
});
test("a launch, a dashboard press and Commit it now each come with their resume command", async () => {
const s = consoleSession(["--workflow", "dashboard"]);
try {
@@ -366,6 +423,15 @@ test("the built skills name the skill file to follow after a hop", async () => {
assert.equal(res.status, 200);
const got = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(got.skillFile, path.join(ROOT, "skills", "plan2code-review", "SKILL.md"));
assert.equal(got.handoffSkill, undefined, "a launch is not a handoff stop");
const stopRes = await fetch(`${m[1]}/submit`, {
method: "POST",
headers: { "content-type": "application/json", cookie, connection: "close" },
body: JSON.stringify({ actions: [{ i: "__stop", type: "stop", handoff: true }], reply: "stop with a handoff" }),
});
assert.equal(stopRes.status, 200);
const stopped = run(["wait", "--session", opened.sid, "--seconds", "10"]).json;
assert.equal(stopped.handoffSkill, path.join(ROOT, "skills", "plan2code-handoff", "SKILL.md"), "a handoff stop in a built skill names the Handoff skill file");
} finally {
run(["stop", "--session", opened.sid]);
}
+4 -1
View File
@@ -28,6 +28,9 @@ 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");
// 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");
// 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.
@@ -51,7 +54,7 @@ for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
// cannot open. An empty file is the portable "no global config".
const EMPTY_GITCONFIG = path.join(HOME, "empty-gitconfig");
fs.writeFileSync(EMPTY_GITCONFIG, "");
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_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 }));