diff --git a/QUICK-REFERENCE.md b/QUICK-REFERENCE.md index e488b48..f4096c9 100644 --- a/QUICK-REFERENCE.md +++ b/QUICK-REFERENCE.md @@ -23,7 +23,7 @@ The install command always opens a menu. Back at your prompt with no output at a Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md). -The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent). +The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`). Private: the agent never reads your Notebook. A tab reaches it only when you start a workflow with it. ## Commands diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs index af397bb..a9db52a 100644 --- a/scripts/test-web-console-logic.mjs +++ b/scripts/test-web-console-logic.mjs @@ -48,6 +48,11 @@ import { handoffText, launchReply, launchTarget, + noteSwitchShows, + noteTabEmpty, + defaultNoteTicks, + toggleNoteTick, + NOTE_LONG_BYTES, deleteAction, deleteReply, chipDetail, @@ -1500,6 +1505,17 @@ test("validate: templates only as \"idea\", only on a text item", () => { assert.ok(validate(item({ templates: "yes" })).includes(message)); }); +test("validate: fill only as \"note\", only on a text item", () => { + const item = (extra) => ({ items: [{ id: "idea", kind: "text", title: "What's the idea?", ...extra }] }); + const message = 'item "idea" has "fill": only a text item can carry it, and its only value is "note".'; + assert.deepEqual(validate(item({ fill: "note" })), []); + assert.deepEqual(validate(item({ fill: "note", templates: "idea" })), []); + assert.ok(validate(item({ kind: "choice", options: [{ k: "A", text: "a" }], fill: "note" })).includes(message)); + assert.ok(validate(item({ kind: "confirm", fill: "note" })).includes(message)); + assert.ok(validate(item({ fill: "idea" })).includes(message)); + assert.ok(validate(item({ fill: true })).includes(message)); +}); + test("attachmentName: slug of the original name, 8 characters of the upload id, the upload's own extension", () => { const up = (uuid, ext) => path.join(HOME, "sessions", "x", "uploads", `${uuid}${ext}`); const a = up("3f2b9c1e-8a4d-4f6e-9b7a-2c5d1e0f4a6b", ".jpg"); @@ -2320,3 +2336,45 @@ test("meter: the weights and labels built from the skill list are the ones writt }); for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t)); }); + +test("noteSwitchShows: Pathfinder, Plan and Quick Task on Start fresh, Revise plan on a picked spec with no brief waiting", () => { + const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill); + const scan = { hasAgents: true, isGit: true, pending: 0, specs: [] }; + const sel = (state, extra = {}) => ({ dir: "specs/x", name: "x", state, ...extra }); + const fresh = ["plan2code-0-pathfinder", "plan2code-1-plan", "plan2code-quick-task"]; + for (const skill of fresh) { + assert.equal(noteSwitchShows(entry(skill), scan, null), true, `${skill} on Start fresh`); + assert.equal(noteSwitchShows(entry(skill), scan, sel("exploring")), false, `${skill} on a picked spec`); + assert.equal(noteSwitchShows(entry(skill), scan, sel("exploring", { planChange: true })), false, `${skill} on a picked spec with a brief`); + } + const revise = entry("plan2code-1b-revise-plan"); + assert.equal(noteSwitchShows(revise, scan, null), false, "Revise plan is grayed on Start fresh"); + for (const state of ["documented", "building", "built"]) { + assert.equal(noteSwitchShows(revise, scan, sel(state)), true, `Revise plan on ${state}`); + assert.equal(noteSwitchShows(revise, scan, sel(state, { planChange: true })), false, `Revise plan on ${state} with a brief waiting`); + } + assert.equal(noteSwitchShows(revise, scan, sel("exploring")), false, "never on a grayed card"); + for (const skill of ["plan2code-3-implement", "plan2code-2-document", "plan2code-git", "plan2code-xray"]) { + assert.equal(noteSwitchShows(entry(skill), scan, null), false, `${skill} on Start fresh`); + assert.equal(noteSwitchShows(entry(skill), scan, sel("documented")), false, `${skill} on a picked spec`); + } + assert.equal(noteSwitchShows(null, scan, null), false); +}); + +test("Notebook pick rules: an empty tab, the first five pictures ticked, and no sixth tick", () => { + assert.equal(noteTabEmpty({ text: "", images: [] }), true); + assert.equal(noteTabEmpty({ text: " \n", images: [] }), true, "whitespace is nothing to send"); + assert.equal(noteTabEmpty({ text: "", images: [{ id: "a" }] }), false); + assert.equal(noteTabEmpty({ text: "idea", images: [] }), false); + assert.equal(noteTabEmpty(null), true); + const imgs = ["a", "b", "c", "d", "e", "f", "g"].map((id) => ({ id })); + assert.deepEqual(defaultNoteTicks(imgs), ["a", "b", "c", "d", "e"]); + assert.deepEqual(defaultNoteTicks(imgs.slice(0, 2)), ["a", "b"]); + assert.deepEqual(defaultNoteTicks(undefined), []); + const five = defaultNoteTicks(imgs); + assert.deepEqual(toggleNoteTick(five, "f"), five, "a sixth tick changes nothing"); + const four = toggleNoteTick(five, "c"); + assert.deepEqual(four, ["a", "b", "d", "e"]); + assert.deepEqual(toggleNoteTick(four, "f"), ["a", "b", "d", "e", "f"], "untick one to tick another"); + assert.equal(NOTE_LONG_BYTES, 51200); +}); diff --git a/scripts/test-web-console-notepad.mjs b/scripts/test-web-console-notepad.mjs index c9f7023..031a06b 100644 --- a/scripts/test-web-console-notepad.mjs +++ b/scripts/test-web-console-notepad.mjs @@ -917,6 +917,79 @@ test("the tab routes refuse bad bodies, unknown tabs and every foreign caller", assert.equal((await getJson(s, "/notepad")).body.last, other.id); }); +test("markTabSent records, replaces and validates a tab's last send, and listTabs and readNotepad return it", () => { + const folder = freshFolder(); + const a = tabOf(folder, "A"); + const b = tabOf(folder, "B"); + assert.deepEqual(listTabs(folder).tabs, [{ id: a, name: "A" }, { id: b, name: "B" }], "no sent until a send"); + + const first = store.markTabSent(folder, a, { workflow: "plan" }); + assert.equal(first.id, a); + assert.deepEqual(Object.keys(first.sent).sort(), ["at", "workflow"]); + assert.equal(first.sent.workflow, "plan"); + assert.ok(!Number.isNaN(Date.parse(first.sent.at))); + assert.deepEqual(listTabs(folder).tabs[0], { id: a, name: "A", sent: first.sent }); + assert.equal(listTabs(folder).tabs[1].sent, undefined, "only the sent tab carries it"); + + const second = store.markTabSent(folder, a, { workflow: "revise-plan", spec: "specs/lunch-vote" }); + assert.deepEqual(second.sent, { workflow: "revise-plan", spec: "specs/lunch-vote", at: second.sent.at }, "replaces the earlier one"); + const read = readNotepad(folder, a); + assert.deepEqual(read.tabs[0].sent, second.sent); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(notepadFolder(folder), "tabs.json"), "utf8")).tabs[a].sent, second.sent); + + // A rename keeps the record; it is the tab's, not the name's. + renameTab(folder, a, "A2"); + assert.deepEqual(listTabs(folder).tabs[0].sent, second.sent); + + for (const bad of [{}, { workflow: "implement" }, { workflow: "plan", spec: "lunch-vote" }, { workflow: "plan", spec: "specs/a/b" }, { workflow: "plan", spec: 5 }]) { + refusal(() => store.markTabSent(folder, b, bad), "bad-sent"); + } + refusal(() => store.markTabSent(folder, "ffffffffffff", { workflow: "plan" }), "no-such-tab"); + refusal(() => store.markTabSent(folder, "nope", { workflow: "plan" }), "no-such-tab"); + assert.equal(listTabs(folder).tabs[1].sent, undefined, "refusals recorded nothing"); +}); + +test("a sent record that does not hold up is dropped on read, never the index", () => { + const folder = freshFolder(); + const a = tabOf(folder, "A"); + const file = path.join(notepadFolder(folder), "tabs.json"); + const index = JSON.parse(fs.readFileSync(file, "utf8")); + index.tabs[a].sent = { workflow: "implement", at: "2026-10-27T00:00:00.000Z" }; + fs.writeFileSync(file, JSON.stringify(index)); + assert.deepEqual(listTabs(folder).tabs, [{ id: a, name: "A" }]); +}); + +test("POST /notepad/tab/sent answers 200, 400 and 404, and GET /notepad carries the record", async (t) => { + const s = openSession(); + t.after(() => fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true })); + fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true }); + const post = async (body) => { + const res = await s.send("/notepad/tab/sent", body); + return { status: res.status, body: await res.json() }; + }; + const id = (await (await s.send("/notepad/tab", { name: "Idea" })).json()).id; + const ok = await post({ id, workflow: "quick-task" }); + assert.equal(ok.status, 200); + assert.equal(ok.body.ok, true); + assert.equal(ok.body.sent.workflow, "quick-task"); + assert.deepEqual((await getJson(s, "/notepad")).body.tabs, [{ id, name: "Idea", sent: ok.body.sent }]); + assert.deepEqual(await post({ id, workflow: "document" }), { status: 400, body: { error: "bad-sent" } }); + assert.deepEqual(await post({ id, workflow: "revise-plan", spec: "../x" }), { status: 400, body: { error: "bad-sent" } }); + assert.deepEqual(await post({ id: "ffffffffffff", workflow: "plan" }), { status: 404, body: { error: "no-such-tab" } }); + assert.deepEqual(await post({ workflow: "plan" }), { status: 404, body: { error: "no-such-tab" } }); + + const body = JSON.stringify({ id, workflow: "plan" }); + const noCookie = await fetch(`${s.base}/notepad/tab/sent`, { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body }); + assert.equal(noCookie.status, 403); + const foreign = await fetch(`${s.base}/notepad/tab/sent`, { + method: "POST", + headers: { "content-type": "application/json", cookie: s.cookie, origin: "http://evil.example", connection: "close" }, + body, + }); + assert.equal(foreign.status, 403); + assert.equal((await getJson(s, "/notepad")).body.tabs[0].sent.workflow, "quick-task", "the refused calls changed nothing"); +}); + test("pictures through ?tab=: upload, thumb, fetch and delete, each under the tab that holds it", async (t) => { const s = openSession(); t.after(() => fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true })); diff --git a/scripts/test-web-console-page-dashboard.mjs b/scripts/test-web-console-page-dashboard.mjs index a891eaa..cd80898 100644 --- a/scripts/test-web-console-page-dashboard.mjs +++ b/scripts/test-web-console-page-dashboard.mjs @@ -12,7 +12,8 @@ import path from "node:path"; import test from "node:test"; import assert from "node:assert/strict"; import { pageSuite, openSession, tempProject, textOf, styleOf } from "./page-test-helpers.mjs"; -import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs"; +import { cli, until, CONSOLE_CLI, HOME, JPEG } from "./web-console-test-helpers.mjs"; +import { addImage, createTab, deleteTab, markTabSent, saveNote } from "../src/web-console/notepads.mjs"; const suite = pageSuite(test); @@ -537,3 +538,140 @@ test("a quick-task build's waiting pane points at its Plan tab, and a plan sessi await otherPane.waitFor(); assert.equal(await otherPane.getByRole("button", { name: "Plan", exact: true }).count(), 0, "a plan session has no live task list to point at"); }); + +// A project with a drafted plan (demo), a documented spec (ready) and one +// paused mid-build with a Plan change brief waiting (paused). +const NOTE_PROJECT = { + ...DRAFT_PROJECT, + "specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n", + "specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n", + "specs/paused/overview.md": "# Overview\n\n## Phase Checklist\n\n- [/] Phase 1: One\n", + "specs/paused/phase-1.md": + "# Phase 1\n\n- [x] **Task 1.1:** One\n- [ ] **Task 1.2:** Two\n\n## Notes\n\n### Paused 2026-10-27\n**Plan change:** add a phase first\n", +}; + +const noteSwitch = (main) => main.getByRole("checkbox", { name: "Start with a note from your Notebook" }); + +// Picks `chip` in the picker, opens `command`'s card and says whether its +// confirm pane offers the switch; Back returns to the menu. +async function offersNote(main, chip, command) { + await chipFor(main, chip).click(); + await pickedChip(main, chip).waitFor(); + const card = lightOf(main, command); + if (!(await card.isVisible()) || (await card.isDisabled())) return null; + await card.click(); + await main.getByRole("button", { name: "Back" }).waitFor(); + const shows = (await noteSwitch(main).count()) === 1; + await main.getByRole("button", { name: "Back" }).click(); + await main.getByRole("heading", { name: "What are we doing today?" }).waitFor(); + return shows; +} + +test("the Notebook switch shows on Start fresh for Pathfinder, Plan and Quick Task, and on Revise plan only with no brief waiting", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(NOTE_PROJECT) }); + const main = await toTheMenu(s); + await hideUnavailable(main, false); + for (const command of ["/plan2code-0-pathfinder", "/plan2code-1-plan", "/plan2code-quick-task"]) { + assert.equal(await offersNote(main, "Start from scratch", command), true, `${command} on Start fresh`); + } + assert.equal(await offersNote(main, "demo", "/plan2code-1-plan"), false, "Plan on a picked spec"); + assert.equal(await offersNote(main, "ready", "/plan2code-1b-revise-plan"), true, "Revise plan with no brief waiting"); + assert.equal(await offersNote(main, "paused", "/plan2code-1b-revise-plan"), false, "Revise plan with a brief waiting"); + assert.equal(await offersNote(main, "ready", "/plan2code-3-implement"), false, "Implement never"); + assert.equal(await offersNote(main, "Start from scratch", "/plan2code-xray"), false, "a utility never"); +}); + +test("the switch lists the Notebook's tabs beside a preview: an empty tab grayed, five ticks at most, a Long tab note, and + note: on the command", async (t) => { + const project = tempProject(DRAFT_PROJECT); + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project }); + createTab(s.project, "Empty"); + const big = createTab(s.project, "Big").id; + const small = createTab(s.project, "Small").id; + saveNote(s.project, big, "# Big idea\n\n" + "x".repeat(52 * 1024)); + for (let i = 0; i < 7; i++) addImage(s.project, big, JPEG); + saveNote(s.project, small, "A small **idea**."); + markTabSent(s.project, small, { workflow: "plan" }); + + const main = await toTheMenu(s); + await chipFor(main, "Start from scratch").click(); + await pickedChip(main, "Start from scratch").waitFor(); + await lightOf(main, "/plan2code-0-pathfinder").click(); + const toggle = noteSwitch(main); + assert.equal(await toggle.isChecked(), false, "off by default"); + const cmd = main.locator(".confirm-cmd"); + assert.equal(await cmd.locator(".confirm-cmd-note").isHidden(), true); + await toggle.check(); + + const tabs = main.locator(".confirm-note-tabs"); + await tabs.locator(".confirm-note-tab").nth(2).waitFor(); + const tab = (name) => tabs.locator(".confirm-note-tab", { has: s.page.locator(".confirm-note-tab-name", { hasText: new RegExp(`^${name}$`) }) }); + assert.equal(await tab("Empty").isDisabled(), true, "an empty tab cannot be picked"); + assert.ok(parseFloat(await styleOf(tab("Empty"), "opacity")) < 1, "and is grayed"); + assert.equal(await tab("Big").isEnabled(), true); + assert.equal(await tab("Small").locator(".notepad-sent-badge").count(), 1, "a sent tab shows its badge"); + assert.equal(await tab("Big").locator(".notepad-sent-badge").count(), 0); + + // Small: its text, rendered, and no Long tab note. + await tab("Small").click(); + const preview = main.locator(".confirm-note-preview"); + await preview.locator("strong", { hasText: "idea" }).waitFor(); + assert.equal(await preview.locator(".confirm-note-long").count(), 0); + assert.equal(await textOf(cmd.locator(".confirm-cmd-note")), "+ note: Small"); + + // Big: over 50 KB, seven pictures, the first five ticked. + await tab("Big").click(); + await preview.locator(".md-h", { hasText: "Big idea" }).waitFor(); + assert.match(await textOf(preview.locator(".confirm-note-long")), /^Long tab: /); + assert.equal(await textOf(cmd.locator(".confirm-cmd-note")), "+ note: Big"); + const ticks = preview.locator(".confirm-note-pic input[type=checkbox]"); + assert.equal(await ticks.count(), 7); + const states = async () => ticks.evaluateAll((bs) => bs.map((b) => (b.checked ? "x" : b.disabled ? "-" : "o")).join("")); + assert.equal(await states(), "xxxxx--", "the first five ticked, no more can be"); + await ticks.nth(1).uncheck(); + await until(async () => (await states()) === "xoxxxoo", 3000); + await ticks.nth(6).check(); + await until(async () => (await states()) === "x-xxx-x", 3000); + + // Off again: no note on the command line. + await noteSwitch(main).uncheck(); + await until(async () => await cmd.locator(".confirm-cmd-note").isHidden(), 3000); + assert.equal(await tabs.count(), 0); +}); + +test("the switch reads the Notebook again when it closes, and starts off again after Back", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) }); + const keep = createTab(s.project, "Keep").id; + const gone = createTab(s.project, "Gone").id; + saveNote(s.project, keep, "first words"); + saveNote(s.project, gone, "soon deleted"); + + const main = await toTheMenu(s); + await chipFor(main, "Start from scratch").click(); + await pickedChip(main, "Start from scratch").waitFor(); + await lightOf(main, "/plan2code-1-plan").click(); + await noteSwitch(main).check(); + const tabs = main.locator(".confirm-note-tabs"); + const tab = (name) => tabs.locator(".confirm-note-tab", { has: s.page.locator(".confirm-note-tab-name", { hasText: new RegExp(`^${name}$`) }) }); + await tab("Keep").click(); + const preview = main.locator(".confirm-note-preview"); + await preview.getByText("first words").waitFor(); + assert.equal(await preview.getAttribute("role"), "region"); + + // Changed in the Notebook while the pane is open: closing it reads again. + saveNote(s.project, keep, "second words"); + deleteTab(s.project, gone); + await s.page.click("#btn-notepad"); + await s.page.locator("#notepad-modal[open]").waitFor(); + await s.page.click("#notepad-close"); + await preview.getByText("second words").waitFor(); + await until(async () => (await tab("Gone").count()) === 0, 5000); + assert.equal(await textOf(main.locator(".confirm-cmd-note")), "+ note: Keep", "the pick survives a read that still has its tab"); + + // Back, then the same card again: the switch is off and nothing is picked. + await main.getByRole("button", { name: "Back" }).click(); + await main.getByRole("heading", { name: "What are we doing today?" }).waitFor(); + await lightOf(main, "/plan2code-1-plan").click(); + assert.equal(await noteSwitch(main).isChecked(), false); + assert.equal(await main.locator(".confirm-cmd-note").isHidden(), true); + assert.equal(await tabs.count(), 0); +}); diff --git a/scripts/test-web-console-page-notepad.mjs b/scripts/test-web-console-page-notepad.mjs index 414cf76..1d2a107 100644 --- a/scripts/test-web-console-page-notepad.mjs +++ b/scripts/test-web-console-page-notepad.mjs @@ -31,6 +31,7 @@ import { defaultTabId, deleteTab, listTabs, + markTabSent, notepadFolder, notepadKey, readNotepad, @@ -1173,3 +1174,39 @@ test("Help's Getting around panel describes the notepad", async (t) => { assert.ok(text.includes(words), `the panel mentions ${words}`); } }); + +test("a sent tab wears a badge after its name, and the open tab shows Sent to · ", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + const sent = createTab(s.project, "Sent one").id; + createTab(s.project, "Plain"); + saveNoteTo(s.project, sent, "an idea"); + const { sent: record } = markTabSent(s.project, sent, { workflow: "revise-plan", spec: "specs/lunch-vote" }); + // The page draws its own short date; the line must carry the same one. + const day = await s.page.evaluate((at) => new Date(at).toLocaleDateString(undefined, { month: "short", day: "numeric" }), record.at); + const line = s.page.locator("#notepad-sent"); + + await openNotepad(s); + // Plain was made last, so it opens first: no badge, no line. + assert.equal(await selectedName(s).then((n) => n.join()), "Plain"); + assert.equal(await line.isHidden(), true, "no Sent to line on a tab never sent"); + const badges = s.page.locator("#notepad-tabs .notepad-sent-badge"); + assert.equal(await badges.count(), 1, "one badge, on the sent tab only"); + assert.equal(await badges.first().textContent(), "sent"); + const wrapOf = (name) => s.page.locator("#notepad-tabs .notepad-tabwrap").filter({ has: s.page.locator(".notepad-tab", { hasText: new RegExp(`^${name}$`) }) }); + assert.equal(await wrapOf("Sent one").locator(".notepad-sent-badge").count(), 1); + assert.equal(await wrapOf("Plain").locator(".notepad-sent-badge").count(), 0); + assert.equal(await tabNamed(s, "Sent one").getAttribute("aria-label"), "Sent one, sent"); + assert.equal(await tabNamed(s, "Plain").getAttribute("aria-label"), null); + assert.ok(parseFloat(await styleOf(badges.first(), "font-size")) < 13, "the badge is small"); + + await tabNamed(s, "Sent one").click(); + assert.equal(await shows(s, "an idea"), "an idea"); + await line.waitFor({ state: "visible" }); + assert.equal(await line.textContent(), `Sent to Revise plan (lunch-vote) · ${day}`); + // Under the editor and above the pictures. + const order = await s.page.evaluate(() => [...document.getElementById("notepad-body").children].map((c) => c.id)); + assert.ok(order.indexOf("notepad-sent") === order.indexOf("notepad-editor") + 1 && order.indexOf("notepad-sent") < order.indexOf("notepad-images"), order.join(", ")); + + await tabNamed(s, "Plain").click(); + await line.waitFor({ state: "hidden" }); +}); diff --git a/scripts/test-web-console-page-send.mjs b/scripts/test-web-console-page-send.mjs new file mode 100644 index 0000000..06bf36a --- /dev/null +++ b/scripts/test-web-console-page-send.mjs @@ -0,0 +1,253 @@ +// Page tests for starting a skill with a Notebook tab: the dashboard's confirm +// pane picks a tab, Start launches, the launched skill's `fill: "note"` box +// arrives filled with the tab's text and ticked pictures, and only the Send +// of that box reaches the agent and marks the tab sent. Run with: +// node --test scripts/test-web-console-page-send.mjs +// +// Each test drives the real console in a real Chrome or Edge through +// scripts/page-test-helpers.mjs: one browser for the file, a fresh console +// session per test. + +import fs from "node:fs"; +import path from "node:path"; +import test from "node:test"; +import assert from "node:assert/strict"; +import { pageSuite, openSession, tempProject, drawn, sendAndCollect, itemCard } from "./page-test-helpers.mjs"; +import { cli, until, CONSOLE_CLI } from "./web-console-test-helpers.mjs"; +import { addImage, createTab, deleteTab, listTabs, readNotepad, removeImage, saveNote } from "../src/web-console/notepads.mjs"; + +const suite = pageSuite(test); + +// Set up (AGENTS.md), with one documented spec for Revise plan to target. +const PROJECT = { + "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n", + "specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n", + "specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n", +}; + +const MENU = { menu: { note: "Ready when you are." }, agent: { status: "waiting" } }; + +// Words no screen or file holds unless the tab put them there. +const MARKER = "Lunch vote by emoji, idea 7Q2X"; +const TEXT = `# Lunch vote\n\n${MARKER}.\n`; + +// A real JPEG drawn in the page, one color per call: the box re-encodes each +// picture the way a pasted one is, so a stub that only looks like a JPEG +// would never attach. +const jpeg = async (s, color) => + Buffer.from( + await s.page.evaluate(async (fill) => { + const c = document.createElement("canvas"); + c.width = 160; + c.height = 100; + const ctx = c.getContext("2d"); + ctx.fillStyle = fill; + ctx.fillRect(0, 0, 160, 100); + const blob = await new Promise((resolve) => c.toBlob(resolve, "image/jpeg")); + let bin = ""; + for (const b of new Uint8Array(await blob.arrayBuffer())) bin += String.fromCharCode(b); + return btoa(bin); + }, color), + "base64" + ); + +// A Notebook tab named `name` holding `text` and `pictures` real pictures. +async function noteTab(s, name, text, pictures) { + const id = createTab(s.project, name).id; + if (text) saveNote(s.project, id, text); + for (let i = 0; i < pictures; i++) addImage(s.project, id, await jpeg(s, `hsl(${i * 40}, 60%, 50%)`)); + return id; +} + +// Past Planny's wake-up and, on this console home's first run, the Welcome, +// to the menu. +async function toTheMenu(s) { + const skip = s.page.getByRole("button", { name: "Skip the intro" }); + await skip.click(); + await skip.waitFor({ state: "hidden" }); + const main = s.page.locator("#main"); + await main.getByRole("heading", { name: "What are we doing today?" }).waitFor(); + const welcomeDone = s.page.getByRole("button", { name: "Start building" }); + if (await welcomeDone.isVisible()) { + await welcomeDone.click(); + await welcomeDone.waitFor({ state: "hidden" }); + } + return main; +} + +const chipFor = (main, name) => main.getByRole("button").filter({ hasText: new RegExp(`^${name}`) }); +const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { hasText: new RegExp(`^${name}`) }); +const lightOf = (main, command) => main.getByRole("button").filter({ has: main.page().locator("code", { hasText: new RegExp(`^${command}$`) }) }); + +// Every file under the session folder that holds `words`. +function filesHolding(dir, words) { + const found = []; + for (const entry of fs.readdirSync(dir, { withFileTypes: true, recursive: true })) { + if (!entry.isFile()) continue; + const file = path.join(entry.parentPath ?? entry.path, entry.name); + if (fs.readFileSync(file).includes(words)) found.push(path.relative(dir, file)); + } + return found; +} + +const sentOf = (project, tab) => (listTabs(project).tabs.find((t) => t.id === tab) || {}).sent || null; + +// From the menu: picks `chip`, opens `command`'s card, switches the Notebook +// on, picks `tabName` and presses Start; then collects the launch and runs its +// resume, as the dashboard agent does. Returns the launch send. +async function startWith(s, main, { chip, command, tabName }) { + await chipFor(main, chip).click(); + await pickedChip(main, chip).waitFor(); + await lightOf(main, command).click(); + await main.getByRole("checkbox", { name: "Start with a note from your Notebook" }).check(); + const tab = main.locator(".confirm-note-tab", { has: s.page.locator(".confirm-note-tab-name", { hasText: new RegExp(`^${tabName}$`) }) }); + await tab.click(); + await main.locator(".confirm-cmd-note", { hasText: `+ note: ${tabName}` }).waitFor(); + await main.locator(".confirm-actions .btn.primary").click(); + const got = s.wait(10); + assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`); + const head = `node "${CONSOLE_CLI}" `; + assert.ok(got.resume.startsWith(head), `resume runs this console: ${got.resume}`); + const r = cli(got.resume.slice(head.length).split(" "), { cwd: s.project }); + assert.equal(r.status, 0, `resume failed: ${r.stderr}`); + return got; +} + +// The launched skill's first card: the box the page fills. +const BOX = { items: [{ id: "idea", kind: "text", title: "What should change", body: "Say it in your own words.", fill: "note" }] }; + +const boxOf = (s) => s.page.locator("#text-idea"); +const readyPictures = (s) => itemCard(s.page, "idea").locator(".attach-thumb.is-ready"); + +const CASES = [ + { workflow: "pathfinder", chip: "Start from scratch", command: "/plan2code-0-pathfinder" }, + { workflow: "plan", chip: "Start from scratch", command: "/plan2code-1-plan" }, + { workflow: "quick-task", chip: "Start from scratch", command: "/plan2code-quick-task" }, + { workflow: "revise-plan", chip: "ready", command: "/plan2code-1b-revise-plan", spec: "specs/ready" }, +]; + +for (const c of CASES) { + test(`${c.workflow}: the box arrives with the tab's text and five pictures, the agent reads it only on Send, and only then is the tab marked sent`, async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const tab = await noteTab(s, "Idea", TEXT, 7); + const main = await toTheMenu(s); + const launch = await startWith(s, main, { chip: c.chip, command: c.command, tabName: "Idea" }); + + // Nothing of the tab rides the launch, and nothing of it is in the session. + assert.ok(!JSON.stringify(launch).includes(MARKER), "the launch send carries no tab text"); + assert.deepEqual(filesHolding(s.session, MARKER), [], "no session file holds the tab's text after Start"); + assert.equal(sentOf(s.project, tab), null, "Start alone marks nothing"); + + s.post(BOX); + await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000); + await until(async () => (await readyPictures(s).count()) === 5, 15000); + assert.equal(await boxOf(s).isEditable(), true, "the filled box stays editable"); + + // Still nothing for the agent before Send. + const result = path.join(s.session, "result.json"); + assert.ok(!fs.existsSync(result) || !fs.readFileSync(result, "utf8").includes(MARKER), "result.json holds no tab text before Send"); + assert.equal(s.wait(1).code, 10, "the agent has nothing to collect before Send"); + assert.equal(sentOf(s.project, tab), null); + + const got = await sendAndCollect(s); + assert.ok(got.reply.includes(MARKER), `the send carries the box: ${got.reply}`); + const note = got.actions.find((a) => a.i === "idea" && a.type === "comment"); + assert.equal(note && note.images.length, 5, "the five pictures go with it"); + await until(() => sentOf(s.project, tab) !== null, 5000); + const sent = sentOf(s.project, tab); + assert.equal(sent.workflow, c.workflow); + assert.equal(sent.spec, c.spec); + }); +} + +test("a pictures-only tab arrives as an empty box with its pictures, and its Send marks the tab sent", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const tab = await noteTab(s, "Shots", "", 2); + const main = await toTheMenu(s); + await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-1-plan", tabName: "Shots" }); + s.post(BOX); + await until(async () => (await readyPictures(s).count()) === 2, 15000); + assert.equal(await boxOf(s).inputValue(), ""); + const got = await sendAndCollect(s); + const note = got.actions.find((a) => a.i === "idea" && a.type === "comment"); + assert.equal(note && note.images.length, 2, "the pictures go on their own"); + await until(() => sentOf(s.project, tab) !== null, 5000); + assert.equal(sentOf(s.project, tab).workflow, "plan"); +}); + +test("a picture deleted between Start and the box is skipped, and the rest still attach", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const tab = await noteTab(s, "Idea", TEXT, 3); + const main = await toTheMenu(s); + await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-1-plan", tabName: "Idea" }); + const first = readNotepad(s.project, tab).images[0].id; + removeImage(s.project, tab, first); + s.post(BOX); + await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000); + await until(async () => (await readyPictures(s).count()) === 2, 15000); + assert.equal(await itemCard(s.page, "idea").locator(".attach-thumb").count(), 2, "no failed or empty slot for the missing one"); +}); + +test("Back to the dashboard after the box fills takes the box with it, as its dialog says, and marks the tab sent", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const tab = await noteTab(s, "Idea", TEXT, 0); + const main = await toTheMenu(s); + await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-0-pathfinder", tabName: "Idea" }); + s.post(BOX); + await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000); + await s.page.click("#btn-home"); + await s.page.locator("#home-modal[open]").waitFor(); + await s.page.click("#home-go"); + const got = s.wait(10); + assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`); + assert.ok(got.actions.some((a) => a.i === "__dashboard"), "the send goes home"); + assert.ok(got.reply.includes(MARKER), "and carries the filled box"); + await until(() => sentOf(s.project, tab) !== null, 5000); +}); + +test("the box is filled once: a redraw or a reload keeps what the person typed, and the pictures are not added again", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + await noteTab(s, "Idea", TEXT, 3); + const main = await toTheMenu(s); + await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-0-pathfinder", tabName: "Idea" }); + s.post(BOX); + await until(async () => (await readyPictures(s).count()) === 3, 15000); + await boxOf(s).fill("My own words now."); + + s.post({ agent: { status: "waiting", activity: "Still here" } }); + await s.page.reload({ waitUntil: "domcontentloaded" }); + await drawn(s.page); + await boxOf(s).waitFor(); + assert.equal(await boxOf(s).inputValue(), "My own words now."); + await until(async () => (await readyPictures(s).count()) === 3, 5000); + // A second marked box later in the session is left alone. + s.post({ items: [{ id: "idea2", kind: "text", title: "Anything else", fill: "note" }] }); + await s.page.locator("#text-idea2").waitFor(); + assert.equal(await s.page.locator("#text-idea2").inputValue(), ""); +}); + +test("a launch that goes back to the dashboard before Send marks nothing", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const tab = await noteTab(s, "Idea", TEXT, 1); + const main = await toTheMenu(s); + await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-quick-task", tabName: "Idea" }); + s.post(BOX); + await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000); + const r = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "dashboard"], { cwd: s.project }); + assert.equal(r.status, 0, `resume failed: ${r.stderr}`); + s.post(MENU); + await main.getByRole("heading", { name: "What are we doing today?" }).waitFor(); + assert.equal(sentOf(s.project, tab), null); +}); + +test("a tab deleted between Start and the box leaves the box empty, with a banner", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + const tab = await noteTab(s, "Idea", TEXT, 1); + const main = await toTheMenu(s); + await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-1-plan", tabName: "Idea" }); + deleteTab(s.project, tab); + s.post(BOX); + await s.page.locator("#banner", { hasText: "That Notebook tab is gone; the box starts empty." }).waitFor(); + assert.equal(await boxOf(s).inputValue(), ""); + assert.equal(await readyPictures(s).count(), 0); +}); diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index 0ae92c3..ac77d44 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -187,7 +187,7 @@ const ROUTE_ORDER = [ "/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft", "/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/cleanup", "/upload", "/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab", - "/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/", + "/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/", "/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace", "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye", ]; diff --git a/scripts/test-web-console-spec-states.mjs b/scripts/test-web-console-spec-states.mjs index 1e94a5c..a4d97d1 100644 --- a/scripts/test-web-console-spec-states.mjs +++ b/scripts/test-web-console-spec-states.mjs @@ -442,6 +442,46 @@ test("the scan: an assumed task counts as done and is named, and numbered task l } }); +test("the scan: planChange is true for a waiting Plan change brief, and absent once it is applied or dropped", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-brief-")); + const notes = (line) => "# Phase 1\n\n- [x] **Task 1.1:** One\n- [ ] **Task 1.2:** Two\n\n## Notes\n\n### Paused 2026-10-27\n" + line + "\n\n## Phase Completion Summary\n"; + const checklist = (mark) => `# Overview\n\n## Phase Checklist\n\n- [${mark}] Phase 1: One\n- [ ] Phase 2: Two\n`; + const specs = { + waiting: { "overview.md": checklist("/"), "phase-1.md": notes("**Plan change:** add a phase first"), "phase-2.md": PHASE([false]) }, + applied: { "overview.md": checklist("/"), "phase-1.md": notes("**Plan change (applied 2026-10-27):** add a phase first"), "phase-2.md": PHASE([false]) }, + dropped: { "overview.md": checklist("/"), "phase-1.md": notes("**Plan change (dropped 2026-10-27):** add a phase first"), "phase-2.md": PHASE([false]) }, + // No phase marked [/]: every phase file is read. + unmarked: { "overview.md": checklist(" "), "phase-1.md": PHASE([false]), "phase-2.md": notes("**Plan change:** rename a task") }, + // A brief in a phase that is not the one in progress is not waiting on it. + otherPhase: { "overview.md": checklist("/"), "phase-1.md": notes("Nothing to change."), "phase-2.md": notes("**Plan change:** later") }, + // Outside the Notes section it is only prose. + notInNotes: { "overview.md": checklist("/"), "phase-1.md": "# Phase 1\n\n**Plan change:** quoted in the overview\n\n- [ ] **Task 1.1:** One\n", "phase-2.md": PHASE([false]) }, + built: { "overview.md": checklist("x"), "phase-1.md": notes("**Plan change:** found in the last checks").replace("- [ ] **Task 1.2:**", "- [x] **Task 1.2:**"), "phase-2.md": PHASE([true]) }, + planned: { "PLAN-DRAFT-20261027.md": "# Plan draft\n\n**Status:** Draft\n\n## Notes\n\n**Plan change:** not a phased spec\n" }, + }; + try { + for (const [name, files] of Object.entries(specs)) + for (const [rel, text] of Object.entries(files)) { + fs.mkdirSync(path.join(root, "specs", name), { recursive: true }); + fs.writeFileSync(path.join(root, "specs", name, rel), text); + } + const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp])); + assert.equal(by.waiting.planChange, true); + assert.equal(by.waiting.state, "building"); + assert.equal("planChange" in by.applied, false); + assert.equal("planChange" in by.dropped, false); + assert.equal(by.unmarked.planChange, true); + assert.equal(by.unmarked.state, "building"); + assert.equal("planChange" in by.otherPhase, false); + assert.equal("planChange" in by.notInNotes, false); + assert.equal(by.built.state, "built"); + assert.equal(by.built.planChange, true, "a built spec can still have a brief waiting"); + assert.equal("planChange" in by.planned, false); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } +}); + // The states no card names in its `states` list: a card that is on for "any" // spec does not count, since it would take a state nobody thought about. A // finished state is taken by no card on purpose. diff --git a/scripts/test-web-console-state.mjs b/scripts/test-web-console-state.mjs index b752807..cc098c7 100644 --- a/scripts/test-web-console-state.mjs +++ b/scripts/test-web-console-state.mjs @@ -22,6 +22,8 @@ test("state: page starts as app.js always started it", () => { homeward: null, launching: null, deleting: null, + noteSend: null, + noteSent: null, retract: {}, chat: { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null }, }); diff --git a/src/web-console/console.md b/src/web-console/console.md index 30298f5..31e52b6 100644 --- a/src/web-console/console.md +++ b/src/web-console/console.md @@ -320,6 +320,11 @@ An option is `{ "k": "A", "text": "short label", "detail": "the trade-off", "rec it, with a one-line summary in `placeholder`. A resumed map, PLAN-DRAFT or checkpoint gets no idea card. Only the box's text comes back; never mention templates in the terminal. +- **Fill from a Notebook tab:** on a `text` item, `"fill": "note"` (its only + value; any other kind or value is exit 3) has the page fill the first open one + once, with the tab's text and ticked pictures, when the person started from a + Notebook tab. You read it only when they send that box (Send, or Stop or + Back to the dashboard, which carry ready answers). - **Recommend only when you genuinely know better and can say why.** "Which format survives Excel?" is yours; "Who is this for?" is not — there a recommendation is an anchor people rubber-stamp. At most one per question. diff --git a/src/web-console/notepads.mjs b/src/web-console/notepads.mjs index 0288e54..64f2adc 100644 --- a/src/web-console/notepads.mjs +++ b/src/web-console/notepads.mjs @@ -5,8 +5,8 @@ // // ~/.plan2code/notepads/-<12 hex>/ // meta.json { v: 2, folder, created } -// tabs.json { v: 1, order: [id], last: id|null, tabs: { id: { name, created } } } -// tabs//note.md the tab's text, UTF-8, written atomically +// tabs.json { v: 1, order: [id], last: id|null, tabs: { id: { name, created, sent? } } } +// tabs//note.md the tab's text, UTF-8, written atomically // tabs//images/.jpg a picture, JPEG from the page // tabs//images/.thumb.jpg its thumbnail, when the page sent one // @@ -17,7 +17,8 @@ // // This module is the only code that names, reads, writes, lists and removes // them. The page reaches it through the /notepad routes; the agent CLI never -// imports it, so nothing in a notepad can reach the agent. Reading never +// imports it, so a tab leaves it only through a send the person starts on the +// dashboard (a test checks the imports). Reading never // creates or touches a file, so only a person's own edits age a notepad. // PLAN2CODE_NOTEPADS_DIR moves the folder, for tests. // @@ -48,7 +49,7 @@ export const LEGACY_TAB_ID = "0000000000a1"; // A refusal the routes turn into `{ error: code }` with this status. Codes: // bad, too-long, too-many, not-jpeg, not-found, and for tabs bad-name (400), -// duplicate-name (409), too-many-tabs (409), no-such-tab (404). +// bad-sent (400), duplicate-name (409), too-many-tabs (409), no-such-tab (404). export class NotepadError extends Error { constructor(code, status) { super(code); @@ -111,8 +112,21 @@ const isFile = (p) => { } }; -// `{ order, last, tabs: { id: { name, created } } }` from tabs.json with every -// part of its shape checked, or null when it is missing or does not hold up. +// The workflows a tab can be sent to from the dashboard, and the spec a Revise +// plan send names. +export const SENT_WORKFLOWS = ["pathfinder", "plan", "quick-task", "revise-plan"]; +const SENT_SPEC_RE = /^specs\/[A-Za-z0-9._-]+$/; + +// A tab's `sent` record as stored, or null when it does not hold up. +function readSent(sent) { + if (!sent || typeof sent !== "object" || !SENT_WORKFLOWS.includes(sent.workflow) || typeof sent.at !== "string") return null; + if (sent.spec !== undefined && !(typeof sent.spec === "string" && SENT_SPEC_RE.test(sent.spec))) return null; + return { workflow: sent.workflow, ...(sent.spec ? { spec: sent.spec } : {}), at: sent.at }; +} + +// `{ order, last, tabs: { id: { name, created, sent? } } }` from tabs.json with +// every part of its shape checked, or null when it is missing or does not hold +// up. A `sent` record that does not hold up is dropped, never the whole index. function readIndex(dir) { const raw = readJson(path.join(dir, INDEX_FILE)); if (!raw || typeof raw !== "object" || !Array.isArray(raw.order)) return null; @@ -125,6 +139,8 @@ function readIndex(dir) { if (!t || typeof t !== "object") return null; try { tabs[id] = { name: normalizeTabName(t.name), created: typeof t.created === "string" ? t.created : null }; + const sent = readSent(t.sent); + if (sent) tabs[id].sent = sent; } catch { return null; } @@ -333,14 +349,18 @@ function imageEntries(dirs) { const imageUrl = (tab, id, thumb) => "/notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg"; /** - * The tabs, as `[{ id, name }]` in order, and the one last used. Read only; a - * notepad still in the first shape answers one virtual tab, Notes. + * The tabs, as `[{ id, name, sent? }]` in order (`sent` only on a tab sent + * from the dashboard), and the one last used. Read only; a notepad still in + * the first shape answers one virtual tab, Notes, never sent. */ export function listTabs(folder) { const dir = notepadFolder(folder); if (!fs.existsSync(dir)) return { tabs: [], last: null }; const index = readIndex(dir); - if (index) return { tabs: index.order.map((id) => ({ id, name: index.tabs[id].name })), last: index.last }; + if (index) { + const tabs = index.order.map((id) => ({ id, name: index.tabs[id].name, ...(index.tabs[id].sent ? { sent: index.tabs[id].sent } : {}) })); + return { tabs, last: index.last }; + } if (legacyShape(dir)) return { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID }; return { tabs: [], last: null }; } @@ -353,7 +373,8 @@ export function defaultTabId(folder) { /** * What the page shows: - * `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images } | null }` + * `{ tabs: [{ id, name, sent? }], last, tab: { id, text, savedAt, images } | null }` + * (`sent` is `{ workflow, spec?, at }`, the tab's last send from the dashboard) * for the tab asked for (else the default one), plus that tab's `text`, * `savedAt` and `images` at the top, where the first page read them. A named * tab that does not exist is a `no-such-tab` refusal. Never creates or writes @@ -426,6 +447,26 @@ export function renameTab(folder, id, name) { }); } +/** + * Record that a tab was sent to a workflow from the dashboard, replacing any + * earlier record. `workflow` is one of SENT_WORKFLOWS and `spec`, when given, + * a `specs/` path. Resolves to `{ id, sent }`. + */ +export function markTabSent(folder, tab, { workflow, spec } = {}) { + requireTab(folder, tab); + return withNotepad(folder, (dir, index) => { + if (!Object.hasOwn(index.tabs, tab)) throw new NotepadError("no-such-tab", 404); + if (!SENT_WORKFLOWS.includes(workflow)) throw new NotepadError("bad-sent", 400); + if (spec !== undefined && spec !== null && !(typeof spec === "string" && SENT_SPEC_RE.test(spec))) { + throw new NotepadError("bad-sent", 400); + } + const sent = { workflow, ...(spec ? { spec } : {}), at: nowIso() }; + index.tabs[tab].sent = sent; + commit(dir, index); + return { id: tab, sent }; + }); +} + /** Remember which tab was open last. */ export function setLastTab(folder, id) { requireTab(folder, id); diff --git a/src/web-console/notes/pathfinder.md b/src/web-console/notes/pathfinder.md index 8e89bb4..0fcd718 100644 --- a/src/web-console/notes/pathfinder.md +++ b/src/web-console/notes/pathfinder.md @@ -7,7 +7,7 @@ Workflow notes for `pathfinder`, part of the web console contract (`console.md`) once it does, and `"specDir": "specs/"` when the folder is created (`console-stop.md` → Saying what stopping would cost). - The menu after a decision is a `menu` card: its `options` are `trail --form C`'s, and the `Start fresh` one keeps its `"fresh": true` (the page words it "Start New Session" under the desktop app and asks the app for one on Send). Set the card's `command` to the resume command printed under `OR START FRESH`: the page copies it first. A declined confirm leaves you the pick: carry on as for any `Start fresh`. -- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds). +- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one. - A doc that is a file exactly as written (the map once it is on disk, a brief) goes up as a `file` block (`{ "id": "body", "file": "specs//pathfinder/map.md" }`) rather than pasted. Keep `md` blocks diff --git a/src/web-console/notes/plan.md b/src/web-console/notes/plan.md index a06def0..9ddb6fd 100644 --- a/src/web-console/notes/plan.md +++ b/src/web-console/notes/plan.md @@ -4,7 +4,7 @@ Workflow notes for `plan`, part of the web console contract (`console.md`). - Open with `--workflow plan`, first thing. Every question and sign-off gate goes through the page, phase breakdowns as an editable `list`. -- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds). +- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one. - Planning has no mid-session save before the Large checkpoint or Phase 7, so for a stop before then say plainly in `finish.body` that nothing was kept, and use `"command": "/plan2code-1-plan"`. After the checkpoint, post diff --git a/src/web-console/notes/quick-task.md b/src/web-console/notes/quick-task.md index 6d7721b..e6148ad 100644 --- a/src/web-console/notes/quick-task.md +++ b/src/web-console/notes/quick-task.md @@ -7,7 +7,7 @@ Workflow notes for `quick-task`, part of the web console contract - Open with the first clarifying question. Clarifying questions go out as `text` or `choice`, at most three at a time. The first, asking what to build, - carries `"templates": "idea"` (`console.md` → The kinds). + carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one. - Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."` at the start, and `"stopWarning": ""` once the build is under way. - **Scope check:** a `choice`, "Too big for a quick task?", options diff --git a/src/web-console/notes/revise-plan.md b/src/web-console/notes/revise-plan.md index 3690727..59c073b 100644 --- a/src/web-console/notes/revise-plan.md +++ b/src/web-console/notes/revise-plan.md @@ -6,7 +6,7 @@ Revision is a short run of gates, and each maps onto a kind you already know: | Step | On the page | | --- | --- | -| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. | +| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. With none waiting, the first card is a `text` item titled "What should change", `"fill": "note"`, asking what to change; its answer feeds the "Is this the change?" recap. | | 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." | | 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. | | 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. | diff --git a/src/web-console/patches.mjs b/src/web-console/patches.mjs index a118ebd..2ac8c8f 100644 --- a/src/web-console/patches.mjs +++ b/src/web-console/patches.mjs @@ -648,6 +648,10 @@ export function validate(state) { if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) { problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`); } + // The box the page fills from a Notebook tab picked at Start. + if (item.fill != null && (item.kind !== "text" || item.fill !== "note")) { + problems.push(`item "${item.id}" has "fill": only a text item can carry it, and its only value is "note".`); + } // The page compiles it as the person types, and a pattern that does not // compile throws there, on every keystroke, with nothing on screen to say why. if (item.pattern != null) { diff --git a/src/web-console/public/answers.js b/src/web-console/public/answers.js index eee8168..f7fd44d 100644 --- a/src/web-console/public/answers.js +++ b/src/web-console/public/answers.js @@ -695,6 +695,49 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) { return off(rule.greyed[taken] || (lookup(taken)?.finished && rule.greyed.finished) || rule.greyed.default); } +// The cards whose confirm pane offers "Start with a note from your Notebook" +// on Start fresh: the three that open on an idea box. +const NOTE_FRESH_CARDS = new Set(["plan2code-0-pathfinder", "plan2code-1-plan", "plan2code-quick-task"]); + +/** + * Whether a lit card's confirm pane offers the Notebook switch: Pathfinder, + * Plan and Quick Task on Start fresh (no spec picked), and Revise plan on a + * picked spec with no plan change brief waiting (a waiting brief is what that + * revision is about). Never on a grayed card, never on any other card. + */ +export function noteSwitchShows(entry, scan, sel) { + if (!entry || !cardAvailability(entry, scan, sel).on) return false; + if (NOTE_FRESH_CARDS.has(entry.skill)) return !sel; + if (entry.skill === "plan2code-1b-revise-plan") return Boolean(sel) && sel.planChange !== true; + return false; +} + +// A Notebook tab's text over this many UTF-8 bytes gets a "Long tab" note in +// the confirm pane's preview, so the person can trim it before it is sent. +export const NOTE_LONG_BYTES = 51200; + +/** Whether a Notebook tab, as GET /notepad?tab= reads it, holds nothing to send. */ +export function noteTabEmpty(tab) { + const text = tab && typeof tab.text === "string" ? tab.text : ""; + const images = tab && Array.isArray(tab.images) ? tab.images : []; + return text.trim() === "" && images.length === 0; +} + +/** The pictures ticked when a tab is first picked: its first MAX_ATTACHMENTS, in its own order. */ +export function defaultNoteTicks(images) { + return (Array.isArray(images) ? images : []).slice(0, MAX_ATTACHMENTS).map((img) => img.id); +} + +/** + * The ticked ids after a click on `id`: unticked if it was ticked, else ticked + * while fewer than MAX_ATTACHMENTS are; past that the click changes nothing. + */ +export function toggleNoteTick(ticked, id) { + const list = Array.isArray(ticked) ? ticked : []; + if (list.includes(id)) return list.filter((t) => t !== id); + return list.length < MAX_ATTACHMENTS ? [...list, id] : list; +} + /** * The spec a card's launch carries: the picker's selection for the cards that * take a spec, and for Quick Task only a diagnosed bug, whose write-up it reads diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 1f85d98..32b0e42 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -35,6 +35,9 @@ + + + @@ -184,6 +187,19 @@ + +
@@ -216,7 +232,8 @@ + folder; a tab reaches the agent only through a send the person + starts on the dashboard. -->

Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.

+