diff --git a/.agents-docs/AGENTS-architecture.md b/.agents-docs/AGENTS-architecture.md index a28ac18..6aebb5e 100644 --- a/.agents-docs/AGENTS-architecture.md +++ b/.agents-docs/AGENTS-architecture.md @@ -302,7 +302,7 @@ Key design points: - **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: "` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean. - **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it. - **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses. -- **`GET /overview` is the one route that reads a project file.** It serves `/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404. +- **`GET /overview` is the one route that reads a project file.** It serves `/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`. - **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it. - **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:` (a month-old notepad, whole; see Notebook below) and `completed:` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `..tmp`, which live for milliseconds. `root:` is only scanned when the console home is `/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**. - **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills//references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session. diff --git a/.readme/web-console-design.md b/.readme/web-console-design.md index 8eea6ff..1aaee90 100644 --- a/.readme/web-console-design.md +++ b/.readme/web-console-design.md @@ -313,7 +313,7 @@ Built for a mixed product and engineering room reading one screen together. - **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off grays the boxes but keeps their ticks, and ticking a box plays it. - **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off. - **Per-tab scroll memory.** An in-memory `Map` keyed by view id holds the scroller's position (the main column on a document or the Overview, the card on the questions view, with the item it belonged to), restored when the tab comes back. Page-local, never persisted, cleared when the session turns into or out of the dashboard. -- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record. +- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. On the dashboard, a spec with no overview gets a **Map** tab (`?file=map`, `pathfinder/map.md`) and a **Plan draft** tab (`?file=draft`, the live `PLAN-DRAFT-*.md`) in its place, each while its file exists, fetched and drawn the same way; away from the dashboard only the overview is read, since a session's own map or draft is the work already in front of it. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record. - **The footer slot.** The workspace label sits centered in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show. - **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on center stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there. diff --git a/.readme/web-console.md b/.readme/web-console.md index 3eabf9b..0459d58 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -129,7 +129,10 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so spec that has an `overview.md`, an **Overview** tab shows it — read-only, and read fresh from disk each time you open the tab, so an edit shows up straight away. No file, no tab. On the dashboard it follows the spec picked - at the top, and disappears for *start from scratch*. + at the top, and disappears for *start from scratch*. A picked spec that is + not documented yet shows its **Map** (`pathfinder/map.md`) and its + **Plan draft** (the live `PLAN-DRAFT-*.md`) as tabs instead, each when it + exists. - **Where you are, at the bottom.** The footer names the folder the session was launched from and its git branch (`plan2code · feature/…`), muted in the middle. Click it to open the Workspace dialog (see *Your workspace*). @@ -869,7 +872,7 @@ origin. | `POST /submit` | The Send. A note may carry `images` and `files`, each `[{ path, name }]`: at most 5 together, images in `images` and documents in `files`, every path inside this session's `uploads/`, otherwise 400. | | `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. | | `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. | -| `GET /overview?spec=specs/` | The Overview tab's read of `/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. | +| `GET /overview?spec=specs/[&file=map\|draft]` | The Overview tab's read of `/overview.md` (or, with `file=`, the Map tab's `pathfinder/map.md` or the Plan draft tab's live `PLAN-DRAFT-*.md`), as `text/markdown` with `cache-control: no-store` and the file's spec-relative name, URL-encoded, in `x-spec-file`. A missing file is a 204. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get the same 204 as a missing file, as does an unscanned `spec` or an unknown `file`. | | `GET /handoff?id=` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. | | `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. | | `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. | diff --git a/CHANGELOG.md b/CHANGELOG.md index 08f7929..9b969bc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ All notable changes to Plan2Code will be documented in this file. - **helpers**: a helper (subagent) no longer has to run on the session's own model and effort. A new shared reference, `helper-strength.md`, shipped in Pathfinder, Quick Task, Implement, Implement + Review and Review, matches each helper job to a strength (`light`, `standard`, `strongest` or `inherit`) and an effort (`low`, `medium` or `high`) from signals that can be checked, with floors, one-step escalation and a fallback order for tools that cannot set either, and never names a model or vendor. Review, Implement + Review and Pathfinder name the strength for the helpers they start, and the rules apply in terminal sessions too. - **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review. - **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort". +- **web console**: picking a spec on the dashboard that is not documented yet now shows its main files as read-only tabs in the top bar, like the **Overview** tab of a documented spec: **Map** for a Pathfinder map (`pathfinder/map.md`) and **Plan draft** for Plan's live `PLAN-DRAFT-*.md`, each when it exists. Once the spec has an `overview.md`, Overview replaces them. - `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command. - **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli ` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed. - **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app. diff --git a/scripts/test-web-console-page-dashboard.mjs b/scripts/test-web-console-page-dashboard.mjs index 5a3170e..0148b69 100644 --- a/scripts/test-web-console-page-dashboard.mjs +++ b/scripts/test-web-console-page-dashboard.mjs @@ -229,6 +229,51 @@ test("picking Start from scratch instead of a spec grays Document, and a launch assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`); }); +// What a person would see break: a spec not documented yet offers nothing to +// read, or its Map and Plan draft tabs stay up for a spec that has an +// overview (or for no spec at all). +test("a spec not documented yet shows its Map and Plan draft as tabs, and a documented one shows only Overview", async (t) => { + const project = tempProject({ + ...DRAFT_PROJECT, + "specs/demo/pathfinder/map.md": "# Map: demo\n\n**Status:** Cleared\n\nWho votes for lunch.\n", + "specs/done/overview.md": "# Overview: done\n\nAll written up.\n", + "specs/done/phase-1.md": "- [ ] **Task 1.1:** x\n", + }); + const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project }); + const main = await toTheMenu(s); + const tab = (name) => s.page.locator("#views .view-tab", { hasText: new RegExp(`^${name}$`) }); + + await chipFor(main, "demo").click(); + await pickedChip(main, "demo").waitFor(); + await tab("Map").waitFor(); + await tab("Plan draft").waitFor(); + assert.equal(await tab("Overview").count(), 0, "no overview.md, no Overview tab"); + + await tab("Plan draft").click(); + await main.getByRole("heading", { name: "Plan draft", exact: true }).waitFor(); + assert.match(await textOf(main), /specs\/demo\/PLAN-DRAFT-20261017\.md · read-only/); + assert.match(await textOf(main), /A lunch vote for the team\./); + await tab("Map").click(); + await main.getByRole("heading", { name: "Map", exact: true }).waitFor(); + assert.match(await textOf(main), /specs\/demo\/pathfinder\/map\.md · read-only/); + assert.match(await textOf(main), /Who votes for lunch\./); + + // The documented spec trades both for its Overview, and the open Map tab, + // gone with them, sends the person home. + await tab("Dashboard").click(); + await chipFor(main, "done").click(); + await pickedChip(main, "done").waitFor(); + await tab("Overview").waitFor(); + assert.ok( + await until(async () => (await tab("Map").count()) === 0 && (await tab("Plan draft").count()) === 0), + "the Map and Plan draft tabs go" + ); + + await chipFor(main, "Start from scratch").click(); + await pickedChip(main, "Start from scratch").waitFor(); + assert.ok(await until(async () => (await tab("Overview").count()) === 0), "no spec, no spec tabs"); +}); + // What a person would see break: the intro cannot be skipped, or it replays // on every reload of the same tab. test("Skip the intro ends the first-open wake-up at once, and a reload of the tab does not play it again", async (t) => { diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index 54213a6..2b9b8cc 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -25,6 +25,7 @@ import { handOff, PROTECTED_CONSOLE_FILES, readOverview, + readSpecFile, removeCleanup, removeScratch, removeSessions, @@ -562,6 +563,12 @@ function overviewProject() { fs.writeFileSync(path.join(root, "specs", "a", "overview.md"), "# Overview A\n"); fs.writeFileSync(path.join(root, "specs", "a", "phase-1.md"), "- [ ] **Task 1.1:** x\n"); fs.writeFileSync(path.join(root, "specs", "b", "notes.md"), "notes\n"); + // Planned, not documented: a Pathfinder map and a live draft beside the + // copy Revise plan keeps of the last one. + fs.mkdirSync(path.join(root, "specs", "c", "pathfinder"), { recursive: true }); + fs.writeFileSync(path.join(root, "specs", "c", "pathfinder", "map.md"), "# Map C\n"); + fs.writeFileSync(path.join(root, "specs", "c", "PLAN-DRAFT-20261020.md"), "# Draft C\n"); + fs.writeFileSync(path.join(root, "specs", "c", "PLAN-DRAFT-20261020-prev.md"), "# Old draft C\n"); fs.mkdirSync(path.join(base, "outside")); fs.writeFileSync(path.join(base, "outside", "overview.md"), "# SECRET\n"); return { base, root }; @@ -598,6 +605,22 @@ test("readOverview reads a spec's overview and nothing outside the root", async } }); +test("readSpecFile reads a spec's map and live plan draft, and names the file", async () => { + const { base, root } = overviewProject(); + try { + assert.deepEqual(await readSpecFile(root, "specs/c", "map"), { file: "pathfinder/map.md", text: "# Map C\n" }); + assert.deepEqual(await readSpecFile(root, "specs/c", "draft"), { file: "PLAN-DRAFT-20261020.md", text: "# Draft C\n" }); + assert.deepEqual(await readSpecFile(root, "specs/a", "overview"), { file: "overview.md", text: "# Overview A\n" }); + assert.equal(await readSpecFile(root, "specs/c", "overview"), null); + assert.equal(await readSpecFile(root, "specs/a", "map"), null); + assert.equal(await readSpecFile(root, "specs/a", "draft"), null); + assert.equal(await readSpecFile(root, "specs/c", "phase-1.md"), null, "only the known kinds"); + assert.equal(await readSpecFile(root, "../outside", "draft"), null); + } finally { + fs.rmSync(base, { recursive: true, force: true }); + } +}); + test("GET /overview serves the session's spec, and on the dashboard only a scanned one", async () => { const { base, root } = overviewProject(); const sids = []; @@ -628,6 +651,16 @@ test("GET /overview serves the session's spec, and on the dashboard only a scann assert.equal((await get(d, "?spec=specs/b")).status, 204); assert.equal((await get(d, "?spec=specs/../..")).status, 204); assert.equal((await get(d, "?spec=specs/not-scanned")).status, 204); + // ?file= picks the map or the live draft, and names it for the page. + const map = await get(d, "?spec=specs/c&file=map"); + assert.equal(map.status, 200); + assert.equal(map.headers.get("x-spec-file"), encodeURIComponent("pathfinder/map.md")); + assert.equal(await map.text(), "# Map C\n"); + const draft = await get(d, "?spec=specs/c&file=draft"); + assert.equal(draft.headers.get("x-spec-file"), "PLAN-DRAFT-20261020.md"); + assert.equal(await draft.text(), "# Draft C\n"); + assert.equal((await get(d, "?spec=specs/c")).status, 204, "no overview.md yet"); + assert.equal((await get(d, "?spec=specs/c&file=nope")).status, 204); } finally { for (const s of sids) cliIn(root, ["stop", "--session", s]); fs.rmSync(base, { recursive: true, force: true }); diff --git a/scripts/test-web-console-session.mjs b/scripts/test-web-console-session.mjs index 7283ca0..64237f4 100644 --- a/scripts/test-web-console-session.mjs +++ b/scripts/test-web-console-session.mjs @@ -734,6 +734,8 @@ test("help: helpTabFor opens on the tab for where the person is", () => { [{ dashboard: true, meterRed: true, view: "ask" }, "ask"], [{ meterRed: true }, "about"], [{ view: "overview" }, "docs"], + [{ view: "map" }, "docs"], + [{ view: "draft" }, "docs"], [{ view: "doc:plan" }, "docs"], [{ view: "doc:plan", workflow: "implement" }, "docs"], [{ workflow: "implement" }, "build"], diff --git a/scripts/test-web-console-state.mjs b/scripts/test-web-console-state.mjs index e739627..b752807 100644 --- a/scripts/test-web-console-state.mjs +++ b/scripts/test-web-console-state.mjs @@ -45,7 +45,7 @@ test("state: the rest of the shared state starts as app.js always started it", ( updateFrame: null, inApp: false, subagentsFrame: null, - overview: { key: null, text: null }, + overview: { key: null, files: {} }, wake: null, dashPick: null, mentionPop: null, diff --git a/src/web-console/public/help.js b/src/web-console/public/help.js index 3de2466..a16d106 100644 --- a/src/web-console/public/help.js +++ b/src/web-console/public/help.js @@ -46,7 +46,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, if (v === "subagents") return "subagents"; if (dashboard && meterRed) return "meter"; if (dashboard) return "dashboard"; - if (v === "overview" || v.startsWith("doc:")) return "docs"; + if (v === "overview" || v === "map" || v === "draft" || v.startsWith("doc:")) return "docs"; if (workflow === "git") return "git"; if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build"; return "about"; diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 8d5d5d7..1f85d98 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -1654,13 +1654,19 @@ Out of date by the title means answers have landed that the document does not reflect yet.

