From ba19f79f1cdf9819b12e0e4654a885ee430ab119 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Thu, 12 Nov 2026 07:56:52 -0800 Subject: [PATCH] Add a Prototypes tab: list a spec's saved prototypes, read an md in place, open an html in a browser AI Assisted --- .../AGENTS-architecture-console-design.md | 1 + .readme/web-console.md | 8 ++ AGENTS.md | 2 +- package.json | 2 +- scripts/test-lanes.json | 1 + scripts/test-web-console-prototypes.mjs | 111 ++++++++++++++++++ scripts/test-web-console-server.mjs | 65 ++++++++++ scripts/test-web-console-shape.mjs | 4 +- src/web-console/open-link.mjs | 21 +++- src/web-console/public/screens/core.js | 20 +++- src/web-console/public/screens/docs.js | 68 ++++++++++- src/web-console/public/selectors.js | 56 +++++++++ src/web-console/public/state.js | 5 + src/web-console/public/styles/docs.css | 19 +++ src/web-console/routes.mjs | 76 +++++++++--- src/web-console/sessions.mjs | 80 +++++++++++++ 16 files changed, 511 insertions(+), 28 deletions(-) create mode 100644 scripts/test-web-console-prototypes.mjs diff --git a/.agents-docs/AGENTS-architecture-console-design.md b/.agents-docs/AGENTS-architecture-console-design.md index 7ba80aa..1ee4359 100644 --- a/.agents-docs/AGENTS-architecture-console-design.md +++ b/.agents-docs/AGENTS-architecture-console-design.md @@ -15,6 +15,7 @@ Key design points: - **`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, `ultrawide` 1440) 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 /agents-doc` is the other route that reads a project file** (the dashboard's AGENTS.md tab, right after Dashboard, shown while the project has an `AGENTS.md`). A dashboard session only; it serves `AGENTS.md` or one markdown file directly under `.agents-docs/` (`?file=`, default `AGENTS.md`; `readAgentsDoc()` in `sessions.mjs` allows exactly those two shapes and `realpath`s the file inside the root), as `text/markdown` with `no-store`, or a `204` for anything else. The page links `.agents-docs/` files in place through `md()`'s `link` option (`renderAgentsDoc()` in `screens/docs.js`). - **`GET /overview` reads a project file too.** 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=`. +- **The Prototypes tab reads a spec's `prototypes/` folder.** `GET /prototypes` lists its `.md` and `.html` files (204 when none), `GET /prototype?name=` serves one `.md`, and `POST /open-prototype` (origin-checked) hands one `.html` to the system's default opener through `openFile()` in `open-link.mjs` (one argument, no shell). The spec is chosen as `/overview` chooses it (`specInView()`); `listPrototypes()`, `readPrototype()` and `prototypeHtmlPath()` in `sessions.mjs` take a bare file name only and refuse any file whose realpath is not directly in the folder. The page shows the tab after the spec file tabs, on the dashboard and in a session alike (`loadPrototypes()`, called from `loadOverview()`). - **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 → System → 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, refused, refusal }`. So Cleanup is the one place the server deletes in a project, and it keeps a completed spec git could not give back: `completedSpecs()` marks each `completed:` item `tracked` only when `git ls-files` lists it and `git ls-files --others` lists nothing inside (outside a repository, or gitignored as `specs--completed/` is by default, it is untracked), and `removeCleanup()` refuses an untracked one into `refused`, with `refusal` the line the page's status shows. Nothing records a backup copy, so tracked by git is the only way through. 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.md b/.readme/web-console.md index c4ea114..028e4e8 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -138,6 +138,11 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so 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. +- **Saved prototypes, beside the spec.** When the spec in view (the one + picked on the dashboard, or the session's own) has saved UI prototypes in + its `prototypes/` folder, a **Prototypes** tab lists them. An `.md` opens + in place, with **Back to Prototypes**; an `.html` opens in your default + browser. - **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*). @@ -1966,6 +1971,9 @@ origin. | `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/[&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 /agents-doc[?file=]` | The Dashboard's AGENTS.md tab: `AGENTS.md` (the default) or one `.agents-docs/.md`, as `text/markdown` with `cache-control: no-store`. A dashboard only; any other file name, a missing file or a path that leaves the project is a 204. | +| `GET /prototypes?spec=specs/` | The Prototypes tab's list: `{ files: [{ name, kind }] }` (`kind` `md` or `html`) for the files directly in `/prototypes/`, or a 204 when there are none. The spec is chosen as for `/overview`. | +| `GET /prototype?spec=specs/&name=.md` | One `.md` from `/prototypes/`, as `text/markdown` with `cache-control: no-store`; any other name, a missing file or a path that leaves the folder is a 204. | +| `POST /open-prototype` | `{ spec, name }`: opens one `.html` from `/prototypes/` in the person's default browser. 404 for any other name, 500 when no browser could start. | | `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/AGENTS.md b/AGENTS.md index 3e49984..ab3c1d5 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -36,7 +36,7 @@ Details: [Status line](./.agents-docs/AGENTS-architecture-statusline.md) ## Web Console -Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the sixteen helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). +Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) installed once under `~/.plan2code/console//` (`installSharedConsole` in `install.js`) and reached from every skill through a forwarding stub, `src/web-console-stub/console.mjs`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, a spec's saved prototypes (a **Prototypes** tab: an `.md` read in place, an `.html` opened in the default browser), an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-.js`, and keeps a best per course, `activityBestGolf`), and one number a game may keep between sessions in `activityMemo` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, setup, Changelog, Git, Handoff and UI Prototype) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the sixteen helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is a card plus pointers: `console.md` (the card) once per conversation, then a topic file (`console-*.md` such as `console-docs.md`, `notes/.md`, `building*.md`) only when the console names it in its own `read` output, once per session per topic (remembered in `pointers.json` in the session folder, owned by `pointers.mjs`); the console refuses the slips it can see (a `stop` with no `finish`, a `finish` while `stopWarning` is set, with `stop --force` for a dead page) instead of the docs repeating each rule. Byte budgets for the card, every notes file and a sample session's outputs run in `npm test` (`scripts/test-console-wire-budgets.mjs`). The server never writes into a project; the one thing it deletes there is an old `specs--completed/` the person picks in Cleanup, and only when git tracks it (an untracked one is refused, with the reason on the page). One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`. Building or changing an Activities game: follow the game rules in [Activities](./.agents-docs/AGENTS-architecture-activities.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window). diff --git a/package.json b/package.json index a6b3f23..25ed305 100644 --- a/package.json +++ b/package.json @@ -13,7 +13,7 @@ "play": "node scripts/play.mjs", "pretest": "node scripts/fix-line-endings.mjs", "test:fast": "node scripts/test-fast.mjs", - "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-ui-prototype-page.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" + "test": "node scripts/check-test-lanes.mjs && node scripts/validate-char-count.js && node install.js --build-skills && node scripts/check-versions.mjs && node scripts/check-doc-size.mjs && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/check-prompt-wording.mjs && node scripts/check-console-openings.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-test-map.mjs scripts/test-script-test-match.mjs scripts/test-script-test-commands.mjs scripts/test-script-run-check.mjs scripts/test-script-pr-prep.mjs scripts/test-script-dead-code.mjs scripts/test-script-ui-prototype.mjs scripts/test-script-coverage.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-agents-doc.mjs scripts/test-web-console-prototypes.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-flock.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-lantern.mjs scripts/test-web-console-activities-ghoul-marrow.mjs scripts/test-web-console-activities-ghoul-mat.mjs scripts/test-web-console-activities-ghoul-eye.mjs scripts/test-web-console-activities-ghoul-bonestair.mjs scripts/test-web-console-activities-ghoul-heart.mjs scripts/test-web-console-activities-ghoul-ending.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-spec-carry.mjs scripts/test-spec-carry-page.mjs scripts/test-web-console-state.mjs scripts/test-web-console-send-state.mjs scripts/test-web-console-strengths.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-ui-prototype-page.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs scripts/test-check-test-lanes.mjs scripts/test-check-doc-size.mjs scripts/test-set-version.mjs scripts/test-console-stub.mjs scripts/test-check-prompt-wording.mjs scripts/test-check-console-openings.mjs" }, "devDependencies": { "gpt-tokenizer": "2.9.0", diff --git a/scripts/test-lanes.json b/scripts/test-lanes.json index 95f27b1..d2569c1 100644 --- a/scripts/test-lanes.json +++ b/scripts/test-lanes.json @@ -34,6 +34,7 @@ "test-us-english.mjs", "test-web-console-agents-doc.mjs", "test-web-console-git-board.mjs", + "test-web-console-prototypes.mjs", "test-web-console-send-state.mjs", "test-web-console-shape.mjs", "test-web-console-skills.mjs", diff --git a/scripts/test-web-console-prototypes.mjs b/scripts/test-web-console-prototypes.mjs new file mode 100644 index 0000000..90255a8 --- /dev/null +++ b/scripts/test-web-console-prototypes.mjs @@ -0,0 +1,111 @@ +// The Prototypes tab: which files the server lists, reads and opens from a +// spec's prototypes/ folder. +// Run with: node --test scripts/test-web-console-prototypes.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { listPrototypes, readPrototype, prototypeHtmlPath } from "../src/web-console/sessions.mjs"; + +const SPEC = "specs/picker"; + +function project(files) { + const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-prototypes-")); + const root = path.join(base, "project"); + fs.mkdirSync(root, { recursive: true }); + for (const [rel, text] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(root, rel)), { recursive: true }); + fs.writeFileSync(path.join(root, rel), text); + } + fs.writeFileSync(path.join(base, "secret.md"), "outside\n"); + fs.writeFileSync(path.join(base, "secret.html"), "

outside

\n"); + return { base, root }; +} + +const clean = (base) => fs.rmSync(base, { recursive: true, force: true }); + +test("listPrototypes lists the .md and .html files directly in prototypes/, by name", async () => { + const { base, root } = project({ + [`${SPEC}/prototypes/picker.md`]: "# Picker\n", + [`${SPEC}/prototypes/picker.html`]: "

picker

\n", + [`${SPEC}/prototypes/Another One.htm`]: "

two

\n", + [`${SPEC}/prototypes/notes.txt`]: "not shown\n", + [`${SPEC}/prototypes/shots/deep.md`]: "not shown\n", + [`${SPEC}/overview.md`]: "not shown\n", + }); + try { + assert.deepEqual(await listPrototypes(root, SPEC), [ + { name: "Another One.htm", kind: "html" }, + { name: "picker.html", kind: "html" }, + { name: "picker.md", kind: "md" }, + ]); + } finally { + clean(base); + } +}); + +test("listPrototypes is empty with no prototypes folder, and for a spec outside the root", async () => { + const { base, root } = project({ [`${SPEC}/overview.md`]: "# O\n" }); + try { + assert.deepEqual(await listPrototypes(root, SPEC), []); + assert.deepEqual(await listPrototypes(root, "../"), []); + assert.deepEqual(await listPrototypes(root, base), []); + assert.deepEqual(await listPrototypes(root, ""), []); + assert.deepEqual(await listPrototypes("", SPEC), []); + } finally { + clean(base); + } +}); + +test("readPrototype reads one .md in prototypes/ and refuses everything else", async () => { + const { base, root } = project({ + [`${SPEC}/prototypes/picker.md`]: "# Picker\n", + [`${SPEC}/prototypes/picker.html`]: "

picker

\n", + [`${SPEC}/overview.md`]: "# O\n", + }); + try { + assert.deepEqual(await readPrototype(root, SPEC, "picker.md"), { file: "picker.md", text: "# Picker\n" }); + const refused = ["picker.html", "../overview.md", "..\\overview.md", "../../../secret.md", "missing.md", path.join(base, "secret.md"), "", null]; + for (const name of refused) assert.equal(await readPrototype(root, SPEC, name), null, String(name)); + assert.equal(await readPrototype(root, "../", "secret.md"), null); + } finally { + clean(base); + } +}); + +test("prototypeHtmlPath names one .html in prototypes/ and refuses everything else", async () => { + const { base, root } = project({ + [`${SPEC}/prototypes/picker.md`]: "# Picker\n", + [`${SPEC}/prototypes/picker.html`]: "

picker

\n", + }); + try { + const found = await prototypeHtmlPath(root, SPEC, "picker.html"); + assert.equal(found, fs.realpathSync(path.join(root, SPEC, "prototypes", "picker.html"))); + const refused = ["picker.md", "../../../secret.html", "missing.html", path.join(base, "secret.html"), "picker.html.exe", "", undefined]; + for (const name of refused) assert.equal(await prototypeHtmlPath(root, SPEC, name), null, String(name)); + } finally { + clean(base); + } +}); + +test("prototype files do not follow a link out of the project", async (t) => { + const { base, root } = project({ [`${SPEC}/prototypes/picker.md`]: "# Picker\n" }); + try { + try { + fs.symlinkSync(path.join(base, "secret.md"), path.join(root, SPEC, "prototypes", "leak.md")); + fs.symlinkSync(path.join(base, "secret.html"), path.join(root, SPEC, "prototypes", "leak.html")); + } catch { + return t.skip("symlinks are not allowed here"); + } + assert.equal(await readPrototype(root, SPEC, "leak.md"), null); + assert.equal(await prototypeHtmlPath(root, SPEC, "leak.html"), null); + assert.deepEqual( + (await listPrototypes(root, SPEC)).map((f) => f.name), + ["picker.md"] + ); + } finally { + clean(base); + } +}); diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index 2f6bae8..cd86e14 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -765,6 +765,71 @@ test("GET /overview serves the session's spec, and on the dashboard only a scann } }); +// The Prototypes tab's routes: the list, one .md, and opening one .html in the +// default browser (PLAN2CODE_NO_BROWSER keeps the suite from starting one). +// The spec is chosen as /overview chooses it, and nothing outside the spec's +// prototypes/ folder is read or opened. +test("the Prototypes routes list, read and open only a scanned spec's prototypes", async () => { + const { base, root } = overviewProject(); + const protos = path.join(root, "specs", "p", "prototypes"); + fs.mkdirSync(protos, { recursive: true }); + fs.writeFileSync(path.join(protos, "pick.md"), "# Pick\n"); + fs.writeFileSync(path.join(protos, "pick.html"), "

pick

\n"); + const sids = []; + try { + const dash = cliIn(root, ["open", "--workflow", "dashboard", "--no-open"]); + sids.push(dash.json.sid); + const d = sessionUrl(dash.json.url); + const get = (q, cookie = d.cookie) => + fetch(`${d.base}${q}`, { headers: cookie ? { cookie, connection: "close" } : { connection: "close" } }); + const open = (body, origin = d.base) => + fetch(`${d.base}/open-prototype`, { + method: "POST", + headers: { "content-type": "application/json", cookie: d.cookie, origin, connection: "close" }, + body: JSON.stringify(body), + }); + + const list = await get("/prototypes?spec=specs/p"); + assert.equal(list.status, 200); + assert.deepEqual(await list.json(), { files: [{ name: "pick.html", kind: "html" }, { name: "pick.md", kind: "md" }] }); + assert.equal((await get("/prototypes?spec=specs/p", null)).status, 403); + assert.equal((await get("/prototypes?spec=specs/a")).status, 204, "no prototypes folder: no tab"); + assert.equal((await get("/prototypes?spec=specs/not-scanned")).status, 204); + + const doc = await get("/prototype?spec=specs/p&name=pick.md"); + assert.equal(doc.status, 200); + assert.equal(await doc.text(), "# Pick\n"); + for (const name of ["pick.html", "../../a/overview.md", "missing.md"]) { + assert.equal((await get("/prototype?spec=specs/p&name=" + encodeURIComponent(name))).status, 204, name); + } + + const ok = await open({ spec: "specs/p", name: "pick.html" }); + assert.equal(ok.status, 200); + assert.deepEqual(await ok.json(), { ok: true }); + for (const body of [ + { spec: "specs/p", name: "pick.md" }, + { spec: "specs/p", name: "../pick.html" }, + { spec: "specs/p", name: path.join(protos, "pick.html") }, + { spec: "specs/not-scanned", name: "pick.html" }, + { spec: "specs/p" }, + ]) { + assert.equal((await open(body)).status, 404, JSON.stringify(body)); + } + assert.notEqual((await open({ spec: "specs/p", name: "pick.html" }, "https://evil.example")).status, 200, "another site's page cannot open files"); + + // Away from the dashboard, the session's own spec is used and ?spec= is ignored. + const plan = cliIn(root, ["open", "--workflow", "plan", "--spec", "specs/p", "--no-open"]); + sids.push(plan.json.sid); + const p = sessionUrl(plan.json.url); + const own = await fetch(`${p.base}/prototypes?spec=specs/a`, { headers: { cookie: p.cookie, connection: "close" } }); + assert.equal(own.status, 200); + assert.equal((await own.json()).files.length, 2); + } finally { + for (const s of sids) cliIn(root, ["stop", "--session", s, "--force"]); + fs.rmSync(base, { recursive: true, force: true }); + } +}); + test("open records worktree and branch, and wakes only a freshly opened dashboard", () => { const dash = cli(["open", "--workflow", "dashboard", "--no-open"]); try { diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index 7db5c49..9f05b17 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -188,11 +188,11 @@ test("shape: no page module sets a style attribute from script", () => { // and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has // no routes of its own: its buttons are sends (`__git`), through /submit. const ROUTE_ORDER = [ - "/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/agents-doc", "/handoff", "/version", "/state", "/events", "/draft", + "/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/agents-doc", "/prototypes", "/prototype", "/handoff", "/version", "/state", "/events", "/draft", "/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/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/tab/sent", "/notepad/images/", - "/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace", + "/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/open-prototype", "/chat", "/chat/decision", "/workspace", "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/spec-carry", "/cancel", "/ping", "/bye", ]; diff --git a/src/web-console/open-link.mjs b/src/web-console/open-link.mjs index db17117..f788e7f 100644 --- a/src/web-console/open-link.mjs +++ b/src/web-console/open-link.mjs @@ -22,14 +22,29 @@ export function linkToOpen(raw) { /** Opens `href` (from linkToOpen) in the default browser; false when it could not start one. */ export function openLink(href) { + return launch(href, process.env.BROWSER); +} + +/** + * Opens a local file the server already checked (an absolute path, such as a + * saved prototype's .html) with the system's default handler for its type, + * which for a web page is the default browser; false when nothing started. + */ +export function openFile(file) { + if (typeof file !== "string" || !file) return false; + return launch(file, null); +} + +// The system's own opener, handed one target as one argument, never a shell. +function launch(target, linuxOpener) { // Tests, and a person who turned the console's own browser launches off. if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return true; const [cmd, args] = process.platform === "win32" - ? ["rundll32.exe", ["url.dll,FileProtocolHandler", href]] + ? ["rundll32.exe", ["url.dll,FileProtocolHandler", target]] : process.platform === "darwin" - ? ["open", [href]] - : [process.env.BROWSER || "xdg-open", [href]]; + ? ["open", [target]] + : [linuxOpener || "xdg-open", [target]]; try { const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true }); child.on("error", () => {}); diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 5072345..ece4c1e 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -56,6 +56,7 @@ import { activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow, AGENTS_VIEW, agentsTabShown, finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadAgentsDoc, loadOverview, loadSpecCarry, myTurn, openItems, finishKey, overviewSpec, patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded, + PROTOTYPES_VIEW, prototypesTabShown, loadPrototypes, topics, workingMs, WORKING_GRACE_MS, workspaceFolders, } from "../selectors.js"; @@ -68,7 +69,7 @@ import { closeMentions } from "../mention-box.js"; import { destroyFields } from "../md-field.js"; import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js"; import { sendState, suggestState } from "../send-state.js"; -import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview } from "./docs.js"; +import { renderAgentsDoc, renderBriefButton, renderDoc, renderOverview, renderPrototypes } from "./docs.js"; import { board, renderGitBoard, resetBoard } from "./git-host.js"; import { renderWorkspace, tellFolderIssues } from "./workspace.js"; import { openHelpOn } from "./help-dialog.js"; @@ -550,6 +551,7 @@ export function adopt(body) { // 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 || isSpecFileView(page.view)) loadOverview(); + else if (page.view === PROTOTYPES_VIEW) loadPrototypes(); // A New Session in the app leaves the spec it was in; the fresh dashboard picks it up once its scan is here. loadSpecCarry(); // The Dashboard's AGENTS.md tab: found on arrival, re-read while it is open. @@ -1030,7 +1032,7 @@ function withFocus(fn) { // (the dashboard menu, the end page). function currentScroller() { if (!drawnView) return null; - if (drawnView.startsWith("doc:") || isSpecFileView(drawnView) || drawnView === AGENTS_VIEW) return $("main"); + if (drawnView.startsWith("doc:") || isSpecFileView(drawnView) || drawnView === AGENTS_VIEW || drawnView === PROTOTYPES_VIEW) return $("main"); if (drawnView === "questions") return $("main").querySelector(":scope > .card.question"); if (drawnView === "ask") return $("main").querySelector(".ask-list"); return null; @@ -1481,6 +1483,10 @@ function renderViews() { 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"; + // After the spec file tabs: the spec's saved prototypes, present while its + // prototypes/ folder holds an .md or .html. Gone, it sends the person home. + if (prototypesTabShown()) tabs.push({ id: PROTOTYPES_VIEW, label: "Prototypes", count: 0 }); + else if (page.view === PROTOTYPES_VIEW) page.view = "questions"; // Right after Dashboard: the project's AGENTS.md, present while the file is. // Like a spec file tab, it sends the person home if the file goes away. if (agentsTabShown()) tabs.splice(1, 0, { id: AGENTS_VIEW, label: "AGENTS.md", count: 0 }); @@ -1533,10 +1539,14 @@ function renderViews() { save(); } page.view = t.id === "questions" && finish() ? "end" : t.id; + // The tab always opens on the list, so the .md last read there must not + // paint first. + if (t.id === PROTOTYPES_VIEW) page.prototypes = { ...page.prototypes, open: null, texts: {} }; // The cached text paints at once; the fresh read repaints if the file // changed on disk since. render(); if (isSpecFileView(t.id)) loadOverview(); + if (t.id === PROTOTYPES_VIEW) loadPrototypes(); if (t.id === AGENTS_VIEW) { page.agentsDoc.open = "AGENTS.md"; loadAgentsDoc(); @@ -1696,7 +1706,10 @@ function renderMain() { } function paintMain(main) { - main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view) || page.view === AGENTS_VIEW); + main.classList.toggle( + "is-doc", + page.view.startsWith("doc:") || isSpecFileView(page.view) || page.view === AGENTS_VIEW || page.view === PROTOTYPES_VIEW + ); main.classList.toggle("is-ask", page.view === "ask"); // An agent-less session has no questions, docs or board to draw: its whole @@ -1706,6 +1719,7 @@ function paintMain(main) { if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4)); if (isSpecFileView(page.view)) return renderOverview(main, page.view); if (page.view === AGENTS_VIEW) return renderAgentsDoc(main); + if (page.view === PROTOTYPES_VIEW) return renderPrototypes(main); if (page.view === "ask") { const held = heldAsk; heldAsk = null; diff --git a/src/web-console/public/screens/docs.js b/src/web-console/public/screens/docs.js index 1167970..8b0e6de 100644 --- a/src/web-console/public/screens/docs.js +++ b/src/web-console/public/screens/docs.js @@ -1,6 +1,8 @@ // Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only. -import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES, loadAgentsDoc } from "../selectors.js"; +import { + docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES, loadAgentsDoc, openPrototypeDoc, closePrototypeDoc, +} 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"; @@ -297,6 +299,70 @@ export function renderAgentsDoc(main) { main.appendChild(box); } +// A saved prototype page, handed to the server to open in the person's +// default browser (the app's webview opens no windows, and a page served over +// http cannot open a file:// link). A failure says so on the banner. +async function openPrototypePage(spec, name) { + const ok = await fetch("/open-prototype", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ spec, name }), + }) + .then((res) => res.ok) + .catch(() => false); + if (!ok) hooks.banner(`${name} could not open in your browser. Open it from ${spec}/prototypes/ yourself.`, "warn"); +} + +// The Prototypes tab: the .md and .html files in the spec's prototypes/ +// folder. An .md opens in place, with a way back to the list (like Back to +// AGENTS.md); an .html opens in the default browser. +export function renderPrototypes(main) { + const { key, files, open, texts } = page.prototypes; + const reading = open && typeof texts[open] === "string"; + const head = el("div", "doc-head"); + head.appendChild(el("h2", null, reading ? open : "Prototypes")); + const tools = el("div", "doc-tools"); + if (reading) { + const list = el("button", "btn small", "Back to Prototypes"); + list.type = "button"; + list.addEventListener("click", () => { + closePrototypeDoc(); + main.scrollTop = 0; + }); + tools.appendChild(list); + } + tools.appendChild(backButton()); + if (reading) tools.appendChild(printButton()); + head.appendChild(tools); + main.appendChild(head); + main.appendChild(el("p", "help", `${key}/prototypes/${reading ? open : ""} · read-only, straight from disk`)); + if (reading) { + const box = el("div", "block settled"); + box.appendChild(md(texts[open], "md")); + main.appendChild(box); + return; + } + const list = el("ul", "proto-list"); + for (const f of files) { + const row = el("li", "proto-row"); + const b = el("button", "proto-open", null); + b.type = "button"; + b.appendChild(el("span", "proto-kind proto-kind-" + f.kind, f.kind === "md" ? "MD" : "HTML")); + b.appendChild(el("span", "proto-name", f.name)); + b.appendChild(el("span", "proto-how", f.kind === "md" ? "Read it here" : "Opens in your browser ↗")); + b.title = f.kind === "md" ? `Read ${f.name} here` : `Open ${f.name} in your default browser`; + b.addEventListener("click", () => { + if (f.kind === "md") { + openPrototypeDoc(f.name); + main.scrollTop = 0; + } else openPrototypePage(key, f.name); + }); + row.appendChild(b); + list.appendChild(row); + } + main.appendChild(list); +} + // The brief dialog's buttons, wired once at start-up. export function wireDocs() { $("btn-brief").addEventListener("click", openBrief); diff --git a/src/web-console/public/selectors.js b/src/web-console/public/selectors.js index bb40abe..481e7bf 100644 --- a/src/web-console/public/selectors.js +++ b/src/web-console/public/selectors.js @@ -322,6 +322,8 @@ async function fetchSpecFile(spec, kind) { // is the work already in front of it. Repaints only when a tab would appear, // vanish or show different text. export async function loadOverview() { + // The Prototypes tab rides on every reason the spec file tabs re-read. + loadPrototypes(); const spec = overviewSpec(); const kinds = isDashboard() ? SPEC_FILES.map((f) => f.id) : ["overview"]; const files = {}; @@ -338,6 +340,60 @@ export async function loadOverview() { if (changed) redraw(); } +// The Prototypes tab: present while the spec in view has .md or .html files +// in its prototypes/ folder, on the dashboard and in a session alike. +export const PROTOTYPES_VIEW = "prototypes"; +export const prototypesTabShown = () => page.prototypes.key === overviewSpec() && page.prototypes.files.length > 0; + +async function fetchPrototypeList(spec) { + try { + const res = await fetch("/prototypes?spec=" + encodeURIComponent(spec), { cache: "no-store" }); + if (res.status !== 200) return []; + const body = await res.json(); + return Array.isArray(body.files) ? body.files : []; + } catch { + return []; + } +} + +async function fetchPrototypeDoc(spec, name) { + try { + const res = await fetch("/prototype?spec=" + encodeURIComponent(spec) + "&name=" + encodeURIComponent(name), { cache: "no-store" }); + return res.status === 200 ? await res.text() : null; + } catch { + return null; + } +} + +// Fresh from disk every time, like the spec file tabs: the list, and the .md +// in view when one is open. A spec switch goes back to the list; an open .md +// that went missing goes back to the list too. Repaints only on a change. +export async function loadPrototypes() { + const spec = overviewSpec(); + const open = page.prototypes.key === spec ? page.prototypes.open : null; + const files = spec ? await fetchPrototypeList(spec) : []; + const text = spec && open && files.some((f) => f.name === open) ? await fetchPrototypeDoc(spec, open) : null; + // The selection or the open file moved on while this was in flight. + if (spec !== overviewSpec() || (page.prototypes.key === spec && page.prototypes.open !== open)) return; + const next = { key: spec, files, open: typeof text === "string" ? open : null, texts: typeof text === "string" ? { [open]: text } : {} }; + const changed = JSON.stringify(next) !== JSON.stringify(page.prototypes); + page.prototypes = next; + if (changed) redraw(); +} + +// Open one .md from the list in place. +export function openPrototypeDoc(name) { + page.prototypes = { ...page.prototypes, open: name }; + redraw(); + loadPrototypes(); +} + +// Back from an .md to the list. +export function closePrototypeDoc() { + page.prototypes = { ...page.prototypes, open: null, texts: {} }; + redraw(); +} + // A New Session in the desktop app leaves the spec it was in for the fresh // dashboard (spec-carry.mjs). Asked once per page, before the picker is // touched; used only if the picker lists that spec, else the default stands. diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index 5435ec1..104d7ee 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -138,6 +138,11 @@ export const page = { // for, `files` maps each SPEC_FILES kind (overview, map, draft) that exists // to `{ file, text }`. See loadOverview(). overview: { key: null, files: {} }, + // The Prototypes tab: `key` is the spec dir `files` ([{ name, kind }], the + // .md and .html in its prototypes/ folder) was read for, `open` the .md in + // view (null for the list), `texts` the .md texts read so far. The tab + // exists while `files` has any. See loadPrototypes(). + prototypes: { key: null, files: [], open: null, texts: {} }, // The Dashboard's AGENTS.md tab: `texts` maps each agent-guide file read so // far (AGENTS.md, .agents-docs/.md) to its text, `open` is the one in // view. The tab exists while texts["AGENTS.md"] does. See loadAgentsDoc(). diff --git a/src/web-console/public/styles/docs.css b/src/web-console/public/styles/docs.css index f7cf4e8..ef2ba17 100644 --- a/src/web-console/public/styles/docs.css +++ b/src/web-console/public/styles/docs.css @@ -40,3 +40,22 @@ .doc-saved code { font-family: var(--mono); font-size: 11.5px; color: var(--ink-2); } .doc-head { align-items: center; } + +/* ------------------------------------------------------ prototypes tab */ + +/* The spec's saved prototypes: one row per .md (read here) or .html (opens + in the browser), as wide as a doc. */ +.proto-list { list-style: none; margin: 0 auto; padding: 0; max-width: min(var(--card-width), 100%); display: grid; gap: 8px; } +.proto-open { + width: 100%; display: flex; align-items: center; gap: 12px; text-align: left; + padding: 12px 14px; border: 1px solid var(--rule); border-radius: 10px; + background: var(--panel); color: var(--ink); font: inherit; cursor: pointer; +} +.proto-open:hover, .proto-open:focus-visible { border-color: var(--accent); background: var(--accent-soft); } +.proto-kind { + flex: none; min-width: 44px; text-align: center; padding: 3px 6px; border-radius: 6px; + font: 700 10.5px/1.2 var(--mono); letter-spacing: 0.05em; border: 1px solid var(--rule-2); color: var(--ink-2); +} +.proto-kind-html { border-color: var(--accent); color: var(--accent); } +.proto-name { flex: 1; min-width: 0; font-weight: 600; overflow-wrap: anywhere; } +.proto-how { flex: none; font-size: 12px; color: var(--ink-3); } diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index 2f7692d..08a2e2f 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -30,7 +30,7 @@ import { } from "./files.mjs"; import { AGENTS_SCHEMA, makeId, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs"; import { findAgent, loadAgentList } from "./agent-lookup.mjs"; -import { checkDocument, cleanupFindings, readAgentsDoc, readSpecFile, removeCleanup } from "./sessions.mjs"; +import { checkDocument, cleanupFindings, listPrototypes, prototypeHtmlPath, readAgentsDoc, readPrototype, readSpecFile, removeCleanup } from "./sessions.mjs"; import { SHOTS_DIR_NAME, SHOT_NAME, shotType, isOpen } from "./patches.mjs"; import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs"; import { specKey } from "./workspace.mjs"; @@ -52,7 +52,7 @@ import { cleanSetting, offered } from "./public/subagents.js"; import { DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, accentId, cardWidth } from "./public/palette.js"; import { SERVABLE, TYPES, asset } from "./static.mjs"; import { handoffsDir, isHandoffId } from "./handoffs.mjs"; -import { linkToOpen, openLink } from "./open-link.mjs"; +import { linkToOpen, openFile, openLink } from "./open-link.mjs"; import { NotepadError, addImage, @@ -87,6 +87,8 @@ const ROUTES = [ { match: (p, req) => req.method === "GET" && SERVABLE.has(p.slice(1)), run: publicFile }, { path: "/overview", method: "GET", run: overview }, { path: "/agents-doc", method: "GET", run: agentsDoc }, + { path: "/prototypes", method: "GET", run: prototypesList }, + { path: "/prototype", method: "GET", run: prototypeDoc }, { path: "/handoff", method: "GET", run: handoffDoc }, { path: "/version", method: "GET", run: version }, { path: "/state", method: "GET", run: stateGet }, @@ -121,6 +123,7 @@ const ROUTES = [ { match: (p, req) => p.startsWith("/uploads/") || req.url.startsWith("/uploads/"), run: uploads }, { path: "/submit", method: "POST", origin: true, run: submit }, { path: "/open-link", method: "POST", origin: true, run: openLinkRoute }, + { path: "/open-prototype", method: "POST", origin: true, run: openPrototypeRoute }, { path: "/chat", method: "POST", origin: true, run: chat }, { path: "/chat/decision", method: "POST", origin: true, run: chatDecision }, { path: "/workspace", method: "GET", run: workspaceGet }, @@ -395,20 +398,11 @@ function renderIndex(ctx) { // 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) - ? asked - : "" - : state.specDir; + const spec = specInView(state, url.searchParams.get("spec")); // Most specs have no overview.md yet, which is normal, not an error: 204 // keeps the browser console free of a failed request per pick. - const noOverview = () => { - res.writeHead(204, baseHeaders({ "cache-control": "no-store" })); - res.end(); - }; + const noOverview = () => noContent(res); readSpecFile(state.worktree || state.project, spec, kind) .then((found) => found @@ -422,16 +416,64 @@ function overview(req, res, ctx, url) { .catch(noOverview); } +// The spec a spec-file route may read: on a dashboard the one asked for, but +// only when its own scan found it; on every other workflow the session's own. +function specInView(state, asked) { + if (state.workflow !== "dashboard") return state.specDir || ""; + return (state.scan?.specs || []).some((s) => s && s.dir === asked) ? asked : ""; +} + +// No file to show: a 204, so the browser console stays free of a failed +// request per spec that has none. +function noContent(res) { + res.writeHead(204, baseHeaders({ "cache-control": "no-store" })); + res.end(); +} + +// The Prototypes tab's list: the .md and .html files in the spec's +// prototypes/ folder (listPrototypes() keeps it inside the project), as +// { files: [{ name, kind }] }, or a 204 when there are none. +function prototypesList(req, res, ctx, url) { + const state = ctx.readState() || {}; + listPrototypes(state.worktree || state.project, specInView(state, url.searchParams.get("spec"))) + .then((files) => (files.length ? json(res, 200, { files }, { "cache-control": "no-store" }) : noContent(res))) + .catch(() => noContent(res)); +} + +// One .md from the spec's prototypes/ folder, read-only; anything else is a 204. +function prototypeDoc(req, res, ctx, url) { + const state = ctx.readState() || {}; + readPrototype(state.worktree || state.project, specInView(state, url.searchParams.get("spec")), url.searchParams.get("name")) + .then((found) => (found ? send(res, 200, found.text, "text/markdown; charset=utf-8", { "cache-control": "no-store" }) : noContent(res))) + .catch(() => noContent(res)); +} + +// A saved prototype page, opened in the person's default browser (the app's +// webview opens no windows, and a file:// link from an http page is blocked). +// The page names only the spec and a bare file name; prototypeHtmlPath() +// turns that into a path inside the spec's prototypes/ folder or refuses it, +// so nothing else on disk can be opened this way. +function openPrototypeRoute(req, res, ctx) { + return readBody(req, res, (err, body) => { + if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" }); + const state = ctx.readState() || {}; + prototypeHtmlPath(state.worktree || state.project, specInView(state, body && body.spec), body && body.name) + .then((file) => { + if (!file) return json(res, 404, { error: "no such prototype page" }); + if (!openFile(file)) return json(res, 500, { error: "no browser could be started" }); + return json(res, 200, { ok: true }); + }) + .catch(() => json(res, 500, { error: "no browser could be started" })); + }); +} + // The project's AGENTS.md (or one file under .agents-docs/), read-only, for the // dashboard's AGENTS.md tab. Only a dashboard serves it, and only the two // shapes readAgentsDoc() allows; anything else, or a missing file, is a 204 // (no tab) so the browser console stays free of a failed request. function agentsDoc(req, res, ctx, url) { const state = ctx.readState() || {}; - const none = () => { - res.writeHead(204, baseHeaders({ "cache-control": "no-store" })); - res.end(); - }; + const none = () => noContent(res); if (state.workflow !== "dashboard") return none(); readAgentsDoc(state.worktree || state.project, url.searchParams.get("file") || "AGENTS.md") .then((found) => diff --git a/src/web-console/sessions.mjs b/src/web-console/sessions.mjs index 9f7ef30..fa9c93d 100644 --- a/src/web-console/sessions.mjs +++ b/src/web-console/sessions.mjs @@ -600,6 +600,86 @@ export async function readSpecFile(root, specDir, kind) { } } +// The Prototypes tab: the .md and .html files saved directly in a spec's +// prototypes/ folder (a UI prototype's page and its brief). A name never +// carries a separator, and every file's realpath must sit inside the folder's, +// which must sit inside the root's, so `../`, an absolute path and a link +// pointing anywhere else all come back null. +const PROTOTYPE_NAME_RE = /^[^\\/:*?"<>|]+\.(md|html?)$/i; +const insideOf = (outer, inner) => { + const rel = path.relative(outer, inner); + return Boolean(rel) && rel !== ".." && !rel.startsWith(".." + path.sep) && !path.isAbsolute(rel); +}; +const prototypeKind = (name) => (/\.md$/i.test(name) ? "md" : "html"); + +// The real path of the spec's prototypes/ folder, or null. +async function prototypesDir(root, specDir) { + if (!root || !specDir || typeof specDir !== "string" || path.isAbsolute(specDir)) return null; + try { + const [realDir, realRoot] = await Promise.all([ + fs.promises.realpath(path.resolve(root, specDir, "prototypes")), + fs.promises.realpath(root), + ]); + return insideOf(realRoot, realDir) ? realDir : null; + } catch { + return null; + } +} + +// The real path of one prototype file of `kind` (md or html), or null. +async function prototypeFile(root, specDir, name, kind) { + const dir = await prototypesDir(root, specDir); + return dir ? fileIn(dir, name, kind) : null; +} + +// The real path of `name` (a bare .md or .html name of `kind`) directly in the +// already-resolved prototypes folder `dir`, as a regular file, or null. +async function fileIn(dir, name, kind) { + if (typeof name !== "string" || !PROTOTYPE_NAME_RE.test(name) || prototypeKind(name) !== kind) return null; + try { + const real = await fs.promises.realpath(path.join(dir, name)); + if (path.dirname(real) !== dir || !(await fs.promises.stat(real)).isFile()) return null; + return real; + } catch { + return null; + } +} + +/** The prototype files of a spec as [{ name, kind }] ("md" or "html"), by name; [] when there are none. */ +export async function listPrototypes(root, specDir) { + const dir = await prototypesDir(root, specDir); + if (!dir) return []; + let names; + try { + names = await fs.promises.readdir(dir); + } catch { + return []; + } + const found = await Promise.all( + names.filter((n) => PROTOTYPE_NAME_RE.test(n)).map(async (n) => ((await fileIn(dir, n, prototypeKind(n))) ? n : null)) + ); + return found + .filter(Boolean) + .sort((a, b) => a.localeCompare(b, "en", { sensitivity: "base" })) + .map((name) => ({ name, kind: prototypeKind(name) })); +} + +/** `{ file, text }` for one .md in the spec's prototypes/ folder, or null. */ +export async function readPrototype(root, specDir, name) { + const real = await prototypeFile(root, specDir, name, "md"); + if (!real) return null; + try { + return { file: name, text: await fs.promises.readFile(real, "utf8") }; + } catch { + return null; + } +} + +/** The real path of one .html (or .htm) in the spec's prototypes/ folder, or null. */ +export async function prototypeHtmlPath(root, specDir, name) { + return prototypeFile(root, specDir, name, "html"); +} + // The project's agent guide as the Dashboard's AGENTS.md tab shows it: only // AGENTS.md itself or one markdown file directly under .agents-docs/, never any // other path. Kept inside the root by realpath, like readSpecFile().