-

The Overview tab

+

The Overview, Map and Plan draft tabs

When the session is working on a spec that has an overview.md, the Overview tab shows it. It is read-only, and read fresh from disk each time you open the tab, so an edit shows up straight away. No file, no tab.

+

+ On the dashboard, a picked spec that is not documented yet shows its + main files the same way instead: Map for its + Pathfinder map and Plan draft for its plan draft, each + when it exists. +

Printing and saving

  • diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 72bf75f..863499c 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -51,8 +51,8 @@ import { helperRows, showTab } from "../subagents.js"; import { FOOTER_TIERS, footerLabel } from "../workspace.js"; import { activity, agentAdrift, agentWorking, asked, awaitingReply, byId, dashboardLive, docs, doingNow, - finish, gitAwaiting, isDashboard, isGitBoard, isOpen, items, loadOverview, myTurn, openItems, - overviewSpec, patience, pressStranded, reviewPending, scan, selSpec, sendCollected, stagedCount, stranded, + finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems, + patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded, topics, workingMs, WORKING_GRACE_MS, workspaceFolders, } from "../selectors.js"; @@ -433,9 +433,9 @@ export function adopt(body) { render(); if ($("workspace-modal").open) renderWorkspace(); tellFolderIssues(); - // The Overview tab's file changes under a build, so a tab you are watching + // A spec file tab's file changes under a build, so a tab you are watching // refetches on every new frame too, not only on the click that opened it. - if (firstLoad || page.S.specDir !== prevSpecDir || page.S.workflow !== prevWorkflow || page.view === "overview") loadOverview(); + if (firstLoad || page.S.specDir !== prevSpecDir || page.S.workflow !== prevWorkflow || isSpecFileView(page.view)) loadOverview(); if (announce) showArrival(announce); // New entries land at the bottom of the rail. Gliding down to them beats // leaving the list parked where it was while it grew underneath. @@ -860,7 +860,7 @@ function withFocus(fn) { // (the dashboard menu, the end page). function currentScroller() { if (!drawnView) return null; - if (drawnView.startsWith("doc:") || drawnView === "overview") return $("main"); + if (drawnView.startsWith("doc:") || isSpecFileView(drawnView)) return $("main"); if (drawnView === "questions") return $("main").querySelector(":scope > .card.question"); if (drawnView === "ask") return $("main").querySelector(".ask-list"); return null; @@ -1249,10 +1249,11 @@ function renderViews() { }, ]; // Built in rather than posted: present exactly while the spec in view has - // an overview.md. A tab that vanishes under the person sends them home. - const hasOverview = typeof page.overview.text === "string" && page.overview.key === overviewSpec(); - if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 }); - else if (page.view === "overview") page.view = "questions"; + // the file (an overview.md, or before one a map or a plan draft). A tab + // that vanishes under the person sends them home. + const fileTabs = specFileTabs(); + for (const f of fileTabs) tabs.push({ id: f.id, label: f.label, count: 0 }); + if (isSpecFileView(page.view) && !fileTabs.some((f) => f.id === page.view)) page.view = "questions"; for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 }); // The helpers the agent reported, from the first one on; cleared by a // dashboard hop, which sends the person home like the Overview tab does. @@ -1301,7 +1302,7 @@ function renderViews() { // The cached text paints at once; the fresh read repaints if the file // changed on disk since. render(); - if (t.id === "overview") loadOverview(); + if (isSpecFileView(t.id)) loadOverview(); }); nav.appendChild(b); } @@ -1436,11 +1437,11 @@ function renderMain() { } function paintMain(main) { - main.classList.toggle("is-doc", page.view.startsWith("doc:") || page.view === "overview"); + main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view)); main.classList.toggle("is-ask", page.view === "ask"); if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4)); - if (page.view === "overview") return renderOverview(main); + if (isSpecFileView(page.view)) return renderOverview(main, page.view); if (page.view === "ask") return renderAsk(main); if (page.view === "subagents") return renderSubagents(main); diff --git a/src/web-console/public/screens/docs.js b/src/web-console/public/screens/docs.js index 538ab6e..7e29f3e 100644 --- a/src/web-console/public/screens/docs.js +++ b/src/web-console/public/screens/docs.js @@ -1,6 +1,6 @@ // Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only. -import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish } from "../selectors.js"; +import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES } from "../selectors.js"; import { el, md } from "../render.js"; import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js"; import { hooks, page, redraw } from "../state.js"; @@ -220,19 +220,22 @@ function printButton() { return print; } -// The spec's overview.md, read-only and drawn through the same markdown path -// as every doc. No Download: the file is already on disk. -export function renderOverview(main) { +// One of the spec's files (overview.md, the Pathfinder map, the Plan draft), +// read-only and drawn through the same markdown path as every doc. No +// Download: the file is already on disk. +export function renderOverview(main, kind = "overview") { + const spec = SPEC_FILES.find((f) => f.id === kind) || SPEC_FILES[0]; + const found = page.overview.files[spec.id]; const head = el("div", "doc-head"); - head.appendChild(el("h2", null, "Overview")); + head.appendChild(el("h2", null, spec.label)); const tools = el("div", "doc-tools"); tools.appendChild(backButton()); tools.appendChild(printButton()); head.appendChild(tools); main.appendChild(head); - main.appendChild(el("p", "help", `${page.overview.key}/overview.md · read-only, straight from disk`)); + main.appendChild(el("p", "help", `${page.overview.key}/${found ? found.file : ""} · read-only, straight from disk`)); const box = el("div", "block settled"); - box.appendChild(md(page.overview.text, "md")); + box.appendChild(md(found ? found.text : "", "md")); main.appendChild(box); } diff --git a/src/web-console/public/selectors.js b/src/web-console/public/selectors.js index 4bbaa06..dbacd75 100644 --- a/src/web-console/public/selectors.js +++ b/src/web-console/public/selectors.js @@ -236,26 +236,61 @@ export function pressStranded() { return Date.now() - Date.parse(page.agentLastSeen) > UNCOLLECTED_MS; } -// The spec whose overview.md the Overview tab shows: the dashboard picker's +// The spec whose files the spec file tabs show: the dashboard picker's // selection on the dashboard, the session's own spec everywhere else. export const overviewSpec = () => (isDashboard() ? selSpec()?.dir || "" : (page.S && page.S.specDir) || ""); -// Fresh from disk every time, never cached: the file changes under a build, -// and the tab is only worth having if it shows what is there now. Repaints -// only when the tab would appear, vanish or show different text. +// The spec files a tab can show, in tab order: each a view id, which is also +// the server's ?file= kind. Document's overview stands for the whole spec +// once it exists; before that the dashboard offers Pathfinder's map and +// Plan's draft. +export const SPEC_FILES = [ + { id: "overview", label: "Overview" }, + { id: "map", label: "Map" }, + { id: "draft", label: "Plan draft" }, +]; +export const isSpecFileView = (v) => SPEC_FILES.some((f) => f.id === v); + +// The spec file tabs to draw now: Overview alone when the spec has one, else +// the map and the draft that exist. Only for the spec in view, so a pick that +// moved on never shows the last spec's files. +export function specFileTabs() { + if (page.overview.key !== overviewSpec()) return []; + const has = (id) => Boolean(page.overview.files[id]); + if (has("overview")) return SPEC_FILES.filter((f) => f.id === "overview"); + return SPEC_FILES.filter((f) => f.id !== "overview" && has(f.id)); +} + +async function fetchSpecFile(spec, kind) { + try { + const res = await fetch("/overview?spec=" + encodeURIComponent(spec) + "&file=" + kind, { cache: "no-store" }); + if (res.status !== 200) return null; + const file = decodeURIComponent(res.headers.get("x-spec-file") || "") || kind; + return { file, text: await res.text() }; + } catch { + return null; + } +} + +// Fresh from disk every time, never cached: the files change under a build, +// and the tabs are only worth having if they show what is there now. Away +// from the dashboard only the overview is read: a session's own map or draft +// is the work already in front of it. Repaints only when a tab would appear, +// vanish or show different text. export async function loadOverview() { const spec = overviewSpec(); - let text = null; + const kinds = isDashboard() ? SPEC_FILES.map((f) => f.id) : ["overview"]; + const files = {}; if (spec) { - try { - const res = await fetch("/overview?spec=" + encodeURIComponent(spec), { cache: "no-store" }); - if (res.status === 200) text = await res.text(); - } catch {} + const found = await Promise.all(kinds.map((k) => fetchSpecFile(spec, k))); + kinds.forEach((k, i) => { + if (found[i]) files[k] = found[i]; + }); } // The selection moved on while this was in flight; its own fetch will land. if (spec !== overviewSpec()) return; - const changed = page.overview.key !== spec || page.overview.text !== text; - page.overview = { key: spec, text }; + const changed = page.overview.key !== spec || JSON.stringify(page.overview.files) !== JSON.stringify(files); + page.overview = { key: spec, files }; if (changed) redraw(); } diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index 26924a7..9ea46a2 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -108,9 +108,10 @@ export const page = { // The frame's Subagents switch ({ offered, supported, on, instruction, max, // revision }), or null before a server that sends it. subagentsFrame: null, - // The spec's overview.md as last fetched: `key` is the spec dir it was read - // for, `text` the file, or null when there is none. See loadOverview(). - overview: { key: null, text: null }, + // The spec's files as last fetched: `key` is the spec dir they were read + // for, `files` maps each SPEC_FILES kind (overview, map, draft) that exists + // to `{ file, text }`. See loadOverview(). + overview: { key: null, files: {} }, // The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns // true at the glide, which lets the menu in; `entered` once its entrance has // played; `typed` is how many characters of the note show, or null once all diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index e45758a..e85a786 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -27,7 +27,7 @@ import { writeJsonAtomic, } from "./files.mjs"; import { AGENTS_SCHEMA, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs"; -import { checkDocument, cleanupFindings, readOverview, removeCleanup } from "./sessions.mjs"; +import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./sessions.mjs"; import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs"; import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs"; import { specKey } from "./workspace.mjs"; @@ -302,12 +302,15 @@ function renderIndex(ctx) { /* ------------------------------------------------------ read-only routes */ -// The spec's overview.md, read-only. A dashboard honors ?spec= only for a -// spec its own scan found; every other workflow reads its own specDir. -// readOverview() keeps the read inside the project root. +// One of the spec's files, read-only: overview.md by default, or with +// ?file=draft or ?file=map the live PLAN-DRAFT or the Pathfinder map. A +// dashboard honors ?spec= only for a spec its own scan found; every other +// workflow reads its own specDir. readSpecFile() keeps the read inside the +// project root, and names the file it read in X-Spec-File. function overview(req, res, ctx, url) { const state = ctx.readState() || {}; const asked = url.searchParams.get("spec"); + const kind = url.searchParams.get("file") || "overview"; const spec = state.workflow === "dashboard" ? (state.scan?.specs || []).some((s) => s && s.dir === asked) @@ -320,10 +323,14 @@ function overview(req, res, ctx, url) { res.writeHead(204, baseHeaders({ "cache-control": "no-store" })); res.end(); }; - readOverview(state.worktree || state.project, spec) - .then((text) => - typeof text === "string" - ? send(res, 200, text, "text/markdown; charset=utf-8", { "cache-control": "no-store" }) + readSpecFile(state.worktree || state.project, spec, kind) + .then((found) => + found + ? send(res, 200, found.text, "text/markdown; charset=utf-8", { + "cache-control": "no-store", + // Encoded: a header value is bytes, and a file name need not be ASCII. + "x-spec-file": encodeURIComponent(found.file), + }) : noOverview() ) .catch(noOverview); diff --git a/src/web-console/sessions.mjs b/src/web-console/sessions.mjs index dff2f97..0b8d242 100644 --- a/src/web-console/sessions.mjs +++ b/src/web-console/sessions.mjs @@ -500,15 +500,38 @@ export async function removeCleanup(ids, opts = {}) { * and a symlink pointing outside all come back null. */ export async function readOverview(root, specDir) { + const found = await readSpecFile(root, specDir, "overview"); + return found ? found.text : null; +} + +// The files a spec folder can show as a tab, by kind: Document's overview, +// Plan's live draft (the newest PLAN-DRAFT that is not a `-prev` copy, as in +// scan.mjs) and Pathfinder's map. +async function specFileName(dir, kind) { + if (kind === "overview") return "overview.md"; + if (kind === "map") return "pathfinder/map.md"; + if (kind !== "draft") return null; + const drafts = (await fs.promises.readdir(dir)).filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n)); + return drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0] || null; +} + +/** + * One of a spec's files (`kind`: overview, draft or map), read-only, as + * `{ file, text }` with `file` relative to the spec folder, or null. Kept + * inside the root the same way readOverview() is. + */ +export async function readSpecFile(root, specDir, kind) { if (!root || !specDir || typeof specDir !== "string" || path.isAbsolute(specDir)) return null; try { - const file = path.resolve(root, specDir, "overview.md"); + const name = await specFileName(path.resolve(root, specDir), kind); + if (!name) return null; + const file = path.resolve(root, specDir, name); const [realFile, realRoot] = await Promise.all([fs.promises.realpath(file), fs.promises.realpath(root)]); // path.relative, not a prefix test: a root of `C:\` or `/` already ends // in the separator, and `root + sep` would then match nothing at all. const rel = path.relative(realRoot, realFile); if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null; - return await fs.promises.readFile(realFile, "utf8"); + return { file: name, text: await fs.promises.readFile(realFile, "utf8") }; } catch { return null; }