From 8e34bf10051c88a584d24e9dd5a04a1ccd99f0bb Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Mon, 2 Nov 2026 12:00:12 -0800 Subject: [PATCH] Update the web console server, screens, help, prefs and loop setup, with matching page and logic suites AI Assisted --- .agents-docs/AGENTS-web-console-contract.md | 74 ++ .readme/web-console.md | 845 +++++++++++++++- scripts/capture-screenshots.mjs | 5 +- scripts/page-test-helpers.mjs | 12 +- scripts/screenshots/README.md | 2 +- scripts/test-web-console-chat-stress.mjs | 39 +- scripts/test-web-console-chat.mjs | 185 ++-- scripts/test-web-console-concurrency.mjs | 35 +- scripts/test-web-console-git-board.mjs | 2 +- scripts/test-web-console-git.mjs | 34 +- scripts/test-web-console-handoffs.mjs | 10 +- scripts/test-web-console-hardening.mjs | 8 +- scripts/test-web-console-in-app.mjs | 41 +- scripts/test-web-console-lifecycle.mjs | 145 ++- scripts/test-web-console-logic.mjs | 231 ++++- scripts/test-web-console-loop.mjs | 625 ++++++++++++ scripts/test-web-console-notepad.mjs | 4 +- scripts/test-web-console-page-ask.mjs | 10 +- scripts/test-web-console-page-cards.mjs | 21 + scripts/test-web-console-page-dashboard.mjs | 2 + scripts/test-web-console-page-help.mjs | 2 +- scripts/test-web-console-page-loop.mjs | 329 ++++++ scripts/test-web-console-page-notepad.mjs | 3 +- scripts/test-web-console-page-prefs.mjs | 582 +++++++++-- scripts/test-web-console-page-session.mjs | 38 +- scripts/test-web-console-pointers.mjs | 286 ++++++ scripts/test-web-console-qa.mjs | 16 +- scripts/test-web-console-server.mjs | 79 +- scripts/test-web-console-session.mjs | 234 ++++- scripts/test-web-console-shape.mjs | 2 +- scripts/test-web-console-skills.mjs | 22 +- scripts/test-web-console-source.mjs | 78 +- scripts/test-web-console-speed.mjs | 66 +- scripts/test-web-console-state.mjs | 6 + scripts/test-web-console-subagents.mjs | 136 +-- scripts/test-web-console-tones.mjs | 344 +++++++ scripts/test-web-console-workspace.mjs | 58 +- scripts/web-console-test-helpers.mjs | 22 + src/web-console/building-review.md | 160 +-- src/web-console/building.md | 149 +-- src/web-console/cmd-chat.mjs | 15 +- src/web-console/cmd-help.mjs | 61 +- src/web-console/cmd-open.mjs | 89 +- src/web-console/cmd-post-wait.mjs | 294 ++++-- src/web-console/cmd-small.mjs | 20 +- src/web-console/console-attachments.md | 16 +- src/web-console/console-chat.md | 189 +--- src/web-console/console-docs.md | 27 + src/web-console/console-finish.md | 155 +-- src/web-console/console-launches.md | 108 +- src/web-console/console-meter.md | 60 +- src/web-console/console-stop.md | 141 +-- src/web-console/console-subagents.md | 110 +- src/web-console/console-trouble.md | 31 +- src/web-console/console-workspace.md | 79 +- src/web-console/console.md | 455 ++------- src/web-console/inbox.mjs | 40 +- src/web-console/loop-setup.mjs | 124 +++ src/web-console/notes/changelog.md | 33 +- src/web-console/notes/diagnose.md | 71 +- src/web-console/notes/document.md | 13 +- src/web-console/notes/finalize.md | 40 +- src/web-console/notes/git.md | 130 +-- src/web-console/notes/handoff.md | 12 +- src/web-console/notes/implement.md | 174 +--- src/web-console/notes/init.md | 15 +- src/web-console/notes/loop.md | 168 ++++ src/web-console/notes/pathfinder.md | 79 +- src/web-console/notes/plan.md | 26 +- src/web-console/notes/quick-task.md | 110 +- src/web-console/notes/review.md | 35 +- src/web-console/notes/revise-plan.md | 30 +- src/web-console/notes/xray.md | 60 +- src/web-console/patches.mjs | 617 +++++++++--- src/web-console/pointers.mjs | 101 ++ src/web-console/public/answers.js | 19 +- src/web-console/public/app-bridge.js | 34 + src/web-console/public/app.js | 10 +- src/web-console/public/chat.js | 26 +- src/web-console/public/help.js | 21 +- src/web-console/public/index.html | 938 ++++++++++++++---- src/web-console/public/looks.js | 83 +- src/web-console/public/meter.js | 10 +- src/web-console/public/palette.js | 1 + src/web-console/public/prefs.js | 31 + src/web-console/public/render.js | 8 +- src/web-console/public/screens/agents-view.js | 713 +++++++++++++ src/web-console/public/screens/ask.js | 16 +- src/web-console/public/screens/cards.js | 57 +- src/web-console/public/screens/cleanup.js | 4 +- src/web-console/public/screens/core.js | 75 +- src/web-console/public/screens/dashboard.js | 68 +- src/web-console/public/screens/ending.js | 118 ++- src/web-console/public/screens/help-dialog.js | 67 +- src/web-console/public/screens/looks.js | 515 +--------- src/web-console/public/screens/loop-setup.js | 550 ++++++++++ .../public/screens/prefs-dialog.js | 206 ++++ src/web-console/public/screens/starting.js | 21 +- src/web-console/public/screens/workspace.js | 12 +- src/web-console/public/selectors.js | 37 +- src/web-console/public/send-state.js | 7 + src/web-console/public/skills.js | 41 +- src/web-console/public/state.js | 15 + src/web-console/public/styles/dashboard.css | 85 +- src/web-console/public/styles/looks.css | 6 +- src/web-console/public/styles/notepad.css | 6 +- src/web-console/public/styles/pieces.css | 4 +- src/web-console/public/styles/prefs.css | 188 ++++ src/web-console/public/styles/responsive.css | 10 - src/web-console/public/styles/shell.css | 6 +- src/web-console/public/styles/tokens.css | 1 + src/web-console/public/subagents.js | 18 +- src/web-console/public/tabs.js | 103 ++ src/web-console/public/tones.js | 618 +++++++++++- src/web-console/routes.mjs | 63 +- src/web-console/server.mjs | 41 +- src/web-console/sessions.mjs | 5 +- src/web-console/spec-files.mjs | 34 + src/web-console/static.mjs | 124 ++- 119 files changed, 9957 insertions(+), 3728 deletions(-) create mode 100644 .agents-docs/AGENTS-web-console-contract.md create mode 100644 scripts/test-web-console-loop.mjs create mode 100644 scripts/test-web-console-page-loop.mjs create mode 100644 scripts/test-web-console-pointers.mjs create mode 100644 scripts/test-web-console-tones.mjs create mode 100644 src/web-console/console-docs.md create mode 100644 src/web-console/loop-setup.mjs create mode 100644 src/web-console/notes/loop.md create mode 100644 src/web-console/pointers.mjs create mode 100644 src/web-console/public/prefs.js create mode 100644 src/web-console/public/screens/agents-view.js create mode 100644 src/web-console/public/screens/loop-setup.js create mode 100644 src/web-console/public/screens/prefs-dialog.js create mode 100644 src/web-console/public/styles/prefs.css create mode 100644 src/web-console/public/tabs.js diff --git a/.agents-docs/AGENTS-web-console-contract.md b/.agents-docs/AGENTS-web-console-contract.md new file mode 100644 index 0000000..ed8ff71 --- /dev/null +++ b/.agents-docs/AGENTS-web-console-contract.md @@ -0,0 +1,74 @@ +# Web Console Contract: the Why + +Maintainer notes for the agent-facing console docs in `src/web-console/`. Installed skills never ship or load this file (nothing under `.agents-docs/` is in `install.js` `additionalReferences`), and the shipped files carry only what an agent must do. Put an explanation here, not there. If a shipped file starts to explain, move the sentence into this file and keep the instruction. + +The shape: a short card (`console.md`) read once per session, topic files the console names in its own `read` output at the moment each is due, and refusals for the silent slips the console can see. Size budgets in `npm test` stop the docs growing back (Phase 7 of `specs/console-wire-format`). + +## Why pointers and refusals instead of repeated rules + +A rule stated in six files is read six times and still skipped. The console sees most slips (a `stop` with no `finish`, a `finish` with `stopWarning` set, a reply left unanswered), so it refuses them and says the fix, and it names a topic file once per session per topic when that topic's moment arrives. The card states each silent rule once. A rule that was broken twice in repeated prose becomes a check in the console, not another sentence. + +## console.md (the card) + +- **Print then stamp.** `wait` prints a result and only then marks it collected (`advanceCursor`). A kill between the two repeats a delivery and never loses one. That is why "handle it once" is in `console-trouble.md`, and why `thread` (which appends) needs care on a repeat. +- **Bounded slices.** A wait runs for a limited number of seconds sized under the agent's shell timeout, so the command returns by itself. A killed wait loses nothing. People step away for hours, so there is no cap on the number of slices. +- **Every turn ends on a `wait`.** The page tells the person "the next question will appear here on its own". A turn that ends on text leaves that promise unkept and strands their next click. The console cannot see this slip, which is why the card states it. +- **Three open questions at most.** More than three open cards turns the page into a form to fill in, not a conversation, and people answer the first three and skip the rest. The server enforces the cap. +- **`settle`.** The server records a send on an item but only the agent decides it is final (a pick that still owes its recap is not). `settle` marks cards answered in the same post that moves on; a card left open stays on the page as a question still owed. +- **Defaults are filled by the console** (`status`, `required`, `allowOther`, empty `options` and `thread`, option keys by position, doc `version` and `stale`): an obvious default costs tokens every patch and carries no decision. A default the console fills is the only thing the card may leave out. +- **Recommend sparingly.** "Which format survives Excel?" is the agent's to recommend; "Who is this for?" is not, because a recommendation there is an anchor people rubber-stamp. +- **A placeholder is an offer.** The Autofill button drops it into the box as a real answer, so it must be a whole answer in the person's voice and satisfy any `pattern`. +- **Titles in plain words.** Internal vocabulary (grill, frontier, fog) means nothing to a newcomer and the server refuses it. The metric words rule exists because the metrics collector scrapes `Requirements`, `Feasibility`, `Integration` and `Risk` followed by a number. +- **Loop markers refused.** `TASK_COMPLETE`, `PHASE_COMPLETE` and the rest are read by the loop CLI as completion; one in page text would end a run. +- **The page owns its stream.** The agent never writes timestamps, versions or `agent.status` for a turn: the server stamps them, and collecting a send already sets the page to working. A second source of truth for them would drift. +- **Quoted heredoc.** Unquoted `<`) are refused because a rendered command is copied and run verbatim. +- **Continue here and Commit it now** are buttons the page derives from `command` and `commit`, so the agent writes nothing extra for them. + +## console-chat.md + +- **Every message gets a reply.** The Ask tab shows "working on the answer" until one lands. The console warns on `post` and `wait` about unanswered Quick questions for that reason. +- **Chat never steers the workflow.** A chat answer that approved a gate would make the record under `specs/` depend on a side channel. +- **Edits need approval first** and happen only at check-ins, so a change cannot land mid-task. +- **Prompts to carry away** start with prose because the page treats a fenced block whose first line looks like a shell command as a command, not a prompt. +- **Replies merge by `id`,** so a repeated delivery is answered by re-posting the same reply, not by answering twice. + +## console-workspace.md + +Added folders are read-only reference because the person added them as context, not as a place to work. The first read of a folder's `AGENTS.md` is once per folder per skill run so layout rules are known without re-reading. A `folderIssue` goes to the ledger, not the page state, so a failed read is reported once. + +## console-subagents.md + +The setting arrives as a standing instruction only when it changes, so a long session is not repeated at. Pathfinder research always uses helpers whatever the switch says; the switch governs recon and lookups. Questions for the person stay with the agent, because a helper has no way to ask and an answer only reaches the agent holding the session. Helpers add no session meter points. + +## building.md and building-review.md + +A build is mostly the agent working, so each task's checkbox write is posted at once (the Disk Write Rule): a session that dies mid-phase must leave disk true. `quietMinutes` exists because the page calls a working agent stuck after two silent minutes and a task can honestly take twenty. A question stops the build because the page reads `working` as "not your turn". The review runs inside the build's session and scores itself once on the meter, so it never resumes under `--workflow review` as well. The way back from a review lands on the sign-off without the review verdict, because re-offering a review that just ran reads as though nothing happened. + +## console-launches.md and console-trouble.md + +A session handed over by the dashboard is resumed, never re-opened, because a fresh `open` strands the page the person is watching. The console never writes into a project, so deletes go through `delete-spec` and `delete-handoff`, which refuse links and anything outside `specs/`. + +## console-meter.md + +The meter is advice, not a gate: it tells the person when a fresh session would be sharper. Per-unit work is reported by the agent with `run`; the same `id` is ignored in the same run so a repeat never double counts. + +## Wire format (outputs) + +Outputs carry what the agent acts on and nothing else. Anything kept in the session files (`type`, `at`, `rev`, answer actions, full chat entries, structured workspace and subagents objects) is dropped from stdout. The desktop app reads `sid`, `url`, `pid`, `port` and `embed` from `open` in every context, so those stay. See `specs/console-wire-format/overview.md` (API Design) for the table. diff --git a/.readme/web-console.md b/.readme/web-console.md index 9ce55f3..69081a6 100644 --- a/.readme/web-console.md +++ b/.readme/web-console.md @@ -103,11 +103,12 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so tab put the most useful ones first. It changes the order, never the questions a skill asks (see *Your role* below). - **Light or dark, and a highlight color you pick.** The gear button at the - top right opens *User Preferences*: your role first, then these. It follows + top right opens *User Preferences* on its Appearance tab, which holds these + and your role. It follows your system by default; set it to one or the other if you would rather it stayed put. Remembered on your machine, so it carries over to every session. -- **A card as wide as you want it.** The same panel has a *Card width* +- **A card as wide as you want it.** The same tab has a *Card width* setting — **Narrow** (720px), **Comfortable** (880px, the default) or **Wide** (1080px) — that widens the question card, the Previous / Next pager and the document tabs together. The dashboard keeps its own layout, and on a @@ -169,7 +170,7 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so turns red if that press was never collected, and goes back to the plain icon once nothing is left, so a console left in a background tab can be checked at a glance. -- **Help.** The **?** at the top right opens a Help dialog with 19 topics, +- **Help.** The **?** at the top right opens a Help dialog with 20 topics, one per tab down the left (across the top on a narrow window), opening on the one for where you are. It is part of the page itself, so it still reads fully when the page has lost its program. @@ -295,13 +296,13 @@ cannot open. ### Your role -The first control in *User Preferences* (the gear button) is **Role**: +The last control on *User Preferences*' Appearance tab (the gear button) is **Role**: Engineer, Product lead / PM, Architect / tech lead, Designer (UX), QA / test engineer, Engineering manager, or **Not set / none of these**, the default. It only reorders things: the starter templates on an idea card and the starter questions on the Ask tab. It never changes what a skill asks or does. It is kept in `looks.json` with your colors, so it follows you into every session, -and **Back to default** sets it back to *Not set*. +and **Back to default** on that tab sets it back to *Not set*. Until you have chosen, the dashboard shows a one-line banner at the top — *Pick your role to get starter templates ordered for you.* — with **Set up @@ -484,21 +485,46 @@ working in. badge and a muted *Sent to · * line under its text. - **Removed only when you say.** No automatic cleanup touches it. Once the newest file in a notebook is 30 days old or more, *User Preferences → - Cleanup* offers it as one item named after its folder's full path + System → Cleanup* offers it as one item named after its folder's full path (*Notebook for /home/sam/code/shop*), and deleting it removes the whole notebook, every tab's text and pictures. ### Activities The **die** in the top bar, right of the megaphone, opens **Activities**: small -games to play while you wait, say through a long build. Two ship today, -**Snake** and **Mini golf**. With two games the window shows a picker, one -button per game, and remembers your last pick. The header shows the current -game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet**. +games to play while you wait, say through a long build. Twelve ship today, +**Snake**, **Mini golf**, **Light Trails**, **Bug Hunt**, **Sunset Drive**, **Stack Deploy**, **Bumper Ring**, **Rapids Run**, **Hot Potato**, **Crossing Rush**, **Bounce Road** and **Ghoul Rush**. The window opens on a +**picker**: a card per game with a small cover scene, a line about it, its best +score, and a **Last played** tag on the one you played last, which also has the +focus. Click a card (or walk the cards with the arrows and press space or +Enter) to open its game, and **All games** at the bottom left goes back to the +picker. One game plays at a time: going back keeps a round paused on its card +(**Round paused, score 14**), reopening the window goes straight back into a +paused round, and picking a different game ends it. While a game is on screen, +the header shows its best, such as **Activities · Snake best: 12**, or +**Snake: no best yet**. + +Every game has its own soundscape, all made in the browser with no audio +files: engines that rev and shift gears with your speed, outboard motors, +rivers, wind, light-cycle drones and the moans of nearby monsters run for as long as +the moment lasts, and crashes, splashes, explosions, pickups, combos, bosses, +new bests and game over each get a sound of their own. A game can play +chiptune music too, made the same way, which builds as play heats up (Sunset +Drive has a song for each road, Ghoul Rush a track for each room, played at +one steady level and fuller in a boss fight): turn on **Play game music** in **User Preferences → Sounds & +activities** (it starts off). **Play game sounds** there turns the games' +sounds (the 3, 2, 1 and the new-best burst included) and their music on or +off and leaves the page's own cues alone; the **Play sounds** switch above it +silences all of it, and a paused or closed game goes quiet at once. A game +with music has its own **Music** slider beside **Full screen**, which sets that +game's music volume and is remembered per game (Sunset Drive starts at 70, +Ghoul Rush at 65). - **Snake** speeds up as it grows: 120 ms a step at its starting three cells, 4 ms quicker for each cell beyond, never under 60 ms, and 3% quicker again - for each level. Every 5 foods is a new level, and the first few each bring + for each level. Every 5 foods is a new level, which opens with Slow-mo on + for its full 7 seconds (Slow-mo eases back to the usual pace over its last + 2.5 seconds, so its end is never a jolt), and the first few each bring something new: **Rocks** at level 2 (a cell flashes before it turns to stone, and never right ahead of the head), **Mystery boxes** at 3, **Portals** at 4, **Comets** at 5 (into the head is a crash, through the @@ -518,24 +544,36 @@ game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet** cells away, rests two steps between hops and tires after seven, so corner it or wear it out for 6 points a level before it runs off after 12 seconds. Food eaten within 2.6 seconds of the last builds a combo (x2 up to x5). Power-ups turn up every few seconds and fade if left: **Shield** - (takes one crash: wraps through a wall, smashes a rock), **Turbo** (faster, - double points), **Slow-mo**, **Magnet** (food slides toward you), + (takes one crash: wraps through a wall, smashes a rock), **Slow-mo**, **Magnet** (food slides toward you), **Ghost** (walls wrap) and **Scissors** (half the tail, a point per cell - cut). A mystery box holds one of ten surprises: Jackpot, Gold rush, Earthquake, - Meteor shower, Mirror world (flipped keys), Lights out, Disco fever (triple + cut). A mystery box holds one of nine surprises: Jackpot, Gold rush, Earthquake, + Meteor shower, Lights out, Disco fever (triple points), Big snack, Incoming! (a comet) and Treasure. Passing your best mid-round plays a fanfare. A power-up, surprise or level banner opens on the half of the board away from the snake's head, and fades almost clear while the head is under it or heading into it, so it never hides what you - are about to hit. The start and end screens show how many of the 24 + are about to hit. The start and end screens show how many of the 22 power-ups, surprises, levels and specials you have ever found, and what to look for next. -- **Mini golf** is eighteen hand-made, thoroughly silly holes seen from above. - The front nine, **Pirate Cove**, floats in a shark sea: Walk the Plank, +- **Mini golf** is six themed courses of eighteen hand-made, thoroughly silly + holes, seen from above. Its card opens a **course dashboard**: a card per + course with a picture of one of its holes, its line, its holes and par, and + your best round on it (each course keeps its own), walked by the arrows like + the picker, with **All courses** to get back. Once a round is over, space + or a click goes back to the dashboard to pick the next course. **Dino Valley** has tar pits, + geysers, raptors, a stomping T-rex and a volcano finale; **Candy Carnival** + has gumdrops, gummy bears, licorice belts, a soda whirlpool and a chocolate + fountain; **Cosmic Glow** is black-light glow golf in space, with black holes + that pull a putt in, repulsor planets, wormholes, UFOs and airlocks; and + **Frosty Peaks** glides on ice past penguins, a yeti, icicle gates and a + frozen waterfall. Two hazards are theirs: ice, where the ball barely slows, + and gravity wells, which pull it in or push it away. Pirate Cove and the + Caves of Doom are eighteen holes each too, and their first holes are these. + **Pirate Cove** floats in a shark sea: Walk the Plank, Shipwreck Cove, Cannon Alley, Treasure Beach, Kraken's Lagoon, Ghost Ship, - The Ship's Wheel, Skull Island and Captain's Plunder, with barrels, + The Ship's Wheel, Skull Island and, at the end, Captain's Plunder, with barrels, cannonballs, a rolling powder keg, a scuttling crab, a kraken's tentacle and a - skull you putt through. The back nine, the **Caves of Doom**, is dark but for + skull you putt through. The **Caves of Doom** are dark but for the ball's own light and whatever glows: Into the Dark, Stalagmite Forest, Lava Lake, Mine Cart Madness, Crystal Pinball, The Bottomless Pit, Glowworm Grotto, Crusher Corridor and The Dragon's Hoard, with glowing pools, lava, a @@ -544,7 +582,8 @@ game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet** and splashes, bonks and tunnels pop up a word or two. Play is quick and arcade style: the aim follows the mouse (or hold left or right to turn it, slowly at first, then faster), and it points back at the cup each time the - ball stops. A click or space starts the power meter beside the ball; a second + ball stops, staying there until the mouse moves a few pixels, so a click + without a move putts along the arrow you see. A click or space starts the power meter beside the ball; a second sets the power. The needle crawls near the bottom, so soft putts are easy, and races near the top: the gold **MAX** band just under full putts 1.15 times as hard, and the red band past it is an overswing that shanks the ball @@ -565,21 +604,717 @@ game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet** runs, following the needle. One is held at a time, a new pad replaces it, and a held one carries over to the next hole. +- **Light Trails** is a race to be the last rider moving. You, with Planny's + star eye, and one to three rivals each leave a glowing wall behind; a wall, a + trail (yours too), a crystal or another rider's head is out, and a rival's + trail goes once it has faded. You get a split second of grace: about to + ride into something, you hold in place for 150 ms first, and a turn pressed + then rides out of it (the rivals get none). Arrows steer and space spends a **boost** + charge for 1.4 seconds of speed (two charges a heat, up to three). A round + is a run of heats through nine arenas, each with its own scenery: Neon Grid, + Sunset Strip, Crystal Field, Warp Zone, Storm Front, Carnival, Glacier, + Volcano and the Golden Arena. Winning a heat moves you to the next arena; a + crash costs one of your three lives and runs the heat again, and you and the + last rival out at once is a draw that costs nothing. Each arena brings + something: a second rival and **power-up pads** at 2 (**Boost**, a charge; + **Phase**, ride through trails for 3 seconds; **Eraser**, wipes the trails + around you; **Slow-mo**, the rivals crawl; coins; and from arena 4 a + **1UP**), **crystals** at 3, a third rival and a pair of **portals** at 4, + **closing walls** at 5 (from 10 seconds in, the outer ring turns to stone + every 3.5 seconds, flashing red first), and a second pair of portals at 6. + The rivals ride sharper each arena, and grab a pad if they get there first. + Points come for riding (a point a level every 6 cells), for each rival out + while you still ride (10 a level, 5 more when it hit your trail), coins and + each heat won (25 a level). The start and end screens show the furthest + arena you have reached and the next one waiting. +- **Bug Hunt** is an arcade shooter. Planny's ship slides along the bottom + (left and right move it, up and down a little too) and fires while space is + held. Each wave of bugs swoops in from the sides into a formation that sways + across the top, and every couple of seconds one or more break off and dive + at you; a bug that misses flies back in from the top. A bomb or a bug that + reaches the ship costs one of three lives, and the ship comes back after a + second, blinking and safe for a moment more. The first waves each bring a new + bug: the everyday **Bug** (wave 1), the **Beetle** (2, two shots, and it + splits into two bugs that dive on their own), the **Race condition** (3, + zigzags as it dives), the **Exception** (4, throws at you), the **Null + pointer** (6, shots pass through it while it fades) and the **Firewall** (7, + five shots, never dives). Every fifth wave is a boss with a health bar: the + **Memory Leak** (grows while you wait and sprays drops), the **Spaghetti + Monster** (shrugs off every shot until its four meatball tentacles are shot + off) and the **Heisenbug** (blurs, then turns up somewhere else, and cannot + be hit while it blurs), then round again with more health. Squashed bugs + drop coins and, now and then, a power-up: **Spread shot**, **Rapid fire**, + **Shield** (takes a hit, up to two), **Slow-mo** (the bugs and their bombs at + half speed), **Magnet** (coins come to you), **Refactor** (clears every bomb + and squashes the everyday bugs on screen) and, from wave 4, a **1UP**. Kills + within 1.2 seconds of each other build a combo up to x5. A wave cleared + scores 50 points a wave, and 100 more a wave without a hit; a boss is 500 + points each time round. The board is Snake's checkerboard scrolling past, + with bits of code drifting by, and new scenery every five waves: the + Codebase, Legacy Code, Production and the Cloud. The start and end screens + show how many of the 16 bugs, bosses and power-ups you have found. +- **Sunset Drive** is a road racer against the clock, seen from behind + Planny's convertible on a road drawn a segment at a time, with bends, + hills and scenery scrolling past. Hold up to drive (five seconds to a top + speed of 150 mph), down to brake, left and right to steer; bends push the + car to their outside, and off the road it slows to a quarter of top speed. + Space burns a **nitro** can for 2.5 seconds of a higher top speed (two to + start, up to three). A round starts with 40 seconds on the clock, shown big + in the top middle (in the last ten seconds it blinks red and swells on + every tick), and each + stage ends at a **checkpoint** that adds time (31.5 seconds + at the first, a second and a half less each stage, never under 18) and + 1,000 points a stage. Just before it the road **splits** around a median: + the side you keep to as it begins picks the next road (the board above the + road names both, the gentler on the left, and a postcard of each road + shows in the top corner on its side as the fork is called), and the + median is a wall that holds you to your side. Six roads, each with its own + sky, scenery, bends, hills and traffic, and its own points bonus: **Sunset + Coast** (x1, where every round starts), **Canyon Road** and **Maple + Valley** (x1.2), **Snowcap Pass** (x1.4), **Neon City** (x1.5, the + heaviest traffic) and **Starlight Highway** (x1.8). Catching up with a car + drops you below its speed, and hitting a palm, cactus, rock or other prop + on the shoulder all but stops you. Points come for every stretch of road + driven (times the road's bonus, and 10% more a stage), coins (100), a + **close call** passing a car within a lane at speed (50) and each + checkpoint; **clocks** on the road add 5 seconds. Under 10 seconds the + clock beeps each second, and at none the car coasts to a stop and the + round is over. Spinning **?** boxes on the road hold **power-ups**, queued + up to three (a box past that pays 250 points): while one is held, space + fires the oldest instead of a nitro can, and timed ones run side by side, + one fired again while it runs adding its time. **Rocket Hop** (1.6 + seconds) leaps over traffic and the shoulder, **Ghost Car** (5 seconds) + drives through cars and props, **Coin Magnet** (6 seconds) pulls in every + item across the road, **Monster Truck** (5 seconds) flings the cars it + hits into the sky (150 points each) and flattens props, and **Coin Storm** + turns the traffic ahead into coins at once. The start and end screens show + how many of the six roads you have found. +- **Stack Deploy** is a one-button tower stacker. A block slides back and + forth above the tower, and space, up or a click on the board drops it where + it is drawn: the part over the block below stays, the overhang is sliced + off and tumbles away, and the next block is that much narrower. A block + that misses the tower ends the round, and the camera pulls back to show the + whole tower once. A drop within 3% of the block's width of exact (or the + distance it slides in 18 ms, whichever is more, but never more than half + the block's width) is a **Perfect**: it snaps + on with nothing sliced, the drop's thunk climbs a scale with each perfect in + a row, and every third in a row grows the block back by 8% of the base's + width, never past it. Points: 1 a floor, a perfect 2 more times the run (up + to x5), and a perfect on a **gold** block (from floor 15, about one floor in + twelve) 10 more and twice the growth. The slide speeds up 2% a floor from + floor 10, and floors bring twists: from 20 blocks come from either side and + some turn back partway, from 30 **lag spikes** freeze a block for 150 ms + before it jumps on, from 40 **wind** eases a block in and out as it swings, + from 70 blocks rush through the middle, and from 90 everything is faster. + The tower changes style as it climbs (server racks, office floors from 25, + glass towers from 50, rockets from 75) under a sky that goes from day to + dusk, night and space, and a dashed line marks the highest floor you have + ever reached, which the start screen names with the next style to reach. +- **Bumper Ring** is sumo in bumper cars on a round platform over the void, + seen from above. Held arrows push your car that way (two at once push on + the diagonal), momentum carries it, and cars bounce off each other: the one + closing faster rams and wins the exchange, and two cars leaning on each + other are a pushing match the stronger push wins. Space **dashes**, a burst + the way you push that also makes the car heavier for a moment (two charges + a heat, one back every six seconds, up to three). A car whose center goes + past the edge falls (the last few units hold it back a little, so a push + back in can save it), and the last car on the ring wins the heat. Rivals + let go and rev before they dash, which is your moment to step aside; a + rival that misses near the edge may fly off on its own. A round runs + through nine arenas: **Training Mat** (the Bully), **The Ring** (a heavy + Turtle that holds the middle, and power pads), **Bumper Alley** (the Sniper, + who lines you up against the edge, and bumpers), **Ice Rink**, **Turntable** + (the ring turns, and the Scrapper hunts whoever is nearest the edge), + **Swiss Cheese** (holes that flash, then open), **Magnet Rink** (the middle + pulls, then pushes), **Hall of Mirrors** (the Mirror copies your moves a + beat later, and the ring turns square and back, its corners flashing before + they go) and the **Grand Final**; past it, Final 2, Final 3 and on, each a + little sharper. Each arena keeps what the earlier ones brought. A win moves + you on; a fall costs one of three lives and runs the heat again, and you + and the last rival off together is a draw. After 12 seconds the ring + shrinks 3 units at a time (the band flashes red first) down to a floor, and + a heat still going after that goes to **sudden death** until two cars no + longer fit. Pads (from arena 2): **Heavy**, **Spring** (the next car you hit + goes flying), **Charge** (a dash), **Shield** (bounce back off the edge + once), **Grow**, **Ghost** (pass through cars) and **Slick** (oil behind + you); rivals can take them too. Points, each times the arena: 10 for a + knockout (the last car to touch the one that fell within two seconds gets + it, and your hit carried through another car counts as yours, as does a + rival you rammed into another), with knockouts within 3.5 seconds of each + other building a combo of up to x5 and + two within a second both counting twice; 25 for a heat won, 15 more if you + never teetered at the edge; a point a second alive; and 5 for a rival that + falls chasing you untouched. The start screen names the furthest arena you + have reached, and the end screen says when you went further. +- **Rapids Run** is a fast vertical scroller on a winding river: Planny + pilots a jet-skimmer up a river that scrolls down the board, its banks + narrowing and splitting around islands. The arrows steer, held up speeds up + (twice the points for distance, and less time to react), held down slows + and held space fires. The battery drains all the while, a little faster at + full speed: run over a green charge buoy to top it up, or shoot it for 10 + points if you can spare the charge. A bank, an island, a foe, a bolt or a + flat battery costs one of three lives, and you start the stretch again + from the last dam with a full battery (once a mini-boss's basin is reached, + from the basin's mouth instead, and a dam already blasted stays open). Each stretch, about 20 to 35 + seconds of river, ends at a dam across it: shoot it open to pass (it takes + more shots each stretch, so slow down for it). Eight stretches, **Willow + Run**, **Reed Bend**, **Stone Gate**, **Mill Basin**, **Fog Narrows**, + **Heron Forks**, **Copper Gorge** and **Old Lock**, then Night Water, + Night Water 2 and on, quicker. Patrol skiffs drift from bank to bank and bob mines sit + still from the start; gull drones swoop across, over land and all, from + Reed Bend, bank sentries shoot back from Stone Gate, whirlpools tug you + toward their eye from Fog Narrows and darters swerve into your lane from + Heron Forks. Every fourth dam a mini-boss holds the basin before it, the + river stopped and your battery held while you fight: **the Dredger** (a + fan of bolts), **Ironclad** (rings of bolts, then one at you) and **Old + Leviathan** (a stream that sweeps). Crates hold **Spread shot**, a + **Shield** (one crash of any kind but a flat battery), a **Magnet** (charge + buoys come to you) and a **Surge** (a full battery). Points: 1 for every 5 + units of river, 2 at full speed; 5 for every quarter second you skim a + bank at speed (10 at full speed); 20 to 60 for each foe, times your combo + (sinks within 1.6 seconds of each other, up to x5); 100 times the dam's + number for each dam blasted (once each), and 50 times it more for a + stretch with no life lost; and 400 for each of the first three + mini-bosses, 800 each the next time around and so on, each of which also + gives a life back. The + score shows big at the end, and the start and end screens show the + furthest dam you have blasted. +- **Hot Potato** is arena tag with a fizzing bomb: a merge conflict, its + `<<<<<<<` markers showing. Held arrows run (light momentum, quick to start + and stop), and whoever holds the bomb runs 1.12 times as fast and passes it + on by touching a runner who holds none. The one just handed it cannot pass + it for 0.6 seconds (it flashes white), and while three or more are left + nobody can hand it straight back to the one who just passed it for 3 + seconds (a white ring at their feet shows who is safe). A pass never + leaves its new holder less than 1.4 seconds of fuse (the 0.6 it cannot + pass in, and 0.8 to reach someone): a fuse handed over lower is topped up + to that, on a rival's pass too, once a fuse for each runner. Space dashes: a lunge while you hold it, a dodge while you do not + (two charges, one back every 4 seconds). The fuse starts at 12 seconds, + ticking quicker as it burns, and each fuse after it in a match is 1.5 + seconds shorter, down to 5; whoever holds the bomb at zero is blown out, + and after a moment the bomb lights again on a survivor picked at random. A + match's first fuse never starts on you. The last one standing wins the match + and moves on a venue; blown up, you lose one of three lives and the match + runs again. Nine venues: **Break Room** (the Sprinter, fast but turning + wide, the Hider, who lurks behind cover and is slow in the open, and the + Trickster, who feints before it dashes), **Open Plan** (pickups), + **Server Room** (long rows of racks, and the Pal, who sticks by you), + **Rooftop** (no wall at the bottom: off it is out, and a holder that goes + over takes the bomb with it), **Ice Machine** (slippery patches, and the + Clingy, who hangs just behind the holder), **Conveyor Hall** (belts), + **Blackout** (you see only round yourself, the bombs and the pickups), + **Two Bombs** (two fuses at once, never more than one bomb for every two + runners left) and the **Finale** (shorter fuses, 10 seconds down to 4, ice, + belts and two bombs); past it, Finale 2, Finale 3 and on, each a little + sharper. Rivals get sharper and quicker as you go, crouch before a lunge + (your moment to dodge), and may dodge yours. Pickups (from venue 2, one at + a time): **Freeze** (every fuse stops for 2 seconds), **Sneakers** (1.3 + times as fast for 3 seconds), **Extra Fuse** (2 seconds more on every fuse) + and **Swap** (trade places with a random runner; a holder keeps the bomb). + Points: 10 times the venue for every fuse that ends on someone else (blown + up, or off the roof with it), 2 for each pass you make, 15 more for a hot + pass (under a second left) times your streak of hot passes in a row (up to + x5; a pass that is not hot ends it, and so does a life lost), and 50 times + the venue for a match won. The start and end screens show the furthest + venue you have reached. +- **Crossing Rush** is a lane-crossing race: Planny and two rival hoppers + hop up a strip of lanes eleven cells wide and 30 to 40 rows tall (the view + follows you, and a race bar beside it shows everyone's height), a cell a + hop (an arrow a hop, 0.12 seconds, with one more press queued). Roads of + cars, vans and trucks; rivers of logs and turtles, which you stand on and + ride (the water, or riding off the edge, is a send-back); train tracks + whose lane flashes red with a bell for 1.2 seconds before a train fills it; + and grass rows with bushes and rocks you cannot hop into. A car, a train or + the water sends you back to the last grass row in a spin, never out, where + you stand dazed for 2 seconds (stars round your head) before you may hop + again; rivals sent back are dazed the same. First to the top wins the heat and + moves on a zone; second or third costs one of three lives and runs the + same heat again (same lanes), except that in zones 1 and 2 second place + still gets through. Nine zones, each bringing something new: **Side + Street** (roads, the Hopper, who waits for a clear gap, and the Daredevil, + who takes the tight ones), **Riverside** (logs), **Rail Yard** (trains), + **Turtle Bay** (turtles that dive now and then; the divers wear a red + mark), **Highway** (trucks, lanes that speed up and slow down, and the + Bruiser, quick and pushy through tight gaps), **Night Market** (a dusk, + every lane still in view, brightened by headlights, lanterns and a glow + round each hopper), + **Rapids** (rivers that turn round, with arrows that blink first, and the + Tagalong, who follows a row behind you, then races you to the top), **Ice + Road** (icy lanes that slide you a cell further) and **Rush Hour** + (everything, tighter gaps); past it, Rush Hour 2, 3 and on, quicker each + time. Rivals get sharper as you go: they look further ahead and wait less + after each hop. Pickups (four to six a heat, on the grass): a **Coin** scores + 10 points at once, and a **Spring**, **Shield** or **Horn** goes on your + stack, shown in the pills as the next one space uses and how many wait + behind it. Space uses the oldest: **Spring** leaps two cells the way you + face, over whatever is in between (it stays on the stack when that cell is + shut), **Shield** lets cars and trains pass through you for 3 seconds, and + **Horn** stops the nearest road for 1.5 seconds, for everyone. Pressed + mid-hop, it goes off as you land. The stack empties at every new heat, and + a rival uses a pickup the moment it lands on it. Points: 1 for each row + higher than you had got in the heat, 50 times the zone for a heat won, + times your streak of clean wins (a win where you were never sent back adds + one, up to x3; any other win, a second place or a lost heat ends it), plus + 3 for each row the runner-up still had to go, 5 for a close call (a car or a train + through the cell you just left within a tenth of a second) and 10 for a + coin. Planny's star is your highlight color, and a rival whose color sits + too close to it wears a spare one. The start and end screens show the + furthest zone you have reached. +- **Bounce Road** is a fast scrolling road seen from above: Planny races a + springy toy car up a road laid across a giant's house and yard, with + rival toy cars on it that mean to stop him. Hold up to drive, down to brake + (a toy car never quite stops), the arrows to steer (a little less in the + air) and space to jump, once a press; a jump needs a little speed and goes + further the faster you are, and a ramp launches you on its own. Bump a + rival sideways and it slides: one that leaves the road within 1.5 seconds + of your bump is yours. Land on one and it is flattened while you bounce up + again; land on another before your wheels touch the road and the **bounce + chain** climbs, up to x8. Every stunt in quick succession (a crush, a + bump-off, a hole, train, ball or barrier jumped, a ramp's big air, a close + shave past a rival, a boost strip) steps the **combo**, which multiplies + the points once more every third stunt in a row, up to x4, and runs out + after 2.6 seconds without one. Water or a hole under your wheels, a crash + (a flowerbed or a toy block nose first, a train, a truck's back) or + anything landing on you (a ring on the road shows where) costs one of three + lives, and you go back a little before the spot, with room to get up to + speed. Ten stages of 25 to 45 seconds each, every one bringing something + new: **Chalk Lane** (cracks, boost strips, cones), **Hose Creek** (broken + bridges, a sprinkler, the Frog), **Kitchen Floor** (oil slicks, a rolling + orange, the Sneak, who drops cones), **Flowerbed Fork** (splits, ramps, + falling flowerpots, the Nudge), **Sandbox Run** (road that crumbles behind + you, the Hauler, the Bruiser), **Toy Room** (a toy train crossing, toy-block + chicanes, the Racer), **Garden Pond** (swaying bridges, drawbridges, the + Cop), **Rooftop Gutter** (gusts), **Night Lights** (everything, in the dark) + and **Monster Mash**, where the Monster truck hops at you and must be + stomped five times; then the road goes round again from Kitchen Floor, + quicker and meaner. The rivals get keener every stage: they block your + line, brake in front of you, swerve from under your landings, hop the gaps + and keep the pack close. Every hole has a warning sign and a straight + run-up, and can be cleared at 80% of the top speed. Power-ups lie on the + road from Hose Creek: **Spring**, **Bubble** (one free save), **Nitro** and + **Mega wheels** (bigger and heavier: flatten whatever you touch). Points + come from new road, rivals flattened (each kind its own, times the chain) + and bumped off, jumps, big air, close shaves, stars and boost strips (times + the combo), the Monster (2,000 for beating it), and each stage line (100 + times the stage, a bonus for beating its par time, and with no life lost + 250 more and a life back, up to five). Planny's car is your highlight + color, and a rival whose color sits too close to it wears a spare one. The + start and end screens show the furthest stage you have reached. +- **Ghoul Rush** is a fast, dark run-and-gun through a haunted house: + Planny sprints left to right through a mansion a room at a time, the view + scrolling with him. The house is pitch dark: you see what his glow, his + flashlight's cone, the candles, the moonlight and the muzzle flash light, + plus the eyes of whatever is waiting in the dark, and now and then + lightning lights the whole room for a moment. Hold left or right to run, + press up to jump (let go early for a short hop), down to drop through a + shelf or, on the ground, to duck (a crow, bat, gargoyle or other swooper + passes over your head if you are down before it reaches you), and hold space to fire his flashlight blaster the way he faces, ten + bolts a second; a bolt tilts toward a monster ahead near his height (and + toward a hovering wraith anywhere the tilt reaches). The blaster heats up + as it fires: about three seconds go at the full rate, then each bolt waits + longer, down to one a second (holding fire or hammering space heats it the + same). A **LIGHT** gauge at the right of the HUD shows it: the bar fills + as the blaster heats and empties as it cools, notched where the bolts + start to slow, pale, then amber near the notch, then red and **HOT** past + it. Let + go of fire and, after a fifth of a second, it cools, the hottest blaster + in about two seconds. Rapid fire's bolts add no heat and ignore it. **Tap + space twice** to use a **secondary weapon** you have picked up, shown by + a glowing icon and count beside the LIGHT gauge and by the same icon over + Planny's head; keep holding after the second + tap and the bolts carry on. The first tap still fires a bolt, feathering + the blaster never throws anything, and hammering space spends one at + most. The weapon you picked up last comes out first, you keep the rest + from room to room and through a lost life, and no weapon ever hurts you. + **Dynamite** (a wide blast on a short fuse), the **Iron Stake** (goes + through a whole line) and the **Bottle Rocket** (three at once: one + ahead, one that climbs and curves down onto the nearest monster above or + ahead, one behind, each going off in a blast with a trail of colored + sparks) turn up anywhere. Each stage has one of its own: + the Manor's **Billiard Ball** (rolls along the floor), the East Wing's + **Cast-Iron Skillet** (three pans circle you, then spiral off screen, each one-shotting what it touches and breaking on it), the + Graveyard's **Grave Salt** (burns the floor, even what is still buried), + the Grounds' **Hedge Sickle** (out and back, hitting on both passes), the + Chapel's **Tuning Fork** (a ring that cracks stone and strikes organ + pipes), the Sanatorium's **Flash Powder** (dazes what is near and shows + what hides), the Village's **Silver Bear Trap** (five a use: two behind, one at your feet and two ahead, each + snapping on the first thing to step in it) and the Mine's Dynamite, by the + bundle. A boss can take only so much from them (about a third of its + health at full force, then next to nothing), so they help a lot without + winning the fight, and one at half health drops its stage's weapon if your + bag is empty. Each room's door opens + once you grab its key, often up on a shelf. A run starts in **the Long + Hall**, an easy walk with only zombies, then goes **stage** by stage: + three rooms, then a boss, and beating it opens the door. Out of the hall + and out of each boss's room you **choose the next stage** from two + (one, once a single stage is left) never played that run, each card + showing the stage with its boss standing in it: left and right pick one + out, space or up goes in. Clear every stage and you **escape**, a win. + Each stage cleared makes the next quicker and tougher. Every other room keeps a **horde** + pouring in from the edges of the view, mostly ahead, so standing still is + never safe. **Zombies** shamble out of doors in the wall and sprint once + you are close, **crawlers** drag themselves up through loose boards, + **bats** swoop in level passes at your chest, **ghosts** drift through + walls and can only be hit (or hurt you) while solid, **skeletons** throw + bones you can shoot down, **hellhounds** crouch growling, then lunge in a + low arc a jump clears, **widows** hang from the ceiling and drop on you as + you pass under, **wraiths** hover ahead, shriek and dive at where you were + (keep moving, or shoot them first), and **bloaters** lob acid that leaves + burning puddles and burst into more acid when they die. Now and then a + zombie comes as a **runner** (fast, down in one bolt) or a **glutton** + (slow, 15 bolts to kill, a stomp only bruises it, and it never leaps or + climbs), and a widow or a hellhound as a **huntsman**, a big spider on the + floor that crouches and springs at you as high as you are. A shot to the head + or a stomp from above doubles a kill, and each kill within 1.2 seconds of + the last steps the chain, which multiplies kills up to x10. The rooms bring + pits, one-way shelves, crumbling boards and falling chandeliers that crush + whatever is below (a monster crushed counts double). Five stages so + far: **the Manor**, the **Foyer**, the **Portrait Gallery**, the **Library**, the **Ballroom** + (the **Rotting Gourd**, a giant rotten pumpkin that picks one of three + moves at random, never one three times running: a hop to where you stood, + its shadow showing where, that shakes loose gourdlings; a spit of two + acid globs after a shake; or a quake straight up and down that sends a + shockwave along the floor both ways). Its arena is stacked with balconies + in three tiers: up on one over its head it only spits at you, never hops, + a corner always leaves a pocket its hop cannot land on, and its gourdlings + jump up onto balconies after you and run off their ends to follow you + down), **the East Wing**, the + **Kitchen**, the **Conservatory**, the **Attic** and the **Crypt** (**Old + Rattlebones**, who throws volleys of five bones, slams shockwaves along + the floor you jump and throws his own skull like a boomerang, level at your + chest and back again, so jump it going and coming; headless meanwhile, he + has no weak spot, but a bolt to the flying skull does triple. His skull on + his shoulders takes double. At half his hp he shakes, his eyes flare and he + fights faster: his slams come in a double, he hurls bones up that come down + around you on shadows, and he raises up to two skeletons out of the floor), + and **the Graveyard**, out + under the night sky: the **Lychgate**, **Open Graves**, **Mausoleum Row** + and **Angel's Rest**. Its monsters are its own: **grasping hands** that lie + unseen under the dirt, burst up as you pass and creep along under the + ground after you; **mourners** whose wail slows you to half speed for a + moment if you are close; **grave robbers** who dig in and come up behind + you; **rotters**, zombies whose legs keep walking after you if you shoot + them down at the body (a headshot or a stomp finishes them); **carrion + crows** that wait on the headstones and dive at you; and rotters climbing + out of open graves. Its boss is **Mother Mourning**, a giant weeping angel: + while she weeps she is stone (your bolts glance off) and flings headstones, + then she turns and watches, and only then can she be hurt, but anything + but standing still while she watches brings a stone fist down where you + are, its shadow first. She does not stay where she was: each time she turns + back to watch she has blinked a few steps nearer, in a puff of stone dust. + At half her health she spreads her wings: a shorter weep, two headstones at + a time, a shockwave each way as each weep begins, and while she watches a + stone fist also falls near you now and then, moving or not. + A fourth stage, **the Grounds**, is the gardens under the night sky: the + **Hedge Maze**, the **Topiary Garden**, the **Gazebo** and the + **Groundskeeper's Yard**. Its monsters: **topiary beasts**, hedges clipped + into animals that stand frozen while you face them and charge the moment + your back is turned (so you can only shoot one while it is still); + **rootlings**, a crack that runs along under the lawn after you, stops + to warn, then bursts up as a solid root that hurts until it sinks again; + **lantern moths**, which come in flocks of three and flutter at you, + quicker in the dark and straighter still while you hold the Lantern; and + **mulch crawlers**, which wait in a leaf pile and burst out as you come + near. Its power-up is the **Hedge shears** (10 seconds, found only here): + one bolt cuts down a topiary beast or a rootling outright. Its boss is + **the Groundskeeper**. Jump his scythe as its low wave sweeps along the + floor, but when he raises it high (a pale band hangs in the air in front + of him) stay on the ground and let the high sweep pass over you; shoot the + lantern at his belt while it flares open (it takes triple damage, but only + then, and only briefly: after the scythe and again when the mower stalls); + jump or stand clear of the fire he lobs where you stand, which burns the + floor for a few seconds. At half his health he climbs onto a rusted mower: + when he revs, get up high on a shelf before he charges across the + arena (the charges come a little oftener), then shoot the lantern while he + is stalled against the far wall. On the mower he lobs a second fire where + you are heading, and each time the lantern opens a few lantern moths + flutter in toward it. + A fifth stage, **the Chapel**, is indoors again, candlelit stone and + stained glass: the **Nave**, the **Bell Tower**, the **Organ Loft** and + **the Choir**. Its monsters: **gargoyles**, stone on their ledges (your + shots glance off and a stomp does nothing) until you pass under one, when + it shakes loose, dives at your chest and flies back to turn to stone + again; **choir ghosts**, which drift at you and sing now and then, and + while they sing every monster near them moves faster, so kill them first; + **censer monks**, who walk at you, swing their censers and leave clouds of + harmless smoke that hide what is inside; and **bell bats**, asleep in the + bells until the bell tolls. The **bell toll** is the stage's twist: in the + tower and the choir the bell swings in view, then tolls, and for one + second everything freezes, you included (a bolt already flying still + hits), while a flock of bats bursts from every bell in view. Its power-up + is **Holy Water** (10 seconds, found only here): your bolts splash, + hurting every monster close to what they hit, hurting ghosts twice as much + and breaking a stone gargoyle even on its ledge. Its boss is **the + Choirmaster**, at his organ. Silence the four pipes to open him: each pipe + takes a handful of bolts, a sounding pipe spews a ghost now and then, and + while any pipe sounds he cannot be hurt. Once all four are silent, shoot + him. Between those he raises his baton and a column of notes flies at you + along the lines of a staff with one gap in it: mind the gap in each column + and be at its height (the floor or one of the boards) as it passes. At + half his health the hymn quickens: the notes fly faster, now and then a + second column follows close behind, and the pipes come back one by one, + each sounding again in turn. + A sixth stage, **Blackmoor Sanatorium**, is a derelict asylum of cracked + green tile: **Admissions**, the **Hydrotherapy Baths**, the **Surgical + Theater** and **the Night Ward**. Its monsters: **orderlies**, huge and + slow, which reach for you when you come close (jump clear while they wind + up), grab you and throw you a long way back (the throw costs no life, but + mind where you land); **gurneys**, solid enough to stand on while parked, + which rattle and roll at you when you come along their floor and hurt only + while rolling; **flickers**, gaunt patients you can neither see nor hit + while the lamps are lit, which lunge at you in the dark; and **specimen + bloaters**, which lob jars that shatter into puddles of formaldehyde. The + **flicker** is the stage's twist: in the baths and the theater the lamps + stutter, then go out for a moment, and in that blackout you see little + beyond your own glow. It has two power-ups found only here (10 seconds + each): **Smelling Salts** (you break an orderly's grab at once, and keep a + wide glow through a blackout, in which flickers show and take double + damage) and the **Bone Saw** (your bolts pierce every monster in a line, + and a gurney breaks in one hit). Its boss is **the Night Matron**. Stay out + of her lantern's beam as it sweeps the ward: a moment in it costs a life, + so hide behind a medicine cabinet or climb above it. Between sweeps she + throws fans of syringes, and cracks of light in a wall warn of a long arm + about to reach across the room at your height. At half her health the ward + goes dark, her lantern the only light, her arms come from both walls at + once and her fans of syringes grow. + A seventh stage, **Hollow End Village**, is out under the night sky again + (all but its inn): **Main Street**, **the Crooked Inn**, **the Town + Square** and **the Village Green**. The **moonrise** is the stage's twist: + in each room the moon climbs the sky, and when it is full every villager + in view turns into a fast, leaping wolf-man and the moonhounds grow, so + clear the villagers before the moon is up. Its monsters: the **torch mob**, + villagers who come in threes and lob torches that leave fire on the + ground; **hanged men**, swaying on their ropes until you pass under, when + they drop to head height and haul back up; **shutter ghouls**, which rattle + their shutters as you come near, then lunge out of the window (shoot them + while they are out); and **moonhounds**, which leap at you like + hellhounds. Its power-up is **Wolfsbane** (10 seconds, found only here): + wolf-men and moonhounds shy away from you, and your bolts do them and the + Beast double damage. Its boss is **the Beast of Hollow End**, a werewolf. + It bounds onto the walls at either end of the green and clings there a + moment, the time to shoot it for double damage, then pounces where you + stand (watch the shadow on the grass); up close it swipes, and its howl + calls moonhounds. At half its health the moon comes full: it waits less, + pounces twice in a row, and its howl calls grown hounds. + An eighth stage, **the Deep Seam Mine**, goes underground, where every room + is always dark: **the Mine Shaft** (ride the cage lifts up and down), + **the Flooded Tunnels** (knee-deep water slows you and your steps splash), + **the Collapse**, **the Runaway Cart** and **the Mother Seam**. **Rockfall** is the stage's + twist: dust trickling from the ceiling warns of a rock about to drop, which + crushes whatever is under it, you included. Its monsters: **Knocker imps**, + small and quick, whose touch steals your light (your glow shrinks to a + sliver for a few seconds, but no life is lost; shoot the imp to get it + back); **canary ghosts**, harmless to touch, but their scream brings three + rocks down around you, so shoot them first; **dead miners**, who burst out + of the walls with their helmet lamps still lit and swing a pickaxe up + close; and **blind crawlers**, which hunt by sound: stand still without + firing for a moment and they lose you. It has two power-ups found only + here: the **Hard Hat** (worn on your head until it is used, like the + Garlic shield: one rock bounces off it, or an imp knocks it off instead of + stealing your light) and bundles of **Dynamite** (three sticks here, + thrown with a double tap like any secondary weapon). Its boss is **the + Tommyknocker**, a miner-giant with a sledgehammer. He knocks on the rock + to bring the ceiling down, sweeps his hammer low along the floor (jump + it), and puts out the lights: in the dark an imp carries his lantern as a + decoy, so follow the knocking instead, and when he bursts out of the floor + he is dazed for a moment and takes double damage. At half his health the + dark lasts longer, his knocks come quicker and imps join in. + **The Runaway Cart** is a ride, not a walk: Planny rides a mine cart down a + roller coaster of track over the chasm and the cart does the moving. It + rolls on its own, quicker down a slope and slower up one; right leans + forward, left brakes, up jumps (left and right steer in the air) and down + ducks. Jump the gaps, the heaps of rubble and the crates (or shoot a crate + twice), duck the low beams, pick the right line where the track splits, and + do not brake for long: a boulder rolls up behind (and once it surges, hold + right to stay ahead of it). It is a **bonus round**: a long, fast ride (about + a minute) played for five hearts of its own, so a hit, a fall off the track + or a flattening costs a bonus heart, never a life, and you come back at the + last checkpoint. Lose all five and the round ends with nothing and the run + goes on to the Seam; get to the buffer stop and the door opens, and you earn + Lucky Dice (three at least, up to nine for hearts left, obstacles passed + untouched, crates broken and monsters shot, and not braking much). + A ninth stage, **the Midnight Carnival**, is a fairground at night: + **the Midway** (booths and counters to hop along), **the Hall of Mirrors** + (indoors), **the Funhouse** (its floors are conveyor belts that carry you + along while you stand on them, slower than you can run) and **the Big Top**. + Its monsters: **grinners**, clowns that honk out a balloon that drifts at + you at chest height (shoot it or it pops by itself, and it leaves a puddle + of acid for a couple of seconds; one on you costs a life, and ducking lets it + float over); **marionettes**, which hang just over your head and drop when + you pass under them (a bolt over its head, on the string, kills one at once, + else it takes four hits); **Mirror You**, which steps out of a mirror, + copies your moves the other way half a second late, and fires a bolt for + every bolt you fire (its bolts and yours cancel when they meet, so fire and + then move); **strongmen**, slow and huge, who lob barbells in an arc (a + stomp hurts one); and **circus hounds**, which crouch while a hoop of fire + flares and then leap, coming down where you stand (a ducked Planny is + passed over). It has two things found only here: **Cotton Candy** (10 + seconds of sticky bolts that slow what they hit) and the **Custard Pie** + (thrown with a double tap in an arc, it splats and leaves everything near + stunned for three seconds; a pied Mirror You copies nothing meanwhile). Its + boss is **the Ringmaster**, on a gantry high over the ring, working a + giant puppet that hangs on three strings and stalks you round the ring: it + leaps to where you stood (watch the shadow, then jump the shockwaves), + charges along the floor to the wall (jump it) and stomps. Shoot the strings, + not the puppet: they follow it and slant as it moves, and from a trapeze + board or in a jump a bolt that crosses a string cuts into it, and + when all three are cut the puppet collapses and the Ringmaster is left + open on the floor for four seconds, the only time he can be hurt. Then he + climbs back and ties the strings again. Now and then he cracks his whip + along the floor at chest height (duck it, or jump it). At half his health the + cages in the wings open and hounds come out, and the strings take more hits. + Between the Funhouse and the Big Top is a second **bonus round**, **the Dark + Ride**: a side-view shooting gallery on rails where Planny sits in a ghost-train + car and twelve rooms of animatronics go wrong (a wax museum, a torture chamber + with the Executioner, a carousel, a hall of mirrors where only the solid ghoul + is real, a tunnel of love with the Black Swan, the Widow's nest, a lift hill, a + burning big top, a fake Exit, the Dark and the Barker), about a minute and a + half. Its title screen waits for a key or a click, and tips you to use the + mouse and to duck by moving your aim below the dashed line. Nothing walks: the **arrows** move an aiming reticle (it speeds up the longer + you hold), **Space** fires (hold to keep firing), and with the **mouse** you + move to aim and click or hold to fire. Pull the reticle down into the car, + below the dashed line, and Planny ducks (he cannot fire while ducked): the + answer to swinging blades, falling chandeliers and the big swings. Shoot + what lights up, chains and webs, and never the green-heart guests or a + mirror's reflections; a shot that just misses still finds a target close + to the reticle (never a guest). You have five hearts of your own and a + hit leaves you safe for a couple of seconds; killing a mini-boss gives one + back. Lose all five and the bonus ends with no dice and the run goes on to the + Big Top, its lives untouched; reach the end alive and you earn five to nine + Lucky Dice by how well you did (the dice pop out in a cascade). + A tenth and last stage, **the Frozen Lake**, is a frozen lake at night under + falling snow: **the Ice Fishing Huts** (open ice with holes in it), **the + Snowbound Lodge** (indoors, a hall the roof fell into), **the Black Ice** + (the longest room, ice nearly everywhere) and **the Widow's Web**. Between + the Black Ice and the Widow is a third **bonus round**, **the Coffin Sled**. + Two rules are its own and work in any room that sets them. **Ice** is + slippery: on it Planny's run eases up and eases off, so he slides a dozen + units past where you let go, a jump keeps the speed you had, and he stops + dead at the ice's edge. **Thin ice** is a tile that shows a crack when you + stand on it, breaks a moment later (the floor is a gap, and if you are on it + a life is lost: "went through the ice") and freezes again after a few + seconds; step off in time and it heals. Its monsters: **under-ice hands**, + which trail you beneath the ice, crack a thin tile under you or burst up and + grab (shoot or stomp one); **snow shades**, which you see only by their + footprints until one winds up or a bolt of yours passes near it, so shoot at + the prints; **frozen ghouls**, zombies that slide on ice and shatter when + they die into three shards (two run along the floor, jump them, and one flies + at head height, duck it); and **ice wraiths**, whose dive freezes you for + most of a second if it passes close (one dives at a time). Two things are + found only here: **Hot Cocoa** (10 seconds of no sliding, no freezing and + thin ice that cracks at half the speed) and the **Road Flare** (thrown with + a double tap in an arc, it lands and burns a patch for four seconds: it burns + what walks in without leaving drops, melts a Frozen Ghoul at once with no + shards, lights up a shade, and never hurts you). Its boss is **the Frost + Widow**, who hangs from the roof, drops to the floor and walks at you + behind a veil of ice that guards her. Kick or shoot the burning barrels at + her to melt the veil (a flare does it too); then, with her low, any shot + hurts and the heart takes triple while her mouth is open. A blizzard now and + then pushes you away from her (a barrel in between breaks the wind), ice + spikes rise from the floor where you stand (the line cracks first; a board + of 18 is over them), her web slows you while you are in it, and at half her + health the barrels are set out again and ice wraiths join in. **The Coffin + Sled** is a ride down a long frozen cemetery hill on a coffin lid, about a + minute and a half: the sled speeds up on the downs and slows on the ups on + its own, so you only jump (cracks in the ice, headstones, snowdrifts, hands), + duck (low branches and tombstone arches) and shoot (icicles, popping ghouls + and hands). It plays for five hearts of its own, so a hit costs a heart, + never a life, and a fall into a crack puts you back on the ice ahead. Lose + all five and the round ends with nothing and the run goes on to the Widow; + reach the snowbank and you earn three to nine Lucky Dice (hearts left, + obstacles passed untouched, things shot and souls and Cocoa taken). + Not every room is dark: each time you enter one it is dark three times in + five and otherwise lit, dim but seen whole (the same for the same run's + seed). In a dark room only half as many monsters come in from the edge + behind you. Power-ups lie in the rooms and now and then drop from + a kill: **Spread shot** and **Rapid fire** (eight seconds each), a **Garlic + shield** (shrugs off one hit and sees off what touched you; lose a life + within 12 seconds of coming in and you come back already holding one), a + **1UP**, a **Lucky die** (a white die, dropped by a kill as often as a + 1UP and never lying in a room; every run starts with three, up to nine are kept for the whole run, shown + as a **DICE** pill, and a ninth more is points; when you would lose a life, + by any cause but the endless-lives code, one die rolls on the field (the rest + are kept). A 4, 5 or 6 brings you back where you fell, or after a pit on the + last ground you stood on, with no life lost and the room as it was: a 5 adds + a heart, a 6 a heart and a Garlic shield, and in an ordinary room every + monster in view blows apart for its points (in a boss's room nothing does). + A 3 or lower loses the life as usual: a 3 brings you back with Rapid fire and + a Garlic shield, a 2 with Bottle Rockets and a Garlic shield, and a 1 only + laughs at you, "Better Luck Next Time"; on your last heart a 2, 3 or 4 instead pays one heart, and you respawn with it as usual; every run starts with 3 dice), a + **Lantern** (15 seconds of the dark pulled far back, found only in a dark + room; in a lit one another power-up lies in its place), **Bat wings** (12 + seconds of one flap in the air per jump, for a second jump; fall down a pit + with them on and they carry you back to the ground you fell from, costing no + life or die, and are used up), a **Church + bell** (4 seconds where every monster but a boss stands still and none + comes, ending at the door) and an **Hourglass** (20 more seconds on the + clock). Every room but a boss's has a **clock** (70 to 80 seconds, its + last ten ticking out loud); at none it costs a life and the room starts + over with a full clock. Two or more zombies, runners, crawlers or + gourdlings bunched under you climb over each other to reach you, arms + raised (land on the arms and they hurt you; only the head between them + takes a stomp), so a shelf over a + crowd is never a safe place to wait. The horde never ends, so its kills + (and those of the dead that come once the bonus is gone) are worth 80% of + the last one in the room, down to a tenth, and drop nothing: farming them + by the door pays next to nothing. A walker at the edge of a pit or a + drop (or a wall up to 8 high, for a zombie, runner or crawler) stops a + moment to think about it (a "?" over it), then leaps (or climbs): across + up to 10 units to floor at its own height, further down to a lower floor, + or straight down off a ledge; a wider pit or floor higher than a step + still stops it. High over each room's key + shelf (but a boss's) float **crystals** (250 points each) and in some + rooms **Silver bolts** (10 seconds of bolts that go on through every + monster they hit, found nowhere else): out of reach of one jump from + anywhere, but a jump and a **Bat wings** flap from the key shelf takes + them, and each such room has Bat wings on the way. + Points: 100 a zombie, 75 a crawler, 50 a bat, 150 a ghost or a hellhound, + 120 a widow, 200 a skeleton or a wraith, 250 a bloater and 40 a gourdling, + all times the chain, 25 a bone or glob of acid shot down, 10 a soul and 50 + a power-up; through a door, 300 times the room number, the time bonus left + (1500, dropping 50 a second; once it runs out, zombies come in from the + edges every second and a half) and 500 more with no life lost; 2000 for + the Gourd and 2500 for Rattlebones (90 hp), a quarter more for each stage + already cleared, with a life back up to nine. A hit or a fall costs one of seven lives and puts you back at the + room's start (in a boss fight, the arena's, the boss's hp kept), safe for + a moment, and on your last life the edges of the view pulse red. The start + and end screens show the most stages you have cleared in a run. When a + room starts again after a loss (a hit, a fall or the clock), a random + power-up shimmers a few steps ahead of Planny on every restart until you + clear the room (never a 1UP, and not in the bonus rides). - **It never hides your turn.** A new question, a sign-off or a finish pauses the game at once and shows a banner with **Go to it**, which closes the window - on that question. Hiding the page or clicking away from it pauses it too, and - nothing resumes by itself. Any game key (arrows, W/A/S/D, space, P) or, in - Mini golf, a click on the board plays on, and the banner stays down until the - next new question or finish. + on that question, and **Unpause game**. While that banner is up, only + **Unpause game** plays on, so a key or click you were already making cannot + wave the banner away unread. Hiding the page or clicking away from it pauses + the game too, and nothing resumes by itself. Otherwise (after **Go to it**, or + once you close and reopen the window) any game key (arrows, W/A/S/D, space, + P, Enter) or, in Mini golf or Stack Deploy, a click on the board plays on, + and the banner stays down until the next new question or finish. +- **Lives at a glance.** A game with lives shows them as a solid pink pill + with a heart per life, and its banners fade almost clear while you, or + whatever is coming at you, are under them. +- **Endless lives.** In any game with lives, type up, down, up, down, left, + right, left, right, B, A, space on the board: the lives pill turns to + "♥ x∞" and no life is lost until the round starts over (R, or a new round) + or you leave the game for the picker or close the window. +- **Stage select (Ghoul Rush).** Type up, down, up, down, left, right, left, + right, S on Ghoul Rush's board for a practice round that opens on its stage + select: up and down pick a stage, left and right one of its rooms (the last + is the boss's), space goes straight in. A practice run keeps no best score + and no record, and starts with a full stock of that stage's weapon and the + common ones. Endless lives typed before it carry over; typed after, they + last for the run as usual. - **A countdown first.** Every game counts down 3, 2, 1 before a round starts and before it plays on after a pause, so nothing moves before you are ready. P or Esc during the count pauses again. -- **Keys.** Arrows or W/A/S/D steer, space starts and plays, P pauses, Esc - closes the window with the game paused. A page with no mouse or trackpad +- **Keys.** Arrows or W/A/S/D steer, space starts and plays (and boosts in + Light Trails, fires while held in Bug Hunt, burns nitro in Sunset Drive, + where held up drives and held down brakes, drops the block in Stack Deploy, dashes in Bumper Ring, where held arrows push, fires while held in Rapids Run, where held up speeds up and held down slows, dashes in Hot Potato, where held arrows run, uses the oldest pickup in Crossing Rush, where an arrow hops once a press, jumps once a press in Bounce Road, where held up drives and held down brakes, and fires while held in Ghoul Rush, where held arrows run, up jumps once a press and down drops through a shelf), P pauses, R starts the round over (from the 3, 2, 1), F (or **Full screen** under the board) gives the game the whole screen and F or Esc puts it back, and Esc closes the window with the game paused. In full screen the board takes the whole screen, as big as its shape allows, with black bars where the shape leaves room, and a panel (the game's name, the score line, the game's **Music** slider for a game with music, Exit full screen) is laid over it: docked in the side bar when that bar is at least 220 px wide, in the bottom bar on a tall screen when that is at least 110 px tall, and otherwise floating in the top right corner (Sunset Drive's 16:9 board on a 16:9 screen), where it shrinks to the score line in the bottom right corner while a round plays and the pointer is still. The board never gives up room for the panel. The pointer hides after two still seconds. In the desktop app the page asks the app (`activities-full`) to lay the console over its bar and terminal and put the window in full screen, since the app's frame allows the page no full screen of its own. A question, a sign-off or a finish takes a full-screen game back to the window's own size as it pauses it. A page with no mouse or trackpad (touch only) shows "Activities need a keyboard." in place of the board. - **Best scores** show beside the score while you play and after each round. - Snake keeps its highest score. Mini golf keeps its lowest full round, and a - half-played round never counts. **Reset best scores** clears them after a + Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush keep their highest score. Mini golf keeps its lowest + full round on each course, every course on its own, and a half-played round never counts. **Reset best scores** clears them after a second click to confirm. The line under the board is a pair of colored chips, Score and Best, with a meter between them filling toward the best (for a game where the highest @@ -588,8 +1323,8 @@ game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet** that beats a saved best ends with **New best!** on the end screen, and Mini golf, which only knows at the end, fires its sparks then. Reduced motion keeps the colors and drops the movement. -- **Private.** Best scores, Snake's surprises found, the last pick and the **Show Activities** switch - (User Preferences, which hides the die everywhere) are saved in +- **Private.** Best scores, Snake's surprises found, Light Trails' furthest arena, Bug Hunt's 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, the most Ghoul Rush stages cleared in a run, the last pick and the **Show Activities** switch + (User Preferences → Sounds & activities, which hides the die everywhere) are saved in `~/.plan2code/console/looks.json`. Nothing about Activities reaches the agent or the session. @@ -777,8 +1512,8 @@ send never holds up a question. - **Pictures.** The same as notes: the button, paste, or drag and drop, up to 5 per question. - **Ten questions per conversation.** The `N of 10` counter is always in view. - After the tenth is answered, **New conversation** starts a clean one. So does - switching skills through the dashboard. + After the tenth is answered, **New conversation** starts a clean one. + Switching skills through the dashboard keeps the conversation going. - **Edits need your approval.** Ask for a change to a file and the agent replies with a summary and the list of files it would touch, with **Approve** and **Decline**. Nothing changes until you approve. Afterwards @@ -826,24 +1561,44 @@ links to the Releases page. | In the Ask box: `Enter` / `Ctrl` + `Enter` (`⌘` + `Enter`) | `Enter` is a new line; `Ctrl` + `Enter` sends the quick question, never the cards | | `Esc` | Closes whichever dialog is open; on the dashboard, backs out of a pick | | In Help: arrow keys, `Home`, `End` | Move between topics (the arrows wrap). `Ctrl` + `Enter` does nothing inside Help | +| In User Preferences: arrow keys, `Home`, `End` | Move between its four tabs (up and down in the side list, left and right in the strip on a narrow window) | Every control is a real button, radio or checkbox, so screen readers and keyboard-only navigation work. -## Models in User Preferences +## User Preferences -The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude, Devin and Codex tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model `, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve. +The gear button in the top bar opens **User Preferences**, always on its first tab. Its four tabs sit in a side list, or in a strip along the top on a window narrower than 720px, and the arrow keys, `Home` and `End` move between them: -## Agents and the desktop app in User Preferences +| Tab | What it holds | +| --- | --- | +| **Appearance** | Theme, Card width, Highlight color and Role | +| **Agents & models** | The agents `plan2code` can start, and the models each one offers | +| **System** | Cleanup, and Desktop app (only inside the desktop app) | +| **Sounds & activities** | Sounds and Activities | -**User Preferences → Agents** adds agent CLIs Plan2Code did not find on its own. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields: +On Appearance and Sounds & activities each change saves the moment you make it, and a small **Saved** mark shows beside it. **Close** (or `Esc`) shuts the dialog. **Back to default** resets only the tab on screen: Appearance's four settings (Role back to *Not set*), or every sound and the two Activities switches (Show Activities and Play game sounds); Activities best scores stay. It is not shown on Agents & models or System, which have nothing to reset. + +### Agents & models + +Most people never need this tab: Plan2Code finds the agents installed on the machine and ships an up-to-date model list with every release. It opens on a summary table, one row per agent with its models and whether its command was found on this machine. **Edit** opens that agent's form and **Add agent** a blank one. Nothing on this tab saves as you type: each form has its own **Save** and **Discard**, and shows an **Unsaved** badge while it holds a change. Leaving a form with an unsaved change (another tab, **Back to summary**, **Close**, `Esc`) asks first: save it, discard it, or keep editing. Saving one agent never sends another's half-typed edit. + +**Models.** The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. Each built-in agent's form (Claude, Devin, Codex) shows that list under *Comes with Plan2Code*, and below it **Models you added**, each a model id and the name shown in the menu, for a model that came out before Plan2Code was updated. Additions are kept in `~/.plan2code/models.json` and survive updates, unless the curated list now includes them; **Remove** takes one out. Restart `plan2code` to see a change. You can always run `plan2code --model `, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve. + +**Agents.** An agent you add is an agent CLI Plan2Code did not find on its own, which the `plan2code` command and the desktop app can then start. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields: -- **Arguments**: one per row. `{prompt}` is replaced by the start prompt (for example `--message={prompt}`); with no `{prompt}` anywhere, the prompt is added last. - **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed. -- **Bypass arguments**: added when permission checks are off. -- **Model arguments**: added when a model is chosen, with `{model}` replaced (`--model` and `{model}` by default), and a list of **models** to offer, each an id and an optional label. +- **Models**: a list to offer, each an id and an optional label. +- Under the **Command-line arguments** fold: + - **Arguments**: one per row. `{prompt}` is replaced by the start prompt (for example `--message={prompt}`); with no `{prompt}` anywhere, the prompt is added last. + - **Bypass arguments**: added when permission checks are off. + - **Model arguments**: added when a model is chosen, with `{model}` replaced (`--model` and `{model}` by default). -**Test** on a card shows where the command is found, or "Not found on PATH", and never runs it. Saving a duplicate name, a blank command or a built-in id marks the card and field and writes nothing. The list is plain text in `~/.plan2code/agents.json`, shared by the `plan2code` command and the desktop app; this page is the only thing that writes it, and a broken file or entry is skipped with a warning shown under the list, never a crash. If the file holds something the page could not read, saving asks first (**Save anyway**). `/plan2code` works only in agents that load the installed Plan2Code skills. +**Test** beside the command shows where it is found, or "Not found on PATH", and never runs it. Saving a duplicate name, a blank command or a built-in id marks the field and writes nothing. **Delete agent** asks once more on the form before it removes one. The list is plain text in `~/.plan2code/agents.json`, shared by the `plan2code` command and the desktop app; this page is the only thing that writes it, and a broken file or entry is skipped with a warning shown on the tab, never a crash. If the file holds something the page could not read, saving asks first (**Save anyway**). `/plan2code` works only in agents that load the installed Plan2Code skills. + +### System + +**Cleanup** lists what Plan2Code does not need in `~/.plan2code/`, with sizes, before anything is deleted (**Find files to clean up**, then **Delete these**); what it offers and what always stays is under *Or clean up on demand* below. **Desktop app** appears only when the page is open inside the desktop app. Its switch, **Show on the taskbar when Plan2Code needs me** (on by default), controls the app's taskbar signal: on Windows a green dot on your move and a red one when it needs attention, plus one short burst of flashes when the window is not focused (the button stays lit until you look); on macOS a red `!` dock badge when it needs attention and one bounce; on Linux a badge where your desktop supports it. Turning it off clears the dot and stops flashes. The choice is kept by the app in its own `~/.plan2code/app.json`. @@ -916,10 +1671,10 @@ exception being the note attachments the agent keeps for a spec, above): | `~/.plan2code/console/sessions//uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched | | `~/.plan2code/handoffs/.md`, `.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not | | `~/.plan2code/notepads/-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs//note.md` and `tabs//images/` (`notepads.mjs` is their one owner; the agent never reads them, except a tab you send) | until you delete it through Cleanup, which offers it once its newest file is 30 days old | -| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities switch, the last activity picked (`lastActivity`), best scores (flat `activityBest` keys: `activityBestSnake`, `activityBestGolf`) and each game's memo (`activityMemo`: Snake's surprises found) | always | +| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities and Play game sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest` keys: `activityBestSnake`, one per Mini golf course from `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`) and each game's memo (`activityMemo`: Snake's surprises found, Light Trails' furthest arena, Bug Hunt's bugs, bosses and power-ups found, 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) | always | | `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always | | `~/.plan2code/console/sessions//subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session | -| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents), read by the `plan2code` command and the desktop app | always | +| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents & models), read by the `plan2code` command and the desktop app | always | | your system temp directory | the port, process id and session token | until reboot | Each of the workspace and meter files has exactly one writer: the server owns @@ -942,7 +1697,7 @@ Your `looks.json` and the `console-dir` pointer are never touched, and neither is the session being opened. Nothing of value goes with them: the page is never the record, `specs/` in your project is. -**Or clean up on demand.** *User Preferences → Cleanup* → **Find files to +**Or clean up on demand.** *User Preferences → System → Cleanup* → **Find files to clean up** lists, with sizes, everything in `~/.plan2code/` that is not needed: sessions untouched for 30 days (never the one you are in), anything at the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`, @@ -1030,7 +1785,7 @@ origin. | Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) | | Ships as | `skills//references/web-console/` | | Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/skills.js` (each entry's `card`; `SKILL_CATALOG` in `public/answers.js` is a lookup on it) | -| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/.md`, and `building.md` / `building-review.md` for the builds; `console.mjs help ` prints any of them | +| Agent contract | a card, `src/web-console/console.md` (read once), plus pointers: the console names a topic file (`console-*.md`, `notes/.md`, `building.md` / `building-review.md`) in its own `read` output, once per session per topic, when its moment comes; `console.mjs help ` prints any of them. A `stop` with no `finish`, or a `finish` while `stopWarning` is set, is refused with the fix; `stop --session --force` ends a dead page or an abandoned session anyway. Patches are one line, with lettered options and the console's own defaults filled in; a refused patch names the field and the fix. Byte budgets keep the card, the notes and a sample session's outputs from growing back (`scripts/test-console-wire-budgets.mjs`) | | Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` | | Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) | | Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) | diff --git a/scripts/capture-screenshots.mjs b/scripts/capture-screenshots.mjs index 709a428..624201d 100644 --- a/scripts/capture-screenshots.mjs +++ b/scripts/capture-screenshots.mjs @@ -164,16 +164,17 @@ const COMPARE_SHOTS = { open: async (page) => { await page.click("#btn-looks"); await page.waitForSelector("#looks-modal[open]", { timeout: 10000 }); + await page.waitForSelector('#prefs-tab-appearance[aria-selected="true"]', { timeout: 10000 }); }, }, - // Preferences scrolled to Cleanup once its scan has answered. + // Preferences on the System tab, once the Cleanup scan has answered. cleanup: { workflow: "plan", posts: ["cleanup"], open: async (page) => { await page.click("#btn-looks"); await page.waitForSelector("#looks-modal[open]", { timeout: 10000 }); - await page.locator(".looks-cleanup").scrollIntoViewIfNeeded(); + await page.click("#prefs-tab-system"); await page.click("#cleanup-scan"); await page.waitForFunction(() => document.getElementById("cleanup-status").textContent.trim() !== "", null, { timeout: 15000 }).catch(() => {}); }, diff --git a/scripts/page-test-helpers.mjs b/scripts/page-test-helpers.mjs index ed22096..ca8aeb0 100644 --- a/scripts/page-test-helpers.mjs +++ b/scripts/page-test-helpers.mjs @@ -68,7 +68,15 @@ export async function openSession(browser, { t, workflow, payload: first, projec }; s.wait = (seconds = 10) => { const r = cli(["wait", "--session", s.sid, "--seconds", String(seconds)], { cwd }); - return { code: r.status, ...(r.json || {}) }; + // The wire carries only what an agent reads (reply, hop fields); what the + // person sent whole stays in result.json, which a page test reads from there. + let sent = {}; + if (r.status === 0) { + try { + sent = JSON.parse(fs.readFileSync(path.join(s.session, "result.json"), "utf8")); + } catch {} + } + return { code: r.status, ...sent, ...(r.json || {}) }; }; // Whether the session's server still answers on its port. s.answers = async () => { @@ -83,7 +91,7 @@ export async function openSession(browser, { t, workflow, payload: first, projec s.stop = async () => { if (stopped) return; stopped = true; - cli(["stop", "--session", s.sid], { cwd }); + cli(["stop", "--session", s.sid, "--force"], { cwd }); if (s.context) await s.context.close().catch(() => {}); await until(async () => !(await s.answers()), 5000); }; diff --git a/scripts/screenshots/README.md b/scripts/screenshots/README.md index 31f4e17..0a28ca0 100644 --- a/scripts/screenshots/README.md +++ b/scripts/screenshots/README.md @@ -30,7 +30,7 @@ script refuses `--compare` with an `--out` inside `docs/screenshots/`. | `delete.json` | The dashboard, behind the first step of a spec chip's Delete | | `help.json` | A Plan question, behind Help on its first tab | | `prefs.json` | A Plan question, behind User Preferences | -| `cleanup.json` | A Plan question, behind User Preferences scrolled to Cleanup after a scan | +| `cleanup.json` | A Plan question, behind User Preferences on the System tab after a Cleanup scan | | `workspace.json` | A Plan question, behind the Workspace panel with a second folder added (shot last: the console remembers the folder) | `node scripts/capture-screenshots.mjs --compare --out ` diff --git a/scripts/test-web-console-chat-stress.mjs b/scripts/test-web-console-chat-stress.mjs index ef5eec6..a3f44b7 100644 --- a/scripts/test-web-console-chat-stress.mjs +++ b/scripts/test-web-console-chat-stress.mjs @@ -14,11 +14,13 @@ import { spawn } from "node:child_process"; // is exactly why this lives in its own file. import { STALE_MS } from "../src/web-console/public/answers.js"; import { + ASK_BUSY_MS, CHAT_LAST_WAIT_TEXT, CHAT_LIMIT_TEXT, CHAT_OFFLINE_TEXT, CHAT_WAITING_TEXT, CHAT_WORKING_TEXT, + chatAnswering, chatOffline, chatView, contextOptions, @@ -83,7 +85,7 @@ test("stress: 200 posts interleaved with 200 chat messages lose no message from assert.equal(all.length, 200); assert.equal(new Set(all.map((e) => e.seq)).size, 200, "no seq handed out twice"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -149,7 +151,7 @@ test("the frame reports how far the agent has picked up the chat", async () => { assert.equal(cli(["chat", "--session", s.sid]).status, 0); assert.equal((await chatFrame(s)).pickedUp, body.seq); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -300,13 +302,36 @@ test("chatOffline: finished, paused, a stale working agent (with quietMinutes), assert.equal(chatOffline({ agent: { status: "waiting", quietMinutes: 30 }, ...ago(4 * 60 * 1000) }), true, "quietMinutes only counts while working"); }); +// A message the agent picked up and has not answered yet: the agent is busy +// with it, not gone, even though it has stopped pinging from `wait`. +test("chatAnswering: a picked-up message with no reply after it, and nothing else", () => { + const person = (seq, kind = "message") => ({ from: "person", kind, seq, text: "q" + seq }); + const reply = (re) => ({ from: "agent", id: "r" + re, re, md: "a" }); + assert.equal(chatAnswering(null), false, "no chat at all"); + assert.equal(chatAnswering({ messages: [person(2)], pickedUp: 1 }), false, "sent, not picked up yet"); + assert.equal(chatAnswering({ messages: [person(2)], pickedUp: 2 }), true, "picked up, no reply"); + assert.equal(chatAnswering({ messages: [person(2), reply(2)], pickedUp: 2 }), false, "answered"); + assert.equal(chatAnswering({ messages: [person(2), reply(2), person(3, "decision")], pickedUp: 3 }), true, "an approved edit in hand"); + assert.equal(chatAnswering({ messages: [person(2), reply(2), person(3)], pickedUp: 2 }), false, "a follow-up not picked up yet"); +}); + +test("chatOffline: an Ask message in hand holds off offline for ASK_BUSY_MS, then gives up", () => { + const now = 10 * 60 * 60 * 1000; + const ago = (ms) => ({ agentLastSeenMs: now - ms, now }); + assert.equal(ASK_BUSY_MS, 10 * 60 * 1000); + assert.equal(chatOffline({ agent: { status: "waiting" }, answering: true, ...ago(9 * 60 * 1000) }), false, "busy with the Ask message"); + assert.equal(chatOffline({ agent: { status: "waiting" }, answering: true, ...ago(ASK_BUSY_MS + 1000) }), true, "quiet past the allowance"); + assert.equal(chatOffline({ agent: { status: "working" }, answering: true, ...ago(STALE_MS + 1000) }), false, "a working agent answering is not stale yet"); + assert.equal(chatOffline({ agent: { status: "working", quietMinutes: 20 }, answering: true, ...ago(15 * 60 * 1000) }), false, "a longer quiet allowance still wins"); +}); + // The agent learns the chat from the console's docs and the help text alone, // so every name it has to type (the command, the reply field, the edit fields) // and every refusal the routes can give must actually be written there. test("the console docs, building.md and help teach the Quick question contract", () => { const dir = path.join(ROOT, "src", "web-console"); const consoleMd = consoleDocs(); - for (const word of ["chat --session", "chat.replies", "proposal", "changed", "too-long", "limit", "offline", "stale"]) { + for (const word of ["chat --session", "\"replies\"", "proposal", "changed", "limit", "stale"]) { assert.ok(consoleMd.includes(word), `the console docs must mention ${word}`); } assert.ok(fs.readFileSync(path.join(dir, "building.md"), "utf8").includes("chat --session"), "building.md must mention chat --session"); @@ -320,16 +345,14 @@ test("the console docs, building.md and help teach the Quick question contract", test("the console docs teach the workspace and session meter contract", () => { const consoleMd = consoleDocs(); const buildingMd = consoleDoc("building.md") + consoleDoc("notes/implement.md"); - for (const word of ["workspace", "pendingWorkspace", "folderIssue", "run", "pathfinder-question", "pathfinder-research", "pathfinder-chart", "AGENTS.md", "/add-dir"]) { + for (const word of ["workspace", "folderIssue", "run", "pathfinder-question", "pathfinder-research", "pathfinder-chart", "AGENTS.md", "/add-dir"]) { assert.ok(consoleMd.includes(word), `the console docs must mention ${word}`); } for (const word of ["implement-phase", "implement-review-phase"]) { assert.ok(buildingMd.includes(word), `the build docs must mention ${word}`); } - const section = consoleDoc("console-meter.md").match(/### Session meter\n([\s\S]*?)\n---/); - assert.ok(section, "console-meter.md has a Session meter section"); - const list = section[1].match(/`event` is one of ([\s\S]*?)An unknown event/); - assert.ok(list, "the Session meter section lists the events"); + const list = consoleDoc("console-meter.md").match(/- `event`: ([\s\S]*?)An unknown event/); + assert.ok(list, "console-meter.md lists the events"); const listed = [...list[1].matchAll(/`([a-z-]+)`/g)].map((m) => m[1]); assert.equal(new Set(listed).size, listed.length, "no event is listed twice"); assert.deepEqual([...listed].sort(), Object.keys(WEIGHTS).sort(), "console-meter.md lists exactly the WEIGHTS events"); diff --git a/scripts/test-web-console-chat.mjs b/scripts/test-web-console-chat.mjs index 596f586..670787f 100644 --- a/scripts/test-web-console-chat.mjs +++ b/scripts/test-web-console-chat.mjs @@ -32,37 +32,32 @@ import { /* ------------------------------------------- quick question: the contract */ -// Every outcome `wait` had before the chat channel existed, pinned by exit -// code and by its exact top-level keys. The only change allowed later is the -// chat keys appearing beside them; anything else breaks an agent somewhere. -const CHAT_KEYS = new Set(["chat", "pendingChat"]); -// The workspace channel, allowed beside them the same way. -const WORKSPACE_KEYS = new Set(["workspace", "pendingWorkspace"]); +// Every outcome of wait, pinned by exit code and by its exact top-level keys. +// The agent reads a trimmed line (spec "API Design (outputs)"): what the +// person sent lives in result.json, so those fields are checked there. const pinKeys = (obj, expected, what) => - assert.deepEqual( - Object.keys(obj).filter((k) => !CHAT_KEYS.has(k) && !WORKSPACE_KEYS.has(k)).sort(), - [...expected].sort(), - `${what}: top-level keys changed` - ); -const RESULT_KEYS = ["type", "at", "sid", "rev", "actions", "reply", "consumedAt", "terminalLine"]; -const WAITING_KEYS = ["status", "sid", "elapsed", "answered", "total", "staged", "url", "message", "next", "terminalLine"]; - + assert.deepEqual(Object.keys(obj).filter((k) => k !== "terminalLine").sort(), [...expected].sort(), what + ": top-level keys changed"); +const RESULT_FILE = (s) => JSON.parse(fs.readFileSync(path.join(s.session, "result.json"), "utf8")); test("wait's existing outcomes are pinned: submit, images, waiting, cancel, carried and server gone", async () => { const s = openSession(); try { const waiting = cli(["wait", "--session", s.sid, "--seconds", "5"]); assert.equal(waiting.status, 10); - assert.equal(waiting.json.status, "waiting"); - pinKeys(waiting.json, WAITING_KEYS, "exit 10"); + assert.equal(waiting.json.waiting, true); + assert.equal(waiting.json.open, 1, "the required question still open"); + pinKeys(waiting.json, ["waiting", "open"], "exit 10"); assert.equal((await s.send("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "A" }], reply: "Export format: a" })).status, 200); const sent = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(sent.status, 0); - assert.equal(sent.json.type, "submit"); - pinKeys(sent.json, RESULT_KEYS, "exit 0 submit"); + assert.equal(sent.json.reply, "Export format: a"); + pinKeys(sent.json, ["reply"], "exit 0 submit"); + const kept = RESULT_FILE(s); + for (const k of ["type", "at", "sid", "rev", "actions", "reply", "consumedAt"]) assert.ok(k in kept, "result.json keeps " + k); + assert.equal(kept.type, "submit"); - const up = await fetch(`${s.base}/upload`, { + const up = await fetch(s.base + "/upload", { method: "POST", headers: { "content-type": "image/jpeg", cookie: s.cookie, origin: s.base, connection: "close", "x-p2c-name": "a.png" }, body: JPEG, @@ -74,8 +69,8 @@ test("wait's existing outcomes are pinned: submit, images, waiting, cancel, carr ); const withImages = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(withImages.status, 0); - assert.equal(withImages.json.actions[0].images.length, 1); - pinKeys(withImages.json, RESULT_KEYS, "exit 0 with images"); + pinKeys(withImages.json, ["reply"], "exit 0 with images"); + assert.equal(RESULT_FILE(s).actions[0].images.length, 1, "result.json holds the image"); // Sent before any wait is running: the next wait hands it over at once. assert.equal((await s.send("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }], reply: "Export format: b" })).status, 200); @@ -83,20 +78,21 @@ test("wait's existing outcomes are pinned: submit, images, waiting, cancel, carr const carried = cli(["wait", "--session", s.sid, "--seconds", "30"]); assert.equal(carried.status, 0); assert.ok(Date.now() - t0 < 5000, "an uncollected result is delivered at once"); - pinKeys(carried.json, RESULT_KEYS, "exit 0 carried"); + assert.equal(carried.json.reply, "Export format: b"); + pinKeys(carried.json, ["reply"], "exit 0 carried"); assert.equal((await s.send("/cancel", {})).status, 200); const cancelled = cli(["wait", "--session", s.sid, "--seconds", "5"]); assert.equal(cancelled.status, 30); - assert.equal(cancelled.json.type, "cancel"); - pinKeys(cancelled.json, RESULT_KEYS, "exit 30"); + assert.equal(RESULT_FILE(s).type, "cancel"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } const gone = cli(["wait", "--session", s.sid, "--seconds", "12"]); assert.equal(gone.status, 20); - assert.equal(gone.json.status, "server-gone"); - pinKeys(gone.json, ["status", "sid", "message"], "exit 20"); + assert.equal(gone.json.gone, true); + assert.ok(gone.json.fix.includes(s.sid)); + pinKeys(gone.json, ["gone", "fix"], "exit 20"); }); /* --------------------------------------------- quick question: the channel */ @@ -109,28 +105,27 @@ test("a chat message and a card send can both be pending, in either order, and w assert.equal((await ask(s, "Where does the export live?")).status, 200, "a pending card never blocks a question"); const both = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(both.status, 0); - assert.equal(both.json.type, "submit"); - assert.equal(both.json.actions[0].k, "A"); - assert.ok(both.json.chat.some((e) => e.kind === "message" && e.text === "Where does the export live?")); + assert.equal(both.json.chat.length, 1, "chat travels as the seq numbers a reply needs"); + assert.equal(typeof both.json.chat[0], "number"); assert.match(both.json.reply, /^Export format: a\n/); - assert.match(both.json.reply, /^Quick question: Where does the export live\?$/m); + assert.match(both.json.reply, /^Quick question \(\d+\): Where does the export live\?$/m); assert.equal((await ask(s, "And the header row?")).status, 200); assert.equal((await s.send("/submit", EXPORT_A)).status, 200, "a pending question never blocks a card"); const again = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(again.status, 0); - assert.equal(again.json.type, "submit"); - assert.deepEqual(again.json.chat.map((e) => e.text), ["And the header row?"]); + assert.equal(again.json.chat.length, 1); + assert.match(again.json.reply, /Quick question \(\d+\): And the header row\?/); assert.equal((await ask(s, "Just a question")).status, 200); const chatOnly = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(chatOnly.status, 0); - assert.equal(chatOnly.json.type, "chat"); - assert.deepEqual(chatOnly.json.actions, []); - assert.equal(chatOnly.json.reply, "Quick question: Just a question"); - assert.ok(chatOnly.json.terminalLine); + assert.equal(chatOnly.json.chat.length, 1); + assert.equal(chatOnly.json.reply, "Quick question (" + chatOnly.json.chat[0] + "): Just a question"); + assert.equal(chatOnly.json.type, undefined); + assert.equal(chatOnly.json.actions, undefined); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -156,9 +151,9 @@ test("wait returns within 100 ms of a chat message landing", async () => { const answeredAt = Date.now(); assert.ok((await printed) - answeredAt < 2000, "wait must hand the chat over well inside its 5 s poll"); assert.equal(await exited, 0); - assert.equal(safeJson(out).type, "chat"); + assert.match(safeJson(out).reply, /^Quick question \(\d+\): Quick one$/m); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -171,27 +166,27 @@ test("the chat command answers at once: 0 with entries, 10 with none, 20 when th assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 1, "an uncollected question shows on the heartbeat"); const got = cli(["chat", "--session", s.sid]); assert.equal(got.status, 0); - assert.ok(got.json.chat.some((e) => e.text === "Mid-build question")); - assert.match(got.json.reply, /Quick question: Mid-build question/); - assert.ok(got.json.terminalLine); + assert.equal(got.json.chat.length, 1); + assert.match(got.json.reply, /Quick question \(\d+\): Mid-build question/); const onDisk = JSON.parse(fs.readFileSync(path.join(s.session, "result.json"), "utf8")); assert.equal(onDisk.consumedAt, undefined, "the card send is still waiting for wait"); assert.equal((await (await s.send("/ping", {})).json()).pendingChat, 0); const none = cli(["chat", "--session", s.sid]); assert.equal(none.status, 10); - assert.deepEqual(none.json, { chat: [] }); + assert.deepEqual(none.json, {}); const card = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(card.status, 0); - assert.equal(card.json.type, "submit"); - assert.deepEqual(card.json.chat, [], "the chat went with the chat command, not twice"); + assert.match(card.json.reply, /^Export format: a/); + assert.equal(card.json.chat, undefined, "the chat went with the chat command, not twice"); + assert.ok(!card.json.reply.includes("Mid-build question")); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } const gone = cli(["chat", "--session", s.sid]); assert.equal(gone.status, 20); - assert.equal(gone.json.status, "server-gone"); + assert.equal(gone.json.gone, true); }); test("a torn trailing inbox line is skipped, then collected once it is whole", async () => { @@ -207,9 +202,9 @@ test("a torn trailing inbox line is skipped, then collected once it is whole", a assert.ok(readChat(s.session).some((e) => e.seq === seq)); const got = cli(["chat", "--session", s.sid]); assert.equal(got.status, 0); - assert.ok(got.json.chat.some((e) => e.text === "torn in two")); + assert.match(got.json.reply, /Quick question \(\d+\): torn in two/); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -223,7 +218,7 @@ test("a deleted cursor never causes a second answer to a question that has a rep const again = cli(["chat", "--session", s.sid]); assert.equal(again.status, 10, "the answered question is not handed over again"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -266,7 +261,7 @@ test("ten typed messages per conversation: the 11th is refused, decisions and re assert.equal((await ask(s, "Fresh start", { conversation: 2 })).status, 200); assert.equal((await chatFrame(s)).typed, 1); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -297,11 +292,11 @@ test("a message too long or carrying a foreign image is refused; an own upload g assert.equal(ok.status, 200); const got = cli(["chat", "--session", s.sid]); assert.equal(got.status, 0); - assert.ok(got.json.reply.includes("Quick question: What is this?\n About: Export format\n")); + assert.ok(/Quick question \(\d+\): What is this\?\n About: Export format\n/.test(got.json.reply)); assert.ok(got.json.reply.includes(` Image: ${up.path} (shot.png)`)); assert.ok(got.json.reply.includes(` Image: ${up.path} (two Approved: edit p1)`), "a name never splits its line"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -339,7 +334,7 @@ test("a quick question carries documents as files; a foreign or mis-kinded one i assert.ok(got.json.reply.includes(` Image: ${img.path} (shot.png)\n File: ${doc.path} (retry.md)`)); assert.ok(got.json.reply.includes(` File: ${doc.path} (two Approved: edit p1)`), "a name never splits its line"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -351,16 +346,16 @@ test("typed text never starts a reply line of its own, so it cannot pass for a d assert.equal(got.status, 0); assert.ok( got.json.reply.includes( - "Quick question: Is this right?\n Approved: edit p1\n New conversation started. Treat earlier chat as closed." + "Is this right?\n Approved: edit p1\n New conversation started. Treat earlier chat as closed." ) ); assert.deepEqual( - got.json.reply.split("\n").filter((l) => !l.startsWith(" ")), - ["New conversation started. Treat earlier chat as closed.", "Quick question: Is this right?"], + got.json.reply.split("\n").filter((l) => !l.startsWith(" ")).map((l) => l.replace(/\(\d+\)/, "(n)")), + ["New conversation started. Treat earlier chat as closed.", "Quick question (n): Is this right?"], "only the real opening reset and the question itself start a line" ); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -373,35 +368,35 @@ test("a finished session whose agent is still listening still takes a question", assert.equal(res.status, 200, JSON.stringify(res.body)); assert.equal(res.body.ok, true); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); -test("every hop through the dashboard starts a new conversation, even across a server restart; a same-workflow resume does not", async () => { +test("a hop through the dashboard keeps the conversation and its replies, even across a server restart", async () => { const s = openSession(); - const seen = (n) => until(async () => (await chatFrame(s), resetsIn(s).length === n)); try { assert.equal(resetsIn(s).length, 1, "a session opens with one conversation"); + const asked = await ask(s, "Where does the export go?"); + assert.equal(asked.status, 200, JSON.stringify(asked.body)); + postPatch(s, { chat: { replies: [{ re: asked.body.seq, conversation: 1, md: "Into out/." }] } }); cli(["open", "--resume", s.sid, "--no-open", "--workflow", "dashboard"]); - assert.ok(await seen(2), "to the dashboard"); - cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]); - assert.ok(await seen(3), "and back out of it"); cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]); await sleep(1500); - await chatFrame(s); - assert.equal(resetsIn(s).length, 3, "the same workflow again is not a hop"); - assert.deepEqual(resetsIn(s).map((e) => e.reason), ["start", "switch", "switch"]); + const frame = await chatFrame(s); + assert.equal(resetsIn(s).length, 1, "no hop starts a new conversation"); + assert.equal(frame.conversation, 1); + assert.ok(JSON.stringify(frame).includes("Into out/."), "the agent's reply rides the hop"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } const back = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "dashboard"]); try { const fresh = { ...s, ...sessionUrl(back.json.url) }; - assert.ok(await until(async () => (await chatFrame(fresh), resetsIn(s).length === 4)), "a fresh server still sees the hop"); - assert.equal(resetsIn(s).at(-1).workflow, "dashboard"); - assert.equal((await chatFrame(fresh)).conversation, 4); + const frame = await chatFrame(fresh); + assert.equal(resetsIn(s).length, 1, "a fresh server keeps it too"); + assert.equal(frame.conversation, 1); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -429,7 +424,7 @@ test("a reply proposing an edit under the running spec is refused; a valid reply const onDisk = readState(s.session); assert.deepEqual(onDisk.chat.replies.map((r) => r.id), ["r1"], "nothing was written"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -437,12 +432,48 @@ test("a reply proposing an edit under the running spec is refused; a valid reply // fenced block, so the agent has to be told when and how to write one. test("console-chat.md teaches the prompt block: when, what it holds, and not to open it with a command word", () => { const text = fs.readFileSync(path.join(ROOT, "src", "web-console", "console-chat.md"), "utf8"); - const section = text.split(/^## /m).find((s) => s.startsWith("Prompts to carry away")); - assert.ok(section, "console-chat.md has no 'Prompts to carry away' section"); + const section = text.split(/^## /m).find((s) => s.startsWith("A prompt to carry away")); + assert.ok(section, "console-chat.md has no 'A prompt to carry away' section"); assert.match(section, /fenced block/); assert.match(section, /Copy/); - assert.match(section, /paste it into the Ask tab/); + assert.match(section, /paste into the Ask tab/); assert.match(section, /out of scope/); assert.match(section, /files to read/); assert.doesNotMatch(section, /\u2014/, "no em dash in the section"); }); + +/* ------------------------------------- quick question: arrives once (FR-18) */ + +test("a Quick question arrives once: a numbered reply line, the seq in chat, no full entries, and a reply with re clears the warning", async () => { + const s = openSession(); + try { + const asked = await ask(s, "Where does the export live?"); + assert.equal(asked.status, 200); + const seq = asked.body.seq; + const got = cli(["wait", "--session", s.sid, "--seconds", "10"]); + assert.equal(got.status, 0); + assert.ok(got.json.reply.endsWith(`Quick question (${seq}): Where does the export live?`), "the numbered line"); + assert.equal(got.json.reply.split("\n").filter((l) => l.startsWith("Quick question")).length, 1); + assert.deepEqual(got.json.chat, [seq], "chat is the seq numbers a reply needs"); + assert.deepEqual(Object.keys(got.json).filter((k) => !["read", "terminalLine"].includes(k)).sort(), ["chat", "reply"], "no full chat entries or old fields"); + assert.equal(got.stdout.split(`Where does the export live?`).length - 1, 1, "the question text appears once in the output"); + + // Handed over and not answered: the next slice warns, naming the seq. + const waiting = cli(["wait", "--session", s.sid, "--seconds", "5"]); + assert.equal(waiting.status, 10); + assert.deepEqual(waiting.json.unansweredChat, [seq]); + assert.match(waiting.json.warning, new RegExp(`Quick questions ${seq} have no reply yet`)); + + // A reply with re: still validates and clears the warning. + assert.equal(postPatch(s, { chat: { replies: [{ re: seq, conversation: 1, md: "In out/." }] } }).status, 0); + const after = cli(["wait", "--session", s.sid, "--seconds", "5"]); + assert.equal(after.status, 10); + assert.equal(after.json.unansweredChat, undefined); + assert.equal(after.json.warning, undefined); + + // It is not handed over a second time. + assert.equal(cli(["chat", "--session", s.sid]).status, 10); + } finally { + cli(["stop", "--session", s.sid, "--force"]); + } +}); diff --git a/scripts/test-web-console-concurrency.mjs b/scripts/test-web-console-concurrency.mjs index 4452e98..be15d5b 100644 --- a/scripts/test-web-console-concurrency.mjs +++ b/scripts/test-web-console-concurrency.mjs @@ -65,7 +65,7 @@ test("helpers: a dashboard hop clears them, a same-workflow or paused resume kee cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]); assert.equal("helpers" in readState(s.session), false, "and the hop back brings none"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -85,7 +85,7 @@ test("meter: a repeated run counts once, a bad one appends nothing, and neither assert.match(unknown.stderr, /run: unknown event "nap"/); const noId = postPatch(s, { run: { event: "plan" } }, { expectFail: true }); assert.equal(noId.status, 3); - assert.match(noId.stderr, /run: id required/); + assert.match(noId.stderr, /run: needs an id/); const badTasks = postPatch(s, { run: { event: "implement-phase", id: "phase-1", tasks: 0 } }, { expectFail: true }); assert.equal(badTasks.status, 3); assert.match(badTasks.stderr, /run: tasks must be a whole number/); @@ -108,7 +108,7 @@ test("meter: a repeated run counts once, a bad one appends nothing, and neither assert.equal("run" in state, false); assert.equal("folderIssue" in state, false); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -132,7 +132,7 @@ test("meter: open --file takes run and folderIssue as post does, scoped to the n assert.equal("run" in state, false); assert.equal("folderIssue" in state, false); } finally { - cli(["stop", "--session", good.json.sid]); + cli(["stop", "--session", good.json.sid, "--force"]); } const bad = cli(["open", "--no-open", "--file", payload("open-run-bad.json", { run: { event: "nap", id: "x" } })], { expectFail: true }); assert.equal(bad.status, 3); @@ -151,7 +151,7 @@ test("meter: a folder issue shows in the frame's workspace.issues until the next cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]); assert.deepEqual((await s.get("/workspace")).issues, [], "a new skill run starts clean"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -182,8 +182,8 @@ test("two sessions keep their own cookies: each server reads only the one named const crossed = b.cookie.replace(/^p2c_console_\d+/, `p2c_console_${new URL(a.base).port}`); assert.equal((await fetch(`${a.base}/state`, { headers: { cookie: crossed, connection: "close" } })).status, 403); } finally { - cli(["stop", "--session", a.sid]); - cli(["stop", "--session", b.sid]); + cli(["stop", "--session", a.sid, "--force"]); + cli(["stop", "--session", b.sid, "--force"]); } }); @@ -222,7 +222,7 @@ test("a post and a submit that overlap both survive: the state lock serializes t assert.equal(fs.existsSync(lock), false, "and the lock is let go"); assert.equal(cli(["wait", "--session", s.sid, "--seconds", "5"]).status, 0); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -237,7 +237,7 @@ test("a lock left by a writer that died is broken rather than waited on for good assert.equal(readState(s.session).agent.status, "working"); assert.equal(fs.existsSync(lock), false); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -256,7 +256,7 @@ test("stop never kills a live process that does not answer /health as ours", () forged, JSON.stringify({ v: 1, sid: sidForged, pid: bystander.pid, port: 1, url: "http://127.0.0.1:1/", startedAt: new Date().toISOString() }) ); - const res = cli(["stop", "--session", sidForged]); + const res = cli(["stop", "--session", sidForged, "--force"]); assert.equal(res.json.stopped, 0); assert.equal(res.json.skippedStaleHandles, 1); assert.equal(fs.existsSync(forged), false, "the handle goes"); @@ -285,11 +285,10 @@ test("open from a linked worktree seeds the workspace with the worktree, not the try { const res = cliIn(wt, ["open", "--workflow", "plan", "--no-open"]); sidOpened = res.json.sid; - assert.deepEqual(res.json.workspace.folders.map((f) => f.path), [worktree]); const onDisk = JSON.parse(fs.readFileSync(path.join(res.json.session, WORKSPACE_FILE), "utf8")); assert.deepEqual(onDisk.folders.map((f) => f.path), [worktree], "workspace.json names the worktree"); } finally { - if (sidOpened) cliIn(wt, ["stop", "--session", sidOpened]); + if (sidOpened) cliIn(wt, ["stop", "--session", sidOpened, "--force"]); // A stopped server can take a while to let go of its working directory on // Windows, and longer while other test files load the machine: under a // full-suite run this needed more than the 5s a 20x250ms retry gave it. @@ -302,8 +301,8 @@ test("open from a linked worktree seeds the workspace with the worktree, not the test("validate refuses a text pattern that does not compile, and post exits 3 on it", () => { const item = (pattern) => ({ items: [{ id: "t1", kind: "text", title: "Ticket number", pattern }] }); assert.deepEqual(validate(item("^[A-Z]+-\\d+$")), []); - assert.match(validate(item("([")).join("\n"), /"pattern" is not a valid JavaScript regular expression/); - assert.match(validate(item(7)).join("\n"), /"pattern" must be a string/); + assert.match(validate(item("([")).join("\n"), /pattern: is not a valid JavaScript regular expression/); + assert.match(validate(item(7)).join("\n"), /pattern: must be a string/); const s = openSession(); try { @@ -313,7 +312,7 @@ test("validate refuses a text pattern that does not compile, and post exits 3 on assert.match(bad.stderr, /pattern/); assert.equal(fs.readFileSync(path.join(s.session, "state.json"), "utf8"), before, "nothing was written"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -342,7 +341,7 @@ test("wait reads --seconds 6s as six seconds, not as nothing", () => { assert.equal(res.status, 10); assert.ok(Date.now() - t0 >= 5000, "the slice ran its length"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -359,7 +358,7 @@ test("only open leaves the console-dir pointer; status, help and a bad command d assert.equal(fs.existsSync(pointer), false); const opened = cli(["open", "--no-open"], { env }); assert.equal(fs.readFileSync(pointer, "utf8").trim(), path.join(ROOT, "src", "web-console")); - cli(["stop", "--session", opened.json.sid], { env }); + cli(["stop", "--session", opened.json.sid, "--force"], { env }); } finally { fs.rmSync(home, { recursive: true, force: true }); } @@ -424,7 +423,7 @@ test("every state-changing route refuses a foreign Origin, and nothing changes", assert.equal(own.status, 200); assert.deepEqual(await own.json(), { path: picked }); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(picked, { recursive: true, force: true }); } }); diff --git a/scripts/test-web-console-git-board.mjs b/scripts/test-web-console-git-board.mjs index 4084efa..7d6eed4 100644 --- a/scripts/test-web-console-git-board.mjs +++ b/scripts/test-web-console-git-board.mjs @@ -517,7 +517,7 @@ test("git board host: the host draws the board only through drawGitBoard, and th test("git board docs: the agent prose, Help topic and readme describe the tabbed board", () => { const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8"); const notes = read("../src/web-console/notes/git.md"); - const finishing = notes.slice(notes.indexOf("**Finishing**")); + const finishing = notes.slice(notes.indexOf("**Finishing")); assert.ok(finishing.includes("Done with git"), "notes/git.md Finishing names Done with git"); assert.ok(finishing.includes("cancel"), "notes/git.md Finishing cancels an open card"); assert.ok(!finishing.includes('"settle": [""]'), "the cancel rule never settles a card nothing was sent to"); diff --git a/scripts/test-web-console-git.mjs b/scripts/test-web-console-git.mjs index 1dec270..6085a57 100644 --- a/scripts/test-web-console-git.mjs +++ b/scripts/test-web-console-git.mjs @@ -18,7 +18,7 @@ import { resumeCommand, SKILL_CATALOG, } from "../src/web-console/public/answers.js"; -import { SKILLS } from "../src/web-console/public/skills.js"; +import { FLOW_SKILLS as SKILLS } from "../src/web-console/public/skills.js"; import { breakdownFrom, pointsFrom } from "../src/web-console/public/meter.js"; import { BRANCH_TYPES, @@ -107,10 +107,10 @@ test("git: open --workflow git writes state.git, and a dashboard open writes non assert.equal(git.repo, true); assert.equal(git.head.branch, "main"); assert.equal(git.refreshFailed, false); - r.cli(["stop", "--session", opened.json.sid]); + r.cli(["stop", "--session", opened.json.sid, "--force"]); const dash = r.open("--workflow", "dashboard"); assert.equal("git" in readState(dash.json.session), false, "the dashboard gets a scan, not a board"); - r.cli(["stop", "--session", dash.json.sid]); + r.cli(["stop", "--session", dash.json.sid, "--force"]); } finally { r.cleanup(); } @@ -131,7 +131,7 @@ test("git: a reread post lands the card and a fresh state.git in one write", () assert.equal(after.git.head.ahead, 1, "and the board moved with it"); assert.ok(Date.parse(after.git.at) >= Date.parse(first.at)); assert.equal("reread" in after, false, "reread never reaches the state"); - r.cli(["stop", "--session", sid]); + r.cli(["stop", "--session", sid, "--force"]); } finally { r.cleanup(); } @@ -155,7 +155,7 @@ test("git: refreshFailed is set by the agent and cleared by a newer FETCH_HEAD", assert.equal(readState(session).git.refreshFailed, false, "a newer FETCH_HEAD clears it"); r.cli(["open", "--resume", sid, "--no-open", "--file", payload("git-open-fail.json", { reread: { refreshFailed: true } })]); assert.equal(readState(session).git.refreshFailed, true, "open --file carries the agent's flag too"); - r.cli(["stop", "--session", sid]); + r.cli(["stop", "--session", sid, "--force"]); } finally { r.cleanup(); } @@ -168,20 +168,20 @@ test("git: reread is refused off the git workflow or malformed, and a patch neve const before = fs.readFileSync(path.join(plan.session, "state.json"), "utf8"); const off = r.cli(["post", "--session", plan.sid, "--file", payload("git-off.json", { reread: true, items: [gitCard] })]); assert.equal(off.status, 3); - assert.match(off.stderr, /reread only goes with the git workflow/); + assert.match(off.stderr, /reread: only goes with the git workflow/); assert.equal(fs.readFileSync(path.join(plan.session, "state.json"), "utf8"), before, "the state is unchanged"); - r.cli(["stop", "--session", plan.sid]); + r.cli(["stop", "--session", plan.sid, "--force"]); const { sid } = r.open("--workflow", "git").json; for (const bad of ["yes", { refreshFailed: "no" }, { refreshFailed: true, extra: 1 }, [], false]) { const res = r.cli(["post", "--session", sid, "--file", payload("git-bad.json", { reread: bad })]); assert.equal(res.status, 3, JSON.stringify(bad)); - assert.match(res.stderr, /reread must be true or \{ refreshFailed: true\|false \}/); + assert.match(res.stderr, /reread: must be true or \{ refreshFailed: true\|false \}/); } const own = r.cli(["post", "--session", sid, "--file", payload("git-own.json", { git: { repo: true } })]); assert.equal(own.status, 3); - assert.match(own.stderr, /state\.git is the console's own: post reread instead/); - r.cli(["stop", "--session", sid]); + assert.match(own.stderr, /git: is the console's own state; post reread instead/); + r.cli(["stop", "--session", sid, "--force"]); } finally { r.cleanup(); } @@ -206,7 +206,7 @@ test("git: resuming into Git hops like a dashboard launch, and leaving for the d assert.equal(board.git.head.branch, "main", "and the board has its data"); r.cli(["open", "--resume", qt.sid, "--no-open", "--workflow", "dashboard"]); assert.equal("git" in readState(qt.session), false, "the dashboard does not keep the old board"); - r.cli(["stop", "--session", qt.sid]); + r.cli(["stop", "--session", qt.sid, "--force"]); } finally { r.cleanup(); } @@ -227,7 +227,7 @@ test("git: POST /pr-host saves to pr-hosts.json and refuses a bad kind or a non- const notGit = await sendTo(sessionUrl(plan.url), { host: "git.example.com", kind: "gitlab" }); assert.equal(notGit.status, 400); assert.equal((await notGit.json()).error, "not-git"); - r.cli(["stop", "--session", plan.sid]); + r.cli(["stop", "--session", plan.sid, "--force"]); const g = r.open("--workflow", "git").json; const gs = sessionUrl(g.url); @@ -237,7 +237,7 @@ test("git: POST /pr-host saves to pr-hosts.json and refuses a bad kind or a non- assert.deepEqual(JSON.parse(fs.readFileSync(store, "utf8")), { "git.example.com": "gitlab" }, "saved lowercased, as it is looked up"); assert.equal(fs.existsSync(path.join(r.repo, "pr-hosts.json")), false, "nothing under the project"); assert.ok(PROTECTED_CONSOLE_FILES.has("pr-hosts.json"), "Cleanup never removes it"); - r.cli(["stop", "--session", g.sid]); + r.cli(["stop", "--session", g.sid, "--force"]); } finally { fs.rmSync(store, { force: true }); r.cleanup(); @@ -275,7 +275,7 @@ test("git: commits on a run go only with git-commits, as a whole number", () => const ok = r.cli(["post", "--session", sid, "--file", payload("git-c3.json", { run: { event: "git-commits", id: "z", commits: 2 } })]); assert.equal(ok.status, 0, ok.stderr); assert.ok(readLedger(session).some((e) => e.event === "git-commits" && e.commits === 2), "the count rides on the ledger line"); - r.cli(["stop", "--session", sid]); + r.cli(["stop", "--session", sid, "--force"]); } finally { r.cleanup(); } @@ -590,11 +590,11 @@ test("git: a board action round-trips as one __git action with its fields intact ); const res = r.cli(["wait", "--session", opened.sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.deepEqual(res.json.actions, [{ i: "__git", type: "git", op: "switch", branch: "main" }]); + assert.deepEqual(res.json.session, [{ i: "__git", op: "switch", branch: "main" }]); assert.equal(res.json.reply, "Switch to main."); const state = readState(opened.session); assert.ok(state.items.every((i) => i.id !== "__git"), "a board action must not become a question"); - r.cli(["stop", "--session", opened.sid]); + r.cli(["stop", "--session", opened.sid, "--force"]); } finally { r.cleanup(); } @@ -608,7 +608,7 @@ test("git: a board.describe post lands in state for the Create panel to read", a const opened = r.open("--workflow", "git").json; r.cli(["post", "--session", opened.sid, "--file", payload("board-describe.json", { board: { describe: "retry the push" } })]); assert.equal(readState(opened.session).board.describe, "retry the push"); - r.cli(["stop", "--session", opened.sid]); + r.cli(["stop", "--session", opened.sid, "--force"]); } finally { r.cleanup(); } diff --git a/scripts/test-web-console-handoffs.mjs b/scripts/test-web-console-handoffs.mjs index cf7fd85..122b99b 100644 --- a/scripts/test-web-console-handoffs.mjs +++ b/scripts/test-web-console-handoffs.mjs @@ -388,7 +388,7 @@ async function withDashboard(fn) { try { return await fn({ sid: opened.json.sid, session: opened.json.session, get }); } finally { - run(["stop", "--session", opened.json.sid]); + run(["stop", "--session", opened.json.sid, "--force"]); } } @@ -411,7 +411,7 @@ test("a dashboard open scans this checkout's handoffs and the folder; other work try { assert.equal(readStateOf(quick.json.session).scan, undefined, "no scan, so no handoffs, off the dashboard"); } finally { - run(["stop", "--session", quick.json.sid]); + run(["stop", "--session", quick.json.sid, "--force"]); } } finally { fresh(); @@ -472,7 +472,7 @@ test("a __pickup round trip prints the hop, marks the handoff used, and the next assert.equal(back.status, 0, back.stderr); assert.deepEqual(readStateOf(opened.json.session).scan.handoffs, [], "a used handoff is no longer listed"); } finally { - run(["stop", "--session", opened.json.sid]); + run(["stop", "--session", opened.json.sid, "--force"]); } } finally { fresh(); @@ -495,12 +495,12 @@ test("a __delete with a handoff round-trips like a spec delete: no resume, no sk assert.equal(res.status, 200); const got = run(["wait", "--session", opened.json.sid, "--seconds", "10"]); assert.equal(got.status, 0, got.stderr); - assert.equal(got.json.actions[0].handoff, made.id); + assert.equal(got.json.session[0].handoff, made.id); assert.equal(got.json.resume, undefined); assert.equal(got.json.skillFile, undefined); assert.equal(got.json.handoffFile, undefined); } finally { - run(["stop", "--session", opened.json.sid]); + run(["stop", "--session", opened.json.sid, "--force"]); } } finally { fresh(); diff --git a/scripts/test-web-console-hardening.mjs b/scripts/test-web-console-hardening.mjs index c3f4579..93e9c44 100644 --- a/scripts/test-web-console-hardening.mjs +++ b/scripts/test-web-console-hardening.mjs @@ -29,7 +29,7 @@ test("another console's cookie beside ours does not lock this one out", async () assert.equal(legacy.status, 403); await legacy.arrayBuffer(); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -145,7 +145,7 @@ test("a cancel that could not be written answers 500 and tells nobody", async () fs.rmSync(blocker, { recursive: true, force: true }); assert.equal((await s.send("/cancel", {})).status, 200, "and once it can land, it does"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -158,7 +158,7 @@ test("wait refuses a --seconds that is not a number instead of spinning", () => assert.match(res.stderr, /--seconds must be a number/); } } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -223,6 +223,6 @@ test("an image block outside the session's shots folder, or not an image, is ref assert.equal(res.status, 3); assert.match(res.stderr, /cannot also carry "md" or "file"/); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); diff --git a/scripts/test-web-console-in-app.mjs b/scripts/test-web-console-in-app.mjs index fa88f6d..951aca8 100644 --- a/scripts/test-web-console-in-app.mjs +++ b/scripts/test-web-console-in-app.mjs @@ -112,7 +112,6 @@ test("under the app, open reuses the app's session, announces the page and launc }); assert.equal(res.status, 0); assert.equal(res.json.sid, appSid, "the window's own session is reused, not a second console"); - assert.equal(res.json.reused, true); assert.equal(res.json.inApp, true); assert.equal(res.json.announced, true); assert.equal(app.seen.length, 1); @@ -123,7 +122,7 @@ test("under the app, open reuses the app's session, announces the page and launc assert.deepEqual(browser.calls(), [], "no browser is launched under the app"); } finally { app.close(); - cli(["stop", "--session", appSid], { cwd, expectFail: true }); + cli(["stop", "--session", appSid, "--force"], { cwd, expectFail: true }); } }); @@ -140,7 +139,7 @@ test("under the app, a hop on the app's session keeps the same url and reports t assert.equal(app.seen[0].workflow, "pathfinder"); } finally { app.close(); - cli(["stop", "--session", first.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", first.json.sid, "--force"], { cwd, expectFail: true }); } }); @@ -167,7 +166,7 @@ test("under the app, a wrong token is reported and the page is not sent to a bro assert.deepEqual(browser.calls(), []); } finally { app.close(); - cli(["stop", "--session", first.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", first.json.sid, "--force"], { cwd, expectFail: true }); } }); @@ -182,7 +181,7 @@ test("under the app, a session that is gone gets a fresh one and its address ann assert.equal(res.status, 0); assert.notEqual(res.json.sid, "20200101-000000-nothere"); assert.equal(app.seen[0].url, res.json.url); - cli(["stop", "--session", res.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); } finally { app.close(); } @@ -204,8 +203,8 @@ test("two app windows never receive each other's pages", async () => { } finally { appA.close(); appB.close(); - cli(["stop", "--session", a.json.sid], { cwd: cwdA, expectFail: true }); - cli(["stop", "--session", b.json.sid], { cwd: cwdB, expectFail: true }); + cli(["stop", "--session", a.json.sid, "--force"], { cwd: cwdA, expectFail: true }); + cli(["stop", "--session", b.json.sid, "--force"], { cwd: cwdB, expectFail: true }); } }); @@ -225,7 +224,7 @@ test("without the signal, open still launches the browser and reports nothing ab assert.ok(calls.length >= 1, "the browser command ran"); assert.match(calls[0], /^http:\/\/127\.0\.0\.1:\d+\/s\//); } finally { - cli(["stop", "--session", res.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); } }); @@ -243,8 +242,8 @@ test("the window's session, not the environment's, decides what open resumes", a assert.equal(app.seen[0].sid, live.json.sid); } finally { app.close(); - cli(["stop", "--session", stale.json.sid], { cwd, expectFail: true }); - cli(["stop", "--session", live.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", stale.json.sid, "--force"], { cwd, expectFail: true }); + cli(["stop", "--session", live.json.sid, "--force"], { cwd, expectFail: true }); } }); @@ -264,7 +263,7 @@ test("with nothing shown in the window yet, open makes the first session and ann assert.equal(app.seen[0].url, res.json.url); await new Promise((r) => setTimeout(r, 700)); assert.deepEqual(browser.calls(), [], "the first page goes to the app too, not a browser"); - cli(["stop", "--session", res.json.sid], { cwd, expectFail: true }); + cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); } finally { app.close(); } @@ -324,10 +323,12 @@ test("the Desktop app group shows only in the app's frame, reflects the app's sa const browser = await pages.browser(); const plain = await openSession(browser, { t, workflow: "implement", payload: ASKING }); await plain.page.locator("#btn-looks").click(); + await plain.page.locator("#prefs-tab-system").click(); assert.equal(await plain.page.locator("#looks-desktop").isVisible(), false, "not in a browser tab"); const s = await openSession(browser, { t, workflow: "implement", payload: ASKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME }); await s.page.locator("#btn-looks").click(); + await s.page.locator("#prefs-tab-system").click(); const box = s.page.locator("#looks-taskbar"); assert.ok(await s.page.locator("#looks-desktop").isVisible(), "shown inside the app"); assert.ok(await box.isChecked(), "on until the app says otherwise"); @@ -352,3 +353,21 @@ test("the Desktop app group shows only in the app's frame, reflects the app's sa await box.check(); assert.deepEqual(await toApp(s, "taskbar"), [{ plan2code: "taskbar", on: true }], "a named request with one boolean"); }); + +test("framed, an Activities game in full screen asks the app for the whole screen, and gives it back on F, Esc and a new question", async (t) => { + const s = await openSession(await pages.browser(), { t, workflow: "plan", payload: { agent: { status: "working", activity: "Reading" } }, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME }); + await s.page.click("#btn-activities"); + await s.page.locator('.activities-card[data-activity="snake"]').click(); + await s.page.locator("#activities-board").waitFor(); + const told = async () => (await toApp(s, "activities-full")).map((m) => m.on); + await s.page.keyboard.press("f"); + assert.deepEqual(await told(), [true], "a named request with one boolean"); + await s.page.keyboard.press("f"); + await s.page.keyboard.press("f"); + await s.page.keyboard.press("Escape"); + assert.deepEqual(await told(), [true, false, true, false], "F and Esc each give it back"); + await s.page.keyboard.press("f"); + s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: "Who opens the export?" }], agent: { status: "waiting" } }); + await until(async () => (await told()).at(-1) === false, 5000); + assert.deepEqual(await told(), [true, false, true, false, true, false], "and so does a new question"); +}); diff --git a/scripts/test-web-console-lifecycle.mjs b/scripts/test-web-console-lifecycle.mjs index 177ec16..ba9b0cb 100644 --- a/scripts/test-web-console-lifecycle.mjs +++ b/scripts/test-web-console-lifecycle.mjs @@ -29,6 +29,7 @@ import { cookieFor, cli, payload, + stopSession, BASE, backdate, readState, @@ -147,7 +148,7 @@ test("open --resume never discards an uncollected result", async () => { test("open clears a result that was already collected", () => { const before = cli(["open", "--resume", sid, "--no-open"]); - assert.equal(before.json.pendingResult, false); + assert.ok(!before.json.pendingResult, "open prints pendingResult only when true"); const res = cli(["wait", "--session", sid, "--seconds", "3"]); assert.equal(res.status, 10, "a consumed result must not be handed over again"); }); @@ -186,6 +187,68 @@ test("open --resume takes a pause down, and only a pause", () => { cli(["post", "--session", sid, "--file", payload("fin-clear.json", { finish: null })]); }); +// Continue here on a finished screen resumes into the SAME skill (Pathfinder +// into Pathfinder), which is no hop. The old ending must still come down, or +// its card freezes every question the new run asks. A question posted over a +// standing ending clears it too, for an agent that forgot `finish: null`. +test("a launch resume and a new question both take a real ending down", () => { + const stateFile = path.join(session, "state.json"); + const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8")); + const wf = readState().workflow; + + cli(["post", "--session", sid, "--file", payload("fin-launch.json", { + finish: { headline: "The map is charted", command: "/plan2code-0-pathfinder", dashboard: true }, + })]); + cli(["open", "--resume", sid, "--no-open", "--workflow", wf]); + assert.equal(readState().finish, undefined, "a launch resume into the same skill clears the ending"); + + cli(["post", "--session", sid, "--file", payload("fin-ask.json", { + finish: { headline: "The map is charted", command: "/plan2code-0-pathfinder" }, + })]); + cli(["post", "--session", sid, "--file", payload("ask-over-fin.json", { + items: [{ id: "q-over-fin", kind: "text", title: "Next thing", body: "Asked after the ending." }], + })]); + assert.equal(readState().finish, undefined, "a new open question clears a standing ending"); + + // A patch that posts its own finish, even with items, keeps it. + cli(["post", "--session", sid, "--file", payload("fin-with-item.json", { + items: [{ id: "q-with-fin", kind: "notice", title: "Heads up", body: "Read only." }], + finish: { headline: "All done", command: "/plan2code-0-pathfinder" }, + })]); + assert.equal(readState().finish.headline, "All done", "a patch's own finish stays"); + + // Leave the session the way later tests expect to find it. + cli(["post", "--session", sid, "--file", payload("fin-clear2.json", { finish: null })]); +}); + +// A new question posted under an answered card's id used to merge into the +// old card and stay answered, leaving the person a dead page. It is refused +// with the fix named; a typo fix on the same title still goes through. +test("a new question under an answered id is refused, a typo fix is not", () => { + const stateFile = path.join(session, "state.json"); + const readState = () => JSON.parse(fs.readFileSync(stateFile, "utf8")); + cli(["post", "--session", sid, "--file", payload("reuse-a.json", { + items: [{ id: "q-reuse", kind: "choice", title: "Pick one", body: "Which?", options: [{ text: "A" }, { text: "B" }] }], + })]); + cli(["post", "--session", sid, "--file", payload("reuse-b.json", { items: [{ id: "q-reuse", status: "answered", answer: { k: "A" } }] })]); + + const typo = cli(["post", "--session", sid, "--file", payload("reuse-typo.json", { items: [{ id: "q-reuse", title: "Pick one", body: "Which one?" }] })]); + assert.equal(typo.status, 0, "a body fix under the same title is allowed"); + assert.equal(readState().items.find((i) => i.id === "q-reuse").status, "answered"); + + const reuse = cli(["post", "--session", sid, "--file", payload("reuse-new.json", { + items: [{ id: "q-reuse", kind: "choice", title: "Something else", body: "A different question", options: [{ text: "X" }, { text: "Y" }] }], + })], { expectFail: true }); + assert.equal(reuse.status, 3, "a new question under an old id is refused"); + assert.match(reuse.stderr, /already used for the answered question "Pick one"/); + assert.match(reuse.stderr, /new id/); + + const reopened = cli(["post", "--session", sid, "--file", payload("reuse-reopen.json", { + items: [{ id: "q-reuse", status: "reopened", title: "Something else", body: "A different question" }], + })]); + assert.equal(reopened.status, 0, "an explicit reopen is allowed"); +}); + // The dashboard hands its live session to the skill it launched: one // `open --resume` turns the page (workflow, title, spec) while reusing the // server. If the flags did not apply on resume, the launched skill would @@ -199,7 +262,7 @@ test("open --resume restates workflow, title and spec on the live session", () = const res = cli(["open", "--resume", sid, "--no-open", "--workflow", "implement", "--title", "Lunch vote: Phase 2", "--spec", "specs/lunch-vote"]); assert.equal(res.json.ok, true); assert.equal(res.json.sid, sid); - assert.equal(res.json.reused, true, "the live server must be reused, not replaced"); + assert.ok(res.json.url.startsWith(baseUrl + "/"), "the live server must be reused, not replaced"); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.equal(state.workflow, "implement"); @@ -243,7 +306,7 @@ test("open with no --workflow still opens a Pathfinder session", () => { assert.equal(res.json.ok, true); assert.equal(readState(res.json.session).workflow, "pathfinder"); } finally { - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); } }); @@ -625,10 +688,10 @@ test("stop leaves a process it cannot identify as ours alone", () => { /* ----------------------------------------------------------- lifecycle */ test("stop shuts the server down and wait then reports exit 20", () => { - cli(["stop", "--session", sid]); + cli(["stop", "--session", sid, "--force"]); const res = cli(["wait", "--session", sid, "--seconds", "12"]); assert.equal(res.status, 20); - assert.equal(res.json.status, "server-gone"); + assert.deepEqual(res.json, { gone: true, fix: `open --resume ${sid} --workflow ` }); }); // A 127.0.0.1 link is only the person's machine if the agent is on it too. @@ -641,7 +704,7 @@ test("open flags an environment where the link may not reach the person", () => assert.equal(res.json.ok, true, "it still starts"); assert.equal(res.json.remote, "SSH_CONNECTION"); assert.match(res.json.note, /not necessarily theirs/); - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); }); test("the runtime dir is isolated by PLAN2CODE_CONSOLE_HOME", () => { @@ -665,7 +728,7 @@ test("resume brings the session back on a new port with state intact", async () const looksRes = await fetch(m[1] + "/looks", { headers: { cookie: cookieFor(m[1], m[2]) } }); assert.deepEqual((await looksRes.json()).looks, { theme: "dark", accent: "cobalt" }); - cli(["stop", "--session", sid]); + cli(["stop", "--session", sid, "--force"]); }); /* ------------------------------------------------- the page's own logic */ @@ -858,7 +921,7 @@ test("a present finish command must be a non-empty string without a placeholder" expectFail: true, }); assert.equal(res.status, 3); - assert.match(res.stderr, /"finish\.command" must be a non-empty string, or left out when there is nothing to run/); + assert.match(res.stderr, /finish\.command: must be a non-empty string, or left out when there is nothing to run/); } const tmpl = cli( [ @@ -967,7 +1030,7 @@ test("a finish can carry the dashboard flag, and only as a boolean", () => { expectFail: true, }); assert.equal(bad.status, 3); - assert.match(bad.stderr, /"finish\.dashboard" must be true or false \(or left out: no dashboard button\)/); + assert.match(bad.stderr, /finish\.dashboard: must be true or false \(or left out: no dashboard button\)/); }); // The Commit it now button is the same kind of opt-in. @@ -981,7 +1044,7 @@ test("a finish can carry the commit flag, and only as a boolean", () => { expectFail: true, }); assert.equal(bad.status, 3); - assert.match(bad.stderr, /"finish.commit" must be true or false/); + assert.match(bad.stderr, /finish.commit: must be true or false/); }); // Taking the review up is the agent posting `"finish": null`: the session goes @@ -1044,3 +1107,65 @@ test("post refuses a misplaced templates flag with exit 3", () => { assert.equal(res.status, 3); assert.match(res.stderr, /only a text item can carry it/); }); + +/* ------------------------------------------- stop needs a finish (FR-12, FR-13) */ + +const healthOf = async (url) => { + const m = url.match(/^(http:\/\/127\.0\.0\.1:\d+)\//); + try { + return (await fetch(m[1] + "/health")).status; + } catch { + return 0; + } +}; + +test("stop with no finish posted exits 3 naming finish and --force, and leaves the server up", async () => { + const opened = cli(["open", "--file", payload("stop-nofinish.json", BASE), "--no-open"]); + try { + const res = cli(["stop", "--session", opened.json.sid], { expectFail: true }); + assert.equal(res.status, 3); + assert.match(res.stderr, /finish/); + assert.match(res.stderr, /--force/); + assert.equal(await healthOf(opened.json.url), 200, "the server still answers /health"); + } finally { + cli(["stop", "--session", opened.json.sid, "--force"]); + } +}); + +test("stop stops a session once a finish is posted", async () => { + const opened = cli(["open", "--file", payload("stop-finish.json", BASE), "--no-open"]); + const res = stopSession(opened.json.sid); + assert.equal(res.status, 0); + assert.equal(res.json.stopped, 1); + assert.equal(await healthOf(opened.json.url), 0, "the server is gone"); +}); + +test("stop --force stops a session with no finish, and stop --all does so unchanged", async () => { + const one = cli(["open", "--file", payload("stop-force.json", BASE), "--no-open"]); + const forced = cli(["stop", "--session", one.json.sid, "--force"]); + assert.equal(forced.status, 0); + assert.equal(forced.json.stopped, 1); + assert.equal(await healthOf(one.json.url), 0); + + const two = cli(["open", "--file", payload("stop-all.json", BASE), "--no-open"]); + const all = cli(["stop", "--all"]); + assert.equal(all.status, 0); + assert.ok(all.json.stopped >= 1, "--all needs no finish"); + assert.equal(await healthOf(two.json.url), 0); +}); + +test("a finish posted while stopWarning is set is refused naming stopWarning, and passes once it is cleared", () => { + const opened = cli(["open", "--file", payload("stopwarn.json", BASE), "--no-open"]); + try { + cli(["post", "--session", opened.json.sid, "--file", payload("stopwarn-set.json", { stopWarning: "Unsaved answers are lost." })]); + const finish = { headline: "Paused: your answers are saved", command: "/plan2code-1-plan" }; + const refused = cli(["post", "--session", opened.json.sid, "--file", payload("stopwarn-finish.json", { finish })], { expectFail: true }); + assert.equal(refused.status, 3); + assert.match(refused.stderr, /stopWarning/); + const ok = cli(["post", "--session", opened.json.sid, "--file", payload("stopwarn-clear.json", { stopWarning: "", finish })]); + assert.equal(ok.status, 0); + assert.equal(ok.json.ok, true); + } finally { + cli(["stop", "--session", opened.json.sid, "--force"]); + } +}); diff --git a/scripts/test-web-console-logic.mjs b/scripts/test-web-console-logic.mjs index a9db52a..a8a4359 100644 --- a/scripts/test-web-console-logic.mjs +++ b/scripts/test-web-console-logic.mjs @@ -576,12 +576,13 @@ test("chat lines list documents after images, and chatView carries files on sent const lines = chatReplyLines([ { kind: "message", + seq: 7, text: "Read these", images: [{ path: "/u/a.jpg", name: "a.png" }], files: [{ path: "/u/b.md", name: "b.md" }], }, ]); - assert.equal(lines, "Quick question: Read these\n Image: /u/a.jpg (a.png)\n File: /u/b.md (b.md)"); + assert.equal(lines, "Quick question (7): Read these\n Image: /u/a.jpg (a.png)\n File: /u/b.md (b.md)"); const view = chatView( { conversation: 1, messages: [{ from: "person", kind: "message", seq: 1, text: "Read", files: [{ path: "/u/b.md", name: "b.md" }] }] }, { pendingSends: [{ tempId: "t", text: "More", files: [{ path: "/u/c.pdf", name: "c.pdf" }] }] } @@ -1498,22 +1499,22 @@ test("no starter steers the workflow: approve, skip, commit, run, execute, delet test("validate: templates only as \"idea\", only on a text item", () => { const item = (extra) => ({ items: [{ id: "idea", kind: "text", title: "What's the idea?", ...extra }] }); - const message = 'item "idea" has "templates": only a text item can carry it, and its only value is "idea".'; + const message = 'item "idea" templates: only a text item can carry it, and its only value is "idea".'; assert.deepEqual(validate(item({ templates: "idea" })), []); assert.deepEqual(validate(item({})), []); - assert.ok(validate(item({ kind: "choice", options: [{ k: "A", text: "a" }], templates: "idea" })).includes(message)); - assert.ok(validate(item({ templates: "yes" })).includes(message)); + assert.ok(validate(item({ kind: "choice", options: [{ k: "A", text: "a" }], templates: "idea" })).some((p) => p.startsWith(message))); + assert.ok(validate(item({ templates: "yes" })).some((p) => p.startsWith(message))); }); test("validate: fill only as \"note\", only on a text item", () => { const item = (extra) => ({ items: [{ id: "idea", kind: "text", title: "What's the idea?", ...extra }] }); - const message = 'item "idea" has "fill": only a text item can carry it, and its only value is "note".'; + const message = 'item "idea" fill: only a text item can carry it, and its only value is "note".'; assert.deepEqual(validate(item({ fill: "note" })), []); assert.deepEqual(validate(item({ fill: "note", templates: "idea" })), []); - assert.ok(validate(item({ kind: "choice", options: [{ k: "A", text: "a" }], fill: "note" })).includes(message)); - assert.ok(validate(item({ kind: "confirm", fill: "note" })).includes(message)); - assert.ok(validate(item({ fill: "idea" })).includes(message)); - assert.ok(validate(item({ fill: true })).includes(message)); + assert.ok(validate(item({ kind: "choice", options: [{ k: "A", text: "a" }], fill: "note" })).some((p) => p.startsWith(message))); + assert.ok(validate(item({ kind: "confirm", fill: "note" })).some((p) => p.startsWith(message))); + assert.ok(validate(item({ fill: "idea" })).some((p) => p.startsWith(message))); + assert.ok(validate(item({ fill: true })).some((p) => p.startsWith(message))); }); test("attachmentName: slug of the original name, 8 characters of the upload id, the upload's own extension", () => { @@ -1748,7 +1749,7 @@ test("meter: a build post's headline.cleared reaches the ledger as progress", () assert.equal(postPatch(s, { headline: { cleared: 7 }, run: { event: "implement-phase", id: "phase-1", tasks: 7 } }).status, 0); assert.equal(points(), 3, "the phase's run took over: 7 tasks score 3, not 3 + 3"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -2040,26 +2041,25 @@ test("subagents: blockFor walks every switch transition, and never says off to a assert.equal(blockFor(setting(false, 1), none), null, "never on: nothing"); assert.equal(blockFor(null, none), null, "no setting: nothing"); + const line = (word, max) => `Subagents: on, ${word} strength, at most ${max} helpers at once (a console setting, not typed by the person).`; const on = blockFor(setting(true, 2), none); - assert.equal(on.lines[0], "Subagents: on (revision 2) — a console setting, not typed by the person."); - assert.ok(!on.lines[0].includes("replaces")); + assert.equal(on.lines[0], line("balanced", 3)); assert.deepEqual(on.field, { state: "on", revision: 2, max: 3, instruction: defaultInstruction("implement"), strength: "balanced" }); assert.deepEqual(on.cursor, { revision: 2, state: "on" }); - assert.equal(on.lines[on.lines.length - 1], " At most 3 helpers at once."); - for (const frame of FRAME_LINES) assert.ok(on.lines.includes(" " + frame), frame); + for (const frame of FRAME_LINES) assert.ok(!on.lines.some((l) => l.includes(frame)), "the frame sentences live in console-subagents.md, not in the block"); const edit = blockFor(setting(true, 5, { instruction: "First line\n\nSecond line", max: 7 }), { revision: 4, state: "on" }); - assert.equal(edit.lines[0], "Subagents: on (revision 5, replaces revision 4) — a console setting, not typed by the person."); + assert.equal(edit.lines[0], line("balanced", 7)); assert.ok(edit.lines.includes(" First line") && edit.lines.includes(" Second line"), "the instruction's own lines are indented"); - assert.ok(!edit.lines.some((line) => !line.trim()), "blank instruction lines are dropped"); + assert.ok(!edit.lines.some((l) => !l.trim()), "blank instruction lines are dropped"); const nested = blockFor(setting(true, 2, { instruction: "- a\r\n - b\n \n" }), none); - assert.deepEqual(nested.lines.slice(-4, -2), [" - a", " - b"], "the person's own indentation survives, CRLF and blank lines do not"); + assert.deepEqual(nested.lines.slice(-2), [" - a", " - b"], "the person's own indentation survives, CRLF and blank lines do not"); assert.equal(edit.field.max, 7); - for (const line of edit.lines.slice(1)) assert.match(line, /^ {2}\S/, "only the first line starts at column 0"); + for (const l of edit.lines.slice(1)) assert.match(l, /^ {2}\S/, "only the first line starts at column 0"); const off = blockFor(setting(false, 6), { revision: 5, state: "on" }); assert.deepEqual(off.lines, [offLine(6)]); - assert.equal(off.lines[0], "Subagents: off (revision 6) — don't start new helpers for the rest of this session."); + assert.equal(off.lines[0], "Subagents: off. Start no new helpers for the rest of this session."); assert.deepEqual(off.cursor, { revision: 6, state: "off" }); assert.equal(off.field.state, "off"); @@ -2067,7 +2067,7 @@ test("subagents: blockFor walks every switch transition, and never says off to a assert.equal(blockFor(setting(true, 6), { revision: 6, state: "on" }), null, "same revision while on: nothing"); assert.equal(blockFor(setting(false, 3), { revision: 2, state: "off" }), null, "off after off: nothing"); - assert.equal(blockFor(setting(true, 6), none).lines[0], "Subagents: on (revision 6) — a console setting, not typed by the person.", "a reset cursor re-states on"); + assert.equal(blockFor(setting(true, 6), none).lines[0], line("balanced", 3), "a reset cursor re-states on"); assert.equal(blockFor(setting(false, 6), none), null, "a reset cursor with it off: nothing"); assert.equal(blockFor({ ...setting(true, 9), workflow: "document" }, none), null, "a workflow that does not offer it: nothing"); }); @@ -2378,3 +2378,194 @@ test("Notebook pick rules: an empty tab, the first five pictures ticked, and no assert.deepEqual(toggleNoteTick(four, "f"), ["a", "b", "d", "e", "f"], "untick one to tick another"); assert.equal(NOTE_LONG_BYTES, 51200); }); + +/* ------------------------------------- the wire: defaults, patch reading, errors */ + +import { applyPatch, blankState } from "../src/web-console/patches.mjs"; +import { readPatch } from "../src/web-console/cmd-post-wait.mjs"; +import { openSession } from "./web-console-test-helpers.mjs"; + +const wireState = () => blankState({ sid: "x", project: "p", workflow: "plan" }); +const wireItem = (kind, options) => ({ id: "q1", kind, title: "Pick one", body: "Which?", ...(options ? { options } : {}) }); + +test("defaults: options with no k are lettered A, B, C on choice, multi and menu", () => { + for (const kind of ["choice", "multi", "menu"]) { + const next = applyPatch(wireState(), { items: [wireItem(kind, [{ text: "CSV" }, { text: "Excel" }, { text: "JSON" }])] }); + assert.deepEqual(next.items[0].options.map((o) => o.k), ["A", "B", "C"], kind); + assert.deepEqual(validate(next), [], kind); + } +}); + +test("defaults: options that all carry a k keep it, and a mix is refused naming the item and options", () => { + const next = applyPatch(wireState(), { items: [wireItem("choice", [{ k: "1", text: "CSV" }, { k: "9", text: "Excel" }])] }); + assert.deepEqual(next.items[0].options.map((o) => o.k), ["1", "9"]); + assert.throws( + () => applyPatch(wireState(), { items: [wireItem("choice", [{ k: "A", text: "CSV" }, { text: "Excel" }])] }), + (e) => /item "q1" options:/.test(e.message) && /Like this:/.test(e.message) + ); +}); + +test("defaults: a new item gets status, required and allowOther filled, and a given value is kept", () => { + const next = applyPatch(wireState(), { items: [wireItem("choice", [{ text: "CSV" }]), { ...wireItem("text"), id: "q2", required: false, allowOther: false }] }); + const [a, b] = next.items; + assert.equal(a.status, "open"); + assert.equal(a.required, true); + assert.equal(a.allowOther, true); + assert.deepEqual(a.thread, []); + assert.equal(b.required, false); + assert.equal(b.allowOther, false); +}); + +test("readPatch: indented, minified, BOM and UTF-16 patches all read the same", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-readpatch-")); + try { + const patch = { title: "Café – résumé", items: [{ id: "q1", kind: "text", title: "Name" }] }; + const json = JSON.stringify(patch); + const write = (name, buf) => { + const p = path.join(dir, name); + fs.writeFileSync(p, buf); + return p; + }; + const le = Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(json, "utf16le")]); + const be = Buffer.concat([Buffer.from([0xfe, 0xff]), Buffer.from(json, "utf16le").swap16()]); + for (const [name, buf] of [ + ["minified.json", json], + ["indented.json", JSON.stringify(patch, null, 4)], + ["bom.json", "" + json], + ["le.json", le], + ["be.json", be], + ]) { + assert.deepEqual(readPatch(write(name, buf)), { patch }, name); + } + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("readPatch: a cut-off, a trailing comma and a missing brace name the line and column, show the spot and a caret", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-readpatch-")); + try { + const read = (text) => { + const p = path.join(dir, "p.json"); + fs.writeFileSync(p, text); + return readPatch(p); + }; + const cases = { + "a cut-off write": '{"title":"Audit export","items":[{"id":"q1","kind":"te', + "a trailing comma": '{"title":"Audit",\n"items":[],\n}', + "a missing brace": '{"title":"Audit","agent":{"status":"waiting"}', + }; + for (const [what, text] of Object.entries(cases)) { + const { error, patch } = read(text); + assert.equal(patch, undefined, what); + const lines = error.split("\n"); + assert.match(lines[0], /^line \d+, column \d+: \S/, `${what}: ${error}`); + assert.equal(lines.length, 3, `${what}: the message, the excerpt, the caret`); + assert.match(lines[2], /^ *\^$/, `${what}: a caret under the spot`); + assert.ok(lines[1].length > 0 && lines[1].length <= 61, `${what}: an excerpt around the spot`); + } + const comma = read(cases["a trailing comma"]).error; + assert.match(comma, /^line 3, column 1:/, "the trailing comma is reported on the closing brace's line"); + const cut = read(cases["a cut-off write"]).error; + assert.match(cut, /^line 1, column \d+:/); + assert.ok(cut.split("\n")[1].includes('"kind":"te'), "the excerpt shows where the write stopped"); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("readPatch: empty input and a JSON array each get their own message", () => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-readpatch-")); + try { + const read = (text) => { + const p = path.join(dir, "p.json"); + fs.writeFileSync(p, text); + return readPatch(p).error; + }; + const empty = read(" \n"); + const array = read("[1,2]"); + const nul = read("null"); + assert.match(empty, /empty/); + assert.match(array, /one JSON object/); + assert.match(array, /an array/); + assert.match(nul, /null/); + assert.notEqual(empty, array); + assert.match(readPatch(path.join(dir, "missing.json")).error, /no such file/); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +// Each rule break names the item id, the field and a "Like this:" fragment. +// The fragment is applied to the patch by `fix`, and the result must pass. +test("rule breaks name the item and field, and their Like this: passes validate() when applied", () => { + const withFragment = (problem) => { + const at = problem.indexOf("Like this: "); + assert.ok(at > 0, `a Like this: in ${problem}`); + return JSON.parse(problem.slice(at + "Like this: ".length)); + }; + const cases = [ + { + what: "an unknown kind", + patch: { items: [{ id: "q1", kind: "nope", title: "Pick one", body: "Which?" }] }, + start: /^item "q1" kind:/, + fix: (p, like) => Object.assign(p.items[0], like), + }, + { + what: "an option with label", + patch: { items: [{ id: "q1", kind: "choice", title: "Pick one", body: "Which?", options: [{ label: "CSV" }, { text: "Excel" }] }] }, + start: /^item "q1" options:/, + fix: (p, like) => (p.items[0].options[0] = like), + }, + { + what: "two recommended options", + patch: { items: [{ id: "q1", kind: "choice", title: "Pick one", body: "Which?", options: [{ text: "CSV", recommended: true }, { text: "Excel", recommended: true }] }] }, + start: /^item "q1" options:/, + fix: (p, like) => (p.items[0].options = like), + }, + { + what: "a finish with a placeholder", + patch: { finish: { headline: "Done", command: "/plan2code-" } }, + start: /^finish\.command:/, + fix: (p, like) => Object.assign(p.finish, like.finish), + }, + ]; + for (const { what, patch, start, fix } of cases) { + const problems = validate(applyPatch(wireState(), structuredClone(patch))); + assert.equal(problems.length, 1, `${what}: ${JSON.stringify(problems)}`); + assert.match(problems[0], start, what); + const fixed = structuredClone(patch); + fix(fixed, withFragment(problems[0])); + assert.deepEqual(validate(applyPatch(wireState(), fixed)), [], `${what}: the Like this: passes`); + } + + // An unanswered note: the person wrote in a thread and the patch settles without replying. + const note = { ...wireItem("choice", [{ k: "A", text: "CSV" }]), thread: [{ who: "user", text: "Why?" }], submitted: { k: "A", at: "2026-01-01T00:00:00.000Z" } }; + const base = { ...wireState(), items: [note] }; + const stuck = validate(applyPatch(base, { settle: ["q1"] })); + assert.equal(stuck.length, 1); + assert.match(stuck[0], /^item "q1" thread:/); + const like = withFragment(stuck[0]); + assert.deepEqual(validate(applyPatch(base, { settle: ["q1"], items: [{ id: "q1", thread: like.thread.map((t) => ({ ...t, text: "Because." })) }] })), []); +}); + +test("a refused patch leaves state.json byte for byte as it was", () => { + const s = openSession(); + try { + const file = path.join(s.session, "state.json"); + const before = fs.readFileSync(file); + const refused = [ + { items: [{ id: "q9", kind: "nope", title: "Pick one", body: "Which?" }] }, + { items: [{ id: "q9", kind: "choice", title: "Pick one", body: "Which?", options: [{ k: "A", text: "x" }, { text: "y" }] }] }, + { finish: { headline: "Done", command: "/plan2code-" } }, + ]; + for (const patch of refused) { + const res = postPatch(s, patch, { expectFail: true }); + assert.equal(res.status, 3, JSON.stringify(patch)); + assert.match(res.stderr, /Like this:/); + assert.ok(fs.readFileSync(file).equals(before), "state.json is untouched"); + } + } finally { + cli(["stop", "--session", s.sid, "--force"]); + } +}); diff --git a/scripts/test-web-console-loop.mjs b/scripts/test-web-console-loop.mjs new file mode 100644 index 0000000..9f1cc01 --- /dev/null +++ b/scripts/test-web-console-loop.mjs @@ -0,0 +1,625 @@ +// Web console tests: the Implementation Loop's console side. Run with: +// node --test scripts/test-web-console-loop.mjs +// +// Three groups, one per piece of the contract (src/web-console/notes/loop.md): +// 1. the `open --loop` gate and the lock it stamps on a session, +// 2. the `loopOutcome`, `loopEnd` and `handledBy` rules of the patch validator, +// 3. the `loop-setup.json` store and its `/loop-setup` route. +// +// Shared setup (a per-process console home, the CLI runner, fixtures) lives in +// web-console-test-helpers.mjs. Every child process here gets an explicit +// environment with the desktop app's variables removed, so a test run from +// inside the app behaves as one run from a terminal. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { spawnSync } from "node:child_process"; +import { pathToFileURL } from "node:url"; +import { applyPatch, blankState, validate } from "../src/web-console/patches.mjs"; +import { ROOT, CONSOLE_CLI, ENV, HOME, cli, readState, sessionUrl, payload } from "./web-console-test-helpers.mjs"; + +const APP_VARS = ["PLAN2CODE_IN_APP", "PLAN2CODE_EMBED_ORIGIN", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"]; + +// The console CLI with the app's variables gone, plus whatever `extra` sets. +function run(args, { cwd = ROOT, extra = {} } = {}) { + const env = { ...ENV }; + for (const key of APP_VARS) delete env[key]; + const res = spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: { ...env, ...extra }, encoding: "utf8", cwd }); + const line = String(res.stdout).trim().split("\n").filter((l) => l.startsWith("{")).pop(); + let json = null; + try { + json = line ? JSON.parse(line) : null; + } catch {} + return { status: res.status, stderr: String(res.stderr), stdout: String(res.stdout), json }; +} + +const IN_APP = { PLAN2CODE_IN_APP: "1" }; + +const tempProject = (name) => fs.mkdtempSync(path.join(HOME, `${name}-`)); +const sessionsDir = path.join(HOME, "sessions"); +const sessionCount = () => (fs.existsSync(sessionsDir) ? fs.readdirSync(sessionsDir).length : 0); + +// Opens a session in a fresh project; the caller stops it. +function openLoop(workflow = "implement", name = "loop") { + const cwd = tempProject(name); + const res = run(["open", "--workflow", workflow, "--loop", "--no-open"], { cwd, extra: IN_APP }); + assert.equal(res.status, 0, res.stderr); + const stop = () => cli(["stop", "--session", res.json.sid, "--force"], { cwd, expectFail: true }); + return { cwd, sid: res.json.sid, session: res.json.session, url: res.json.url, stop }; +} + +const post = (s, obj) => run(["post", "--session", s.sid, "--file", payload(`loop-post-${Date.now()}-${Math.random().toString(16).slice(2)}.json`, obj)], { cwd: s.cwd }); + +/* ---------------------------------------------------------- 7.5: the gate */ + +test("open --loop is refused with one line and exit 3 when the desktop app's signal is unset", () => { + const cwd = tempProject("gate-off"); + const before = sessionCount(); + for (const extra of [{}, { PLAN2CODE_IN_APP: "0" }]) { + const res = run(["open", "--workflow", "implement", "--loop", "--no-open"], { cwd, extra }); + assert.equal(res.status, 3, `exit 3 with ${JSON.stringify(extra)}`); + assert.equal(res.stderr.trim().split("\n").length, 1, "a one-line reason"); + assert.match(res.stderr, /Loop mode runs only inside the Plan2Code desktop app\./); + assert.equal(res.stdout.trim(), "", "nothing is printed on stdout"); + } + assert.equal(sessionCount(), before, "no session folder was made"); +}); + +test("open --loop under the app locks the session: loop { driving: true } in state.json", () => { + for (const workflow of ["implement", "implement-review"]) { + const s = openLoop(workflow, `gate-on-${workflow}`); + try { + const state = readState(s.session); + assert.deepEqual(state.loop, { driving: true }); + assert.equal(state.workflow, workflow); + assert.equal("loopOutcome" in state, false); + assert.equal("loopEnd" in state, false); + } finally { + s.stop(); + } + } +}); + +test("open --loop goes only with Implement or Implement + Review: any other workflow, or none, exits 2", () => { + const cwd = tempProject("gate-wf"); + const before = sessionCount(); + for (const args of [["--workflow", "plan"], ["--workflow", "dashboard"], []]) { + const res = run(["open", ...args, "--loop", "--no-open"], { cwd, extra: IN_APP }); + assert.equal(res.status, 2, `exit 2 for ${args.join(" ") || "no workflow"}`); + assert.match(res.stderr, /--loop goes only with --workflow implement or --workflow implement-review/); + } + assert.equal(sessionCount(), before, "no session folder was made"); +}); + +test("a later open --resume without --loop clears the lock and the loop's cards; --loop locks it again", () => { + const s = openLoop("implement", "resume"); + try { + const card = { + id: "fixes", + kind: "multi", + title: "Which to fix", + options: [{ k: "1", text: "One" }, { k: "2", text: "Two" }], + status: "answered", + answer: { ks: ["1"] }, + handledBy: "loop", + }; + const posted = post(s, { items: [card] }); + assert.equal(posted.status, 0, posted.stderr); + assert.equal(readState(s.session).items[0].handledBy, "loop"); + + const plain = run(["open", "--resume", s.sid, "--no-open"], { cwd: s.cwd }); + assert.equal(plain.status, 0, plain.stderr); + const unlocked = readState(s.session); + assert.equal("loop" in unlocked, false, "the lock is gone"); + assert.equal(unlocked.items.length, 1, "the card stays as a record"); + assert.equal("handledBy" in unlocked.items[0], false, "but it is no longer the loop's"); + assert.equal(post(s, { agent: { status: "waiting" } }).status, 0, "the unlocked session takes an ordinary post"); + + const again = run(["open", "--resume", s.sid, "--workflow", "implement", "--loop", "--no-open"], { cwd: s.cwd, extra: IN_APP }); + assert.equal(again.status, 0, again.stderr); + assert.deepEqual(readState(s.session).loop, { driving: true }); + } finally { + s.stop(); + } +}); + +/* ------------------------------------- 7.6: loopOutcome, loopEnd, handledBy */ + +// A loop session's state, with the patch applied as `post` would: applyPatch +// may throw (who may send it, how often), then validate() lists the rest. +const loopState = (extra = {}) => ({ ...blankState({ sid: "s", workflow: "implement", project: "p" }), loop: { driving: true }, ...extra }); +function tryPatch(state, patch) { + let next; + try { + next = applyPatch(state, patch); + } catch (e) { + return { next: null, problems: [e.message] }; + } + return { next, problems: validate(next) }; +} + +const goodOutcome = () => ({ + phase: 2, + result: "passed", + reason: null, + summary: "Built the setup screen; 6 of 6 tasks", + tests: { ran: true, passed: true, summary: "14 pass" }, + review: { + ran: true, + recheck: true, + left: { critical: 0, warning: 0, suggestion: 2 }, + fixed: [{ level: "warning", title: "Close the file handle", file: "src/z.js" }], + unfixed: [{ level: "suggestion", title: "Name the timer", file: "src/x.js" }], + }, + tasks: { blocked: [], assumed: ["2.4"] }, + conflicts: [], + decisions: ["Kept the old route so existing callers still work"], + subject: "Add the loop setup screen", +}); +const withTriage = (skipped) => { + const o = goodOutcome(); + o.review.triage = { ran: true, skipped }; + return o; +}; +const skip = (extra = {}) => ({ level: "warning", title: "Rename the helper", file: "src/y.js", reason: "Outside this phase's tasks", ...extra }); + +test("a valid loopOutcome is stored in a loop session, with and without a triage block", () => { + const plain = tryPatch(loopState(), { loopOutcome: goodOutcome() }); + assert.deepEqual(plain.problems, []); + assert.deepEqual(plain.next.loopOutcome, goodOutcome()); + + const triaged = tryPatch(loopState(), { loopOutcome: withTriage([skip(), skip({ level: "suggestion", title: "Name the timer" })]) }); + assert.deepEqual(triaged.problems, []); + assert.equal(triaged.next.loopOutcome.review.triage.skipped.length, 2); + + const empty = tryPatch(loopState(), { loopOutcome: withTriage([]) }); + assert.deepEqual(empty.problems, [], "a triage that skipped nothing is a valid, empty list"); + + const failed = goodOutcome(); + Object.assign(failed, { result: "failed", reason: "tests" }); + assert.deepEqual(tryPatch(loopState(), { loopOutcome: failed }).problems, [], "a failed outcome carries a reason"); +}); + +test("each bad loopOutcome field is refused with a message naming it", () => { + const cases = [ + ["a bad result", (o) => (o.result = "done"), /loopOutcome\.result must be/], + ["a reason on a passed outcome", (o) => (o.reason = "tests"), /loopOutcome\.reason must be null when the phase passed/], + ["a failed outcome with no reason", (o) => Object.assign(o, { result: "failed", reason: null }), /loopOutcome\.reason must be one of/], + ["a failed outcome with an unknown reason", (o) => Object.assign(o, { result: "failed", reason: "sulking" }), /loopOutcome\.reason must be one of/], + ["a negative left.warning", (o) => (o.review.left.warning = -1), /loopOutcome\.review\.left\.warning must be a non-negative integer/], + ["a fractional left.critical", (o) => (o.review.left.critical = 1.5), /loopOutcome\.review\.left\.critical must be a non-negative integer/], + [ + "51 unfixed entries", + (o) => (o.review.unfixed = Array.from({ length: 51 }, (_, i) => ({ level: "suggestion", title: `Finding ${i}` }))), + /loopOutcome\.review\.unfixed can hold at most 50 entries/, + ], + ["no fixed list", (o) => delete o.review.fixed, /loopOutcome\.review\.fixed must be an array/], + ["a fixed entry at an unknown level", (o) => (o.review.fixed[0].level = "nit"), /loopOutcome\.review\.fixed\[0\]\.level must be one of/], + ["a fixed entry with no title", (o) => (o.review.fixed[0].title = " "), /loopOutcome\.review\.fixed\[0\]\.title must be a non-empty one-line string/], + ["51 fixed entries", (o) => (o.review.fixed = Array.from({ length: 51 }, (_, i) => ({ level: "suggestion", title: `Finding ${i}` }))), /loopOutcome\.review\.fixed can hold at most 50 entries/], + ["no decisions list", (o) => delete o.decisions, /loopOutcome\.decisions must be an array/], + ["a two-line decision", (o) => (o.decisions = ["one\ntwo"]), /loopOutcome\.decisions\[0\] must be one line of 1 to 200 characters/], + ["a 201-character decision", (o) => (o.decisions = ["x".repeat(201)]), /loopOutcome\.decisions\[0\] must be one line/], + ["51 decisions", (o) => (o.decisions = Array.from({ length: 51 }, (_, i) => `Decision ${i}`)), /loopOutcome\.decisions can hold at most 50 entries/], + ["an unfixed entry at an unknown level", (o) => (o.review.unfixed[0].level = "nit"), /loopOutcome\.review\.unfixed\[0\]\.level must be one of/], + ["a two-line subject", (o) => (o.subject = "Add the screen\nand more"), /loopOutcome\.subject must be one line of 1 to 100 characters/], + ["a 101-character subject", (o) => (o.subject = "a".repeat(101)), /loopOutcome\.subject must be one line of 1 to 100 characters/], + ["an empty subject", (o) => (o.subject = ""), /loopOutcome\.subject must be one line/], + ["a forbidden completion marker in the summary", (o) => (o.summary = "All done, PHASE_COMPLETE"), /loopOutcome\.summary: contains a loop completion marker \(PHASE_COMPLETE\)/], + ["a task id that is not like 2.4", (o) => (o.tasks.assumed = ["two"]), /loopOutcome\.tasks\.assumed must be an array of task ids/], + ["a missing tests object", (o) => delete o.tests, /loopOutcome\.tests must be an object/], + ["a non-integer phase", (o) => (o.phase = 0), /loopOutcome\.phase must be a positive integer/], + ["a triage skip at a bad level", (o) => (o.review.triage = { ran: true, skipped: [skip({ level: "major" })] }), /loopOutcome\.review\.triage\.skipped\[0\]\.level must be one of/], + ["a triage skip with no reason", (o) => (o.review.triage = { ran: true, skipped: [skip({ reason: undefined })] }), /loopOutcome\.review\.triage\.skipped\[0\]\.reason must be one line of 1 to 200/], + ["a 201-character triage reason", (o) => (o.review.triage = { ran: true, skipped: [skip({ reason: "r".repeat(201) })] }), /loopOutcome\.review\.triage\.skipped\[0\]\.reason must be one line of 1 to 200/], + [ + "51 triage skips", + (o) => (o.review.triage = { ran: true, skipped: Array.from({ length: 51 }, (_, i) => skip({ title: `Finding ${i}` })) }), + /loopOutcome\.review\.triage\.skipped can hold at most 50 entries/, + ], + ["a triage with no ran flag", (o) => (o.review.triage = { skipped: [] }), /loopOutcome\.review\.triage\.ran must be true or false/], + ["a triage that is not an object", (o) => (o.review.triage = "yes"), /loopOutcome\.review\.triage must be an object/], + ]; + for (const [what, mutate, expected] of cases) { + const outcome = goodOutcome(); + mutate(outcome); + const { problems } = tryPatch(loopState(), { loopOutcome: outcome }); + assert.ok(problems.some((p) => expected.test(p)), `${what}: expected ${expected}, got ${JSON.stringify(problems)}`); + } + + // The boundaries themselves are fine. + const edge = goodOutcome(); + edge.subject = "a".repeat(100); + edge.review.unfixed = Array.from({ length: 50 }, (_, i) => ({ level: "suggestion", title: `Finding ${i}` })); + edge.review.triage = { ran: true, skipped: Array.from({ length: 50 }, (_, i) => skip({ title: `Finding ${i}`, reason: "r".repeat(200) })) }; + assert.deepEqual(tryPatch(loopState(), { loopOutcome: edge }).problems, [], "100 characters, 50 entries and 200 characters are the limits, not over them"); +}); + +test("loopOutcome is refused outside a loop session and a second time", () => { + const unlocked = loopState(); + delete unlocked.loop; + assert.match(tryPatch(unlocked, { loopOutcome: goodOutcome() }).problems.join("\n"), /loopOutcome: is only accepted in a loop session/); + + const first = tryPatch(loopState(), { loopOutcome: goodOutcome() }); + assert.deepEqual(first.problems, []); + const second = tryPatch(first.next, { loopOutcome: goodOutcome() }); + assert.match(second.problems.join("\n"), /loopOutcome: was already posted for this session/); + assert.deepEqual(tryPatch(first.next, { agent: { status: "waiting" } }).problems, [], "the stored outcome does not block later posts"); + + assert.match(tryPatch(loopState(), { loop: { driving: true } }).problems.join("\n"), /loop: is set by open --loop, not by a patch/, "a patch cannot lock a session itself"); +}); + +test("a loopOutcome through post is stored in state.json, and refused with exit 3 and the field named", () => { + const s = openLoop("implement-review", "outcome-post"); + try { + const bad = goodOutcome(); + bad.subject = "a".repeat(101); + const refused = post(s, { loopOutcome: bad }); + assert.equal(refused.status, 3); + assert.match(refused.stderr, /loopOutcome\.subject must be one line of 1 to 100 characters/); + assert.equal("loopOutcome" in readState(s.session), false, "nothing was written"); + + const stored = post(s, { loopOutcome: withTriage([skip()]) }); + assert.equal(stored.status, 0, stored.stderr); + assert.deepEqual(readState(s.session).loopOutcome, withTriage([skip()])); + + const again = post(s, { loopOutcome: goodOutcome() }); + assert.equal(again.status, 3); + assert.match(again.stderr, /already posted/); + } finally { + s.stop(); + } +}); + +test("a loopOutcome through post is refused outside a loop session", () => { + const cwd = tempProject("outcome-plain"); + const opened = run(["open", "--workflow", "implement", "--no-open"], { cwd }); + assert.equal(opened.status, 0, opened.stderr); + try { + const res = post({ sid: opened.json.sid, cwd }, { loopOutcome: goodOutcome() }); + assert.equal(res.status, 3); + assert.match(res.stderr, /loopOutcome: is only accepted in a loop session/); + } finally { + cli(["stop", "--session", opened.json.sid, "--force"], { cwd, expectFail: true }); + } +}); + +const goodEnd = (extra = {}) => ({ + kind: "stopped", + line: "Stopped at phase 2: a Critical finding was skipped", + phases: [{ n: 1, name: "Setup", commit: "abc1234", unfixed: 0, retries: 0 }], + uncommitted: ["src/x.js"], + can: ["resume", "fix"], + ...extra, +}); +const EVIDENCE = { id: "evidence", title: "What happened", blocks: [{ id: "b1", md: "The phase stopped on a skipped Critical." }] }; + +test("loopEnd: a valid stopped with an evidence doc in the same patch is stored", () => { + const withDoc = tryPatch(loopState(), { docs: [EVIDENCE], loopEnd: goodEnd({ evidence: "evidence" }) }); + assert.deepEqual(withDoc.problems, []); + assert.equal(withDoc.next.loopEnd.evidence, "evidence"); + assert.equal(withDoc.next.docs[0].id, "evidence"); + + const finished = tryPatch(loopState(), { loopEnd: goodEnd({ kind: "finished", can: ["finalize"] }) }); + assert.deepEqual(finished.problems, [], "evidence is optional"); + + const replaced = tryPatch(withDoc.next, { loopEnd: goodEnd({ line: "A later word replaces the earlier" }) }); + assert.deepEqual(replaced.problems, [], "a later loopEnd replaces the earlier"); + assert.equal(replaced.next.loopEnd.line, "A later word replaces the earlier"); +}); + +test("loopEnd: an unknown evidence id, a push in can, and the other bad fields are refused, each named", () => { + const cases = [ + ["an unknown evidence id", goodEnd({ evidence: "nope" }), /loopEnd\.evidence must be the id of a doc on the page/], + ["a push in can", goodEnd({ can: ["resume", "push"] }), /loopEnd\.can must be an array with entries from resume, fix, finalize/], + ["a bad kind", goodEnd({ kind: "paused" }), /loopEnd\.kind must be "stopped" or "finished"/], + ["a two-line line", goodEnd({ line: "one\ntwo" }), /loopEnd\.line must be one line/], + ["an absolute uncommitted path", goodEnd({ uncommitted: ["/etc/passwd"] }), /loopEnd\.uncommitted must be an array of relative paths/], + ["an uncommitted path that climbs out", goodEnd({ uncommitted: ["../x"] }), /loopEnd\.uncommitted must be an array of relative paths/], + ["a bad decision count", goodEnd({ phases: [{ n: 1, name: "Setup", commit: "abc1234", unfixed: 0, retries: 0, assumed: -1 }] }), /loopEnd\.phases\[0\]\.assumed must be a non-negative integer/], + ["a bad commit hash", goodEnd({ phases: [{ n: 1, name: "Setup", commit: "zzz", unfixed: 0, retries: 0 }] }), /loopEnd\.phases\[0\]\.commit must be a short hex hash or null/], + ["a forbidden completion marker in line", goodEnd({ line: "TASK_COMPLETE" }), /loopEnd\.line: contains a loop completion marker/], + ]; + for (const [what, end, expected] of cases) { + const { problems } = tryPatch(loopState(), { loopEnd: end }); + assert.ok(problems.some((p) => expected.test(p)), `${what}: expected ${expected}, got ${JSON.stringify(problems)}`); + } +}); + +test("handledBy: \"loop\" is accepted in a loop session and refused outside one or with any other value", () => { + const card = (extra = {}) => ({ + id: "fixes", + kind: "multi", + title: "Which to fix", + options: [{ k: "1", text: "One" }, { k: "2", text: "Two" }], + status: "answered", + answer: { ks: ["1"] }, + handledBy: "loop", + ...extra, + }); + const ok = tryPatch(loopState(), { items: [card()] }); + assert.deepEqual(ok.problems, []); + assert.equal(ok.next.items[0].handledBy, "loop"); + + const unlocked = loopState(); + delete unlocked.loop; + const outside = tryPatch(unlocked, { items: [card()] }); + assert.ok(outside.problems.some((p) => /item "fixes" handledBy: is only valid in a loop session/.test(p)), JSON.stringify(outside.problems)); + + const other = tryPatch(loopState(), { items: [card({ handledBy: "app" })] }); + assert.ok(other.problems.some((p) => /item "fixes" handledBy: can only be "loop"/.test(p)), JSON.stringify(other.problems)); + + assert.deepEqual(tryPatch(unlocked, { items: [card({ handledBy: undefined })] }).problems, [], "no handledBy is an ordinary card anywhere"); +}); + +/* ------------------------------------ 7.7: the loop-setup.json store, routes */ + +const LOOP_SETUP_PATH = path.join(HOME, "loop-setup.json"); +const LOOP_SETUP_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "loop-setup.mjs")).href; + +// Runs `fn(m, args)` in a child process with this file's console home, where m +// is loop-setup.mjs. The module fixes its file at import time from +// PLAN2CODE_CONSOLE_HOME, which this process cannot set early enough. `fn` +// must be self-contained: it is sent as source text. Returns its JSON result. +function inStore(fn, args = {}) { + const env = { ...ENV }; + for (const key of APP_VARS) delete env[key]; + const code = + `const m = await import(${JSON.stringify(LOOP_SETUP_URL)});` + + `const out = await (${fn.toString()})(m, ${JSON.stringify(args)});` + + "console.log(JSON.stringify(out));"; + const res = spawnSync(process.execPath, ["--input-type=module", "-e", code], { env, encoding: "utf8", cwd: ROOT }); + assert.equal(res.status, 0, res.stderr); + return JSON.parse(String(res.stdout).trim().split("\n").pop()); +} + +const projectA = path.join(HOME, "store-project-a"); +const projectB = path.join(HOME, "store-project-b"); + +test("loop-setup: a new project reads as the defaults with remembered false, and nothing is written", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const got = inStore((m, { project }) => ({ setup: m.readLoopSetup(project), defaults: m.LOOP_DEFAULTS }), { project: projectA }); + assert.deepEqual(got.setup, { ...got.defaults, remembered: false }); + assert.equal(got.setup.fixMode, "smart"); + assert.equal(got.setup.onQuestion, "guess"); + assert.deepEqual(got.setup.fix, ["critical", "warning", "suggestion"]); + assert.equal(got.setup.silenceMinutes, 20); + assert.equal(got.setup.notifyUrl, "", "no web address is called by default"); + assert.equal(got.setup.notifyKind, "query"); + assert.equal(got.setup.notifyParam, "message"); + assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "reading never creates the file"); +}); + +test("loop-setup: a save reads back per project, keeps another project's entry, and smart round-trips", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const saved = inStore( + (m, { a, b }) => { + const base = { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix] }; + const forA = { ...base, fixMode: "levels", review: false, fix: ["critical"], onQuestion: "guess", quickCheck: "npm run build", silenceMinutes: 7 }; + const forB = { ...base, fixMode: "smart", afterLast: "run-finalize", retryOnce: false }; + m.saveLoopSetup(a, forA); + const returnedB = m.saveLoopSetup(b, forB); + return { forA, forB, returnedB, readA: m.readLoopSetup(a), readB: m.readLoopSetup(b), readC: m.readLoopSetup(a + "-other") }; + }, + { a: projectA, b: projectB } + ); + // A read also carries the save time. + const { saved: savedA, ...readA } = saved.readA; + const { saved: savedB, ...readB } = saved.readB; + assert.match(savedA, /^\d{4}-\d{2}-\d{2}T/); + assert.match(savedB, /^\d{4}-\d{2}-\d{2}T/); + assert.deepEqual(readA, { ...saved.forA, remembered: true }); + assert.deepEqual(readB, { ...saved.forB, remembered: true }); + assert.equal(saved.readB.fixMode, "smart", "smart round-trips"); + assert.equal(saved.readA.fixMode, "levels"); + assert.deepEqual(saved.returnedB, saved.readB, "a save returns what a read gives"); + assert.equal(saved.readC.remembered, false, "an unsaved project still reads as new"); + + const file = JSON.parse(fs.readFileSync(LOOP_SETUP_PATH, "utf8")); + assert.equal(file.schema, 1); + assert.equal(Object.keys(file.projects).length, 2, "one entry per project"); + for (const entry of Object.values(file.projects)) assert.match(entry.saved, /^\d{4}-\d{2}-\d{2}T/); + + // A second save for A replaces A's entry and leaves B's alone. + const again = inStore( + (m, { a, b }) => { + const { saved, remembered, ...entry } = m.readLoopSetup(a); + m.saveLoopSetup(a, { ...entry, fixMode: "smart" }); + return { a: m.readLoopSetup(a), b: m.readLoopSetup(b) }; + }, + { a: projectA, b: projectB } + ); + assert.equal(again.a.fixMode, "smart"); + assert.equal(again.a.quickCheck, "npm run build", "the rest of A's entry is as saved"); + assert.deepEqual(again.b, saved.readB, "B is untouched"); +}); + + +const WORKSPACE_URL = pathToFileURL(path.join(ROOT, "src", "web-console", "workspace.mjs")).href; + +test("loop-setup: an entry saved before fixMode existed reads as levels", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const got = inStore( + async (m, { project, workspace }) => { + const fs = await import("node:fs"); + const { foldKey } = await import(workspace); + const { fixMode, ...legacy } = { ...m.LOOP_DEFAULTS, fix: ["warning"], saved: "2026-01-01T00:00:00.000Z" }; + fs.writeFileSync(m.LOOP_SETUP_FILE, JSON.stringify({ schema: 1, projects: { [foldKey(project)]: legacy } })); + const stored = JSON.parse(fs.readFileSync(m.LOOP_SETUP_FILE, "utf8")).projects[foldKey(project)]; + return { read: m.readLoopSetup(project), onDisk: "fixMode" in stored }; + }, + { project: projectA, workspace: WORKSPACE_URL } + ); + assert.equal(got.onDisk, false, "the stored entry has no fixMode"); + assert.equal(got.read.remembered, true); + assert.equal(got.read.fixMode, "levels", "an older entry keeps fixing by level, not the new default"); + assert.deepEqual(got.read.fix, ["warning"], "the saved fields are kept"); +}); + +test("loop-setup: good web addresses save, with a bad name allowed only while no address is set", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const got = inStore( + (m, { project }) => { + const base = { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix] }; + const good = ["http://example.com", "https://example.com/hook?x=1#top", "HTTPS://EXAMPLE.COM/a%20b", "http://127.0.0.1:8080/"].map((notifyUrl) => m.saveLoopSetup(project, { ...base, notifyUrl, notifyParam: "msg_1.a-b~c" }).notifyUrl); + const hidden = m.saveLoopSetup(project, { ...base, notifyUrl: "", notifyParam: "a b" }); + const kinds = ["discord", "slack", "teams", "google-chat"].map((notifyKind) => m.saveLoopSetup(project, { ...base, notifyKind, notifyUrl: "https://example.com/x", notifyParam: "a b" }).notifyKind); + return { good, hidden, kinds }; + }, + { project: projectA } + ); + assert.equal(got.good.length, 4); + assert.equal(got.hidden.notifyUrl, ""); + assert.deepEqual(got.kinds, ["discord", "slack", "teams", "google-chat"], "a chat service ignores the hidden name"); +}); + +test("loop-setup: a bad field throws with the problem named and leaves the file unchanged", () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const cases = [ + ["silenceMinutes: 0", { silenceMinutes: 0 }, /"silenceMinutes" must be a whole number from 1 to 60/], + ["silenceMinutes: 61", { silenceMinutes: 61 }, /"silenceMinutes"/], + ...["example.com", "ftp://example.com", "javascript:alert(1)", "https:/example.com", "https://", "https://me:secret@example.com/", "https://exa mple.com", "https://example.com/é", "https://example.com/\nx", `https://e.com/${"x".repeat(2000)}`].map((notifyUrl) => [`notifyUrl: ${notifyUrl.slice(0, 30)}`, { notifyUrl }, /"notifyUrl" must be an http or https web address/]), + ["notifyUrl as a number", { notifyUrl: 5 }, /"notifyUrl"/], + ["notifyKind: carrier-pigeon", { notifyKind: "carrier-pigeon" }, /"notifyKind" must be one of query, discord, slack, teams, google-chat, json/], + ["a JSON field name with a space", { notifyKind: "json", notifyUrl: "https://example.com/", notifyParam: "a b" }, /"notifyParam"/], + ...["", "a b", "a=b", "a&b", "a%20b", "é", "x".repeat(65)].map((notifyParam) => [`notifyParam: ${notifyParam.slice(0, 10)}`, { notifyUrl: "https://example.com/", notifyParam }, /"notifyParam" must be 1 to 64 letters/]), + ["onQuestion: later", { onQuestion: "later" }, /"onQuestion" must be one of pause, stop, guess/], + ["an unknown key", { surprise: true }, /"surprise" is not a setup field/], + ["a two-line quickCheck", { quickCheck: "npm run build\nrm -rf x" }, /"quickCheck" must be one line of at most 500 characters/], + ["a 501-character quickCheck", { quickCheck: "x".repeat(501) }, /"quickCheck"/], + ["fixMode: sometimes", { fixMode: "sometimes" }, /"fixMode" must be one of levels, smart/], + ["a repeated fix level", { fix: ["critical", "critical"] }, /"fix" must list distinct levels/], + ["review as a string", { review: "yes" }, /"review" must be true or false/], + ["afterLast: never", { afterLast: "never" }, /"afterLast" must be one of offer-finalize, run-finalize/], + ]; + + const attempt = () => + inStore( + (m, { project, list }) => + list.map(([what, change]) => { + try { + m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: [...m.LOOP_DEFAULTS.fix], ...change }); + return { what, threw: false }; + } catch (e) { + return { what, threw: true, message: e.message, problems: e.problems }; + } + }), + { project: projectA, list: cases.map(([what, change]) => [what, change]) } + ); + const check = (results) => { + for (const [i, [what, , expected]] of cases.entries()) { + assert.equal(results[i].threw, true, `${what} is refused`); + assert.match(results[i].message, /^the loop setup is not valid: /); + assert.match(results[i].message, expected, what); + assert.ok(Array.isArray(results[i].problems) && results[i].problems.length >= 1); + } + }; + + // First with no file at all: a refusal must not create one. + check(attempt()); + assert.equal(fs.existsSync(LOOP_SETUP_PATH), false, "no file was created by a refused save"); + + // Then with a good entry on file: the bytes stay as they were. + inStore((m, { project }) => m.saveLoopSetup(project, { ...m.LOOP_DEFAULTS, fix: ["warning"], quickCheck: "npm run lint" }), { project: projectA }); + const before = fs.readFileSync(LOOP_SETUP_PATH, "utf8"); + check(attempt()); + assert.equal(fs.readFileSync(LOOP_SETUP_PATH, "utf8"), before, "the file is byte for byte unchanged"); + + // A non-object and a partial entry are refused too. + const odd = inStore( + (m, { project }) => + [null, [], "x", { review: true }].map((entry) => { + try { + m.saveLoopSetup(project, entry); + return { threw: false }; + } catch (e) { + return { threw: true, message: e.message }; + } + }), + { project: projectA } + ); + assert.ok(odd.every((r) => r.threw), "a non-object or a partial entry is refused"); + assert.match(odd[0].message, /must be an object/); + assert.match(odd[3].message, /"fixMode" must be one of/); + assert.equal(fs.readFileSync(LOOP_SETUP_PATH, "utf8"), before); +}); + +test("loop-setup: GET /loop-setup lists the phases left for a spec and refuses anything but specs/", async () => { + fs.rmSync(LOOP_SETUP_PATH, { force: true }); + const cwd = tempProject("route"); + fs.mkdirSync(path.join(cwd, "specs", "demo"), { recursive: true }); + fs.writeFileSync( + path.join(cwd, "specs", "demo", "overview.md"), + [ + "# Demo", + "", + "## Phase Checklist", + "", + "- [x] **Phase 1:** Setup - [phase-1.md](phase-1.md)", + "- [ ] **Phase 2:** Build the screen - [phase-2.md](phase-2.md)", + "- [/] **Phase 3:** Ship it - [phase-3.md](phase-3.md)", + "", + "## Notes", + "", + "- [ ] Phase 9: not in the checklist", + "", + ].join("\n") + ); + fs.mkdirSync(path.join(cwd, "specs", "empty"), { recursive: true }); + fs.writeFileSync(path.join(cwd, "package.json"), JSON.stringify({ scripts: { build: "tsc", lint: "eslint ." } })); + + const opened = run(["open", "--workflow", "implement", "--no-open"], { cwd }); + assert.equal(opened.status, 0, opened.stderr); + const { base, cookie } = sessionUrl(opened.json.url); + const get = async (query) => { + const res = await fetch(`${base}/loop-setup${query}`, { headers: { cookie, connection: "close" } }); + return { status: res.status, body: await res.json() }; + }; + const send = (body) => + fetch(`${base}/loop-setup`, { + method: "POST", + headers: { "content-type": "application/json", cookie, origin: base, connection: "close" }, + body: JSON.stringify(body), + }); + try { + const bare = await get(""); + assert.equal(bare.status, 200); + assert.equal(bare.body.remembered, false); + assert.equal(bare.body.fixMode, "smart"); + assert.equal("phasesLeft" in bare.body, false, "without a spec, only the setup"); + + const demo = await get("?spec=specs/demo"); + assert.equal(demo.status, 200); + assert.deepEqual(demo.body.phasesLeft, [{ n: 2, name: "Build the screen" }, { n: 3, name: "Ship it" }]); + assert.equal(demo.body.suggestedQuickCheck, "npm run build"); + assert.equal(demo.body.remembered, false); + + assert.deepEqual((await get("?spec=specs/empty")).body.phasesLeft, [], "no overview.md, nothing to build"); + assert.deepEqual((await get("?spec=specs/missing")).body.phasesLeft, []); + + for (const spec of ["../x", "specs/../x", "specs/a/b", "specs/.hidden", "/etc", "specs", "specs/", "specs%2F..%2Fx"]) { + const refused = await get(`?spec=${spec}`); + assert.equal(refused.status, 400, `spec=${spec} is refused`); + assert.match(refused.body.error, /spec must be a folder directly under specs\//); + } + + // Saving through the route, then reading it back in a new request. + const save = await send({ review: true, fixMode: "smart", fix: ["critical"], commit: true, onQuestion: "stop", afterLast: "offer-finalize", quickCheck: "", notifyKind: "query", notifyUrl: "https://example.com/hook", notifyParam: "msg", retryOnce: true, silenceMinutes: 30 }); + assert.equal(save.status, 200, await save.clone().text()); + const after = await get("?spec=specs/demo"); + assert.equal(after.body.remembered, true); + assert.equal(after.body.fixMode, "smart"); + assert.equal(after.body.silenceMinutes, 30); + assert.equal(after.body.notifyUrl, "https://example.com/hook"); + assert.equal(after.body.notifyParam, "msg"); + + const refusedSave = await send({ silenceMinutes: 0 }); + assert.equal(refusedSave.status, 400); + assert.ok((await refusedSave.json()).problems.some((p) => /"silenceMinutes"/.test(p))); + assert.equal((await get("")).body.silenceMinutes, 30, "a refused save changed nothing"); + } finally { + cli(["stop", "--session", opened.json.sid, "--force"], { cwd, expectFail: true }); + } +}); diff --git a/scripts/test-web-console-notepad.mjs b/scripts/test-web-console-notepad.mjs index 031a06b..3ee67c7 100644 --- a/scripts/test-web-console-notepad.mjs +++ b/scripts/test-web-console-notepad.mjs @@ -779,7 +779,7 @@ test("two folders get two notepads through their own sessions", async (t) => { // live process sits in: stop both, and wait until neither answers, before // cleaning up (stop returns before the process has gone). t.after(async () => { - for (const [cwd, sid] of sids) cliIn(cwd, ["stop", "--session", sid]); + for (const [cwd, sid] of sids) cliIn(cwd, ["stop", "--session", sid, "--force"]); const gone = async ({ base }) => { try { await fetch(`${base}/health`, { signal: AbortSignal.timeout(1000) }); @@ -1204,7 +1204,7 @@ test("the sweeps at open leave a 60-day-old notepad untouched", async () => { assert.equal(readNotepad(folder).text, "kept for months"); assert.equal(readNotepad(folder).images.length, 1); assert.equal(fs.statSync(noteFile).mtimeMs, before, "not even touched"); - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); removeNotepad(notepadKey(folder)); }); diff --git a/scripts/test-web-console-page-ask.mjs b/scripts/test-web-console-page-ask.mjs index dd09e0a..7d5efda 100644 --- a/scripts/test-web-console-page-ask.mjs +++ b/scripts/test-web-console-page-ask.mjs @@ -11,6 +11,7 @@ import test from "node:test"; import assert from "node:assert/strict"; import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs"; import { reportedHelper } from "./web-console-test-helpers.mjs"; +import { readChat } from "../src/web-console/inbox.mjs"; const suite = pageSuite(test); @@ -31,6 +32,13 @@ const PNG = Buffer.from( function collect(s) { const got = s.wait(10); assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`); + // The wire hands over the Quick questions' seq numbers; the entries stay in the + // session's chat log, so the tests read them from there. + if (Array.isArray(got.chat)) { + const seqs = new Set(got.chat); + got.chat = readChat(s.session).filter((e) => seqs.has(e.seq)); + got.type ||= "chat"; + } return got; } @@ -65,7 +73,7 @@ test("a Quick question typed in Ask reaches the agent under chat, and the agent' const [asked, ...more] = messages(got); assert.equal(more.length, 0, "one question, one message"); assert.equal(asked.text, "Where does the export live?"); - assert.match(got.reply, /^Quick question: Where does the export live\?$/m); + assert.match(got.reply, /^Quick question \(\d+\): Where does the export live\?$/m); // The question is in the pane, and the box is empty for the next one. await s.page.locator(".ask-row.person").getByText("Where does the export live?").waitFor(); assert.equal(await s.page.locator("#ask-input").inputValue(), ""); diff --git a/scripts/test-web-console-page-cards.mjs b/scripts/test-web-console-page-cards.mjs index 5935696..72b3b08 100644 --- a/scripts/test-web-console-page-cards.mjs +++ b/scripts/test-web-console-page-cards.mjs @@ -616,6 +616,27 @@ test("Something else in your own words replaces the pick, and picking an option assert.deepEqual(answerTo(got, "c1"), { text: "A shared drive" }); }); +// What a person sees break: a stray pick on a one-answer question can only be +// swapped for another, never taken back, or Clear shows on a card already sent. +test("Clear on a one-answer question takes back the pick and the words, and a sent card has no Clear", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan" }); + const card = await ask(s, { id: "c1", kind: "choice", title: "Where", body: "Where?", options: [opt("A", "Email"), opt("B", "Slack")] }); + const clear = card.getByRole("button", { name: "Clear your answer to this question" }); + await card.getByRole("radio", { name: "Something else, in your own words" }).check(); + await card.locator("textarea.other-text").fill("A shared drive"); + await clear.click(); + await s.page.waitForFunction(() => !document.querySelector("#main .card.is-staged")); + assert.equal(await card.locator("textarea.other-text").inputValue(), "", "the words go too"); + await card.getByLabel("Slack").check(); + await clear.click(); + await s.page.waitForFunction(() => !document.querySelector("#main .card.is-staged")); + assert.equal(await card.locator("input[type=radio]:checked").count(), 0, "no pick is left"); + await card.getByLabel("Email").check(); + await s.page.click("#btn-send"); + await card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/).waitFor(); + assert.equal(await clear.count(), 0, "a sent card cannot be cleared"); +}); + // What a person sees break: a note typed on a card is dropped by the verdict, // or is lost when the verdict comes first. test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => { diff --git a/scripts/test-web-console-page-dashboard.mjs b/scripts/test-web-console-page-dashboard.mjs index cd80898..79d1c35 100644 --- a/scripts/test-web-console-page-dashboard.mjs +++ b/scripts/test-web-console-page-dashboard.mjs @@ -207,6 +207,8 @@ const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { test("picking Start from scratch instead of a spec grays Document, and a launch then carries no spec", async (t) => { const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) }); const main = await toTheMenu(s); + // A grayed card has to show to be checked, whatever an earlier test left. + await hideUnavailable(main, false); const document = lightOf(main, "/plan2code-2-document"); await pickedChip(main, "demo").waitFor(); assert.equal(await document.isEnabled(), true, "Document is lit for the drafted spec"); diff --git a/scripts/test-web-console-page-help.mjs b/scripts/test-web-console-page-help.mjs index ab04d7b..8a528e1 100644 --- a/scripts/test-web-console-page-help.mjs +++ b/scripts/test-web-console-page-help.mjs @@ -20,7 +20,7 @@ import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js"; // The agent's side of `stop`, leaving the browser context open (s.stop() // closes it, which would hide what the page does next). async function stopServer(s) { - cli(["stop", "--session", s.sid], { cwd: s.project }); + cli(["stop", "--session", s.sid, "--force"], { cwd: s.project }); assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop"); } diff --git a/scripts/test-web-console-page-loop.mjs b/scripts/test-web-console-page-loop.mjs new file mode 100644 index 0000000..f5b3053 --- /dev/null +++ b/scripts/test-web-console-page-loop.mjs @@ -0,0 +1,329 @@ +// Page tests for the Implementation Loop's setup screen. The dashboard card +// that opens it only shows inside the desktop app, so these open the screen +// through its own module, then drive the real page. Run with: +// node --test scripts/test-web-console-page-loop.mjs + +import test from "node:test"; +import assert from "node:assert/strict"; +import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs"; + +const suite = pageSuite(test); + +const PROJECT = { + "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n", + "specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n- [ ] Phase 2: Two\n", + "specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n", + "specs/ready/phase-2.md": "# Phase 2\n\n- [ ] **Task 2.1:** Two\n", +}; + +const MENU = { menu: { note: "Ready when you are." }, agent: { status: "waiting" } }; + +async function openSetup(t) { + const browser = await suite.browser(); + const s = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) }); + // Past Planny's wake-up and, on a first run, the Welcome. + const skip = s.page.getByRole("button", { name: "Skip the intro" }); + await skip.click(); + await skip.waitFor({ state: "hidden" }); + await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor(); + const welcomeDone = s.page.getByRole("button", { name: "Start building" }); + if (await welcomeDone.isVisible()) { + await welcomeDone.click(); + await welcomeDone.waitFor({ state: "hidden" }); + } + await s.page.evaluate(async () => { + const m = await import(new URL("screens/loop-setup.js", document.baseURI).href); + await m.openLoopSetup({ dir: "specs/ready" }); + }); + await s.page.locator("#loop-start").waitFor(); + return s; +} + +test("the setup lists each phase on its own line, in the agreed order of fields and radios", async (t) => { + const s = await openSetup(t); + const left = s.page.locator(".loop-fact dd").first(); + assert.equal(await textOf(left), "Phase 1: One\nPhase 2: Two"); + + const labels = await s.page.locator(".loop-label").allInnerTexts(); + assert.deepEqual(labels, [ + "Review", + "Fix findings", + "When a phase asks something", + "After the last phase", + "Send a notification", + "Quick check", + "If a phase crashes or goes quiet", + "Commit", + ]); + const radios = (name) => s.page.locator(`input[name="${name}"]`).evaluateAll((all) => all.map((r) => [r.id, r.checked])); + assert.deepEqual(await radios("fixmode"), [["loop-fixmode-smart", true], ["loop-fixmode-levels", false]]); + assert.deepEqual(await radios("onquestion"), [["loop-onquestion-guess", true], ["loop-onquestion-pause", false], ["loop-onquestion-stop", false]]); +}); + +test("the web address field shows the name only beside an address, warns while typing and saves", async (t) => { + const s = await openSetup(t); + const url = s.page.locator("#loop-notify-url"); + const param = s.page.locator("#loop-notify-param"); + const warn = s.page.locator(".loop-field", { hasText: "Send a notification" }).locator(".loop-warn"); + + assert.equal(await url.inputValue(), ""); + assert.equal(await param.isVisible(), false, "no address, no name to set"); + assert.equal(await warn.isVisible(), false); + + await url.fill("example.com"); + assert.match(await textOf(warn), /must start with http:\/\/ or https:\/\//); + await url.fill("https://me:secret@example.com/"); + assert.match(await textOf(warn), /Leave out any user name or password/); + await url.fill("https://example.com/hook?team=a"); + assert.equal(await warn.isVisible(), false); + assert.equal(await param.isVisible(), true); + assert.equal(await param.inputValue(), "message", "the default name"); + + await param.fill("a b"); + assert.match(await textOf(warn), /letters, digits/); + await param.fill("msg"); + assert.equal(await warn.isVisible(), false); + + // What Start would send; Start itself waits on facts only the app gives. + const saved = await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + const res = await fetch("/loop-setup", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify(page.loopSetup.form), + }); + return { status: res.status, body: await res.json() }; + }); + assert.equal(saved.status, 200, JSON.stringify(saved.body)); + const reread = await s.page.evaluate(async () => (await fetch("/loop-setup")).json()); + assert.equal(reread.notifyUrl, "https://example.com/hook?team=a"); + assert.equal(reread.notifyParam, "msg"); + assert.equal(reread.remembered, true); +}); + +// Stands a real window in for the app that frames the page, listening to what +// the page tells it; `answer` then replies the way the app's window does. +async function frameInFakeApp(s) { + await s.page.evaluate(() => { + const frame = document.createElement("iframe"); + frame.hidden = true; + document.body.appendChild(frame); + const app = frame.contentWindow; + window.__told = []; + app.postMessage = (message) => window.__told.push(message); + Object.defineProperty(window, "parent", { value: app, configurable: true }); + }); + return (data) => + s.page.evaluate((message) => { + window.dispatchEvent(new MessageEvent("message", { source: window.parent, data: message })); + }, data); +} + +test("Cancel in the app's confirm leaves Start ready to press again; a real start locks it", async (t) => { + const s = await openSetup(t); + const answer = await frameInFakeApp(s); + const start = s.page.locator("#loop-start"); + const asked = () => s.page.evaluate(() => window.__told.filter((m) => m.plan2code === "loop-start").length); + await answer({ plan2code: "loop-facts", facts: { permissionMode: "skip", promptSupport: true } }); + await s.page.waitForFunction(() => !document.getElementById("loop-start").disabled); + + await start.click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "loop-start")); + await s.page.getByText("Waiting for the app's confirm...").waitFor(); + assert.equal(await start.isDisabled(), true, "no second confirm while one is open"); + + await answer({ plan2code: "loop-start-result", ok: true, started: false, error: null }); + await s.page.getByText("Waiting for the app's confirm...").waitFor({ state: "hidden" }); + assert.equal(await start.isDisabled(), false, "pressing Cancel gives the button back"); + assert.doesNotMatch(await textOf(s.page.locator(".loop-start")), /The loop is starting/); + + await start.click(); + await s.page.waitForFunction(() => window.__told.filter((m) => m.plan2code === "loop-start").length === 2); + assert.equal(await asked(), 2, "and it asks the app again"); + + await answer({ plan2code: "loop-start-result", ok: true, started: true, error: null }); + await s.page.getByText("The loop is starting...").waitFor(); + assert.equal(await start.isDisabled(), true); +}); + +test("Send a test saves what is on screen, names nothing to the app, and shows what the app answered", async (t) => { + const s = await openSetup(t); + const answer = await frameInFakeApp(s); + const button = s.page.locator("#loop-notify-test"); + const url = s.page.locator("#loop-notify-url"); + const told = () => s.page.evaluate(() => window.__told.filter((m) => m.plan2code === "loop-notify-test")); + const line = s.page.locator(".loop-test p"); + + assert.equal(await button.isDisabled(), true, "nothing to test yet"); + await url.fill("example.com"); + assert.equal(await button.isDisabled(), true, "not an address yet"); + await url.fill("https://hooks.slack.com/services/T/B/x"); + assert.equal(await button.isDisabled(), false); + + await button.click(); + await s.page.waitForFunction(() => window.__told.some((m) => m.plan2code === "loop-notify-test")); + assert.deepEqual(await told(), [{ plan2code: "loop-notify-test" }], "no address in the message"); + const saved = await s.page.evaluate(async () => (await fetch("/loop-setup")).json()); + assert.equal(saved.notifyUrl, "https://hooks.slack.com/services/T/B/x", "saved before the app was asked"); + assert.equal(saved.notifyKind, "slack"); + assert.match(await line.innerText(), /Waiting for the app's confirm/); + assert.equal(await button.isDisabled(), true, "one test at a time"); + + await answer({ plan2code: "loop-notify-test-result", ok: false, sent: false, error: "The test was not sent: it answered 404" }); + await s.page.locator(".loop-test p.loop-error").waitFor(); + assert.equal(await line.innerText(), "The test was not sent: it answered 404"); + assert.equal(await url.inputValue(), "https://hooks.slack.com/services/T/B/x", "the redraw kept the address"); + + await s.page.locator("#loop-notify-test").click(); + await line.getByText("Waiting").waitFor(); + await answer({ plan2code: "loop-notify-test-result", ok: true, sent: true, error: null }); + await line.getByText("Check that the message arrived").waitFor(); + + await s.page.locator("#loop-notify-url").fill("https://hooks.slack.com/services/T/B/y"); + assert.equal(await line.count(), 0, "a changed address forgets what the test said"); + + // Cancel in the app's confirm: nothing to report. + await s.page.locator("#loop-notify-test").click(); + await line.getByText("Waiting").waitFor(); + await answer({ plan2code: "loop-notify-test-result", ok: true, sent: false, error: null }); + await s.page.waitForFunction(() => !document.querySelector(".loop-test p")); + assert.equal(await s.page.locator("#loop-notify-test").isDisabled(), false); +}); + +test("a pasted webhook picks its own kind, a chat service hides the name, and a kind chosen by hand stays", async (t) => { + const s = await openSetup(t); + const kind = s.page.locator("#loop-notify-kind"); + const url = s.page.locator("#loop-notify-url"); + const param = s.page.locator("#loop-notify-param"); + + assert.equal(await kind.inputValue(), "query"); + for (const [address, expected] of [ + ["https://discord.com/api/webhooks/1/abc", "discord"], + ["https://hooks.slack.com/services/T/B/x", "slack"], + ["https://chat.googleapis.com/v1/spaces/A/messages?key=k", "google-chat"], + ["https://prod-1.westus.logic.azure.com/workflows/x", "teams"], + ]) { + await kind.selectOption("query"); + await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + page.loopSetup.notifyKindChosen = false; + }); + await url.fill(address); + assert.equal(await kind.inputValue(), expected, address); + assert.equal(await param.isVisible(), false, "the service fixes the field"); + } + + // The person's own choice wins over what the address looks like. + await kind.selectOption("query"); + await url.fill("https://discord.com/api/webhooks/2/def"); + assert.equal(await kind.inputValue(), "query"); + assert.equal(await param.isVisible(), true); + + await kind.selectOption("json"); + assert.equal(await s.page.locator('label:has(#loop-notify-param) span').innerText(), "JSON field name for the message"); + await kind.selectOption("slack"); + assert.equal(await url.getAttribute("placeholder"), "https://hooks.slack.com/services/..."); + + const saved = await s.page.evaluate(async () => { + const { page } = await import(new URL("state.js", document.baseURI).href); + const res = await fetch("/loop-setup", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(page.loopSetup.form) }); + return res.status; + }); + assert.equal(saved, 200); + assert.equal((await s.page.evaluate(async () => (await fetch("/loop-setup")).json())).notifyKind, "slack"); +}); + +test("the finish card counts each kind of decision per phase and opens on the full report", async (t) => { + const s = await openSetup(t); + const seen = await s.page.evaluate(async () => { + const m = await import(new URL("screens/ending.js", document.baseURI).href); + const card = m.renderLoopEnd({ + kind: "finished", + line: "All 1 phases built", + phases: [{ n: 2, name: "API", commit: "abc1234", unfixed: 3, retries: 1, fixed: 4, skipped: 2, left: 1, assumed: 5, decisions: 6 }], + uncommitted: [], + can: ["finalize"], + }); + return { + head: [...card.querySelectorAll("th")].map((c) => c.textContent), + row: [...card.querySelectorAll("td")].map((c) => c.textContent), + }; + }); + assert.deepEqual(seen.head, ["Phase", "Commit", "Fixed", "Not fixed", "Left open", "Assumed", "Other decisions", "Retries"]); + assert.deepEqual(seen.row.slice(0, 1), ["Phase 2: API"]); + assert.deepEqual(seen.row.slice(2), ["4", "2", "1", "5", "6", "1"]); +}); + +// A real loop session: `open --loop` under the app's signal stamps the lock. +async function openLoopPage(t) { + return openSession(await suite.browser(), { + t, + workflow: "implement", + open: ["--loop"], + env: { PLAN2CODE_IN_APP: "1" }, + payload: { title: "demo: Phase 1", headline: { stage: "Build", cleared: 9, total: 11 }, agent: { status: "working", activity: "Task 10 of 11" } }, + project: tempProject(PROJECT), + }); +} + +test("a loop at work tells the person they have nothing to do, and Send comes back when a question waits", async (t) => { + const s = await openLoopPage(t); + const foot = s.page.locator(".footer"); + const send = s.page.locator("#btn-send"); + await s.page.waitForFunction(() => document.querySelector(".footer")?.classList.contains("is-loop-idle")); + assert.equal(await send.isVisible(), false, "no Send to suggest there is something to send"); + assert.equal(await s.page.locator("#footer-summary").isVisible(), false); + assert.equal(await textOf(s.page.locator("#progress-text")), "9 of 11 tasks in this phase"); + assert.match(await textOf(s.page.locator("#main")), /The loop is running this phase by itself, so you don't need to do anything/); + + s.post({ items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } }); + await s.page.waitForFunction(() => !document.querySelector(".footer").classList.contains("is-loop-idle")); + assert.equal(await send.isVisible(), true, "the person has something to do now"); + assert.equal((await foot.getAttribute("class")).includes("is-loop-idle"), false); +}); + +test("an ordinary build keeps its Send, its count and its words", async (t) => { + const s = await openSession(await suite.browser(), { + t, + workflow: "implement", + payload: { title: "demo: Phase 1", headline: { stage: "Build", cleared: 9, total: 11 }, agent: { status: "working", activity: "Task 10 of 11" } }, + project: tempProject(PROJECT), + }); + await s.page.locator("#progress-text").getByText("9 of 11 done").waitFor(); + assert.equal(await s.page.locator("#btn-send").isVisible(), true); + assert.equal((await s.page.locator(".footer").getAttribute("class")).includes("is-loop-idle"), false); + assert.match(await textOf(s.page.locator("#main")), /If Plan2Code needs you, the question appears here on its own/); +}); + +test("a phase that has reported says the loop is checking it, not that it is starting", async (t) => { + const s = await openLoopPage(t); + s.post({ + agent: { status: "waiting" }, + loopOutcome: { + phase: 1, + result: "failed", + reason: "tests", + summary: "One test fails", + tests: { ran: true, passed: false, summary: "1 fail" }, + review: { ran: true, recheck: false, left: { critical: 0, warning: 0, suggestion: 0 }, fixed: [], unfixed: [] }, + tasks: { blocked: [], assumed: [] }, + conflicts: [], + decisions: [], + subject: "Add a thing", + }, + }); + await s.page.getByRole("heading", { name: "The loop is checking this phase" }).waitFor(); + assert.doesNotMatch(await textOf(s.page.locator("#main")), /starting this phase/); +}); + +test("a loop phase still starting says the loop is starting it, and promises no approval prompt", async (t) => { + const s = await openSession(await suite.browser(), { + t, + workflow: "implement", + open: ["--loop"], + env: { PLAN2CODE_IN_APP: "1" }, + project: tempProject(PROJECT), + }); + await s.page.getByRole("heading", { name: "The loop is starting this phase" }).waitFor(); + assert.doesNotMatch(await textOf(s.page.locator("#main")), /pause for approvals/); +}); diff --git a/scripts/test-web-console-page-notepad.mjs b/scripts/test-web-console-page-notepad.mjs index 1d2a107..586a0e3 100644 --- a/scripts/test-web-console-page-notepad.mjs +++ b/scripts/test-web-console-page-notepad.mjs @@ -190,7 +190,7 @@ test("typing Markdown styles it in place, saves within two seconds, and survives assert.equal(await shows(s, expected), expected, "a reload shows the saved note"); // A server restart (the agent's open --resume) keeps it too. - cli(["stop", "--session", s.sid], { cwd: s.project }); + cli(["stop", "--session", s.sid, "--force"], { cwd: s.project }); await until(async () => !(await s.answers()), 5000); const resumed = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "plan"], { cwd: s.project }).json; s.url = resumed.url; @@ -1113,6 +1113,7 @@ test("User Preferences, Cleanup offers a month-old notepad by its folder and rem t.after(() => fs.rmSync(notepadFolder(other), { recursive: true, force: true })); await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-system"); await s.page.click("#cleanup-scan"); const list = s.page.locator("#cleanup-list"); const row = list.locator(".cleanup-row").filter({ hasText: "Notebook for" }); diff --git a/scripts/test-web-console-page-prefs.mjs b/scripts/test-web-console-page-prefs.mjs index 25bc058..5b53b18 100644 --- a/scripts/test-web-console-page-prefs.mjs +++ b/scripts/test-web-console-page-prefs.mjs @@ -1,5 +1,6 @@ -// Page tests for User Preferences: the saved looks (highlight and theme), the -// launcher's model menus and the Cleanup tab. Run with: +// Page tests for User Preferences: its four tabs, the saved looks (highlight +// and theme), the Agents & models tab (the launcher's model menus and the +// person's agents) and Cleanup. Run with: // node --test scripts/test-web-console-page-prefs.mjs // // Each test drives the real console in a real Chrome or Edge through @@ -10,7 +11,7 @@ import fs from "node:fs"; import path from "node:path"; import test from "node:test"; import assert from "node:assert/strict"; -import { pageSuite, openSession, textOf, drawn } from "./page-test-helpers.mjs"; +import { pageSuite, openSession, textOf, drawn, styleOf, stylesOf } from "./page-test-helpers.mjs"; import { HOME, MODELS_DIR, backdate } from "./web-console-test-helpers.mjs"; import { formatBytes } from "../src/web-console/public/answers.js"; @@ -84,148 +85,315 @@ test("the violet highlight and dark theme chosen in preferences stick across a r assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks"); }); -test("the launcher's model menus have Claude, Devin and Codex tabs, and a model id typed on the Codex tab is saved", async (t) => { +// The Agents & models tab: the summary table, its rows and the form Edit opens. +const AGENTS_FILE = path.join(MODELS_DIR, "agents.json"); +const agentsTable = (s) => s.page.locator("#agents-table"); +const agentRow = (s, key) => s.page.locator(`#agents-table tr[data-key="${key}"]`); +const agentForm = (s) => s.page.locator("#agents-form"); +const formField = (s, name) => agentForm(s).getByRole("textbox", { name, exact: true }); +const formButton = (s, name) => agentForm(s).getByRole("button", { name, exact: true }); +const unsavedPrompt = (s) => s.page.locator("#prefs-unsaved"); + +async function openAgentsTab(s) { + await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-agents"); + await agentRow(s, "cli:claude").waitFor(); +} + +// agents.json as the test starts it: none, or the entries given. Removed after. +function seedAgents(t, agents) { + fs.rmSync(AGENTS_FILE, { force: true }); + if (agents) { + fs.mkdirSync(MODELS_DIR, { recursive: true }); + fs.writeFileSync(AGENTS_FILE, JSON.stringify({ schema: 1, agents }, null, 2)); + } + t.after(() => fs.rmSync(AGENTS_FILE, { force: true })); +} + +test("Agents & models: the table lists Claude, Devin and Codex, and a model id typed in Codex's form is saved only on Save", async (t) => { noSavedLooks(t); + seedAgents(t); // The file the launcher reads: put back as the suite had it (no file). t.after(() => fs.rmSync(path.join(MODELS_DIR, "models.json"), { force: true })); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); - await s.page.click("#btn-looks"); - const tabs = s.page.getByRole("group", { name: "Which agent" }); - for (const name of ["Claude", "Devin", "Codex"]) assert.equal(await tabs.getByRole("button", { name, exact: true }).count(), 1, `a ${name} tab`); - const pressed = async () => (await tabs.locator('button[aria-pressed="true"]').allInnerTexts()).map((x) => x.trim()); - assert.deepEqual(await pressed(), ["Claude"], "the menus open on Claude"); + await openAgentsTab(s); + const keys = await agentsTable(s).locator("tbody tr[data-key]").evaluateAll((rows) => rows.map((r) => r.dataset.key)); + assert.deepEqual(keys, ["cli:claude", "cli:devin", "cli:codex"]); + assert.equal(await textOf(agentRow(s, "cli:codex").locator(".prefs-agents-name > span").first()), "Codex"); - await tabs.getByRole("button", { name: "Codex", exact: true }).click(); - assert.deepEqual(await pressed(), ["Codex"]); - await s.page.click("#models-add"); - const id = s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }); + await s.page.getByRole("button", { name: "Edit Codex" }).click(); + await agentForm(s).waitFor(); + assert.equal(await agentsTable(s).isVisible(), false, "the form takes the table's place"); + await agentForm(s).locator(".prefs-agents-none").filter({ hasText: /^No models ship for Codex yet/ }).waitFor(); + assert.equal(await agentForm(s).locator(".models-row.locked").count(), 0, "nothing comes with Plan2Code for Codex"); + + await formButton(s, "Add a model").click(); + const id = formField(s, "Model id"); await id.fill("gpt-test-codex-1"); await id.press("Tab"); - await s.page.locator("#models-status").filter({ hasText: /^Saved\./ }).waitFor(); + await s.page.waitForTimeout(300); + const before = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user); + assert.deepEqual(before.codex, [], "nothing is saved before Save"); + assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), true); + + await formButton(s, "Save").click(); + await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved\. Restart plan2code/ }).waitFor(); const saved = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user); assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-1"], "the id was not saved under Codex"); assert.deepEqual([saved.claude, saved.devin], [[], []], "the id leaked into another agent's menu"); + assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), false, "saved, nothing is unsaved"); - // Back on Claude the typed id is not listed; on Codex it is, after a reload. - await tabs.getByRole("button", { name: "Claude", exact: true }).click(); - assert.equal(await s.page.locator("#models-user .models-row").count(), 0); + // The summary counts it on Codex's row, and so does a fresh page. + await formButton(s, "Back to summary").click(); + assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label") || document.activeElement?.id), "Edit Codex", "focus comes back to the row just left"); + assert.match(await textOf(agentRow(s, "cli:codex").locator(".prefs-agents-models")), /^1: gpt-test-codex-1$/); await s.page.reload({ waitUntil: "domcontentloaded" }); await drawn(s.page); - await s.page.click("#btn-looks"); - await s.page.locator("#models-tab-codex").click(); - await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).waitFor(); - assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1"); + await openAgentsTab(s); + await s.page.getByRole("button", { name: "Edit Codex" }).click(); + assert.equal(await formField(s, "Model id").inputValue(), "gpt-test-codex-1"); }); -test("Agents: a person adds an agent, tests its command, sees it saved after a reload, and deletes it", async (t) => { +test("Agents & models: a person adds an agent, tests its command, sees it after a reload, and deletes it", async (t) => { noSavedLooks(t); - const file = path.join(MODELS_DIR, "agents.json"); - fs.rmSync(file, { force: true }); - t.after(() => fs.rmSync(file, { force: true })); + seedAgents(t); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); - await s.page.click("#btn-looks"); - const list = s.page.locator("#agents-list"); - assert.equal(await list.locator(".agent-card").count(), 0, "no agents before one is added"); + await openAgentsTab(s); + assert.equal(await agentsTable(s).locator('tr[data-key^="agent:"]').count(), 0, "no agents before one is added"); await s.page.click("#agents-add"); - const card = list.locator(".agent-card").last(); - await card.getByRole("textbox", { name: "Name", exact: true }).fill("Test Agent"); - await card.getByRole("textbox", { name: "Command", exact: true }).fill("node"); - await card.getByRole("textbox", { name: "Command", exact: true }).press("Tab"); - await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor(); + await agentForm(s).waitFor(); + assert.equal(await agentForm(s).locator("details.prefs-agents-args").evaluate((d) => d.open), true, "the arguments are open on a new agent"); + await formField(s, "Name").fill("Test Agent"); + await formField(s, "Command").fill("node"); + await formButton(s, "Test").click(); + await agentForm(s).locator(".agent-test-result").filter({ hasText: /^Found at / }).waitFor(); + assert.equal(fs.existsSync(AGENTS_FILE), false, "Test never saves"); - await card.getByRole("button", { name: "Test", exact: true }).click(); - await card.locator(".agent-test-result").filter({ hasText: /^Found at / }).waitFor(); - - const saved = JSON.parse(fs.readFileSync(file, "utf8")); + await formButton(s, "Save").click(); + await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved$/ }).waitFor(); + const saved = JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")); assert.equal(saved.schema, 1); assert.deepEqual(saved.agents.map((a) => [a.id, a.name, a.command, a.prompt]), [["test-agent", "Test Agent", "node", "/plan2code"]]); - - // A second agent with the same name is refused on its own card and field. - await s.page.click("#agents-add"); - const second = list.locator(".agent-card").nth(1); - await second.getByRole("textbox", { name: "Command", exact: true }).fill("x"); - await second.getByRole("textbox", { name: "Name", exact: true }).fill("TEST AGENT"); - await second.getByRole("textbox", { name: "Name", exact: true }).press("Tab"); - await list.locator(".agent-card").nth(1).locator(".agent-error").filter({ hasText: /already used/ }).waitFor(); - assert.equal(await list.locator(".agent-card").nth(1).locator('input.invalid[data-field="name"]').count(), 1, "the name field is marked"); - assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).agents.length, 1, "a refused save writes nothing"); + assert.equal(await agentForm(s).locator(".prefs-agents-delete").count(), 1, "once saved it has Delete agent"); await s.page.reload({ waitUntil: "domcontentloaded" }); await drawn(s.page); - await s.page.click("#btn-looks"); - await list.locator(".agent-card").first().waitFor(); - assert.equal(await list.locator(".agent-card").count(), 1); - assert.equal(await list.locator(".agent-card").first().getByRole("textbox", { name: "Name", exact: true }).inputValue(), "Test Agent"); + await openAgentsTab(s); + const row = agentRow(s, "agent:test-agent"); + await row.locator(".prefs-badge.ok").waitFor(); + assert.equal(await textOf(row.locator(".prefs-badge")), "Found"); + await s.page.getByRole("button", { name: "Edit Test Agent" }).click(); + assert.equal(await formField(s, "Name").inputValue(), "Test Agent"); + assert.equal(await agentForm(s).locator("details.prefs-agents-args").evaluate((d) => d.open), false, "the arguments are folded on a saved agent"); - await list.locator(".agent-card").first().getByRole("button", { name: "Delete", exact: true }).click(); - await list.locator(".agent-card").first().getByRole("button", { name: "Yes, delete" }).click(); - await s.page.waitForFunction(() => document.querySelectorAll("#agents-list .agent-card").length === 0); - await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor(); - assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).agents, []); -}); - -test("Agents: a new card's first field is not saved alone, and a redraw keeps focus and what was typed", async (t) => { - noSavedLooks(t); - const file = path.join(MODELS_DIR, "agents.json"); - fs.rmSync(file, { force: true }); - t.after(() => fs.rmSync(file, { force: true })); - const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); - await s.page.click("#btn-looks"); - const list = s.page.locator("#agents-list"); + await formButton(s, "Delete agent").click(); + await formButton(s, "Yes, delete").click(); + await agentsTable(s).waitFor(); + assert.equal(await agentsTable(s).locator('tr[data-key^="agent:"]').count(), 0); + assert.deepEqual(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents, []); + assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label") || document.activeElement?.id), "agents-add", "with its row gone, focus goes to Add agent"); + assert.equal(await textOf(s.page.locator("#agents-status")), "Deleted."); await s.page.click("#agents-add"); - const card = list.locator(".agent-card").last(); - const name = card.getByRole("textbox", { name: "Name", exact: true }); - const command = card.getByRole("textbox", { name: "Command", exact: true }); - - await name.fill("Focus Agent"); - await name.press("Tab"); - await s.page.waitForTimeout(300); - assert.equal(await list.locator(".agent-error").count(), 0, "a name alone is not sent, so nothing is refused"); - assert.equal(fs.existsSync(file), false, "and nothing is written"); - assert.equal(await command.evaluate((el) => el === document.activeElement), true, "Tab lands on Command"); - - // The first good save assigns an id and redraws every card: focus stays where Tab put it. - await command.fill("node"); - await command.press("Tab"); - await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor(); - assert.equal(JSON.parse(fs.readFileSync(file, "utf8")).agents[0].id, "focus-agent"); - assert.equal(await s.page.evaluate(() => document.activeElement?.textContent), "Add an argument", "focus survives the redraw"); - - // A refused save redraws too: the field being typed in keeps its text, and leaving it saves it. - const prompt = list.locator(".agent-card").last().getByRole("textbox", { name: "Start prompt", exact: true }); - await name.fill(""); - await prompt.click(); - await prompt.fill("/plan2code hi"); - await list.locator(".agent-error").filter({ hasText: /name is missing/ }).waitFor(); - assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label")), "Start prompt"); - assert.equal(await s.page.evaluate(() => document.activeElement?.value), "/plan2code hi"); + assert.equal(await s.page.locator("#agents-status").innerText(), "", "opening a form clears Deleted."); }); -test("Agents: a file holding entries the page could not read is only replaced after Save anyway", async (t) => { +test("Agents & models: a new agent with only a name is not sent, its command is marked, and focus and text survive", async (t) => { + noSavedLooks(t); + seedAgents(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await openAgentsTab(s); + await s.page.click("#agents-add"); + await formField(s, "Name").fill("Focus Agent"); + await formButton(s, "Save").click(); + await agentForm(s).locator(".agent-error").filter({ hasText: "Give it a name and a command first." }).waitFor(); + assert.equal(fs.existsSync(AGENTS_FILE), false, "nothing is written"); + assert.equal(await agentForm(s).locator('input.invalid[data-field="command"]').count(), 1, "the command field is marked"); + assert.equal(await formField(s, "Name").inputValue(), "Focus Agent", "the typed name survives the redraw"); + assert.equal(await s.page.evaluate(() => document.activeElement?.textContent), "Save", "focus stays on Save"); + + // The first good save assigns an id; the form stays open on it. + await formField(s, "Command").fill("node"); + await formButton(s, "Save").click(); + await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved$/ }).waitFor(); + assert.equal(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents[0].id, "focus-agent"); + assert.equal(await textOf(agentForm(s).locator(".prefs-agents-title")), "Focus Agent"); + + // A refused save marks the field the server names, and keeps what was typed. + await formField(s, "Name").fill(""); + await formField(s, "Start prompt").fill("/plan2code hi"); + await formButton(s, "Save").click(); + await agentForm(s).locator(".agent-error").filter({ hasText: /name is missing/ }).waitFor(); + assert.equal(await agentForm(s).locator('input.invalid[data-field="name"]').count(), 1); + assert.equal(await formField(s, "Start prompt").inputValue(), "/plan2code hi"); + assert.equal(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents[0].name, "Focus Agent", "a refused save writes nothing"); +}); + +test("Agents & models: a file holding entries the page could not read is only replaced after Save anyway", async (t) => { noSavedLooks(t); - const file = path.join(MODELS_DIR, "agents.json"); - fs.mkdirSync(MODELS_DIR, { recursive: true }); const text = JSON.stringify({ schema: 2, agents: [{ id: "future", name: "Future", command: "future" }] }); - fs.writeFileSync(file, text); - t.after(() => fs.rmSync(file, { force: true })); + fs.mkdirSync(MODELS_DIR, { recursive: true }); + fs.writeFileSync(AGENTS_FILE, text); + t.after(() => fs.rmSync(AGENTS_FILE, { force: true })); const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); - await s.page.click("#btn-looks"); + await openAgentsTab(s); await s.page.locator("#agents-status").filter({ hasText: /schema 2/ }).waitFor(); - assert.equal(await s.page.locator("#agents-replace").isVisible(), false, "no Save anyway before a save is tried"); await s.page.click("#agents-add"); - const card = s.page.locator("#agents-list .agent-card").last(); - await card.getByRole("textbox", { name: "Name", exact: true }).fill("Mine"); - await card.getByRole("textbox", { name: "Command", exact: true }).fill("node"); - await card.getByRole("textbox", { name: "Command", exact: true }).press("Tab"); - await s.page.locator("#agents-status").filter({ hasText: /could not read/ }).waitFor(); - assert.equal(fs.readFileSync(file, "utf8"), text, "the refused save writes nothing"); + assert.equal(await formButton(s, "Save anyway").count(), 0, "no Save anyway before a save is tried"); + await formField(s, "Name").fill("Mine"); + await formField(s, "Command").fill("node"); + await formButton(s, "Save").click(); + await agentForm(s).locator(".agent-error").filter({ hasText: /could not read/ }).first().waitFor(); + assert.equal(fs.readFileSync(AGENTS_FILE, "utf8"), text, "the refused save writes nothing"); - await s.page.locator("#agents-replace").click(); - await s.page.locator("#agents-status").filter({ hasText: /^Saved./ }).waitFor(); - assert.equal(await s.page.locator("#agents-replace").isVisible(), false); - assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).agents.map((a) => a.id), ["mine"]); + await formButton(s, "Save anyway").click(); + await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved$/ }).waitFor(); + assert.equal(await formButton(s, "Save anyway").count(), 0); + assert.deepEqual(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents.map((a) => a.id), ["mine"]); +}); + +const TWO_AGENTS = [ + { id: "alpha", name: "Alpha", command: "alpha-cli" }, + { id: "beta", name: "Beta", command: "beta-cli" }, +]; + +test("Agents & models: nothing reaches agents.json before Save", async (t) => { + noSavedLooks(t); + seedAgents(t, TWO_AGENTS); + const before = fs.readFileSync(AGENTS_FILE, "utf8"); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await openAgentsTab(s); + await s.page.getByRole("button", { name: "Edit Alpha" }).click(); + await formField(s, "Command").fill("alpha-cli --edited"); + await formField(s, "Command").press("Tab"); + await s.page.waitForTimeout(500); + assert.equal(fs.readFileSync(AGENTS_FILE, "utf8"), before, "agents.json is byte for byte unchanged"); + await formButton(s, "Save").click(); + await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved$/ }).waitFor(); + assert.equal(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents[0].command, "alpha-cli --edited"); +}); + +test("Agents & models: a discarded edit never rides along with another agent's Save", async (t) => { + noSavedLooks(t); + seedAgents(t, TWO_AGENTS); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await openAgentsTab(s); + await s.page.getByRole("button", { name: "Edit Alpha" }).click(); + await formField(s, "Command").fill("alpha-cli --dropped"); + await formButton(s, "Back to summary").click(); + await unsavedPrompt(s).waitFor(); + assert.equal(await textOf(s.page.locator("#prefs-unsaved-name")), "Alpha"); + assert.equal(await s.page.locator("#looks-modal .prefs-body").evaluate((b) => b.inert), true, "the dialog behind the prompt is out of reach"); + await unsavedPrompt(s).getByRole("button", { name: "Discard", exact: true }).click(); + await agentsTable(s).waitFor(); + assert.equal(await s.page.locator("#looks-modal .prefs-body").evaluate((b) => b.inert), false); + assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label") || document.activeElement?.id), "Edit Alpha", "focus comes back to the row just left"); + + await s.page.getByRole("button", { name: "Edit Beta" }).click(); + await formField(s, "Command").fill("beta-cli --kept"); + await formButton(s, "Save").click(); + await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved$/ }).waitFor(); + const agents = JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents; + assert.deepEqual(agents.map((a) => [a.id, a.command]), [["alpha", "alpha-cli"], ["beta", "beta-cli --kept"]]); +}); + +test("Agents & models: an unsaved edit asks first on Back, Close, Esc, a backdrop click and a tab switch", async (t) => { + noSavedLooks(t); + seedAgents(t, TWO_AGENTS); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await openAgentsTab(s); + const modal = s.page.locator("#looks-modal"); + const edit = async (command) => { + if (!(await agentForm(s).isVisible())) await s.page.getByRole("button", { name: "Edit Alpha" }).click(); + await formField(s, "Command").fill(command); + }; + const triggers = { + back: () => formButton(s, "Back to summary").click(), + close: () => s.page.click("#looks-done"), + esc: () => formField(s, "Command").press("Escape"), + backdrop: () => s.page.mouse.click(4, 4), + tab: () => s.page.click("#prefs-tab-appearance"), + }; + for (const [name, leave] of Object.entries(triggers)) { + // Keep editing: the form and the draft stay. + await edit(`alpha-${name}-kept`); + await leave(); + await unsavedPrompt(s).waitFor(); + assert.equal(await s.page.evaluate(() => document.activeElement?.id), "prefs-unsaved-save", `${name}: Save has focus`); + await unsavedPrompt(s).getByRole("button", { name: "Keep editing" }).click(); + await unsavedPrompt(s).waitFor({ state: "hidden" }); + assert.equal(await modal.evaluate((d) => d.open), true, `${name}: the dialog stays open`); + assert.equal(await formField(s, "Command").inputValue(), `alpha-${name}-kept`, `${name}: the draft stays`); + assert.equal(await s.page.locator("#prefs-tab-agents").getAttribute("aria-selected"), "true"); + } + const before = fs.readFileSync(AGENTS_FILE, "utf8"); + + // Discard drops the edit and goes on (here, Close). + await triggers.close(); + await unsavedPrompt(s).getByRole("button", { name: "Discard", exact: true }).click(); + await modal.waitFor({ state: "hidden" }); + assert.equal(fs.readFileSync(AGENTS_FILE, "utf8"), before, "Discard writes nothing"); + + // Save writes and goes on (here, a tab switch). + await openAgentsTab(s); + await edit("alpha-saved"); + await triggers.tab(); + await unsavedPrompt(s).getByRole("button", { name: "Save", exact: true }).click(); + await s.page.locator('#prefs-tab-appearance[aria-selected="true"]').waitFor(); + assert.equal(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents[0].command, "alpha-saved"); +}); + +test("Agents & models: Esc in the unsaved prompt keeps editing, and a Save that fails there stays and marks the field", async (t) => { + noSavedLooks(t); + seedAgents(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await openAgentsTab(s); + await s.page.click("#agents-add"); + await formField(s, "Name").fill("Half Agent"); + + await s.page.click("#looks-done"); + await unsavedPrompt(s).waitFor(); + await s.page.keyboard.press("Escape"); + await unsavedPrompt(s).waitFor({ state: "hidden" }); + assert.equal(await s.page.locator("#looks-modal").evaluate((d) => d.open), true, "Esc in the prompt does not close the dialog"); + assert.equal(await formField(s, "Name").inputValue(), "Half Agent", "the draft stays"); + + // Save from the prompt with no command: nothing is sent, the dialog stays, focus is on the marked field. + await s.page.click("#looks-done"); + await unsavedPrompt(s).getByRole("button", { name: "Save", exact: true }).click(); + await unsavedPrompt(s).waitFor({ state: "hidden" }); + assert.equal(await s.page.locator("#looks-modal").evaluate((d) => d.open), true, "a failed Save keeps the dialog open"); + assert.equal(fs.existsSync(AGENTS_FILE), false, "nothing is written"); + assert.equal(await s.page.evaluate(() => document.activeElement?.matches('input.invalid[data-field="command"]')), true, "focus is on the marked field"); +}); + +test("Agents & models: a command not on PATH is marked, and the orchestrator row has no Edit", async (t) => { + noSavedLooks(t); + seedAgents(t, [{ id: "ghost", name: "Ghost", command: "plan2code-no-such-command-xyz" }]); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await openAgentsTab(s); + const badge = agentRow(s, "agent:ghost").locator(".prefs-badge"); + await badge.filter({ hasText: "Not found on PATH" }).waitFor(); + assert.equal(await badge.evaluate((b) => b.classList.contains("missing")), true); + const soon = agentsTable(s).locator("tr.prefs-agents-soon"); + assert.match(await textOf(soon), /v3 orchestrator\s+Nothing to set yet\./); + assert.equal(await soon.getByRole("button").count(), 0); +}); + +test("Agents & models: below 720 px the Models column is hidden and the form is one column", async (t) => { + noSavedLooks(t); + seedAgents(t, TWO_AGENTS); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.setViewportSize({ width: 600, height: 800 }); + await openAgentsTab(s); + const cells = agentsTable(s).locator(".prefs-agents-models"); + const shown = []; + for (let i = 0; i < (await cells.count()); i++) shown.push(await styleOf(cells.nth(i), "display")); + assert.ok(shown.length > 0 && shown.every((d) => d === "none"), `the Models cells are hidden: ${shown}`); + await s.page.getByRole("button", { name: "Edit Alpha" }).click(); + const cols = await styleOf(agentForm(s).locator(".prefs-agents-fields"), "grid-template-columns"); + assert.equal(cols.trim().split(/\s+/).length, 1, `one column: ${cols}`); }); test("Cleanup scans the console home and lists an old session folder with its size", async (t) => { @@ -243,6 +411,7 @@ test("Cleanup scans the console home and lists an old session folder with its si t.after(() => fs.rmSync(dir, { recursive: true, force: true })); await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-system"); const list = s.page.locator("#cleanup-list"); assert.equal(await list.locator(".cleanup-row").count(), 0, "Cleanup lists things before a scan"); assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true, "Delete is offered before a scan"); @@ -262,6 +431,201 @@ test("Cleanup scans the console home and lists an old session folder with its si // Closing preferences forgets the scan: a reopened dialog starts clean. await s.page.click("#looks-done"); await s.page.click("#btn-looks"); + await s.page.click("#prefs-tab-system"); assert.equal(await list.locator(".cleanup-row").count(), 0, "the old scan is still listed"); assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true); }); + +/* ------------------------------------------------------------- the tabs */ + +const tabNames = async (s) => (await s.page.locator("#prefs-tabs [role=tab] .prefs-tab-label").allInnerTexts()).map((x) => x.trim()); +const selectedTab = (s) => s.page.evaluate(() => document.querySelector('#prefs-tabs [aria-selected="true"]')?.id); +const focusedId = (s) => s.page.evaluate(() => document.activeElement?.id); +const visiblePanels = (s) => s.page.evaluate(() => [...document.querySelectorAll("#prefs-panels [role=tabpanel]")].filter((p) => !p.hidden).map((p) => p.id)); + +test("the gear opens User Preferences on Appearance, with four tabs in order and one panel shown", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.setViewportSize({ width: 1000, height: 800 }); + await s.page.click("#btn-looks"); + await s.page.locator("#looks-modal[open]").waitFor(); + assert.deepEqual(await tabNames(s), ["Appearance", "Agents & models", "System", "Sounds & activities"]); + assert.equal(await selectedTab(s), "prefs-tab-appearance"); + assert.equal(await focusedId(s), "prefs-tab-appearance", "focus is on the selected tab"); + assert.equal(await s.page.locator('#prefs-tabs [tabindex="0"]').count(), 1, "one tab in the tab order"); + assert.deepEqual(await visiblePanels(s), ["prefs-panel-appearance"]); + assert.equal(await s.page.locator("#prefs-tab-appearance").getAttribute("aria-controls"), "prefs-panel-appearance"); + assert.equal(await s.page.locator("#prefs-panel-appearance").getAttribute("aria-labelledby"), "prefs-tab-appearance"); + assert.equal(await textOf(s.page.locator("#looks-done")), "Close", "the footer button no longer says Done"); +}); + +test("Preferences' tabs move with the arrow, Home and End keys, wrapping at the ends", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.click("#btn-looks"); + await s.page.locator("#looks-modal[open]").waitFor(); + const press = async (key, want) => { + await s.page.keyboard.press(key); + assert.equal(await selectedTab(s), want, `${key} selects ${want}`); + assert.equal(await focusedId(s), want, `${key} focuses ${want}`); + assert.deepEqual(await visiblePanels(s), [want.replace("-tab-", "-panel-")]); + }; + await press("ArrowDown", "prefs-tab-agents"); + await press("ArrowRight", "prefs-tab-system"); + await press("End", "prefs-tab-sounds"); + await press("ArrowDown", "prefs-tab-appearance"); + await press("ArrowUp", "prefs-tab-sounds"); + await press("Home", "prefs-tab-appearance"); + await press("ArrowLeft", "prefs-tab-sounds"); +}); + +test("below 720 px the side list is a horizontal strip with no hints", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.setViewportSize({ width: 1000, height: 800 }); + await s.page.click("#btn-looks"); + const list = s.page.locator("#prefs-tabs"); + const hint = s.page.locator("#prefs-tab-appearance .prefs-tab-hint"); + assert.equal(await list.getAttribute("aria-orientation"), "vertical"); + assert.equal(await styleOf(hint, "display"), "block", "hints show in the side list"); + assert.equal(await styleOf(list, "flex-direction"), "column"); + await s.page.setViewportSize({ width: 600, height: 800 }); + await s.page.waitForFunction(() => document.getElementById("prefs-tabs").getAttribute("aria-orientation") === "horizontal"); + assert.equal(await styleOf(hint, "display"), "none", "no hints in the strip"); + assert.deepEqual(await stylesOf(list, ["flex-direction", "overflow-x"]), { "flex-direction": "row", "overflow-x": "auto" }); + await s.page.setViewportSize({ width: 1000, height: 800 }); + await s.page.waitForFunction(() => document.getElementById("prefs-tabs").getAttribute("aria-orientation") === "vertical"); +}); + +test("Set up preferences on the dashboard opens on Appearance with agents and models loaded", async (t) => { + fs.mkdirSync(HOME, { recursive: true }); + fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true } })); + t.after(() => fs.rmSync(LOOKS_FILE, { force: true })); + const file = path.join(MODELS_DIR, "agents.json"); + fs.mkdirSync(MODELS_DIR, { recursive: true }); + fs.writeFileSync(file, JSON.stringify({ schema: 1, agents: [{ id: "goose", name: "Goose", command: "goose" }] })); + t.after(() => fs.rmSync(file, { force: true })); + const s = await openSession(await suite.browser(), { + t, + workflow: "dashboard", + payload: { menu: { note: "Nothing yet." }, agent: { status: "waiting" } }, + }); + const skip = s.page.getByRole("button", { name: "Skip the intro" }); + await skip.click(); + await skip.waitFor({ state: "hidden" }); + await s.page.getByRole("button", { name: "Set up preferences" }).click(); + await s.page.locator("#looks-modal[open]").waitFor(); + assert.equal(await selectedTab(s), "prefs-tab-appearance"); + await s.page.click("#prefs-tab-agents"); + const goose = s.page.locator('#agents-table tr[data-key="agent:goose"]'); + await goose.waitFor(); + assert.match(await textOf(goose.locator(".prefs-agents-name")), /^Goose/); + assert.equal(await s.page.locator('#agents-table tr[data-key="cli:claude"]').count(), 1, "the built-ins are listed"); + assert.doesNotMatch(await s.page.locator("#agents-status").innerText(), /could not be loaded/); +}); + +test("Back to default resets only the tab on screen, and is hidden on Agents & models and System", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.click("#btn-looks"); + await s.page.locator('input[name="looks-theme"][value="dark"]').check(); + await swatch(s, "violet").click(); + await s.page.click("#prefs-tab-sounds"); + await s.page.locator("#looks-sound").uncheck(); + await s.page.locator("#looks-activities").uncheck(); + + await s.page.click("#prefs-tab-agents"); + assert.equal(await s.page.locator("#looks-reset").isHidden(), true, "hidden on Agents & models"); + await s.page.click("#prefs-tab-system"); + assert.equal(await s.page.locator("#looks-reset").isHidden(), true, "hidden on System"); + + await s.page.click("#prefs-tab-appearance"); + await s.page.click("#looks-reset"); + await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme")); + assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "false"); + await s.page.click("#prefs-tab-sounds"); + assert.equal(await s.page.locator("#looks-sound").isChecked(), false, "Appearance's reset left sounds off"); + assert.equal(await s.page.locator("#looks-activities").isChecked(), false); + + await s.page.click("#prefs-tab-appearance"); + await s.page.locator('input[name="looks-theme"][value="dark"]').check(); + await s.page.click("#prefs-tab-sounds"); + await s.page.click("#looks-reset"); + await s.page.locator("#looks-sound:checked").waitFor(); + assert.equal(await s.page.locator("#looks-activities").isChecked(), true); + assert.equal(await root(s, "data-theme"), "dark", "the sounds reset left the dark theme"); + await s.page.waitForFunction(async () => { + const saved = (await (await fetch("/looks")).json()).looks || {}; + return saved.sound === true && saved.hideActivities === false && saved.theme === "dark"; + }); +}); + +test("a theme change shows Saved level with the Theme legend, outside the fieldset's grid", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.click("#btn-looks"); + await s.page.locator('input[name="looks-theme"][value="light"]').check(); + const mark = s.page.locator('fieldset[data-section="theme"] .prefs-saved'); + await mark.filter({ hasText: "Saved" }).waitFor(); + assert.equal(await mark.getAttribute("role"), "status"); + // Out of the fieldset's grid: the three choices still share one row. + assert.equal(await styleOf(mark, "position"), "absolute"); + const tops = await s.page.locator('fieldset[data-section="theme"] label').evaluateAll((ls) => ls.map((l) => l.offsetTop)); + assert.equal(new Set(tops).size, 1, `the theme choices sit on one row: ${tops}`); +}); + +test("a save the server refuses shows its error in the Saved mark's place, until a save lands", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + let refuse = true; + await s.page.route("**/looks", (route) => + refuse && route.request().method() === "POST" + ? route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "Disk is full." }) }) + : route.continue() + ); + await s.page.click("#btn-looks"); + await s.page.locator('input[name="looks-theme"][value="dark"]').check(); + const mark = s.page.locator('fieldset[data-section="theme"] .prefs-saved'); + await mark.filter({ hasText: "Disk is full." }).waitFor(); + assert.equal(await mark.evaluate((m) => m.classList.contains("error")), true); + refuse = false; + await s.page.locator('input[name="looks-theme"][value="light"]').check(); + await mark.filter({ hasText: "Saved" }).waitFor(); + assert.equal(await mark.evaluate((m) => m.classList.contains("error")), false, "the error clears once a save lands"); +}); + +test("a Preferences tab is named by its label alone, with the hint as its description", async (t) => { + noSavedLooks(t); + const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION }); + await s.page.click("#btn-looks"); + for (const name of ["Appearance", "Agents & models", "System", "Sounds & activities"]) { + assert.equal(await s.page.getByRole("tab", { name, exact: true }).count(), 1, `a tab named ${name}`); + } + const tab = s.page.locator("#prefs-tab-system"); + assert.equal(await textOf(s.page.locator("#" + (await tab.getAttribute("aria-describedby")))), "Cleanup, desktop app"); +}); + +// Read from the Subagents dialog at 1000 px before Preferences moved to tabs: +// it borrows Preferences' .looks classes, and must not change with them. +const SUBAGENTS_BEFORE = { + modal: { "max-width": "none", width: "900px" }, + row: { display: "grid", "grid-template-columns": "repeat(2, minmax(0px, 1fr))", "margin-top": "0px" }, + second: { "margin-top": "0px" }, + actions: { display: "flex", "justify-content": "flex-end" }, +}; + +test("the Subagents dialog looks as it did before Preferences moved to tabs", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 2" } } }); + await s.page.setViewportSize({ width: 1000, height: 800 }); + const modal = s.page.locator("#subagents-modal"); + await s.page.locator("#btn-subagents").click(); + await modal.waitFor(); + const got = { + modal: await stylesOf(modal, ["max-width", "width"]), + row: await stylesOf(modal.locator("fieldset.looks-row").first(), ["display", "grid-template-columns", "margin-top"]), + second: await stylesOf(modal.locator("fieldset.modal-ranges").nth(1), ["margin-top"]), + actions: await stylesOf(modal.locator(".modal-actions"), ["display", "justify-content"]), + }; + if (process.env.P2C_PRINT_SUBAGENTS) console.log("SUBAGENTS " + JSON.stringify(got)); + assert.deepEqual(got, SUBAGENTS_BEFORE); +}); diff --git a/scripts/test-web-console-page-session.mjs b/scripts/test-web-console-page-session.mjs index 5a2ae7b..d6cfacc 100644 --- a/scripts/test-web-console-page-session.mjs +++ b/scripts/test-web-console-page-session.mjs @@ -14,6 +14,7 @@ import path from "node:path"; import { pageSuite, openSession, itemCard, drawn, textOf, tempProject } from "./page-test-helpers.mjs"; import { cli, until } from "./web-console-test-helpers.mjs"; import { STOP_HANDOFF_REPLY, HOME_REPLY } from "../src/web-console/public/answers.js"; +import { CHAT_OFFLINE_TEXT } from "../src/web-console/public/chat.js"; // How long the page waits without contact before it calls itself offline: // the page's own constant, so this file never drifts from it. import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js"; @@ -34,7 +35,7 @@ const PLAN_QUESTION = { // The agent's side of `stop`, leaving the browser context open (s.stop() // closes it, which would hide what the page does next). async function stopServer(s) { - cli(["stop", "--session", s.sid], { cwd: s.project }); + cli(["stop", "--session", s.sid, "--force"], { cwd: s.project }); assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop"); } @@ -578,6 +579,33 @@ test("answers a working agent has not collected bring up the saved-and-waiting l assert.equal(await whatToCheck(s).count(), 1, "the line carries What to check"); }); +// The agent picked up an Ask message and is answering it, so it is not in +// `wait` to collect a card sent meanwhile. That is busy, not gone: the line +// says so for ten minutes of silence before the not running help shows. +test("a card sent while the agent answers an Ask message says it is answering, and not running only after ten minutes", async (t) => { + const s = await openSession(await suite.browser(), { t, workflow: "plan", clock: true, payload: PLAN_QUESTION }); + await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click(); + await s.page.locator("#ask-input").fill("What does the export include?"); + await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click(); + const got = s.wait(10); + assert.equal(got.code, 0, `the Ask message was not handed over (wait exit ${got.code})`); + await s.page.locator("#views").getByRole("button", { name: /^Questions/ }).click(); + await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export"); + await s.page.click("#btn-send"); + await lineSays(s, /^Plan2Code is answering your Ask message\./); + await s.page.clock.fastForward(70_000); + await lineSays(s, /^Plan2Code is answering your Ask message\./); + await s.page.clock.fastForward(8 * 60_000); + await lineSays(s, /^Plan2Code is answering your Ask message\./); + // The Ask tab agrees: still answering, not "No agent available". + await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click(); + await s.page.locator("#ask-input").waitFor(); + assert.ok(!(await s.page.locator("body").innerText()).includes(CHAT_OFFLINE_TEXT), "the Ask tab went offline while the agent was answering"); + await s.page.clock.fastForward(2 * 60_000); + await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./); + await s.page.waitForFunction((t) => document.body.innerText.includes(t), CHAT_OFFLINE_TEXT, { timeout: 10000 }); +}); + // A failed Send says why at once, rather than one line for every cause and // the real state only showing once the page's own timers catch up. test("a Send that finds the server gone says so at once, with the reconnect help", async (t) => { @@ -851,7 +879,13 @@ test("every finished shape shows Before you close this with its three rows, and assert.ok(!text.includes("—"), `${headline}: the guide carries an em dash`); } // With a stop warning up, a pause's command starts the work again. - s.post({ stopWarning: "Answers since the last save will not be kept." }); + // The console now refuses a post that leaves both a finish and a stop warning up, + // so the state the page can still be handed is written straight into the + // session's state file. + const statePath = path.join(s.session, "state.json"); + const withWarning = JSON.parse(fs.readFileSync(statePath, "utf8")); + withWarning.stopWarning = "Answers since the last save will not be kept."; + fs.writeFileSync(statePath, JSON.stringify(withWarning)); await closeGuide(s).getByText(/The command above starts it again\./).waitFor(); assert.equal(await s.page.locator("#btn-home").isVisible(), false, "a finished screen carries its own way back"); }); diff --git a/scripts/test-web-console-pointers.mjs b/scripts/test-web-console-pointers.mjs new file mode 100644 index 0000000..c6ba03d --- /dev/null +++ b/scripts/test-web-console-pointers.mjs @@ -0,0 +1,286 @@ +// Web console tests, the pointers: which topic file the console names, and when. +// Run with: node --test scripts/test-web-console-pointers.mjs +// +// The card leaves a topic out and the console's own output names its file at +// the moment it is due (`read`), once per session per topic and again after a +// resume. Shared setup lives in web-console-test-helpers.mjs. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { POINTER_FILES, duePointers, pointersForSend, rememberPointers, resetPointers } from "../src/web-console/pointers.mjs"; +import { + HOME, + ROOT, + cli, + openSession, + postPatch, + readState, + tempFolder, + waitOnce, + addFolder, + ask, +} from "./web-console-test-helpers.mjs"; + +const WEB = path.join(ROOT, "src", "web-console"); +const file = (name) => path.join(WEB, name); +const SUBAGENTS_STORE = path.join(HOME, "subagents.json"); + +// A fresh session, a send made as the page makes it, and the one `wait` that +// collects it: the `read` that wait printed. +const fresh = (extra = {}) => openSession(extra); +async function send(s, actions) { + const res = await s.send("/submit", { actions, reply: "sent from the page" }); + assert.equal(res.status, 200, `the page's send was accepted: ${res.status}`); + return waitOnce(s.sid, 10); +} +const finishUp = (s) => postPatch(s, { finish: { headline: "Done", command: "/plan2code" } }); +const done = (s) => cli(["stop", "--session", s.sid, "--force"]); + +/* ------------------------------------------- every moment names its file */ + +test("pointer: __commit names console-finish.md", async () => { + const s = fresh(); + try { + const { code, out } = await send(s, [{ i: "__commit", type: "commit" }]); + assert.equal(code, 0); + assert.deepEqual(out.read, [file("console-finish.md")]); + } finally { + done(s); + } +}); + +test("pointer: __dashboard with a finish up names console-finish.md", async () => { + const s = fresh(); + try { + finishUp(s); + const { out } = await send(s, [{ i: "__dashboard", type: "dashboard" }]); + assert.deepEqual(out.read, [file("console-finish.md")]); + } finally { + done(s); + } +}); + +test("pointer: __stop names console-stop.md", async () => { + const s = fresh(); + try { + const { out } = await send(s, [{ i: "__stop", type: "stop" }]); + assert.deepEqual(out.read, [file("console-stop.md")]); + } finally { + done(s); + } +}); + +test("pointer: __stop with a handoff names console-stop.md", async () => { + const s = fresh(); + try { + const { out } = await send(s, [{ i: "__stop", type: "stop", handoff: true }]); + assert.deepEqual(out.read, [file("console-stop.md")]); + } finally { + done(s); + } +}); + +test("pointer: __dashboard with no finish up names console-stop.md", async () => { + const s = fresh(); + try { + const { out } = await send(s, [{ i: "__dashboard", type: "dashboard" }]); + assert.deepEqual(out.read, [file("console-stop.md")]); + } finally { + done(s); + } +}); + +test("pointer: the first post carrying docs names console-docs.md on post's own line", () => { + const s = fresh(); + try { + const first = postPatch(s, { docs: [{ id: "map", title: "Map", blocks: [{ id: "b1", state: "settled", md: "## One" }] }] }); + assert.deepEqual(first.json.read, [file("console-docs.md")]); + assert.equal(first.json.ok, true); + const plain = postPatch(s, { agent: { status: "working" } }); + assert.equal(plain.json.read, undefined, "a post with no docs names nothing"); + } finally { + done(s); + } +}); + +test("pointer: the first Quick question names console-chat.md", async () => { + const s = fresh(); + try { + assert.equal((await ask(s, "What does this do?")).status, 200); + const { code, out } = waitOnce(s.sid, 10); + assert.equal(code, 0); + assert.deepEqual(out.read, [file("console-chat.md")]); + } finally { + done(s); + } +}); + +test("pointer: a Workspace change names console-workspace.md", async () => { + const s = fresh(); + const extra = tempFolder(); + try { + assert.equal((await addFolder(s, { path: extra })).status, 200); + const { out } = await send(s, [{ i: "q1", type: "answer", kind: "choice", k: "A" }]); + assert.match(out.reply, /Workspace:/); + assert.ok(out.read.includes(file("console-workspace.md"))); + } finally { + done(s); + fs.rmSync(extra, { recursive: true, force: true }); + } +}); + +test("pointer: a Subagents change names console-subagents.md", async () => { + fs.rmSync(SUBAGENTS_STORE, { force: true }); + const s = fresh({ workflow: "implement" }); + try { + const set = await s.send("/subagents", { on: false, instruction: null, max: 3 }); + assert.equal(set.status, 200); + const { out } = await send(s, [{ i: "q1", type: "answer", kind: "choice", k: "A" }]); + assert.match(out.reply, /Subagents: off/); + assert.ok(out.read.includes(file("console-subagents.md"))); + } finally { + done(s); + } +}); + +test("pointer: __review names building-review.md", async () => { + const s = fresh(); + try { + const { out } = await send(s, [{ i: "__review", type: "review" }]); + assert.deepEqual(out.read, [file("building-review.md")]); + } finally { + done(s); + } +}); + +test("pointer: a review card answered with a verdict names building-review.md", async () => { + const s = fresh({ workflow: "implement" }); + try { + postPatch(s, { + docs: [{ id: "report", title: "Report", blocks: [{ id: "b1", state: "settled", md: "## Report" }] }], + items: [ + { + id: "signoff", + kind: "review", + title: "Approve this phase", + doc: "report", + verdicts: [ + { id: "review", label: "Review the code first" }, + { id: "approve", label: "Approve" }, + ], + }, + ], + }); + const { out } = await send(s, [{ i: "signoff", type: "answer", kind: "review", verdict: "review" }]); + assert.deepEqual(out.read, [file("building-review.md")]); + } finally { + done(s); + } +}); + +/* ------------------------------------------- the memory rules */ + +test("pointer memory: the same moment a second time prints no read", async () => { + const s = fresh(); + try { + const first = await send(s, [{ i: "__stop", type: "stop" }]); + assert.deepEqual(first.out.read, [file("console-stop.md")]); + // The page is back on the person's turn after the agent posts again. + postPatch(s, { items: [{ id: "q2", kind: "text", title: "Anything else", body: "Say it." }] }); + const second = await send(s, [{ i: "__stop", type: "stop" }]); + assert.equal(second.out.read, undefined, "console-stop.md was named once already"); + } finally { + done(s); + } +}); + +test("pointer memory: it lives in pointers.json in the session folder, never in state.json", async () => { + const s = fresh(); + try { + await send(s, [{ i: "__stop", type: "stop" }]); + const saved = JSON.parse(fs.readFileSync(path.join(s.session, "pointers.json"), "utf8")); + assert.deepEqual(saved.printed, ["stop"]); + assert.ok(!JSON.stringify(readState(s.session)).includes("pointers"), "state.json has no pointer key"); + const frame = await (await fetch(`${s.base}/state`, { headers: { cookie: s.cookie, connection: "close" } })).text(); + assert.ok(!frame.includes("pointers"), "the page's frame never carries pointers"); + } finally { + done(s); + } +}); + +test("pointer memory: open --resume starts the reading over", async () => { + const s = fresh(); + try { + assert.deepEqual((await send(s, [{ i: "__stop", type: "stop" }])).out.read, [file("console-stop.md")]); + const back = cli(["open", "--resume", s.sid, "--workflow", "pathfinder", "--no-open"]); + assert.equal(back.json.sid, s.sid); + assert.equal(fs.existsSync(path.join(s.session, "pointers.json")), false, "a resume forgets what was printed"); + postPatch(s, { items: [{ id: "q3", kind: "text", title: "Once more", body: "Say it." }] }); + const again = await send(s, [{ i: "__stop", type: "stop" }]); + assert.deepEqual(again.out.read, [file("console-stop.md")]); + } finally { + done(s); + } +}); + +test("pointer memory: two moments due at once print both, each once", async () => { + const s = fresh(); + try { + const { out } = await send(s, [ + { i: "__review", type: "review" }, + { i: "__stop", type: "stop" }, + ]); + assert.deepEqual(out.read, [file("building-review.md"), file("console-stop.md")]); + } finally { + done(s); + } +}); + +/* ------------------------------------------- the pure part, with no server */ + +const noFlags = { workspaceChanged: false, subagentsChanged: false }; + +test("pointersForSend: the whole table", () => { + const withFinish = { finish: { headline: "Done" }, items: [] }; + const empty = { items: [] }; + const act = (...as) => ({ actions: as }); + assert.deepEqual(pointersForSend(act({ i: "__commit" }), empty, noFlags), ["finish"]); + assert.deepEqual(pointersForSend(act({ i: "__dashboard" }), withFinish, noFlags), ["finish"]); + assert.deepEqual(pointersForSend(act({ i: "__dashboard" }), empty, noFlags), ["stop"]); + assert.deepEqual(pointersForSend(act({ i: "__stop" }), empty, noFlags), ["stop"]); + assert.deepEqual(pointersForSend(act({ i: "__stop", handoff: true }), empty, noFlags), ["stop"]); + assert.deepEqual(pointersForSend(act({ i: "__review" }), empty, noFlags), ["review"]); + const reviewCard = { items: [{ id: "signoff", kind: "review" }] }; + assert.deepEqual(pointersForSend(act({ i: "signoff", type: "answer", verdict: "review" }), reviewCard, noFlags), ["review"]); + assert.deepEqual(pointersForSend(act({ i: "signoff", type: "answer", answer: { verdict: "approve" } }), reviewCard, noFlags), ["review"]); + assert.deepEqual(pointersForSend(act({ i: "signoff", type: "answer" }), reviewCard, noFlags), [], "a review card with no verdict names nothing"); + assert.deepEqual(pointersForSend(act({ i: "q1", type: "answer", verdict: "x" }), { items: [{ id: "q1", kind: "choice" }] }, noFlags), []); + assert.deepEqual(pointersForSend({}, empty, noFlags, [{ kind: "message", seq: 1 }]), ["chat"]); + assert.deepEqual(pointersForSend({}, empty, noFlags, [{ kind: "decision", seq: 1 }]), [], "only a typed message names the chat file"); + assert.deepEqual(pointersForSend({}, empty, { workspaceChanged: true, subagentsChanged: true }), ["workspace", "subagents"]); + assert.deepEqual(pointersForSend(act({ i: "__stop" }, { i: "__stop" }), empty, noFlags), ["stop"], "a topic appears once"); + assert.deepEqual(pointersForSend(null, null, null), []); +}); + +test("duePointers, rememberPointers and resetPointers keep one memory per session folder", () => { + const dir = fs.mkdtempSync(path.join(HOME, "pointers-")); + try { + assert.deepEqual(duePointers(dir, ["stop", "chat"]), [file("console-stop.md"), file("console-chat.md")]); + rememberPointers(dir, ["stop", "not-a-topic"]); + assert.deepEqual(duePointers(dir, ["stop", "chat"]), [file("console-chat.md")], "printed topics drop out"); + assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "pointers.json"), "utf8")).printed, ["stop"], "an unknown topic is never recorded"); + fs.writeFileSync(path.join(dir, "pointers.json"), "{ not json"); + assert.deepEqual(duePointers(dir, ["stop"]), [file("console-stop.md")], "an unreadable memory reads as nothing printed"); + rememberPointers(dir, ["chat"]); + resetPointers(dir); + assert.deepEqual(duePointers(dir, ["stop", "chat"]), [file("console-stop.md"), file("console-chat.md")]); + } finally { + fs.rmSync(dir, { recursive: true, force: true }); + } +}); + +test("every pointer file exists beside the console", () => { + for (const name of Object.values(POINTER_FILES)) assert.ok(fs.existsSync(file(name)), `${name} exists`); +}); diff --git a/scripts/test-web-console-qa.mjs b/scripts/test-web-console-qa.mjs index 7b7cf1d..e8e96a0 100644 --- a/scripts/test-web-console-qa.mjs +++ b/scripts/test-web-console-qa.mjs @@ -50,7 +50,7 @@ test("settle: true records the send wait handed over, never a later one still un assert.equal(items.find((i) => i.id === "q1").status, "answered"); assert.equal(items.find((i) => i.id === "q2").status, "open", "q2's send is not the agent's yet"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -90,7 +90,7 @@ test("a notice never takes one of the three question slots", () => { test("agent.status is working or waiting, nothing else", () => { const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), agent: { status: "sleeping" } }; - assert.ok(validate(state).some((p) => p.includes('"agent.status"'))); + assert.ok(validate(state).some((p) => p.startsWith("agent.status:"))); }); test("an approved sign-off does not stop the next phase asking for its own", () => { @@ -114,7 +114,7 @@ test("an unanswered note blocks a settle that ignores it", () => { }; const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), items: [withNote] }; const next = applyPatch(state, { settle: ["q1"] }); - assert.ok(validate(next).some((p) => p.includes('item "q1" has an unanswered note'))); + assert.ok(validate(next).some((p) => p.includes('item "q1" thread: has an unanswered note'))); }); test("adding a thread reply in the same patch clears the note and allows the settle", () => { @@ -170,7 +170,7 @@ test("post --file reads a patch PowerShell wrote: a UTF-8 BOM, or UTF-16", () => assert.equal(runCli(["post", "--session", s.sid, "--file", u16]).status, 0); assert.equal(readState(s.session).agent.activity, "From UTF-16"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -180,10 +180,10 @@ test("wait and stop find a session's server from any folder, not only its projec try { const waited = runCli(["wait", "--session", s.sid, "--seconds", "1"], { cwd: elsewhere }); assert.notEqual(waited.status, 20, "the server is alive: " + waited.stdout); - const stopped = runCli(["stop", "--session", s.sid], { cwd: elsewhere }); + const stopped = runCli(["stop", "--session", s.sid, "--force"], { cwd: elsewhere }); assert.equal(JSON.parse(stopped.stdout).stopped, 1, stopped.stdout); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(elsewhere, { recursive: true, force: true }); } }); @@ -208,7 +208,7 @@ test("keep refuses a --from file outside the project, and keeps one copy per upl fs.rmSync(path.join(ROOT, spec), { recursive: true, force: true }); } } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -293,7 +293,7 @@ test("a patch that is valid JSON but not one object is refused (exit 2), never m } assert.ok(!("0" in readState(s.session)), "no junk keys in the state"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); diff --git a/scripts/test-web-console-server.mjs b/scripts/test-web-console-server.mjs index 2b9b8cc..8dd83a0 100644 --- a/scripts/test-web-console-server.mjs +++ b/scripts/test-web-console-server.mjs @@ -80,14 +80,14 @@ test("the page carries its first state, title and badge, so the first paint need assert.ok(html.includes('Building')); assert.ok(html.includes("Starting Implement"), "the static starting screen names the skill"); assert.ok(html.includes('rel="modulepreload" href="/app.js"')); - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); }); test("open without --title names the session after the project folder", () => { const res = cli(["open", "--workflow", "pathfinder", "--no-open"]); const state = JSON.parse(fs.readFileSync(path.join(res.json.session, "state.json"), "utf8")); assert.equal(state.title, path.basename(ROOT)); - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); }); // A saved dark theme and accent used to flash the default light accent for as @@ -110,7 +110,7 @@ test("saved looks are painted by the server before any script runs", async () => assert.ok(!css.includes(`data-looks-accent="${DEFAULT_ACCENT}"`), "the default needs no rule"); const boot = JSON.parse(html.match(/id="boot">([\s\S]*?)<\/script>/)[1]); assert.equal(boot.looks.accent, "violet"); - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); } finally { if (before) fs.writeFileSync(looksFile, before); else fs.rmSync(looksFile, { force: true }); @@ -129,7 +129,7 @@ test("static assets revalidate with an ETag instead of downloading again", async await first.arrayBuffer(); const again = await fetch(m[1] + "/app.js", { headers: { cookie, "if-none-match": etag } }); assert.equal(again.status, 304); - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); }); // The page drew from the inline state; the stream's opening frame would only @@ -173,7 +173,7 @@ test("the stream skips its opening frame only when the page already has that exa await sleep(1200); const still = await (await fetch(m[1] + "/state", { headers: { cookie } })).json(); assert.doesNotMatch(await firstChunk(still.have), /event: state/, "the page's own key: skipped"); - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); }); // `open` binds the port and sends the browser before the server has booted. @@ -227,7 +227,7 @@ test("the card-width presets validate a saved width and fall back to comfortable assert.equal(DEFAULT_CARD_WIDTH, "comfortable"); assert.deepEqual( Object.values(CARD_WIDTHS).map((w) => w.px), - [720, 880, 1080] + [720, 880, 1080, 1440] ); }); @@ -360,6 +360,8 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe const kept = [ file("looks.json"), file("workspaces.json"), + file("loop-setup.json"), + file("loop-reports.json"), file("subagents.json"), file("pr-hosts.json"), file("console-dir"), @@ -375,7 +377,7 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe const stale = staleScratch(dir, Date.now(), SESSION_MAX_AGE_MS).sort(); assert.deepEqual(stale, ["helper.mjs", "p2.json"]); assert.deepEqual( - (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "subagents.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), + (await removeScratch(dir, [...stale, "looks.json", "workspaces.json", "loop-setup.json", "loop-reports.json", "subagents.json", "pr-hosts.json", "../p.json", "console-dir", "update-check.json"])).sort(), ["helper.mjs", "p2.json"] ); for (const p of removable) assert.equal(fs.existsSync(p), false, p); @@ -383,6 +385,8 @@ test("the scratch sweep removes old patches and helpers, never looks, the pointe assert.deepEqual([...PROTECTED_CONSOLE_FILES].sort(), [ "console-dir", "looks.json", + "loop-reports.json", + "loop-setup.json", "pr-hosts.json", "subagents.json", "update-check.json", @@ -662,7 +666,7 @@ test("GET /overview serves the session's spec, and on the dashboard only a scann 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]); + for (const s of sids) cliIn(root, ["stop", "--session", s, "--force"]); fs.rmSync(base, { recursive: true, force: true }); } }); @@ -683,32 +687,28 @@ test("open records worktree and branch, and wakes only a freshly opened dashboar cli(["open", "--resume", dash.json.sid, "--no-open"]); assert.equal("wake" in readState(dash.json.session), false); } finally { - cli(["stop", "--session", dash.json.sid]); + cli(["stop", "--session", dash.json.sid, "--force"]); } const plan = cli(["open", "--workflow", "plan", "--no-open"]); assert.equal("wake" in readState(plan.json.session), false); - cli(["stop", "--session", plan.json.sid]); + cli(["stop", "--session", plan.json.sid, "--force"]); }); -test("open reports a month-old session under swept and removes it after printing", async () => { - const quiet = cli(["open", "--workflow", "plan", "--no-open"]); - assert.equal("swept" in quiet.json, false, "nothing old, nothing reported"); - cli(["stop", "--session", quiet.json.sid]); - +test("open removes a month-old session without printing it", async () => { const oldSid = "20250101-101010-abcdef"; const oldDir = path.join(HOME, "sessions", oldSid); fs.mkdirSync(oldDir, { recursive: true }); fs.writeFileSync(path.join(oldDir, "state.json"), "{}"); backdate(path.join(oldDir, "state.json")); const res = cli(["open", "--workflow", "plan", "--no-open"]); - cli(["stop", "--session", res.json.sid]); - assert.deepEqual(res.json.swept.sessions, [oldSid]); + cli(["stop", "--session", res.json.sid, "--force"]); + assert.equal("swept" in res.json, false, "the sweep is housekeeping, not output"); for (let i = 0; i < 20 && fs.existsSync(oldDir); i++) await new Promise((r) => setTimeout(r, 100)); assert.equal(fs.existsSync(oldDir), false); }); -test("open reports a month-old handoff under swept.handoffs and removes both its files", async () => { +test("open removes a month-old handoff and both its files without printing them", async () => { const id = "2025-01-01-0900-handoff"; fs.mkdirSync(HANDOFFS_DIR, { recursive: true }); const files = [path.join(HANDOFFS_DIR, id + ".md"), path.join(HANDOFFS_DIR, id + ".json")]; @@ -716,24 +716,23 @@ test("open reports a month-old handoff under swept.handoffs and removes both its fs.writeFileSync(files[1], "{}"); for (const f of files) backdate(f); const res = cli(["open", "--workflow", "plan", "--no-open"]); - cli(["stop", "--session", res.json.sid]); - assert.deepEqual(res.json.swept.handoffs, [id]); + cli(["stop", "--session", res.json.sid, "--force"]); + assert.equal("swept" in res.json, false, "the sweep is housekeeping, not output"); for (let i = 0; i < 20 && files.some((f) => fs.existsSync(f)); i++) await new Promise((r) => setTimeout(r, 100)); assert.deepEqual(files.filter((f) => fs.existsSync(f)), []); }); -test("post and wait hand back the terminal line; the collected result on disk does not carry it", async () => { +test("open prints the terminal line; post and wait leave it out until it changes; the collected result on disk does not carry it", async () => { const res = cli(["open", "--file", payload("tl.json", BASE), "--no-open"]); const s = sessionUrl(res.json.url); try { const posted = cli(["post", "--session", res.json.sid, "--file", payload("tl2.json", { agent: { status: "waiting" } })]); - assert.equal(posted.json.terminalLine, terminalLine(res.json.url)); + assert.equal(res.json.terminalLine, terminalLine(res.json.url)); + assert.equal("terminalLine" in posted.json, false, "unchanged, so not repeated"); const waiting = cli(["wait", "--session", res.json.sid, "--seconds", "5"]); assert.equal(waiting.status, 10); - assert.equal(waiting.json.message, "Waiting on your answer in the web console"); - assert.match(waiting.json.next, /run this same wait command again/); - assert.equal(waiting.json.terminalLine, terminalLine(res.json.url)); + assert.deepEqual(waiting.json, { waiting: true, open: 1 }); const sent = await fetch(`${s.base}/submit`, { method: "POST", @@ -743,7 +742,8 @@ test("post and wait hand back the terminal line; the collected result on disk do assert.equal(sent.status, 200); const done = cli(["wait", "--session", res.json.sid, "--seconds", "10"]); assert.equal(done.status, 0); - assert.equal(done.json.terminalLine, terminalLine(res.json.url)); + assert.equal("terminalLine" in done.json, false); + assert.equal(done.json.reply, "Export format: a"); const onDisk = JSON.parse(fs.readFileSync(path.join(res.json.session, "result.json"), "utf8")); assert.equal("terminalLine" in onDisk, false); assert.ok(onDisk.consumedAt); @@ -752,25 +752,24 @@ test("post and wait hand back the terminal line; the collected result on disk do assert.equal(js.status, 200); assert.match(js.headers.get("content-type"), /javascript/); } finally { - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); } }); test("notes/quick-task.md has a quick-task build tick the Plan tab's steps live", () => { const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8"); - const section = md.slice(md.indexOf("## Quick task (`quick-task`)"), md.indexOf("## Stop requests during a build")); - assert.ok(!section.includes('"title": "Build progress"'), "no separate progress tab"); - assert.match(section, /post after every step/i); - assert.ok(section.includes('{ "id": "steps", "state": "settled", "md": "## Steps\\n\\n- [ ] **1.**'), "the plan's Steps start as a checklist"); - assert.ok(section.includes('"docs": [{ "id": "plan", "blocks": [\n { "id": "steps"'), "a step post reposts the plan's steps block, its version moving by itself"); + const section = md; + assert.ok(!section.includes('"title":"Build progress"'), "no separate progress tab"); + assert.match(section, /After each step/); + assert.ok(section.includes('{"id":"steps","state":"settled","md":"## Steps\\n\\n- [ ] **1.**'), "the plan's Steps start as a checklist"); + assert.ok(section.includes('"docs":[{"id":"plan","blocks":[{"id":"steps"'), "a step post reposts the plan's steps block, its version moving by itself"); assert.ok(section.includes("- [x] **1.** Step one")); }); test("notes/quick-task.md has the finished quick task offer Back to the dashboard as well as the review", () => { const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8"); - const section = md.slice(md.indexOf("## Quick task (`quick-task`)")); - const bullet = section.slice(section.indexOf("**The finish after the build:**"), section.indexOf("**Escalated / aborted:**")); - assert.ok(bullet.includes('"dashboard": true')); + const bullet = md.slice(md.indexOf("**Finish after the build:**"), md.indexOf("**Escalated / aborted:**")); + assert.ok(bullet.includes('"dashboard":true')); assert.ok(bullet.includes("Review it now")); }); @@ -795,7 +794,7 @@ test("an image block under the session's shots folder round-trips, and /shots/ s const jargon = { docs: [{ id: "shown", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "Grilling the home page" }] }] }; const refused = cli(["post", "--session", res.json.sid, "--file", payload("shots-jargon.json", jargon)], { expectFail: true }); assert.equal(refused.status, 3); - assert.match(refused.stderr, /alt text contains internal vocabulary/); + assert.match(refused.stderr, /alt: contains internal vocabulary/); // A changed picture or caption is a new version of the doc. const before = readState(res.json.session).docs.find((d) => d.id === "shown").version; const recaption = { docs: [{ id: "shown", blocks: [{ id: "s1", image: "shots/home-page.png", alt: "The home page, after the fix" }] }] }; @@ -826,7 +825,7 @@ test("an image block under the session's shots folder round-trips, and /shots/ s assert.equal(await raw(p), 404, p); } } finally { - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); } }); @@ -864,7 +863,7 @@ test("/app.css is the style files joined in CSS_ORDER with the accent rules last await own.arrayBuffer(); } } finally { - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); } }); @@ -884,7 +883,7 @@ test("the built skills tree serves the same /app.css as the source console", asy assert.equal(res.status, 200); assert.equal(await res.text(), asset("app.css").body.toString("utf8")); } finally { - execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid], { env: ENV, cwd: ROOT }); + execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid, "--force"], { env: ENV, cwd: ROOT }); } }); @@ -917,6 +916,6 @@ test("/open-link takes an http or https link and refuses every other kind", asyn }); assert.notEqual(foreign.status, 200, "another site's page cannot open links through the console"); } finally { - cli(["stop", "--session", res.json.sid]); + cli(["stop", "--session", res.json.sid, "--force"]); } }); diff --git a/scripts/test-web-console-session.mjs b/scripts/test-web-console-session.mjs index b097e1d..8d504f8 100644 --- a/scripts/test-web-console-session.mjs +++ b/scripts/test-web-console-session.mjs @@ -33,6 +33,10 @@ import { import { CHAT_LIMIT, CHAT_MAX_CHARS } from "../src/web-console/public/chat.js"; import { ACCENTS, CARD_WIDTHS, SOUND_EVENTS, soundKey, soundPrefs } from "../src/web-console/public/palette.js"; import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js"; +import { tabKeyTarget } from "../src/web-console/public/tabs.js"; +import { PREFS_TABS, prefsOpenTab, prefsResetScope } from "../src/web-console/public/prefs.js"; +import { DEFAULT_LOOKS, looks, resetLooks } from "../src/web-console/public/looks.js"; +import { ROLE_NOT_SET } from "../src/web-console/public/starters.js"; import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js"; import { REMOTE_FOLD } from "../src/web-console/public/git-board.js"; import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs"; @@ -122,11 +126,14 @@ test("the page is served with a CSP that forbids inline script", async () => { assert.ok(csp.includes("media-src 'self'")); }); +// result.json keeps the whole send; the agent's output carries only `reply`, +// the `__` session actions and the hop fields. +const sentActions = () => JSON.parse(fs.readFileSync(path.join(session, "result.json"), "utf8")).actions; + test("wait returns 10 with a progress summary while nobody has answered", () => { const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 10); - assert.equal(res.json.status, "waiting"); - assert.equal(res.json.total, 1); + assert.deepEqual(res.json, { waiting: true, open: 1 }, "nothing else rides on a quiet slice"); }); test("a submit round-trips to the agent with the literal reply token", async () => { @@ -136,9 +143,11 @@ test("a submit round-trips to the agent with the literal reply token", async () }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.type, "submit"); assert.equal(res.json.reply, "Export format: b"); - assert.equal(res.json.actions[0].k, "B"); + for (const dropped of ["type", "at", "sid", "rev", "consumedAt", "actions"]) assert.equal(res.json[dropped], undefined, `${dropped} stays in result.json`); + const kept = JSON.parse(fs.readFileSync(path.join(session, "result.json"), "utf8")); + assert.equal(kept.type, "submit"); + assert.equal(kept.actions[0].k, "B"); }); test("a collected answer is written to the meter ledger once, and a button press is not", async () => { @@ -176,8 +185,8 @@ test("a brief request round-trips with a range the playbook can read", async () }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].type, "brief"); - assert.equal(res.json.actions[0].range, "since 2026-09-15"); + assert.equal(res.json.session[0].i, "__brief"); + assert.equal(res.json.session[0].range, "since 2026-09-15"); assert.match(res.json.reply, /since 2026-09-15/); // `__brief` is not an item, so nothing on the board may have been touched. @@ -195,7 +204,7 @@ test("a review request round-trips without touching any question", async () => { }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].i, "__review"); + assert.equal(res.json.session[0].i, "__review"); assert.equal(res.json.reply, REVIEW_REPLY); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__review"), "a review request must not become a question"); @@ -212,9 +221,10 @@ test("a launch request round-trips with the skill the dashboard resumes as", asy }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].i, "__launch"); - assert.equal(res.json.actions[0].skill, "plan2code-3-implement"); - assert.equal(res.json.actions[0].workflow, "implement"); + assert.equal(res.json.session[0].i, "__launch"); + assert.equal(res.json.session[0].skill, "plan2code-3-implement"); + assert.equal(res.json.session[0].workflow, "implement"); + assert.match(res.json.resume, /--no-open --workflow implement$/); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__launch"), "a launch must not become a question"); }); @@ -228,7 +238,7 @@ test("a launch sent from a finished screen carries the resume for the next skill }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].i, "__launch"); + assert.equal(res.json.session[0].i, "__launch"); assert.match(res.json.resume, /--no-open --workflow document --spec specs\/lunch-vote$/); }); @@ -263,8 +273,8 @@ test("a delete request round-trips with the spec folder and no resume", async () }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].i, "__delete"); - assert.equal(res.json.actions[0].spec, "specs/lunch-vote"); + assert.equal(res.json.session[0].i, "__delete"); + assert.equal(res.json.session[0].spec, "specs/lunch-vote"); assert.equal(res.json.resume, undefined); assert.equal(res.json.skillFile, undefined); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); @@ -289,7 +299,7 @@ test("a dashboard request round-trips and the session resumes as the dashboard", const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.deepEqual(res.json.actions, [{ i: "__dashboard", type: "dashboard" }]); + assert.deepEqual(res.json.session, [{ i: "__dashboard" }]); assert.equal(res.json.reply, DASHBOARD_REPLY); const after = readState(); assert.ok(after.items.every((i) => i.id !== "__dashboard"), "a dashboard request must not become a question"); @@ -409,11 +419,8 @@ test("a stop request carries the staged answers, reaches the agent as a send, an const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 0, "a stop is a send, not a cancel"); - assert.deepEqual( - res.json.actions.map((a) => a.type), - ["answer", "stop"], - "the answers and the stop arrive together" - ); + assert.deepEqual(res.json.session, [{ i: "__stop" }], "the stop arrives whole, the answer in reply"); + assert.match(res.json.reply, /^Export format: b/, "the staged answer arrives with it"); assert.equal((await ping()).pendingStop, false); }); @@ -430,7 +437,7 @@ test("a handoff stop keeps its flag, reports as a stop until collected, and name assert.equal((await ping()).pendingStop, true, "an uncollected handoff stop shows on the heartbeat"); const res = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].handoff, true, "the flag reaches the agent"); + assert.equal(res.json.session[0].handoff, true, "the flag reaches the agent"); assert.equal(res.json.handoffSkill, undefined, "no built skill beside the source tree"); assert.equal((await ping()).pendingStop, false); }); @@ -453,7 +460,8 @@ test("a mid-workflow way home carries the staged answers and resumes as the dash assert.equal(res.status, 200); const got = cli(["wait", "--session", sid, "--seconds", "5"]); assert.equal(got.status, 0, "the way home is a send, not a cancel"); - assert.deepEqual(got.json.actions.map((a) => a.type), ["answer", "dashboard"], "the answers and the way home arrive together"); + assert.deepEqual(got.json.session, [{ i: "__dashboard" }], "the way home arrives whole, the answer in reply"); + assert.match(got.json.reply, /^Export format: a/, "the staged answer arrives with it"); assert.ok(got.json.reply.endsWith(HOME_REPLY)); cli(["open", "--resume", sid, "--no-open", "--workflow", "dashboard"]); @@ -520,12 +528,11 @@ test("the way home cannot be mistaken for a brief request", () => { test("console-stop.md, building.md and the dashboard prompt teach the mid-workflow way home", () => { const read = (...p) => fs.readFileSync(path.join(ROOT, ...p), "utf8"); const stopMd = read("src", "web-console", "console-stop.md"); - assert.ok(stopMd.includes("## Back to the dashboard, mid-workflow")); - assert.ok(stopMd.includes(HOME_REPLY), "console-stop.md quotes the reply line the agent will see"); - assert.match(stopMd, /No `finish` and no `stop` in between/); - assert.ok(stopMd.includes("## Stop with a handoff")); + assert.ok(stopMd.includes("## `__dashboard` with no finish up (home, mid-workflow)")); + assert.match(stopMd, /No `finish` and no `stop`: the menu is the ending/); + assert.ok(stopMd.includes("## `__stop` with a handoff")); for (const word of ["handoff new", "--from-stop", "handoffSkill"]) assert.ok(stopMd.includes(word), `console-stop.md names ${word}`); - assert.match(read("src", "web-console", "console.md"), /`__stop` \(plain, or with `handoff: true`\), `__dashboard` \(no finish up\) \| `console-stop\.md`/, "console.md's action table sends a handoff stop and a mid-workflow __dashboard there"); + assert.match(read("src", "web-console", "console.md"), /`__stop`, `__dashboard`[^\n]*covered by the topic file `read` names/, "the card hands a stop and a dashboard press to the topic file its pointer names"); assert.ok(read("src", "web-console", "building.md").includes("mid-build `__dashboard`")); assert.ok(read("src", "plan2code.md").includes("mid-workflow from the top bar's triangle")); }); @@ -536,7 +543,7 @@ test("console-launches.md and the dashboard prompt teach the handoff pick-up and for (const word of ["__pickup", "handoffFile", "delete-handoff", "handoffsDir", "fallback"]) { assert.ok(launches.includes(word), `console-launches.md names ${word}`); } - assert.ok(launches.includes("handoffs, handoffsDir"), "console-launches.md lists the scan fields"); + assert.ok(launches.includes("handoffs,handoffsDir"), "console-launches.md lists the scan fields"); const prompt = read("src", "plan2code.md"); for (const word of ["__pickup", "delete-handoff"]) assert.ok(prompt.includes(word), `src/plan2code.md names ${word}`); }); @@ -644,12 +651,14 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at /* ---------------------------------------------------------------- help */ -test("help: 19 tabs with unique ids", () => { - assert.equal(HELP_TABS.length, 19); - assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 19); +test("help: 20 tabs with unique ids", () => { + assert.equal(HELP_TABS.length, 20); + assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 20); assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen"); const ids = HELP_TABS.map((t) => t.id); - assert.equal(ids.indexOf("git"), ids.indexOf("build") + 1, "The git board comes right after Watching a build"); + assert.equal(ids.indexOf("loop"), ids.indexOf("build") + 1, "Implementation Loop comes right after Watching a build"); + assert.equal(HELP_TABS[ids.indexOf("loop")].label, "Implementation Loop"); + assert.equal(ids.indexOf("git"), ids.indexOf("loop") + 1, "The git board comes right after Implementation Loop"); assert.equal(HELP_TABS[ids.indexOf("git")].label, "The git board"); assert.equal(helpTabFor({ workflow: "git" }), "git"); assert.equal(ids.indexOf("activities"), ids.indexOf("ask") + 1, "Activities comes right after Ask a quick question"); @@ -789,6 +798,64 @@ test("help: helpKeyTarget moves, wraps and jumps", () => { assert.equal(helpKeyTarget("a", 3, n), -1); }); +test("tabs: tabKeyTarget is Help's key rule, shared under both names", () => { + assert.equal(helpKeyTarget, tabKeyTarget, "help.js re-exports the shared function"); + const n = 4; + for (const [key, from, to] of [["ArrowDown", 3, 0], ["ArrowRight", 1, 2], ["ArrowUp", 0, 3], ["ArrowLeft", 2, 1], ["Home", 2, 0], ["End", 0, 3]]) { + assert.equal(tabKeyTarget(key, from, n), to, `${key} from ${from}`); + } + assert.equal(tabKeyTarget("Enter", 1, n), -1); +}); + +test("prefs: four tabs in order, each section in exactly one", () => { + assert.deepEqual(PREFS_TABS.map((t) => t.id), ["appearance", "agents", "system", "sounds"]); + assert.deepEqual(PREFS_TABS.map((t) => t.label), ["Appearance", "Agents & models", "System", "Sounds & activities"]); + for (const t of PREFS_TABS) assert.ok(t.hint, `${t.id} has a hint`); + const sections = PREFS_TABS.flatMap((t) => t.sections); + assert.equal(new Set(sections).size, sections.length, "no section sits in two tabs"); + assert.deepEqual(PREFS_TABS[0].sections, ["theme", "width", "accent", "role"], "Appearance in its order"); +}); + +test("prefs: the dialog opens on the tab asked for, else Appearance", () => { + for (const t of PREFS_TABS) assert.equal(prefsOpenTab(t.id), t.id); + for (const asked of [undefined, "", "nope", "Appearance"]) assert.equal(prefsOpenTab(asked), "appearance", String(asked)); +}); + +test("prefs: Back to default resets Appearance or Sounds & activities only, and nothing on the other two", () => { + assert.deepEqual(prefsResetScope("appearance"), ["theme", "width", "accent", "role"]); + const sounds = prefsResetScope("sounds"); + assert.deepEqual(sounds, ["sound", ...Object.keys(SOUND_EVENTS).map(soundKey), "hideActivities", "activitySounds", "gameMusic"]); + for (const key of [...prefsResetScope("appearance"), ...sounds]) { + if (key !== "role") assert.ok(Object.hasOwn(DEFAULT_LOOKS, key), `${key} has a default`); + } + assert.equal(prefsResetScope("agents"), null); + assert.equal(prefsResetScope("system"), null); + assert.equal(prefsResetScope("nope"), null); +}); + +test("looks: resetLooks(keys) changes only those keys, and the role is marked as asked", () => { + const before = { ...looks }; + try { + Object.assign(looks, { theme: "dark", width: "wide", accent: "violet", role: "pm", sound: false, soundQuestion: false, hideActivities: true, activityBestSnake: 7, lastActivity: "snake" }); + resetLooks(prefsResetScope("appearance")); + assert.equal(looks.theme, DEFAULT_LOOKS.theme); + assert.equal(looks.width, DEFAULT_LOOKS.width); + assert.equal(looks.accent, DEFAULT_LOOKS.accent); + assert.equal(looks.role, ROLE_NOT_SET, "cleared but marked as asked"); + assert.equal(looks.sound, false, "sounds untouched by Appearance"); + assert.equal(looks.hideActivities, true); + resetLooks(prefsResetScope("sounds")); + assert.equal(looks.sound, true); + assert.equal(looks.soundQuestion, true); + assert.equal(looks.hideActivities, false); + assert.equal(looks.activityBestSnake, 7, "best scores stay"); + assert.equal(looks.lastActivity, "snake", "the last pick stays"); + } finally { + for (const key of Object.keys(looks)) delete looks[key]; + Object.assign(looks, before); + } +}); + // A constant's value from source text, for files the test cannot import. Only // products of integer literals are accepted, so nothing is ever evaluated. const productOf = (expr) => @@ -957,7 +1024,7 @@ test("a send refuses comment images that are too many or not this session's uplo assert.equal(ok.status, 200); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0, "collected, so the tests after this start with no send in flight"); - assert.equal(res.json.actions[0].images.length, 2); + assert.equal(sentActions()[0].images.length, 2); }); test("a note with two images reaches the agent with both absolute paths, in the action and the reply", async () => { @@ -971,7 +1038,7 @@ test("a note with two images reaches the agent with both absolute paths, in the assert.equal(ok.status, 200); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - const note = res.json.actions.find((x) => x.type === "comment"); + const note = sentActions().find((x) => x.type === "comment"); assert.deepEqual(note.images, [ { path: a.path, name: "first.png" }, { path: b.path, name: "second.png" }, @@ -1157,7 +1224,7 @@ test("a send takes documents as files, counts them with images, and keeps each k assert.equal(ok.status, 200); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - const note = res.json.actions.find((x) => x.type === "comment"); + const note = sentActions().find((x) => x.type === "comment"); assert.deepEqual(note.images, [i1, i2]); assert.deepEqual(note.files, [d1, d2, d3]); assert.match(res.json.reply, /^Note on Export format: \(attachments only\)$/m); @@ -1400,7 +1467,7 @@ test("a changelog request from a finished screen carries the resume into the cha }); const res = cli(["wait", "--session", sid, "--seconds", "10"]); assert.equal(res.status, 0); - assert.equal(res.json.actions[0].i, "__changelog"); + assert.equal(res.json.session[0].i, "__changelog"); assert.match(res.json.resume, /--no-open --workflow changelog$/); const state = JSON.parse(fs.readFileSync(path.join(session, "state.json"), "utf8")); assert.ok(state.items.every((i) => i.id !== "__changelog"), "a changelog request must not become a question"); @@ -1420,7 +1487,7 @@ test("a thread reply in another shape is lifted into { who, text }, and an empty "aliases lifted, and the echoed note is not shown twice"); assert.equal(thread[1].md, undefined); assert.equal(thread[1].from, undefined); - assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent" }] }] }), /thread entry has no "text"/); + assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent" }] }] }), /an entry has no "text"/); assert.throws(() => applyPatch(base, { items: [{ id: "n1", thread: [{ who: "agent", md: " " }] }] }), /no "text"/); }); @@ -1431,3 +1498,98 @@ test("the page reads older { from, md } thread entries", () => { assert.equal(threadText({ who: "agent", text: "Now." }), "Now."); assert.equal(threadText({ who: "agent" }), ""); }); + +/* --------------------------------- output shape at each exit code (FR-1 to FR-3) */ + +test("the shape of every exit: 0 for an answer and a launch, 10, 30, 3 and 2", async (t) => { + const opened = cli(["open", "--file", payload("shape-open.json", BASE), "--no-open"]); + const s = opened.json; + // open names the link; the very next post and wait do not repeat it. + assert.equal(typeof s.terminalLine, "string"); + assert.ok(s.terminalLine.length > 0); + const m = s.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//); + const sendTo = (pathname, body) => + fetch(m[1] + pathname, { + method: "POST", + headers: { "content-type": "application/json", cookie: cookieFor(m[1], m[2]), connection: "close" }, + body: JSON.stringify(body), + }); + try { + await t.test("post prints only ok and open, no terminalLine", () => { + const res = cli(["post", "--session", s.sid, "--file", payload("shape-post.json", { headline: { stage: "Working" } })]); + assert.deepEqual(Object.keys(res.json).sort(), ["ok", "open"]); + }); + + await t.test("exit 10 is {waiting, open} and nothing else", () => { + const res = cli(["wait", "--session", s.sid, "--seconds", "5"]); + assert.equal(res.status, 10); + assert.deepEqual(res.json, { waiting: true, open: 1 }); + }); + + await t.test("exit 0 for an answer: reply only, the rest stays in result.json", async () => { + assert.equal((await sendTo("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }], reply: "Export format: b" })).status, 200); + const res = cli(["wait", "--session", s.sid, "--seconds", "10"]); + assert.equal(res.status, 0); + assert.deepEqual(res.json, { reply: "Export format: b" }); + const kept = JSON.parse(fs.readFileSync(path.join(s.session, "result.json"), "utf8")); + for (const k of ["type", "at", "sid", "rev", "consumedAt", "actions"]) assert.ok(k in kept, `result.json keeps ${k}`); + }); + + await t.test("exit 0 for a launch carries the session action whole, with resume", async () => { + const send = { actions: [{ i: "__launch", type: "launch", skill: "plan2code-3-implement", workflow: "implement" }], reply: "Start Implement." }; + assert.equal((await sendTo("/submit", send)).status, 200); + const res = cli(["wait", "--session", s.sid, "--seconds", "10"]); + assert.equal(res.status, 0); + assert.equal(res.json.session[0].i, "__launch"); + assert.match(res.json.resume, /--no-open --workflow implement$/); + assert.equal(res.json.actions, undefined); + assert.equal(res.json.terminalLine, undefined, "the link is not repeated"); + }); + + await t.test("exit 30 for a cancel", async () => { + await sendTo("/cancel", {}); + const res = cli(["wait", "--session", s.sid, "--seconds", "5"]); + assert.equal(res.status, 30); + }); + + await t.test("exit 3 names the item id, the field and a way to do it right", () => { + const bad = { items: [{ id: "bad1", kind: "choice", title: "Pick", options: [{ k: "A", label: "x" }] }] }; + const res = cli(["post", "--session", s.sid, "--file", payload("shape-bad.json", bad)], { expectFail: true }); + assert.equal(res.status, 3); + assert.equal(res.stdout.trim(), ""); + assert.match(res.stderr, /bad1/); + assert.match(res.stderr, /options/); + assert.match(res.stderr, /Like this:/); + }); + + await t.test("exit 2 gives the line, column and a caret for a cut-off patch", () => { + const file = path.join(HOME, "shape-cut.json"); + fs.writeFileSync(file, '{\n "headline": { "stage": "Working"\n'); + const res = cli(["post", "--session", s.sid, "--file", file], { expectFail: true }); + assert.equal(res.status, 2); + assert.match(res.stderr, /line \d+, column \d+/); + assert.match(res.stderr, /\^/); + }); + } finally { + cli(["stop", "--session", s.sid, "--force"]); + } +}); + +test("exit 20 is {gone, fix} naming the session, and a resume to a restarted server prints the link again", () => { + const opened = cli(["open", "--file", payload("shape-gone.json", BASE), "--no-open"]); + const sid2 = opened.json.sid; + assert.equal(typeof opened.json.terminalLine, "string"); + cli(["stop", "--session", sid2, "--force"]); + const gone = cli(["wait", "--session", sid2, "--seconds", "5"]); + assert.equal(gone.status, 20); + assert.deepEqual(gone.json, { gone: true, fix: `open --resume ${sid2} --workflow ` }); + const again = cli(["open", "--resume", sid2, "--no-open"]); + try { + assert.notEqual(again.json.url, opened.json.url, "a restart has a new link"); + assert.equal(typeof again.json.terminalLine, "string", "the new link is printed again"); + const post = cli(["post", "--session", sid2, "--file", payload("shape-after.json", { headline: { stage: "Working" } })]); + assert.equal(post.json.terminalLine, undefined, "and not again on the next post"); + } finally { + cli(["stop", "--session", sid2, "--force"]); + } +}); diff --git a/scripts/test-web-console-shape.mjs b/scripts/test-web-console-shape.mjs index ac77d44..abc9ed0 100644 --- a/scripts/test-web-console-shape.mjs +++ b/scripts/test-web-console-shape.mjs @@ -189,7 +189,7 @@ const ROUTE_ORDER = [ "/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", - "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye", + "WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/loop-setup", "/loop-setup", "/cancel", "/ping", "/bye", ]; test("shape: routes.mjs lists every URL the server answers, in order", () => { diff --git a/scripts/test-web-console-skills.mjs b/scripts/test-web-console-skills.mjs index c738b4e..5e09d1f 100644 --- a/scripts/test-web-console-skills.mjs +++ b/scripts/test-web-console-skills.mjs @@ -5,7 +5,8 @@ import test from "node:test"; import assert from "node:assert/strict"; import { - SKILLS, + SKILLS as EVERY_ENTRY, + FLOW_SKILLS as SKILLS, skillFor, skillByName, isBuild, @@ -298,7 +299,7 @@ function sectionOf(text, heading) { test("docs: console.md's open step names every workflow", () => { const text = readSrc("web-console", "console.md"); - const m = text.match(/where `` is one of ([\s\S]*?)\. Get it right/); + const m = text.match(/`` is one of ([\s\S]*?)\. Launched from the dashboard/); assert.ok(m, "console.md: the open step's `` sentence is not where the test looks"); const said = [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]); assert.deepEqual(listProblems("src/web-console/console.md", said, WORKFLOWS), []); @@ -399,3 +400,20 @@ test("helper-strength.md ships in the seven skills that start helpers, and in no "plan2code-review", ]); }); + +// The Implementation Loop is a card the desktop app offers, not a skill: it +// has no workflow, so no list built from the workflows may hold it. +test("the app-only Implementation Loop entry stays out of every workflow list", () => { + const loop = EVERY_ENTRY.find((s) => s.appOnly); + assert.ok(loop, "skills.js has an appOnly entry"); + assert.equal(loop.skill, "plan2code-loop"); + assert.equal(loop.workflow, null); + assert.deepEqual(EVERY_ENTRY.filter((s) => s.appOnly).length, 1); + assert.ok(!SKILLS.includes(loop), "FLOW_SKILLS leaves it out"); + assert.ok(!WORKFLOWS.includes(null) && !isWorkflow("plan2code-loop") && !isWorkflow(null)); + assert.equal(skillByName("plan2code-loop"), null); + assert.ok(!CONSOLE_WORKFLOWS.includes(loop.command), "no console page is offered for it"); + assert.ok(!SKILL_CATALOG.some((e) => e.skill === loop.skill), "the dashboard does not draw it yet"); + assert.ok(!("null" in WORKFLOW_LABEL)); + assert.deepEqual([...loop.states], ["documented", "building"]); +}); diff --git a/scripts/test-web-console-source.mjs b/scripts/test-web-console-source.mjs index 0d7177b..0f427c3 100644 --- a/scripts/test-web-console-source.mjs +++ b/scripts/test-web-console-source.mjs @@ -15,6 +15,8 @@ import path from "node:path"; import { cardAvailability, SKILL_CATALOG } from "../src/web-console/public/answers.js"; import { SKILLS } from "../src/web-console/public/skills.js"; import { HELP_TABS } from "../src/web-console/public/help.js"; +import { PREFS_TABS } from "../src/web-console/public/prefs.js"; +import { SERVABLE } from "../src/web-console/static.mjs"; import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js"; import { CACHE_MS, @@ -245,7 +247,7 @@ test("update check: the frame carries update only when a newer release is cached } assert.deepEqual(await get("/version"), { version: REPO_VERSION, latest }); } finally { - cli(["stop", "--session", res.json.sid], { env }); + cli(["stop", "--session", res.json.sid, "--force"], { env }); fs.rmSync(home, { recursive: true, force: true }); } } @@ -294,8 +296,8 @@ test("sign-off: approve leads show, and the approve button wears the accent", () const doc = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", f), "utf8"); for (const f of ["notes/implement.md", "building-review.md"]) { const text = doc(f); - const approve = text.indexOf('{ "id": "approve", "label": "Approve this phase" }'); - const show = text.indexOf('{ "id": "show", "label": "Show me it working" }'); + const approve = text.indexOf('{"id":"approve","label":"Approve this phase"}'); + const show = text.indexOf('{"id":"show","label":"Show me it working"}'); assert.ok(approve > 0 && show > approve, `${f} lists Approve this phase before Show me it working`); } assert.match(joinedCss(), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent"); @@ -399,18 +401,17 @@ test("help: the stuck tab is second, and openHelpOn only opens a tab that exists assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists"); }); -test("models: Codex is a model CLI on the server and the page, with its own tab", () => { +test("models: Codex is a model CLI on the server and the page, with its own row in the agents table", () => { const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8"); - const app = publicSource("screens/looks.js"); - const html = publicSource("index.html"); + const app = publicSource("screens/agents-view.js"); const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]); assert.deepEqual(list(server), ["claude", "devin", "codex"]); - assert.deepEqual(list(app), list(server), "the page's tabs match the server's lists"); + assert.deepEqual(list(app), list(server), "the page's rows match the server's lists"); assert.ok(!/for \(const cli of \["claude", "devin"\]\)/.test(app), "no loop over a hard-coded pair"); - const labels = { claude: "Claude", devin: "Devin", codex: "Codex" }; - for (const cli of list(app)) { - assert.match(html, new RegExp(`id="models-tab-${cli}"[^>]*>${labels[cli]}`), `${cli} has a tab`); - } + assert.match(app, /\.\.\.MODEL_CLIS\.map\(\(cli\) => \(\{\s*key: "cli:" \+ cli,/, "the table draws a built-in row per MODEL_CLIS entry"); + const names = app.match(/const BUILT_IN = \{([^}]*)\};/)[1]; + for (const cli of list(app)) assert.match(names, new RegExp(`\\b${cli}: "`), `${cli} has a name in the table`); + assert.ok(!publicSource("index.html").includes("models-tab-"), "the separate Models toggles are gone"); const shipped = JSON.parse(fs.readFileSync(path.join(ROOT, "src", "launcher", "models.json"), "utf8")); for (const cli of list(server)) assert.ok(Array.isArray(shipped[cli]), `the launcher's models.json has ${cli}`); }); @@ -467,3 +468,58 @@ test("no agent CLI module imports notepads.mjs, directly or through a module it assert.ok(dep.names && dep.names.every((n) => n === "staleNotepads" || n === "removeNotepad"), `Cleanup takes only staleNotepads and removeNotepad, not ${dep.names}`); } }); + +test("prefs: the dialog is four tab panels in PREFS_TABS order, each section in the one panel that lists it", () => { + const html = publicSource("index.html"); + const dialog = html.match(/]*>([\s\S]*?)<\/dialog>/)[1]; + assert.match(dialog, /
([\s\S]*?)<\/section>/g)]; + assert.deepEqual(panels.map((m) => m[1]), PREFS_TABS.map((t) => t.id), "one panel per tab, in order"); + const everywhere = [...dialog.matchAll(/data-section="([^"]+)"/g)].map((m) => m[1]); + assert.equal(new Set(everywhere).size, everywhere.length, "no section appears twice"); + for (const [, id, body] of panels) { + const inPanel = [...body.matchAll(/data-section="([^"]+)"/g)].map((m) => m[1]); + const listed = PREFS_TABS.find((t) => t.id === id).sections; + assert.deepEqual(inPanel, [...listed], `${id} holds ${listed.join(", ")} in that order`); + } +}); + +test("prefs: the new modules are served and preloaded, and Preferences' styles leave the shared classes alone", () => { + const html = publicSource("index.html"); + for (const m of ["tabs.js", "prefs.js", "screens/prefs-dialog.js", "screens/agents-view.js"]) { + assert.ok(SERVABLE.has(m), `${m} is servable`); + assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`); + } + const css = publicSource("styles/prefs.css"); + for (const cls of ["looks", "looks-row", "modal-ranges"]) { + assert.ok(!new RegExp(`\\.${cls}(?![\\w-])`).test(css), `prefs.css does not style .${cls} (the Subagents dialog shares it)`); + } +}); + +test("prefs: Help and the readme name every tab and section, and the dialog's unused fieldset classes stay gone", () => { + const prefs = helpTemplate().match(/
([\s\S]*?)<\/section>/)[1]; + // The help topic writes "&" as "&". Each section is named in bold, so a + // tab label such as "Sounds & activities" does not count for "Sounds". + const helpText = prefs.replace(/&/g, "&"); + const sections = ["Theme", "Card width", "Highlight color", "Role", "Models", "Agents", "Cleanup", "Desktop app", "Sounds", "Activities"]; + for (const name of [...PREFS_TABS.map((t) => t.label), ...sections]) { + assert.ok(helpText.includes(`${name}`), `the prefs help topic names ${name}`); + } + // Only the readme's own User Preferences section counts, up to the next "## " heading. + const readme = fs.readFileSync(path.join(ROOT, ".readme", "web-console.md"), "utf8"); + const start = readme.indexOf("\n## User Preferences\n"); + assert.ok(start >= 0, ".readme/web-console.md has a User Preferences section"); + const end = readme.indexOf("\n## ", start + 1); + const section = readme.slice(start, end < 0 ? undefined : end); + for (const heading of ["### Agents & models", "### System"]) { + assert.ok(section.includes(`\n${heading}\n`), `the readme's User Preferences section has ${heading}`); + } + for (const name of [...PREFS_TABS.map((t) => t.label), "Models", "Agents", "Desktop app"]) { + // In bold, as a table cell or a paragraph's lead-in ("**Models.**"). + assert.ok(section.includes(`**${name}**`) || section.includes(`**${name}.**`), `the readme's User Preferences section names ${name}`); + } + const html = publicSource("index.html"); + for (const cls of ["looks-models", "looks-agents", "looks-role", "looks-accents", "looks-cleanup"]) { + assert.ok(!new RegExp(`class="[^"]*\\b${cls}\\b[^"]*"`).test(html), `index.html has no .${cls} left`); + } +}); diff --git a/scripts/test-web-console-speed.mjs b/scripts/test-web-console-speed.mjs index 22f56f5..248bb50 100644 --- a/scripts/test-web-console-speed.mjs +++ b/scripts/test-web-console-speed.mjs @@ -10,6 +10,7 @@ // web-console-test-helpers.mjs; see the comment at its top. import test from "node:test"; +import { POINTER_FILES } from "../src/web-console/pointers.mjs"; import assert from "node:assert/strict"; import fs from "node:fs"; import os from "node:os"; @@ -63,7 +64,7 @@ test("a collected send marks the agent working and drops the last stretch's acti assert.equal(agent.activity, undefined); assert.ok(agent.since, "the CLI stamps the time"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -74,7 +75,7 @@ test("a Quick question alone never marks the agent working", async () => { assert.equal(waitFor(s).status, 0); assert.equal(readState(s.session).agent.status, "waiting", "chat rides its own channel"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -89,7 +90,7 @@ test("post --wait posts, then waits in the same command", async () => { const lines = res.stdout.trim().split("\n").map((l) => JSON.parse(l)); assert.equal(lines.length, 2, "the post's line, then the wait's"); assert.equal(lines[0].ok, true); - assert.equal(lines[1].status, "waiting"); + assert.deepEqual(lines[1], { waiting: true, open: 1 }); assert.ok(Date.now() - started >= 4500, "it really waited the slice"); assert.equal(readState(s.session).title, "Posted then waited"); @@ -98,7 +99,7 @@ test("post --wait posts, then waits in the same command", async () => { assert.equal(got.status, 0, "a waiting send comes straight back"); assert.equal(got.json.reply, "Export format: a"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -115,7 +116,7 @@ test("a rejected post --wait exits 3 at once and never waits", () => { const bad = cli(["post", "--session", s.sid, "--file", payload("pw-ok.json", {}), "--wait", "soon"], { expectFail: true }); assert.equal(bad.status, 2, "a slice that is no number is bad usage"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -126,7 +127,7 @@ test("a wait slice ends on time: a health check in flight never holds the proces assert.equal(waitFor(s, 6).status, 10); assert.ok(Date.now() - started < 9000, `took ${Date.now() - started}ms`); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -193,7 +194,7 @@ test("a doc block with a file takes its text from disk; select tasks keeps the t p.run(["post", "--session", opened.sid, "--file", payload("fd-3.json", { docs: [{ id: "phasefile", refresh: true }] })]); assert.equal(readState(opened.session).docs.find((d) => d.id === "phasefile").version, 2, "an unchanged file is not a new version"); } finally { - p.run(["stop", "--session", opened.sid]); + p.run(["stop", "--session", opened.sid, "--force"]); p.cleanup(); } }); @@ -223,9 +224,9 @@ test("a doc block's file must exist, be inside the project, and select only take const fresh = p.run(["open", "--no-open", "--workflow", "implement", "--file", payload("fd-open.json", { docs: [{ id: "phasefile", title: "phase-1.md", blocks: [{ id: "body", file: "specs/lunch/phase-1.md" }] }] })]); assert.equal(fresh.status, 0, fresh.stderr); assert.ok(readState(fresh.json.session).docs[0].blocks[0].md.startsWith("# Phase 1"), "open --file reads files too"); - p.run(["stop", "--session", fresh.json.sid]); + p.run(["stop", "--session", fresh.json.sid, "--force"]); } finally { - p.run(["stop", "--session", opened.sid]); + p.run(["stop", "--session", opened.sid, "--force"]); fs.rmSync(outside, { force: true }); p.cleanup(); } @@ -308,7 +309,9 @@ test("settle and a defaulted reply id go through post end to end", async () => { assert.equal((await s.send("/submit", { actions: [{ i: "q1", type: "answer", kind: "choice", k: "B" }], reply: "Question q1: B" })).status, 200); assert.equal(waitFor(s).status, 0); assert.equal((await ask(s, "Why?")).status, 200); - const msg = waitFor(s).json.chat.find((e) => e.kind === "message"); + const seqs = waitFor(s).json.chat; + assert.equal(seqs.length, 1, "chat arrives as the seq numbers a reply needs"); + const msg = { seq: seqs[0], conversation: 1 }; const res = postPatch(s, { settle: true, chat: { replies: [{ re: msg.seq, conversation: msg.conversation, md: "Because." }] } }); assert.equal(res.status, 0, res.stderr); const state = readState(s.session); @@ -318,7 +321,7 @@ test("settle and a defaulted reply id go through post end to end", async () => { assert.equal(state.items.find((i) => i.id === "q2").status, "open"); assert.equal(state.chat.replies[0].id, `r${msg.seq}`); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -375,7 +378,7 @@ test("a pick-up comes with the stored skill's resume command, handoffFile, and f assert.equal(bad.handoffFile, undefined); assert.equal(bad.fallback, true); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(worktree, { recursive: true, force: true }); } }); @@ -402,7 +405,7 @@ test("a launch, a dashboard press, Commit it now and Update CHANGELOG first each assert.equal((await s.send("/submit", EXPORT_A)).status, 200); assert.equal(waitFor(s).json.resume, undefined, "an answer is no hop"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -436,7 +439,7 @@ test("the built skills name the skill file to follow after a hop", async () => { const stopped = run(["wait", "--session", opened.sid, "--seconds", "10"]).json; assert.equal(stopped.handoffSkill, path.join(ROOT, "skills", "plan2code-handoff", "SKILL.md"), "a handoff stop in a built skill names the Handoff skill file"); } finally { - run(["stop", "--session", opened.sid]); + run(["stop", "--session", opened.sid, "--force"]); } }); @@ -449,17 +452,19 @@ test("the built skills name the skill file to follow after a hop", async () => { // and the skills point at is real, and the core stays small. const DOC_REF = /`((?:console-[a-z-]+|building(?:-review)?|console|notes\/[a-z-]+)\.md)`|\/((?:console-[a-z-]+|building(?:-review)?|console|notes\/[a-z-]+)\.md)/g; -test("every doc console.md's index names exists, prints through help, and every topic file is indexed", () => { +test("every doc the card or a pointer names exists, prints through help, and every topic file is reachable", () => { const core = consoleDoc("console.md"); - const index = core.slice(core.indexOf("## What to read, and when"), core.indexOf("## Starting it")); - const named = new Set([...index.matchAll(/`([a-z/-]+\.md)`/g)].map((m) => m[1])); + const index = core.slice(core.indexOf("## Read when")); + const named = new Set([...index.matchAll(/`([a-z/<>-]+.md)`/g)].map((m) => m[1])); + const pointed = new Set(Object.values(POINTER_FILES)); for (const file of consoleDocFiles().filter((f) => f !== "console.md" && !f.startsWith("notes/"))) { - assert.ok(named.has(file), `console.md's index names ${file}`); + assert.ok(named.has(file) || pointed.has(file), `${file} is named in the card's Read when table or by a pointer`); } for (const file of named) { if (file.includes("<")) continue; assert.ok(fs.existsSync(path.join(WEB_CONSOLE_DIR, file)), `${file} exists`); } + for (const file of pointed) assert.ok(fs.existsSync(path.join(WEB_CONSOLE_DIR, file)), `pointer file ${file} exists`); const topics = cli(["help", "topics"]).json.topics; for (const [topic, file] of Object.entries(topics)) { assert.ok(fs.existsSync(path.join(WEB_CONSOLE_DIR, file)), `help ${topic} -> ${file} exists`); @@ -547,7 +552,7 @@ test("post --wait with no number takes the slice from --seconds", () => { assert.equal(res.status, 10); assert.ok(Date.now() - started < 12000, `took ${Date.now() - started}ms, not the default 240s`); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -566,7 +571,7 @@ test("a file block's own words are never refused by the prose scan, but typed te assert.equal(block.file, undefined, "typed text over a file block stops it being one"); assert.equal(post("bait-5.json", [{ id: "summary", refresh: true }]).status, 3, "so a refresh finds nothing to re-read"); } finally { - p.run(["stop", "--session", opened.sid]); + p.run(["stop", "--session", opened.sid, "--force"]); p.cleanup(); } }); @@ -583,7 +588,7 @@ test("a file named again without select is the whole file, on every refresh", () assert.equal(block.select, undefined); assert.ok(block.md.startsWith("# Phase 1"), "the whole file, not the task lines"); } finally { - p.run(["stop", "--session", opened.sid]); + p.run(["stop", "--session", opened.sid, "--force"]); p.cleanup(); } }); @@ -603,7 +608,7 @@ test("collecting a send restarts the working clock and keeps a build's quietMinu assert.equal(agent.quietMinutes, 20, "the build's patience survives the question"); assert.ok(Date.parse(agent.since) > Date.parse(opened), "a fresh working turn, not the session's age"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -614,7 +619,7 @@ test("a wait with nothing open leaves a working agent working", () => { assert.equal(waitFor(s, 5).status, 10); assert.equal(readState(s.session).agent.status, "working", "research subagents still out: the page keeps saying so"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -630,9 +635,9 @@ test("post --file - reads the patch from stdin, UTF-8 and a BOM included", () => assert.equal(waited.status, 10, "stdin and --wait together"); const bad = run("not json"); assert.equal(bad.status, 2); - assert.match(bad.stderr, /could not read --file - as one JSON object/); + assert.match(bad.stderr, /line 1, column 2/); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -667,10 +672,11 @@ test("collecting a send puts the phase back to collecting", async () => { assert.equal(readState(s.session).phase, "submitted", "waiting to be picked up"); assert.equal(waitFor(s).status, 0); assert.equal(readState(s.session).phase, "collecting"); - assert.equal(postPatch(s, { settle: true }).json.phase, "collecting", "and post says so"); + assert.equal(postPatch(s, { settle: true }).status, 0); + assert.equal(readState(s.session).phase, "collecting", "and a post leaves it there"); assert.equal(readState(s.session).agent.handled, undefined, "no dead fields on a fresh agent block"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -682,11 +688,11 @@ test("a run of resets reaches the agent as one line", async () => { assert.equal((await ask(s, "Hello?", { conversation: 3 })).status, 200); const res = waitFor(s); assert.equal(res.status, 0); - assert.equal(res.json.chat.filter((e) => e.kind === "reset").length, 1, JSON.stringify(res.json.chat)); + assert.equal(res.json.chat.length, 1, "only the question needs a reply: " + JSON.stringify(res.json.chat)); assert.equal(res.json.reply.match(/New conversation started/g).length, 1); assert.equal(cli(["chat", "--session", s.sid]).status, 10, "the cursor moved past every reset"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -706,7 +712,7 @@ test("a finish ends the working stretch, and resuming a pause starts a fresh one const told = applyPatch({ agent: { status: "working" } }, { finish: { headline: "Done" }, agent: { status: "working" } }); assert.equal(told.agent.status, "working", "a status the patch says still wins"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); diff --git a/scripts/test-web-console-state.mjs b/scripts/test-web-console-state.mjs index cc098c7..a03d67f 100644 --- a/scripts/test-web-console-state.mjs +++ b/scripts/test-web-console-state.mjs @@ -46,6 +46,12 @@ test("state: the rest of the shared state starts as app.js always started it", ( meterFrame: null, updateFrame: null, inApp: false, + loop: null, + loopSetup: null, + loopFacts: null, + loopNotifyTest: null, + loopStart: null, + loopAction: null, subagentsFrame: null, overview: { key: null, files: {} }, wake: null, diff --git a/scripts/test-web-console-subagents.mjs b/scripts/test-web-console-subagents.mjs index 9b98ce9..6c89c88 100644 --- a/scripts/test-web-console-subagents.mjs +++ b/scripts/test-web-console-subagents.mjs @@ -70,15 +70,19 @@ test("subagents: a change reaches the next pickup once, last in reply, edits nam assert.equal((await addFolder(s, { path: extra })).status, 200); const first = await submitAndWait(s); assert.equal(first.status, 0); - assert.deepEqual(first.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement"), strength: "balanced" }); + assert.equal("subagents" in first.json, false, "no structured subagents object on the wire"); + assert.equal("workspace" in first.json, false, "no structured workspace object on the wire"); const reply = first.json.reply; const at = (re) => reply.search(re); assert.ok(at(/^Export format: a$/m) === 0, reply); - assert.ok(at(/^Quick question:/m) > 0, reply); - assert.ok(at(/^Workspace:/m) > at(/^Quick question:/m), reply); + assert.ok(at(/^Quick question \(/m) > 0, reply); + assert.ok(at(/^Workspace:/m) > at(/^Quick question \(/m), reply); assert.ok(at(/^Subagents:/m) > at(/^Workspace:/m), reply); - assert.match(reply, new RegExp(`^Subagents: on \\(revision ${rev}\\) — a console setting, not typed by the person\\.$`, "m")); - assert.ok(reply.endsWith("\n At most 3 helpers at once."), "the block goes last"); + assert.equal(subagentLines(reply)[0], "Subagents: on, balanced strength, at most 3 helpers at once (a console setting, not typed by the person)."); + assert.ok(reply.endsWith("\n " + defaultInstruction("implement").split("\n").pop().trim()), "the block goes last, ending on the instruction"); + for (const old of ["revision", "Helper strength:", "At most 3 helpers", "Report each helper", "Match each helper"]) { + assert.ok(!reply.includes(old), "the old frame sentence is gone: " + old); + } assert.deepEqual(subagentLines(reply).length, 1, "one block"); assert.deepEqual(readSubagentCursor(s.session), { revision: rev, state: "on" }); @@ -89,10 +93,9 @@ test("subagents: a change reaches the next pickup once, last in reply, edits nam const edited = await setSubagents(s, { ...ON3, max: 5 }); assert.equal(edited.body.setting.revision, rev + 1); const third = await submitAndWait(s); - assert.equal(third.json.subagents.revision, rev + 1); - assert.equal(third.json.subagents.max, 5); + assert.equal("subagents" in third.json, false); assert.deepEqual(subagentLines(third.json.reply), [ - `Subagents: on (revision ${rev + 1}, replaces revision ${rev}) — a console setting, not typed by the person.`, + "Subagents: on, balanced strength, at most 5 helpers at once (a console setting, not typed by the person).", ]); const same = await setSubagents(s, { ...ON3, max: 5 }); @@ -103,13 +106,10 @@ test("subagents: a change reaches the next pickup once, last in reply, edits nam const off = await setSubagents(s, { ...ON3, on: false, max: 5 }); assert.equal(off.body.setting.revision, rev + 2, "off is a revision of its own"); const fourth = await submitAndWait(s); - assert.equal(fourth.json.subagents.state, "off"); - assert.deepEqual(subagentLines(fourth.json.reply), [ - `Subagents: off (revision ${rev + 2}) — don't start new helpers for the rest of this session.`, - ]); + assert.deepEqual(subagentLines(fourth.json.reply), ["Subagents: off. Start no new helpers for the rest of this session."]); assert.equal("subagents" in (await submitAndWait(s)).json, false, "off is said once"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(extra, { recursive: true, force: true }); } }); @@ -118,28 +118,26 @@ test("subagents: never on means never a line, and chat hands a pending block ove // A project that saved "off" starts its next session off and untold. const first = subagentsSession(); assert.equal((await setSubagents(first, { on: false, instruction: null, max: 4 })).status, 200); - cli(["stop", "--session", first.sid]); + cli(["stop", "--session", first.sid, "--force"]); const s = subagentsSession({}, { keepStore: true }); try { const off = await setSubagents(s, { on: false, instruction: null, max: 4 }); assert.equal(off.status, 200); const got = await submitAndWait(s); assert.equal("subagents" in got.json, false); - assert.deepEqual(subagentLines(got.json.reply), [], "off is never said to an agent not told on"); + assert.deepEqual(subagentLines(got.json.reply ?? ""), [], "off is never said to an agent not told on"); assert.equal(cli(["chat", "--session", s.sid]).status, 10); assert.equal((await setSubagents(s, { on: true, instruction: "Split by file.", max: 4 })).status, 200); const chat = cli(["chat", "--session", s.sid]); assert.equal(chat.status, 0); - assert.deepEqual(chat.json.chat, []); - assert.equal(chat.json.subagents.state, "on"); - assert.equal(chat.json.subagents.instruction, "Split by file."); - assert.match(chat.json.reply, /^Subagents: on \(revision \d+\)/); + assert.equal(chat.json.chat, undefined, "no question, no chat key"); + assert.equal("subagents" in chat.json, false); + assert.match(chat.json.reply, /^Subagents: on, balanced strength, at most 4 helpers at once/); assert.match(chat.json.reply, /^ {2}Split by file\.$/m); - assert.ok(chat.json.terminalLine); assert.equal(cli(["chat", "--session", s.sid]).status, 10, "then nothing"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -149,16 +147,16 @@ test("subagents: a resume re-states an on setting once, says nothing when off, a const rev = (await setSubagents(s, ON3)).body.setting.revision; const resumed = cli(["open", "--resume", s.sid, "--no-open"]); assert.equal(resumed.json.ok, true); - assert.deepEqual(resumed.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement"), strength: "balanced" }); - assert.equal(subagentLines(resumed.json.reply)[0], `Subagents: on (revision ${rev}) — a console setting, not typed by the person.`); + assert.equal("subagents" in resumed.json, false, "no structured object on the wire"); + assert.equal(subagentLines(resumed.json.reply)[0], "Subagents: on, balanced strength, at most 3 helpers at once (a console setting, not typed by the person)."); + assert.equal(readSubagentCursor(s.session).revision, rev, "open stamped the cursor"); assert.ok(resumed.json.reply.split("\n").every((l, i) => i === 0 || l.startsWith(" ")), "only the block's lines"); assert.equal("subagents" in (await submitAndWait(s)).json, false, "the next pickup carries nothing"); // The print happened but the cursor write did not: the block comes again. fs.writeFileSync(path.join(s.session, "subagents-cursor.json"), JSON.stringify({ revision: 0, state: "none" })); const again = await submitAndWait(s); - assert.equal(again.json.subagents.state, "on"); - assert.deepEqual(subagentLines(again.json.reply), [`Subagents: on (revision ${rev}) — a console setting, not typed by the person.`]); + assert.deepEqual(subagentLines(again.json.reply), ["Subagents: on, balanced strength, at most 3 helpers at once (a console setting, not typed by the person)."]); assert.deepEqual(readSubagentCursor(s.session), { revision: rev, state: "on" }); assert.equal((await setSubagents(s, { ...ON3, on: false })).status, 200); @@ -167,7 +165,7 @@ test("subagents: a resume re-states an on setting once, says nothing when off, a assert.equal("reply" in quiet.json, false); assert.equal("subagents" in (await submitAndWait(s)).json, false, "nor does the next pickup"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -176,7 +174,7 @@ test("subagents: a dashboard launch into implement hears implement's saved setti try { assert.equal((await setSubagents(seed, ON3)).status, 200); } finally { - cli(["stop", "--session", seed.sid]); + cli(["stop", "--session", seed.sid, "--force"]); } const s = consoleSession(["--workflow", "dashboard"]); try { @@ -184,15 +182,15 @@ test("subagents: a dashboard launch into implement hears implement's saved setti const launched = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]); // On the launch itself, not at a later pickup: a skill may do its main // work before it ever collects anything. - assert.equal(launched.json.subagents?.state, "on", "the launch's own open output carries the block"); - assert.match(launched.json.reply, /^Subagents: on \(revision \d+\)/); + assert.match(launched.json.reply, /^Subagents: on, balanced strength/m, "the launch's own open output carries the block"); + assert.equal("subagents" in launched.json, false); // open consumed the subagents block and advanced the cursor before it // printed, so chat has nothing left to hand over. assert.equal(cli(["chat", "--session", s.sid]).status, 10, "never both"); const view = await s.get("/state"); assert.deepEqual([view.subagents.offered, view.subagents.supported, view.subagents.on], [true, true, true]); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -203,7 +201,7 @@ test("subagents: the setting survives a restart at the same revision and starts const saved = await setSubagents(s, { on: true, instruction: "Split by file.", max: 7 }); assert.equal(saved.status, 200); const rev = saved.body.setting.revision; - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); const resumed = cli(["open", "--resume", s.sid, "--no-open"]); const frame = await ( await fetch(`${sessionUrl(resumed.json.url).base}/state`, { headers: { cookie: sessionUrl(resumed.json.url).cookie, connection: "close" } }) @@ -218,8 +216,8 @@ test("subagents: the setting survives a restart at the same revision and starts const fresh = await frameSubagents(next); assert.deepEqual([fresh.on, fresh.instruction, fresh.max], [true, "Split by file.", 7], "a new session in the same project starts there"); } finally { - cli(["stop", "--session", s.sid]); - if (next) cli(["stop", "--session", next.sid]); + cli(["stop", "--session", s.sid, "--force"]); + if (next) cli(["stop", "--session", next.sid, "--force"]); } }); @@ -238,7 +236,7 @@ test("subagents: a save that matches this session still becomes the project's se c = subagentsSession({}, { keepStore: true }); assert.equal((await frameSubagents(c)).on, true, "the next session starts from the person's latest pick"); } finally { - for (const s of [a, b, c]) if (s) cli(["stop", "--session", s.sid]); + for (const s of [a, b, c]) if (s) cli(["stop", "--session", s.sid, "--force"]); } }); @@ -268,8 +266,8 @@ test("subagents: a workflow without the switch refuses it, bad bodies name the f fs.rmSync(path.join(s.session, "subagents-setting.json"), { force: true }); assert.equal("subagents" in (await submitAndWait(s)).json, false); } finally { - cli(["stop", "--session", doc.sid]); - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", doc.sid, "--force"]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -282,15 +280,15 @@ test("subagents: a strength-only change reaches the agent once, with its profile assert.equal(thrifty.body.setting.revision, before + 1, "a strength alone is a change"); assert.equal(thrifty.body.setting.strength, "thrifty"); const picked = await submitAndWait(s); - assert.equal(picked.json.subagents.strength, "thrifty"); - assert.ok(picked.json.reply.endsWith(["", STRENGTH_LINES.thrifty, "At most 3 helpers at once."].join("\n ")), picked.json.reply); + assert.equal("subagents" in picked.json, false); + assert.deepEqual(subagentLines(picked.json.reply), ["Subagents: on, thrifty strength, at most 3 helpers at once (a console setting, not typed by the person)."]); assert.equal((await frameSubagents(s)).strength, "thrifty"); const again = await setSubagents(s, { ...ON3, strength: "thrifty" }); assert.equal(again.body.setting.revision, before + 1, "the same strength again bumps nothing"); assert.equal("subagents" in (await submitAndWait(s)).json, false); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -307,12 +305,12 @@ test("subagents: a setting saved before strength existed reads as balanced and b strip(path.join(s.session, "subagents-setting.json"), (setting) => [setting]); const rev = JSON.parse(fs.readFileSync(path.join(s.session, "subagents-setting.json"), "utf8")).revision; - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); const resumed = sessionUrl(cli(["open", "--resume", s.sid, "--no-open"]).json.url); const frame = (await (await fetch(`${resumed.base}/state`, { headers: { cookie: resumed.cookie, connection: "close" } })).json()).subagents; assert.deepEqual([frame.max, frame.strength, frame.revision], [4, "balanced", rev], "an upgrade alone bumps nothing"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -320,11 +318,12 @@ test("subagents: every strength renders its own profile line, and a missing one const base = { revision: 1, max: 3, instruction: "Split by file." }; for (const strength of STRENGTHS) { const lines = onLines({ ...base, strength }); - assert.equal(lines[lines.length - 2], " " + STRENGTH_LINES[strength], strength); - assert.equal(lines.filter((l) => l.includes("Helper strength:")).length, 1, strength); + const word = strength; + assert.equal(lines[0], `Subagents: on, ${word} strength, at most 3 helpers at once (a console setting, not typed by the person).`, strength); + assert.equal(lines.filter((l) => l.includes("Helper strength:")).length, 0, "the old profile sentence is gone: " + strength); } - assert.equal(new Set(STRENGTHS.map((k) => STRENGTH_LINES[k])).size, STRENGTHS.length, "four different lines"); - assert.equal(onLines(base).at(-2), " " + STRENGTH_LINES.balanced); + assert.equal(new Set(STRENGTHS.map((k) => onLines({ ...base, strength: k })[0])).size, STRENGTHS.length, "four different lines"); + assert.equal(onLines(base)[0], onLines({ ...base, strength: "balanced" })[0], "a missing strength is balanced"); }); /* ------------------------------------------ subagents: helper reports */ @@ -356,7 +355,7 @@ test("helpers: post merges them by id, a real helper supersedes working alone, a assert.equal(postPatch(s, { helpers: [reportedHelper("h1")] }).status, 0); assert.deepEqual(readState(s.session).helpers.map((h) => h.id), ["h1"], "a real helper removes the working-alone marker"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -372,11 +371,11 @@ test("helpers: every malformed report exits 3 naming the helper, and nothing is ["81-char title", [reportedHelper("h3", { title: "t".repeat(81) })], /helper "h3": title must be at most 80 characters/], ["401-char ask", [reportedHelper("h3", { ask: "a".repeat(401) })], /helper "h3": ask must be at most 400 characters/], ["201-char result", [reportedHelper("h3", { state: "done", result: "r".repeat(201) })], /helper "h3": result must be at most 200 characters/], - ["completion marker", [reportedHelper("h3", { state: "done", result: "PHASE_COMPLETE" })], /helper "h3" result contains a loop completion marker/], - ["metrics bait", [reportedHelper("h3", { title: "Risk 3" })], /helper "h3" title contains "Risk 3"/], - ["not an array", { id: "h3" }, /"helpers" must be an array/], - ["null entry", [null], /"helpers" entries must be objects/], - ["string entry", ["h3"], /"helpers" entries must be objects/], + ["completion marker", [reportedHelper("h3", { state: "done", result: "PHASE_COMPLETE" })], /helper "h3" result: contains a loop completion marker/], + ["metrics bait", [reportedHelper("h3", { title: "Risk 3" })], /helper "h3" title: contains "Risk 3"/], + ["not an array", { id: "h3" }, /helpers: must be an array/], + ["null entry", [null], /helpers: entries must be objects/], + ["string entry", ["h3"], /helpers: entries must be objects/], ]; for (const [name, helpers, re] of cases) { const res = postPatch(s, { helpers }, { expectFail: true }); @@ -385,7 +384,7 @@ test("helpers: every malformed report exits 3 naming the helper, and nothing is assert.equal(fs.readFileSync(statePath, "utf8"), before, `${name}: nothing written`); } } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -409,7 +408,7 @@ test("helpers: a reported strength and effort are kept, other values exit 3 nami assert.equal(postPatch(s, { helpers: [reportedHelper("h3")] }).status, 0, "a helper without the fields still posts"); assert.deepEqual(readState(s.session).helpers.map((h) => h.id), ["h1", "h3"]); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); @@ -423,7 +422,7 @@ test("docs: a doc's version never goes back; the same version again is fine, and const before = fs.readFileSync(statePath, "utf8"); const stale = postPatch(s, doc(1, "- [ ] Task 4.1"), { expectFail: true }); assert.equal(stale.status, 3); - assert.match(stale.stderr, /doc "phase" is at version 7 on the page; this patch sends version 1/); + assert.match(stale.stderr, /doc "phase" version: the page is at version 7; this patch sends 1/); assert.equal(fs.readFileSync(statePath, "utf8"), before, "nothing written"); assert.equal(postPatch(s, doc(8, "- [ ] Task 5.1")).status, 0, "a higher version goes through"); assert.equal(postPatch(s, { docs: [{ id: "phase", blocks: [{ id: "tasks", state: "settled", md: "- [x] Task 5.1" }] }] }).status, 0, "a patch with no version is not checked"); @@ -432,15 +431,14 @@ test("docs: a doc's version never goes back; the same version again is fine, and cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]); assert.equal(postPatch(s, doc(1, "- [ ] Task 1.1")).status, 0, "after a hop the doc starts fresh"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); } }); test("docs: a second phase in one build session goes through as notes/implement.md teaches it", () => { const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "implement.md"), "utf8"); - assert.match(md, /A later phase in the same session posts the same two docs/); - assert.match(md, /versions move up by themselves/); - assert.match(md, /Leave\s+`version` out/); + assert.match(md, /A later phase posts the same two docs/); + assert.match(fs.readFileSync(path.join(ROOT, "src", "web-console", "console-docs.md"), "utf8"), /`version`: moves by itself when content changes and never goes back; leave it out/); const taught = consoleSession(["--workflow", "implement"]); try { // As taught: no version anywhere, and the second phase simply goes through. @@ -459,7 +457,7 @@ test("docs: a second phase in one build session goes through as notes/implement. [["phase", "Phase 2 tasks", 3], ["phasefile", "phase-2.md", 3]] ); } finally { - cli(["stop", "--session", taught.sid]); + cli(["stop", "--session", taught.sid, "--force"]); } // An explicit version still never goes back. const s = consoleSession(["--workflow", "implement"]); @@ -482,6 +480,24 @@ test("docs: a second phase in one build session goes through as notes/implement. [["phase", "Phase 2 tasks", 3], ["phasefile", "phase-2.md", 3]] ); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); + } +}); + +test("subagents: a change arrives as reply lines only, carrying state, strength and limit and none of the old frame sentences", async () => { + const s = subagentsSession(); + try { + assert.equal((await setSubagents(s, { on: true, instruction: "Split by file.", max: 6, strength: "thrifty" })).status, 200); + const got = await submitAndWait(s); + assert.equal(got.status, 0); + assert.equal("subagents" in got.json, false, "no subagents object"); + assert.equal("workspace" in got.json, false, "no workspace object"); + assert.deepEqual(subagentLines(got.json.reply), ["Subagents: on, thrifty strength, at most 6 helpers at once (a console setting, not typed by the person)."]); + assert.ok(got.json.reply.endsWith("\n Split by file."), "the person's instruction follows, indented"); + for (const old of ["revision", "Helper strength:", "Hand independent", "Report each helper", "If your tools cannot"]) { + assert.ok(!got.json.reply.includes(old), "no old frame sentence: " + old); + } + } finally { + cli(["stop", "--session", s.sid, "--force"]); } }); diff --git a/scripts/test-web-console-tones.mjs b/scripts/test-web-console-tones.mjs new file mode 100644 index 0000000..a9f46db --- /dev/null +++ b/scripts/test-web-console-tones.mjs @@ -0,0 +1,344 @@ +// Web console tests, the activities' sound engine: every chiptune track readable and playable, every tone and hum named once across tones.js and the games' own sound files, every spec well formed, every one playable through a stand-in AudioContext, hums held only while asked for, and every name a game's source asks for one that exists. +// Run with: node --test scripts/test-web-console-tones.mjs +// +// No browser: a stub AudioContext records what each sound builds. + +import test from "node:test"; +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { HUM_TABLES, TONE_TABLES, hum, humNames, hushTones, tone, toneNames } from "../src/web-console/public/tones.js"; +import { looks } from "../src/web-console/public/looks.js"; +import { compileTrack, hushMusic, music, musicNames, noteFreq } from "../src/web-console/public/music.js"; +import { MUSIC_TABLES } from "../src/web-console/public/tones.js"; +import { REGIONS, ROAD_MUSIC } from "../src/web-console/public/activities/drive.js"; + +const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), ".."); +const GAMES = path.join(ROOT, "src/web-console/public/activities"); + +const WAVES = new Set(["sine", "triangle", "square", "sawtooth"]); +const NOISES = new Set(["noise", "pink", "brown"]); +const FILTERS = new Set(["lowpass", "highpass", "bandpass"]); + +// A stand-in context: counts the sources each sound starts and stops, and +// keeps every gain node with the ramps asked of it. +function stubAudio() { + const made = { oscillators: 0, noises: 0, started: 0, stopped: 0, filters: 0, gains: [] }; + const param = () => ({ + value: 0, + ramps: [], + setValueAtTime(v, t) { this.ramps.push({ kind: "set", v, t }); }, + exponentialRampToValueAtTime(v, t) { this.ramps.push({ kind: "exp", v, t }); }, + linearRampToValueAtTime(v, t) { this.ramps.push({ kind: "linear", v, t }); }, + setTargetAtTime(v, t) { this.ramps.push({ kind: "target", v, t }); }, + cancelScheduledValues() {}, + }); + const node = (extra = {}) => ({ connect() {}, disconnect() {}, ...extra }); + const source = (kind) => node({ + frequency: param(), + start() { made.started += 1; }, + stop() { made.stopped += 1; }, + kind, + }); + class Ctx { + state = "running"; + // Two seconds pass between reads, so every sound has ended before the next. + #clock = 0; + get currentTime() { return (this.#clock += 2); } + sampleRate = 8000; + destination = node(); + resume() { return Promise.resolve(); } + createOscillator() { made.oscillators += 1; return source("osc"); } + createBufferSource() { made.noises += 1; return source("noise"); } + createBuffer(_, length) { const data = new Float32Array(length); return { getChannelData: () => data }; } + createGain() { const g = node({ gain: param() }); made.gains.push(g); return g; } + createBiquadFilter() { made.filters += 1; return node({ frequency: param(), Q: param(), type: "" }); } + createDynamicsCompressor() { return node({ threshold: param(), knee: param(), ratio: param(), attack: param(), release: param() }); } + } + return { Ctx, made }; +} + +// tones.js keeps the first context it makes, so the whole file shares one. +const AUDIO = stubAudio(); + +const partsOf = (spec) => (spec.layers ? spec.layers : spec.notes ? spec.notes.map(() => spec) : [spec]); + +test("every tone and hum is named once across tones.js and every game's sound file", () => { + const seen = new Map(); + for (const tables of [TONE_TABLES, HUM_TABLES]) { + for (const table of tables) { + for (const name of Object.keys(table)) { + assert.ok(!seen.has(name), `${name} is defined twice`); + seen.set(name, true); + } + } + } + assert.ok(toneNames().length > 100, "the kit and the old blips"); + assert.ok(humNames().includes("car"), "and the hums"); +}); + +test("every tone is well formed: a known wave or noise, a sane length, a filter of a known kind", () => { + for (const name of toneNames()) { + const spec = TONE_TABLES.find((t) => Object.hasOwn(t, name))[name]; + assert.ok(Object.isFrozen(spec), `${name} is frozen`); + for (const p of partsOf(spec)) { + assert.ok(WAVES.has(p.type) || (spec.layers && NOISES.has(p.type)), `${name}: ${p.type} is a wave, or a noise in a layered tone`); + assert.ok(p.seconds > 0 && p.seconds + (p.delay || 0) <= 1.2, `${name} is over within 1.2 s`); + if (WAVES.has(p.type)) assert.ok(p.notes ? p.notes.every((f) => f > 0) : p.from > 0 && p.to > 0, `${name} has its pitches`); + if (p.filter) assert.ok(FILTERS.has(p.filter.type) && p.filter.from > 0, `${name}'s filter is known`); + if (p.gain !== undefined) assert.ok(p.gain > 0 && p.gain <= 1, `${name}'s part gain is a share`); + } + } +}); + +test("every hum is well formed: parts or noise, a positive peak, quiet enough to sit under the page", () => { + for (const name of humNames()) { + const spec = HUM_TABLES.find((t) => Object.hasOwn(t, name))[name]; + assert.ok((spec.parts && spec.parts.length) || spec.noise, `${name} makes a sound`); + for (const p of spec.parts || []) assert.ok(WAVES.has(p.type) && p.freq > 0, `${name}'s parts are waves`); + if (spec.noise) assert.ok(NOISES.has(spec.noise.color), `${name}'s noise is a known color`); + if (spec.filter) assert.ok(FILTERS.has(spec.filter.type) && spec.filter.freq > 0, `${name}'s filter is known`); + assert.ok(spec.peak > 0 && spec.peak <= 0.08, `${name} peaks at most as loud as a blip`); + } +}); + +test("every tone plays through a full AudioContext, one source per part, and never throws", () => { + const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; + const { Ctx, made } = AUDIO; + globalThis.AudioContext = Ctx; + try { + looks.sound = true; + for (const name of toneNames()) { + const spec = TONE_TABLES.find((t) => Object.hasOwn(t, name))[name]; + const before = made.oscillators + made.noises; + tone(name, 0.7, 1.2); + const vibratos = partsOf(spec).filter((p) => p.vibrato && WAVES.has(p.type)).length; + assert.equal(made.oscillators + made.noises - before, partsOf(spec).length + vibratos, `${name} starts a source per part`); + } + looks.sound = false; + const before = made.oscillators + made.noises; + tone("explode"); + assert.equal(made.oscillators + made.noises, before, "Play sounds off: silence"); + } finally { + looks.sound = saved.sound; + globalThis.AudioContext = saved.ctor; + } +}); + +test("a hum starts once, follows each call without starting more, and goes quiet when hushed or Play sounds is off", async () => { + const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; + const { Ctx, made } = AUDIO; + globalThis.AudioContext = Ctx; + try { + looks.sound = true; + hushTones(); + const start = made.started; + hum("you", "car", 0.5, 1); + const one = made.started - start; + assert.ok(one >= 3, "the car's oscillators, its noise and its pulse"); + for (let i = 0; i < 10; i++) hum("you", "car", 0.6, 1 + i / 10); + assert.equal(made.started - start, one, "revving it starts nothing new"); + hum("rival", "car", 0.3, 1); + assert.equal(made.started - start, one * 2, "a second id is its own voice"); + hum("you", "toycar", 0.3, 1); + assert.ok(made.stopped >= one, "a new name restarts the voice"); + const stoppedBefore = made.stopped; + hushTones(); + assert.ok(made.stopped > stoppedBefore, "hushed"); + hum("again", "nope"); + looks.sound = false; + const s = made.started; + hum("you", "car"); + assert.equal(made.started, s, "Play sounds off: no hum"); + looks.sound = true; + hum("held", "wind"); + const st = made.stopped; + await new Promise((r) => setTimeout(r, 320)); + assert.ok(made.stopped > st, "a hum not asked for again fades by itself"); + } finally { + hushTones(); + looks.sound = saved.sound; + globalThis.AudioContext = saved.ctor; + } +}); + +test("every tone or hum a game's source names is one the engine has", () => { + const tones = new Set(toneNames()); + const hums = new Set(humNames()); + for (const file of fs.readdirSync(GAMES).filter((f) => f.endsWith(".js") && !f.endsWith("-sfx.js"))) { + const source = fs.readFileSync(path.join(GAMES, file), "utf8"); + for (const m of source.matchAll(/\btone\(\s*"(\w+)"/g)) assert.ok(tones.has(m[1]), `${file}: tone "${m[1]}" exists`); + for (const m of source.matchAll(/\bhum\([^,()]+,\s*"(\w+)"/g)) assert.ok(hums.has(m[1]), `${file}: hum "${m[1]}" exists`); + } +}); + +/* ---------------------------------------------------------------- music */ + +const trackOf = (name) => MUSIC_TABLES.find((t) => Object.hasOwn(t, name))[name]; + +test("music: notes read as their pitch, sharps and flats included", () => { + assert.equal(noteFreq("A4"), 440); + assert.ok(Math.abs(noteFreq("C#5") - 554.37) < 0.01); + assert.equal(noteFreq("Db5"), noteFreq("C#5")); + assert.ok(Math.abs(noteFreq("A3") - 220) < 1e-9); + assert.ok(Number.isNaN(noteFreq("H2"))); +}); + +test("music: every track reads, with known waves, shares for gains and a start for each voice", () => { + assert.ok(musicNames().length >= 1, "at least one track"); + for (const name of musicNames()) { + const track = trackOf(name); + const song = compileTrack(track); + assert.ok(song.length >= 16, `${name} runs a bar at least`); + for (const [v, voice] of Object.entries(track.voices)) { + assert.ok(voice.kit || ["pulse", "triangle", "sine", "square", "sawtooth"].includes(voice.wave), `${name}.${v} has a known wave`); + assert.ok((voice.gain ?? 1) > 0 && (voice.gain ?? 1) <= 1, `${name}.${v}'s gain is a share`); + assert.ok((voice.from ?? 0) >= 0 && (voice.from ?? 0) <= 1, `${name}.${v} comes in between 0 and 1`); + } + } +}); + +test("music: a track that does not read is turned away", () => { + const ok = { bpm: 120, voices: { a: { wave: "pulse" } }, patterns: { A: { a: "A4 - . C5" } }, order: ["A"] }; + assert.equal(compileTrack(ok).length, 4); + assert.throws(() => compileTrack({ ...ok, bpm: 900 }), /bpm/); + assert.throws(() => compileTrack({ ...ok, patterns: { A: { a: "A4 - . Z9" } } }), /not a note/); + assert.throws(() => compileTrack({ ...ok, voices: { a: { wave: "pulse" }, b: { kit: true } }, patterns: { A: { a: "A4 - . C5", b: "k ." } } }), /steps/); + assert.throws(() => compileTrack({ ...ok, voices: { a: { wave: "pulse" }, b: { kit: true } }, patterns: { A: { a: "A4 - . C5", b: "k . x ." } } }), /not a drum/); + assert.throws(() => compileTrack({ ...ok, order: ["B"] }), /missing pattern/); + const arp = compileTrack({ ...ok, patterns: { A: { a: "A3^037 - - ." } } }); + assert.equal(arp.patterns.A.lines.a[0].freqs.length, 3, "an arpeggio cycles three notes"); + assert.equal(arp.patterns.A.lines.a[0].len, 3, "held for three steps"); +}); + +test("music: a track plays notes while asked for, quiets when hushed, and stays silent while Play sounds is off", () => { + const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; + const { Ctx, made } = AUDIO; + globalThis.AudioContext = Ctx; + try { + looks.sound = true; + const name = musicNames()[0]; + const before = made.started; + music(name, 1); + assert.ok(made.started > before, "notes booked at once"); + music("nope", 1); + hushMusic(); + looks.sound = false; + const quiet = made.started; + music(name, 1); + assert.equal(made.started, quiet, "Play sounds off: no music"); + } finally { + hushMusic(); + looks.sound = saved.sound; + globalThis.AudioContext = saved.ctor; + } +}); + +test("music: plays through its own gentle compressor (as on the prototype pages), never the sounds' harder one", () => { + const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; + const { Ctx } = AUDIO; + const proto = Ctx.prototype; + const was = { gain: proto.createGain }; + const buses = []; + // Each node remembers what it is connected to. + const wired = (n) => Object.assign(n, { to: [], connect(x) { n.to.push(x); } }); + proto.createGain = function () { const g = wired(was.gain.call(this)); buses.push(g); return g; }; + globalThis.AudioContext = Ctx; + try { + hushMusic(); + looks.sound = true; + music(musicNames()[0], 1); + // The compressor is made once per context, maybe before this test, so + // it is found through the track's bus rather than by being watched. + const isComp = (x) => x && x.threshold && x.ratio; + const bus = buses.find((g) => g.to.some(isComp)); + assert.ok(bus, "the track's bus feeds a compressor"); + const comp = bus.to.find(isComp); + assert.equal(comp.threshold.value, -14, "the prototype pages' threshold, not the sounds' -20"); + assert.equal(comp.ratio.value, 4); + } finally { + hushMusic(); + proto.createGain = was.gain; + looks.sound = saved.sound; + globalThis.AudioContext = saved.ctor; + } +}); + +test("music: a new track crossfades in over seconds while the last keeps playing, and a hush cuts both", () => { + const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; + const { Ctx, made } = AUDIO; + globalThis.AudioContext = Ctx; + try { + looks.sound = true; + const [first, second] = musicNames(); + hushMusic(); + const mark = made.gains.length; + music(first, 1); + const firstBus = made.gains.slice(mark).find((g) => g.gain.ramps.some((r) => r.kind === "linear" && r.v > 0.1)); + const at = made.gains.length; + music(second, 1); + const out = firstBus.gain.ramps.at(-1); + const from = firstBus.gain.ramps.at(-2); + assert.equal(out.kind, "linear", "the last track ramps down, not cut"); + assert.ok(out.v < 0.001 && out.t - from.t >= 2, "over seconds"); + const secondBus = made.gains[at]; + const up = secondBus.gain.ramps.find((r) => r.kind === "linear"); + assert.ok(up.v > 0.1 && up.t - secondBus.gain.ramps[0].t >= 2, "the new track ramps up over the same seconds"); + hushMusic(); + assert.equal(secondBus.gain.ramps.at(-1).kind, "target", "a hush fades the new track at once"); + } finally { + hushMusic(); + looks.sound = saved.sound; + globalThis.AudioContext = saved.ctor; + } +}); + +test("music: every track a game's source asks for is one the sequencer has", () => { + const tracks = new Set(musicNames()); + for (const file of fs.readdirSync(GAMES).filter((f) => f.endsWith(".js") && !f.endsWith("-sfx.js"))) { + const source = fs.readFileSync(path.join(GAMES, file), "utf8"); + for (const m of source.matchAll(/\bmusic\(\s*"(\w+)"/g)) assert.ok(tracks.has(m[1]), `${file}: track "${m[1]}" exists`); + } +}); + +test("music: the volume scales the track's level, a change glides there, and a volume of 0 plays nothing", () => { + const saved = { sound: looks.sound, ctor: globalThis.AudioContext }; + const { Ctx, made } = AUDIO; + globalThis.AudioContext = Ctx; + try { + looks.sound = true; + const [first, second] = musicNames(); + hushMusic(); + const peak = (volume) => { + hushMusic(); + const mark = made.gains.length; + music(first, 1, volume); + return made.gains.slice(mark).find((g) => g.gain.ramps.some((r) => r.kind === "linear" && r.v > 0.01)); + }; + const full = peak(1).gain.ramps.find((r) => r.kind === "linear").v; + const bus = peak(0.5); + assert.ok(Math.abs(bus.gain.ramps.find((r) => r.kind === "linear").v - full / 2) < 1e-9, "half the volume, half the level"); + music(first, 1, 0.25); + const glide = bus.gain.ramps.at(-1); + assert.equal(glide.kind, "target", "a slider move glides"); + assert.ok(Math.abs(glide.v - full / 4) < 1e-9, "to the new level"); + hushMusic(); + const quiet = made.started; + music(second, 1, 0); + assert.equal(made.started, quiet, "a volume of 0: nothing booked"); + } finally { + hushMusic(); + looks.sound = saved.sound; + globalThis.AudioContext = saved.ctor; + } +}); + +test("music: every Sunset Drive road has a song, and every song is a real track", () => { + const tracks = new Set(musicNames()); + assert.deepEqual(Object.keys(ROAD_MUSIC).sort(), Object.keys(REGIONS).sort(), "a song for every road"); + for (const [road, name] of Object.entries(ROAD_MUSIC)) { + assert.ok(Object.hasOwn(REGIONS, road), `road ${road} exists`); + assert.ok(tracks.has(name), `${road}: track "${name}" exists`); + } +}); diff --git a/scripts/test-web-console-workspace.mjs b/scripts/test-web-console-workspace.mjs index 44a28c4..f8f540b 100644 --- a/scripts/test-web-console-workspace.mjs +++ b/scripts/test-web-console-workspace.mjs @@ -47,7 +47,8 @@ test("workspace: a folder added on the dashboard survives dashboard → plan → const s = consoleSession(["--workflow", "dashboard"]); const extra = tempFolder(); try { - assert.deepEqual(s.opened.workspace.folders, [{ name: defaultName(ROOT), path: ROOT, original: true }]); + assert.equal("workspace" in s.opened, false, "open prints the folder list only with more than one folder"); + assert.deepEqual(wsFile(s).folders.map((f) => [f.name, f.path, f.original]), [[defaultName(ROOT), ROOT, true]]); const added = await addFolder(s, { path: extra, description: " the design notes " }); assert.equal(added.status, 200); assert.equal(added.body.name, defaultName(extra)); @@ -85,10 +86,10 @@ test("workspace: a folder added on the dashboard survives dashboard → plan → ); assert.equal(meterView(readLedger(fresh.session)).points, 0); } finally { - cli(["stop", "--session", fresh.sid]); + cli(["stop", "--session", fresh.sid, "--force"]); } } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(extra, { recursive: true, force: true }); } }); @@ -122,7 +123,7 @@ test("workspace: a spec starts from the project's list, then stands alone, and t assert.deepEqual(again.folders.map((f) => f.path), [ROOT, shared, specOnly], "the spec's own list comes back"); assert.equal((await s.send("/workspace/scope", { spec: "../elsewhere" })).status, 400); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(shared, { recursive: true, force: true }); fs.rmSync(specOnly, { recursive: true, force: true }); } @@ -138,7 +139,7 @@ test("workspace: open --spec starts on that spec's list, a posted specDir takes await addFolder(s, { path: shared }); await s.send("/workspace/scope", { spec: "specs/demo" }); await addFolder(s, { path: specOnly }); - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); other = consoleSession(["--workflow", "implement", "--spec", "specs/demo"], { keepRemembered: true }); assert.deepEqual(other.opened.workspace.folders.map((f) => f.path), [ROOT, shared, specOnly]); @@ -159,7 +160,7 @@ test("workspace: open --spec starts on that spec's list, a posted specDir takes assert.ok(rememberedFor(""), "the project's list is kept"); assert.equal(cli(["forget"], { expectFail: true }).status, 2); } finally { - for (const x of [s, other, planned]) if (x) cli(["stop", "--session", x.sid]); + for (const x of [s, other, planned]) if (x) cli(["stop", "--session", x.sid, "--force"]); fs.rmSync(shared, { recursive: true, force: true }); fs.rmSync(specOnly, { recursive: true, force: true }); } @@ -202,7 +203,7 @@ test("workspace: add resolves from the session's folder and refuses a file, a mi assert.deepEqual(wsFile(s).folders.map((f) => f.id), ["f0", "f1", "f2"], "refusals changed nothing"); assert.deepEqual(wsFile(s).changes.map((c) => [c.kind, c.version]), [["added", 1], ["added", 2]]); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(quoted, { recursive: true, force: true }); } }); @@ -246,7 +247,7 @@ test("workspace: the original can be renamed and described but never removed; ot assert.deepEqual(wsFile(s).folders.map((f) => f.id), ["f0"]); assert.equal(wsFile(s).changes.at(-1).kind, "removed"); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(extra, { recursive: true, force: true }); } }); @@ -271,7 +272,7 @@ test("workspace: browse returns the picked folder, or canceled, and is hidden wh assert.equal(hidden.status, 404); assert.deepEqual(await hidden.json(), { reason: "no-picker" }); } finally { - for (const s of [echo, cancel, remote]) cli(["stop", "--session", s.sid]); + for (const s of [echo, cancel, remote]) cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(picked, { recursive: true, force: true }); } }); @@ -300,7 +301,7 @@ test("workspace: a folder deleted on disk is marked missing once, and found agai "the launch alone marked the folder missing" ); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(gone, { recursive: true, force: true }); } }); @@ -316,13 +317,15 @@ test("workspace: a change never ends a wait slice, rides on the next send exactl await sleep(1500); assert.equal((await addFolder(s, { path: extra })).status, 200); assert.equal(await exited, 10, "the change alone did not end the slice"); - assert.equal(safeJson(out).pendingWorkspace, 1); + const slice = safeJson(out); + assert.equal(slice.waiting, true); + assert.equal("pendingWorkspace" in slice, false, "the slice line no longer reports the pending change"); const name = defaultName(extra); assert.equal((await s.send("/submit", EXPORT_A)).status, 200); const first = cli(["wait", "--session", s.sid, "--seconds", "10"]); assert.equal(first.status, 0); - assert.deepEqual(first.json.workspace.map((c) => [c.kind, c.name]), [["added", name]]); + assert.equal("workspace" in first.json, false, "a change arrives as a reply line only"); assert.match(first.json.reply, /^Export format: a\n/); assert.match(first.json.reply, new RegExp(`^Workspace: added @${name} — `, "m")); assert.equal(readWorkspaceCursor(s.session), 1); @@ -337,9 +340,11 @@ test("workspace: a change never ends a wait slice, rides on the next send exactl fs.writeFileSync(path.join(s.session, "workspace-cursor.json"), JSON.stringify({ version: 0 })); assert.equal((await s.send("/submit", EXPORT_A)).status, 200); const again = cli(["wait", "--session", s.sid, "--seconds", "10"]); - assert.deepEqual(again.json.workspace.map((c) => c.name), [name]); + assert.equal("workspace" in again.json, false); + assert.equal(again.json.reply.split("\n").filter((l) => l.startsWith("Workspace:")).length, 1, "the change comes again as one line"); + assert.ok(again.json.reply.includes("@" + name)); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(extra, { recursive: true, force: true }); } }); @@ -351,13 +356,30 @@ test("workspace: chat hands over a workspace change on its own, then has nothing assert.equal((await addFolder(s, { path: extra })).status, 200); const got = cli(["chat", "--session", s.sid]); assert.equal(got.status, 0); - assert.deepEqual(got.json.chat, []); - assert.deepEqual(got.json.workspace.map((c) => c.kind), ["added"]); + assert.equal(got.json.chat, undefined, "no question, no chat key"); + assert.equal("workspace" in got.json, false, "reply lines only"); assert.match(got.json.reply, /^Workspace: added @/); - assert.ok(got.json.terminalLine); + assert.equal(got.json.reply.split("\n").length, 1); assert.equal(cli(["chat", "--session", s.sid]).status, 10); } finally { - cli(["stop", "--session", s.sid]); + cli(["stop", "--session", s.sid, "--force"]); + fs.rmSync(extra, { recursive: true, force: true }); + } +}); + +test("workspace: a change arrives as a Workspace line in reply only, never as a workspace object", async () => { + const s = openSession(); + const extra = tempFolder(); + try { + assert.equal((await addFolder(s, { path: extra })).status, 200); + assert.equal((await s.send("/submit", EXPORT_A)).status, 200); + const got = cli(["wait", "--session", s.sid, "--seconds", "10"]); + assert.equal(got.status, 0); + assert.equal("workspace" in got.json, false); + assert.equal("pendingWorkspace" in got.json, false); + assert.match(got.json.reply, new RegExp(`^Workspace: added @${defaultName(extra)}`, "m")); + } finally { + cli(["stop", "--session", s.sid, "--force"]); fs.rmSync(extra, { recursive: true, force: true }); } }); diff --git a/scripts/web-console-test-helpers.mjs b/scripts/web-console-test-helpers.mjs index c974069..449b884 100644 --- a/scripts/web-console-test-helpers.mjs +++ b/scripts/web-console-test-helpers.mjs @@ -109,6 +109,28 @@ export function safeJson(s) { } } +// One wait slice of a session, parsed: { code, out } where out is the last +// stdout line as JSON (null when it is not). Exit 10 and 20 are results here, +// not failures. +export function waitOnce(sid, seconds = 5, opts) { + const res = cli(["wait", "--session", sid, "--seconds", String(seconds)], opts); + return { code: res.status, out: res.json, stdout: res.stdout, stderr: res.stderr }; +} + +// The last non-empty line of a command's stdout: `post --wait` prints the +// post's line, then the wait's. +export const lastLine = (stdout) => String(stdout).trim().split("\n").filter(Boolean).pop() ?? ""; + +// End one session the way an agent must: a finish first, then stop. A test +// that only wants a session gone for cleanup may pass --force to stop instead. +export function stopSession(sid, opts) { + postFinish(sid, opts); + return cli(["stop", "--session", sid], opts); +} +function postFinish(sid, opts) { + cli(["post", "--session", sid, "--file", payload(`finish-${sid}.json`, { finish: { headline: "Test done" } })], opts); +} + export function payload(file, obj) { const p = path.join(HOME, file); fs.writeFileSync(p, JSON.stringify(obj)); diff --git a/src/web-console/building-review.md b/src/web-console/building-review.md index 0f9f6ae..675fef4 100644 --- a/src/web-console/building-review.md +++ b/src/web-console/building-review.md @@ -1,154 +1,56 @@ -# The Review, Mid-Session, on the Web Console +# The Review, Mid-Session -Part of the build contract (`building.md`). Read when the person asks for the -review on the page: the `review` verdict on Implement's sign-off card, the -**Review it now** button on a finished quick task, or Implement + Review's -Stage 2. +The console points here on `__review`, or on a `review` card answered with a verdict. Part of the build contract (`building.md`). The same focused review runs from three doors: -The same focused review runs from either of two doors: +- **`implement`:** the `review` verdict on the sign-off card, before anything is approved. A note sent with it is focus for the review. Settle the card in the post that goes back to work: `{"settle":true,"headline":{"stage":"Reviewing Phase 3","cleared":0,"total":0},"run":{"event":"review","id":"review"},"agent":{"status":"working","activity":"Reviewing the 7 files this phase changed","quietMinutes":15}}` +- **`quick-task`:** the **Review it now** button on the finished screen (`finish.review`), arriving as `__review`. Take it up with the same post minus `settle`, plus `"finish":null`. +- **`implement-review`:** Stage 2 (`notes/implement.md`). -- **`implement`:** the `review` verdict on the sign-off card, before anything - is approved. A note sent with it is theirs — read it as focus for the - review. Settle the card with it in the same post that goes back to work: +Either way the post that takes the review up carries `"run":{"event":"review","id":"review"}`: the review runs inside this session, so no launch scores it. Never also resume under `--workflow review`, or it counts twice. - ```jsonc - { - "settle": true, - "headline": { "stage": "Reviewing Phase 3", "cleared": 0, "total": 0 }, - "run": { "event": "review", "id": "review" }, - "agent": { "status": "working", "activity": "Reviewing the 7 files this phase changed", "quietMinutes": 15 } - } - ``` +A quick-task finish carries `review` and `dashboard:true` and waits for whichever comes first: -- **`quick-task`:** the **Review it now** button on the finished screen, which - `finish.review` puts there. It arrives through the wait loop as an action - `{ "i": "__review", "type": "review" }`, like any send. Take it up with the - same post minus `settle`, plus `"finish": null` — that takes the session off - its ending and back to work. - -Either way, the post that takes the review up carries `"run": { "event": -"review", "id": "review" }`: the review runs inside this skill's session, so no -launch scores it on the session meter. Never resume the session under -`--workflow review` for it as well, or it counts twice. - -A finish carrying `review` keeps the session alive for the answer, so a -`quick-task` that just posted one keeps waiting — there is no timeout after -a finish. -A quick-task finish carries both `review` and `"dashboard": true` and waits -for whichever comes first: - -| What arrives | What you do | +| Arrives | Do | | --- | --- | -| An action `{ "i": "__review", "type": "review" }` | Take the review up (below). | -| An action `{ "i": "__dashboard", "type": "dashboard" }` | Take the session back as the dashboard (`console-finish.md` → After the finish). | -| An action `{ "i": "__done", "type": "done" }` | `stop` the server. The session is over. | -| `wait` exit `20` | The server is gone. Resume it (`open --resume --workflow `), give them the new link, and keep waiting. | -| The session ends without a press (the terminal closes) | The server sweeps itself after its idle window; the page then shows the terminal command for a review instead of a button that would go nowhere. | +| `__review` | Take the review up (below) | +| `__dashboard` | Take the session back as the dashboard (`console-finish.md`) | +| `__done` | `stop` the server: the session is over | +| `wait` exit 20 | `open --resume --workflow `, give the new link, keep waiting | -**Read references/review.md** and run Review Mode with these overrides: +**Read `references/review.md`** and run Review Mode with these overrides: -- **Scope is Focused, and already decided:** the exact change set of this - session (files created or modified by the phase or the quick task, plus the - tests and docs changed for it). Do not ask about scope. Use overview.md and - the phase file for spec compliance; they do not widen the scope. -- **The helper rule still applies:** a fresh helper runs the analysis when - available, you verify every finding, and the report carries its Reviewed by - line. -- **No commit instructions and no next-conversation routing** mid-review. The - way back out carries both. -- The page takes the whole report, so the "top 10 of 15+" rule does not apply, - and tables go in the doc. +- Scope is Focused and decided: the exact change set of this session (files created or modified by the phase or the quick task, plus the tests and docs changed for it). Do not ask about scope. `overview.md` and the phase file give spec compliance; they do not widen scope. +- The helper rule applies: a fresh helper runs the analysis when available, you verify every finding, and the report carries its Reviewed by line. +- No commit instructions and no next-conversation routing mid-review; the way back out carries both. +- The page takes the whole report: the "top 10 of 15+" rule does not apply, and tables go in the doc. ## The findings -The full Review Mode report as a doc, and the fix choice as one `multi` item, -posted with `--wait`: +In loop mode the pick comes from `--fix`: post the findings and the pick as settled `handledBy:"loop"` items and ask nothing (`notes/loop.md`). -```jsonc -{ - "docs": [{ "id": "review", "title": "Review findings", "blocks": [ - { "id": "report", "state": "settled", "md": "## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..." } - ]}], - "items": [{ - "id": "fixes", "kind": "multi", "title": "Which to fix", "required": false, "doc": "review", - "body": "Tick what should be fixed now. Anything left unticked is written up as still open. Nothing changes until you send.", - "options": [ - { "k": "1", "text": "Critical: token is logged in plain text", "detail": "src/auth.ts:42. Fix: redact before logging." }, - { "k": "2", "text": "Warning: missing null check on the user lookup", "detail": "src/users.ts:88. Fix: ..." }, - { "k": "3", "text": "Suggestion: repeated query could be batched", "detail": "src/report.ts:17. Fix: ..." } - ], - "presets": [ - { "label": "Critical and warnings", "ks": ["1", "2"] }, - { "label": "All of them", "ks": ["1", "2", "3"] } - ] - }] -} -``` +Post the full report as a doc, and the fix choice as one `multi` item, with `--wait`: -`"doc": "review"` puts a **Read "Review findings" in full** button on the -card, so the report is one click from the list rather than behind a tab -nobody notices. Always carry it. +`{"docs":[{"id":"review","title":"Review findings","blocks":[{"id":"report","md":"## Overview\n\n...\n\n## Findings\n\n| # | Severity | Issue | File |\n..."}]}],"items":[{"id":"fixes","kind":"multi","title":"Which to fix","required":false,"doc":"review","body":"Tick what should be fixed now. Anything unticked is written up as still open. Nothing changes until you send.","options":[{"k":"1","text":"Critical: token is logged in plain text","detail":"src/auth.ts:42. Fix: redact before logging."},{"k":"2","text":"Warning: missing null check on the user lookup","detail":"src/users.ts:88. Fix: ..."}],"presets":[{"label":"Critical and warnings","ks":["1","2"]},{"label":"All of them","ks":["1","2","3"]}]}]}` -Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`, -every finding ticked is `A`, and `skip` (or nothing ticked) is "fix none, -keep them as unresolved". Leave out `presets` a set would not change (no -warnings, one finding). With **zero findings** there is no item: say so in the -doc and go straight to the way back out. +Findings keep numeric `k` (they are not lettered). `"doc":"review"` puts a "Read in full" button on the card: always carry it. Read the reply as Review Mode's fix choice: `Which to fix: 1, 2` is `S 1,2`, all ticked is `A`, `skip` or nothing ticked is "fix none, keep them as unresolved". Leave out a `preset` a set would not change. With zero findings there is no item: say so in the doc and go to the way back out. ## Fixing -Settle the `fixes` item (`"settle": true`) in the same post that goes back to -work. The server records their send on the item, but only you decide it is -settled; left open it stays on the page as an outstanding question, beside the -card you ask next. A send with nothing ticked settles as `{ "ks": [] }`. Then -follow Review Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the -null check") and `quietMinutes` as in a build. +Settle `fixes` (`"settle":true`) in the same post that goes back to work. A send with nothing ticked settles as `{"ks":[]}`. Then follow Review Mode's Post-Fix Flow, posting `activity` per fix ("Fix 2 of 3: the null check") and `quietMinutes` as in a build. In loop mode: one fix round, then a fresh re-check of only the fixes; with `--fix smart` a triage helper picks the findings first (`notes/loop.md`). ## The way back out -**`implement` — back to the sign-off.** The review was the preamble to an -approval that has not happened yet, so this is where it lands. Fold the review -results and any still-open findings into the report doc, then reopen the -sign-off **without the review verdict** — re-offering a review that just ran -reads as though nothing happened — and post the build's `headline` back (the -review set it to its own stage): +In loop mode the way out is the `loopOutcome` post, not a sign-off. -```jsonc -{ - "headline": { "cleared": 9, "total": 9 }, - "items": [{ "id": "signoff", "status": "reopened", - "body": "Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab. The report is updated.", - "verdicts": [ - { "id": "approve", "label": "Approve this phase" }, - { "id": "show", "label": "Show me it working" }, - { "id": "changes", "label": "I want changes" } - ], - "token": { "approve": "approved", "changes": "needs changes", "show": "show me" }, - "thread": [{ "who": "agent", "text": "Review done: 2 of 3 findings fixed; the rest is written up in the findings tab." }] - }] -} -``` +**`implement` and `implement-review`: back to the sign-off.** Fold the review results and still-open findings into the report doc, then reopen the sign-off without the review verdict and post the build's `headline` back: -`show` runs as `notes/implement.md` → Show me it working says, then reopens -this card without it. Review Mode's own closing gate ("Reply approved to commit") is this card: -approving the phase now covers the fixes too, so there is no separate "Check -the fixes" step. On approval, continue at `notes/implement.md` → After -approval: the finish. +`{"headline":{"cleared":9,"total":9},"items":[{"id":"signoff","status":"reopened","body":"Reviewed and ready for sign-off. The review found 3 issues: 2 fixed, 1 still open in the Review findings tab.","verdicts":[{"id":"approve","label":"Approve this phase"},{"id":"show","label":"Show me it working"},{"id":"changes","label":"I want changes"}],"token":{"approve":"approved","changes":"needs changes","show":"show me"},"thread":[{"who":"agent","text":"Review done: 2 of 3 findings fixed; the rest is in the findings tab."}]}]}` -**`quick-task` — the closing gate, then the finish.** Review Mode's closing -gate ("Reply approved to commit, or request changes") becomes a `review` item -titled "Check the fixes", `doc: "review"`, `"nothingYet": false` (the fixes are already made), verdicts `approve` ("The fixes look -right") and `changes`, token `approved` / `needs changes`. When it clears, -settle it (`"settle": true`) in the same post as the new finish, post the finish -**without** `review` (and with `dashboard: true`), then keep waiting for its -buttons as `console-finish.md` says; `stop` only on `__done`. An item left open survives on the page as -a question still owed, above the ending itself: +`show` runs as `notes/implement.md` says and reopens this card without it. Approving now covers the fixes: there is no separate "Check the fixes" step. On approval continue at `notes/implement.md` (the finish). + +**`quick-task`: the closing gate, then the finish.** Post a `review` item "Check the fixes": `doc:"review"`, `"nothingYet":false`, verdicts `approve` ("The fixes look right") and `changes`, token `approved` / `needs changes`. When it clears, settle it in the same post as the new finish, posted without `review` and with `dashboard:true`; keep waiting for its buttons, `stop` only on `__done`. The finish: - `headline`: "The review is done" -- `body`: findings by severity, what was fixed, what is still open, and the - commit command for the fixes, in the project's commit format. -- `command`: one commit for the whole quick task, its changes and the fixes - together, in the project's commit format (not a second command beside the - first), with `commit: true` so **Commit it now** is still on offer, and `changelog: true` so **Update CHANGELOG first** is too. -- `headline`: the quick task's own again, e.g. `{ "cleared": 4, "total": 4 }`. -- `doc`: `"review"`. +- `body`: findings by severity, what was fixed, what is still open, and the commit command for the fixes +- `command`: one commit for the whole quick task (changes and fixes together) in the project's commit format, with `commit:true` and `changelog:true` +- `doc`: `"review"`. The `headline` object goes back to the quick task's own (`{"cleared":4,"total":4}`). diff --git a/src/web-console/building.md b/src/web-console/building.md index 5c62a2a..6cb7437 100644 --- a/src/web-console/building.md +++ b/src/web-console/building.md @@ -1,149 +1,54 @@ -# Build Sessions on the Web Console +# Build Sessions -For `/plan2code-3-implement`, `/plan2code-3-implement-review` and -`/plan2code-quick-task`. Everything in `console.md` still applies (the turn, -one post per send, `finish` before `stop`, the house rules). This file adds what -a build needs, because a build is mostly you working, and the page has to be -told so. Then read your workflow's own notes: `notes/implement.md` (Implement -and Implement + Review) or `notes/quick-task.md`. `building-review.md` is read -only when a review is asked for on the page. - -**The console changes where you ask, not what you build.** Every rule of the -workflow stands: the same specs, the same checkbox writes to disk after every -task, the same sign-off wording, the same "no git commands". The files under -`specs/` and the code are the record. The page is a window onto them. - ---- +For `implement`, `implement-review` and `quick-task`; read right after `open`, then `notes/implement.md` or `notes/quick-task.md`. `building-review.md` is named by `read` when a review is asked for on the page. The workflow's rules stand: the same specs, the same checkbox writes to disk after every task, the same sign-off wording, no git commands. The files under `specs/` and the code are the record; the page is a window onto them. ## Opening -Open first, before reading the spec — the page shows a starting screen while -you work out the phase: +Open before reading the spec; the page shows a starting screen meanwhile. -| Workflow you are running | `--workflow` | `--spec` | +| Workflow | `--workflow` | `--spec` | | --- | --- | --- | | `/plan2code-3-implement` | `implement` | `specs/` | | `/plan2code-3-implement-review` | `implement-review` | `specs/` | -| `/plan2code-quick-task` | `quick-task` | leave it out | +| `/plan2code-quick-task` | `quick-task` | leave out | -`--spec` is what the page builds a resume command from if you ever cannot -answer a stop yourself. Pass it to `open` when you already know the spec; -otherwise post `"specDir": "specs/"` and a real `title` (": -Phase 3") in your first update, once the phase is chosen, or with the phase -question as its first item if there is one to ask. - -**Launched from the dashboard?** Then the session is already open and the -person is watching it — run the `resume` the launch carried (`open --resume - --no-open --workflow `, plus `--spec` once known) instead of a -fresh `open`, exactly as `console-launches.md` says. Everything below is -unchanged; the only difference is whose session it was a minute ago. - ---- +Without `--spec` at `open`, post `"specDir":"specs/"` and a real `title` (": Phase 3") once the phase is chosen. Launched from the dashboard? The session is open: run the `resume` the launch carried (`open --resume --no-open --workflow `, plus `--spec` once known). ## While you build -Post after every task, in the same breath as writing its checkbox to disk, -with no `--wait`. Your notes file shows the exact post; every one carries: +Post after every task, in the same breath as writing its checkbox to disk, with no `--wait`. Every post carries: -- **`headline.cleared` / `total`**: tasks done out of tasks in the run. The - progress bar is the first thing someone watching a build looks at, and on - Implement (and Implement + Review) the session meter counts the build's tasks - from `cleared` as it rises; a quick task scores once, when it opens. Start every - phase (a second one in the same run too) at `"cleared": 0`. If the task list - grows mid-build, raise `headline.total` in the same post. -- **`agent.activity`**: one plain sentence saying what you are doing now. The - page shows it beside Planny and in place of "questions coming". No internal - vocabulary, no loop completion markers. Number tasks by their position in - the run, of the task count (`Task 5 of 9`), not by the file's `5.5`-style - labels: the phase is already in the headline. The page rewrites the old form - as a safety net. -- **`agent.quietMinutes`** (on the post that starts the build): how long you - might go without posting (1 to 60; the page always allows at least two). The page calls a working agent stuck - after two minutes of silence unless you say otherwise, and a build task can - honestly take twenty. Set it to the longest gap you expect, usually 10 to 30. - Every post is also a heartbeat. It only counts while you are working, so it - holds across the questions you ask: set it once. -- **The task list re-read from disk** (Implement): the doc blocks that mirror - the spec are `file` blocks, so a progress post re-reads them with - `"refresh": true` rather than repeating the text. A quick task's plan lives - only on the page, so its steps block stays `md` (`notes/quick-task.md`). - Versions move by themselves. +- `headline.cleared` / `total`: tasks done of tasks in the run. Start every phase at `"cleared":0`; raise `total` if the list grows. On Implement and Implement + Review the meter counts a build's tasks from `cleared`; a quick task scores once, when it opens. +- `agent.activity`: one plain sentence, no internal vocabulary or loop markers. Number tasks by position in the run (`Task 5 of 9`), not the file's `5.5` labels. +- `agent.quietMinutes` (on the post that starts the build): the longest gap you expect, usually 10 to 30 (the page calls you stuck after two silent minutes otherwise). Set it once. +- the doc blocks that mirror the spec are `file` blocks: re-read them with `"refresh":true`, never repeat the text (`notes/implement.md`). A quick task's steps block stays `md`. -Do not call `wait` while building. There is nothing to collect, and the page -holds anything the person sends until you next look. +Do not call `wait` while building. After each progress post, run `node "" chat --session ` before the next task: exit 0 means answer everything waiting, under `console-chat.md`, in one post, then continue (a `Workspace:` change takes effect from the next task); 10 nothing waiting; 20 server gone, `open --resume --workflow `, give the link, carry on. An approved chat edit is made here, between tasks. -A build may receive a `Subagents:` standing instruction, on `open` output or a -`chat` check between tasks. Follow `console-subagents.md` for handing -independent tasks to helpers and reporting them as `helpers`. Keep the -per-task progress posts, the checkbox writes, the chat checks and the sign-off -with you. +A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are not questions: put them in the phase doc and the report. A `Subagents:` block: hand independent tasks to helpers as `console-subagents.md` says; keep the progress posts, checkbox writes, chat checks and sign-off with you. -### Quick questions between tasks +## When the workflow asks something -The person can ask a Quick question on the Ask tab at any point in a build -(`console-chat.md`). After each task's progress post, check for one before -starting the next task: - -``` -node "" chat --session -``` - -| Exit | What you do | -| --- | --- | -| `0` | Answer everything waiting, under `console-chat.md`, in one post, then start the next task. A `workspace` list in the output is a change to the session's folders (`console-workspace.md`): take it into account from the next task on; it needs no reply. | -| `10` | Nothing waiting. Carry on. | -| `20` | The server is gone: `open --resume --workflow `, give them the new link, then carry on. | - -This is an instant check, not a wait: it never sleeps and never touches card -sends. It does not replace `wait` at a gate, and no build calls `wait` -mid-build for cards. An approved chat edit is made here, between tasks, never -in the middle of one. - -A blocker (`[!]`), a `SPEC NOTE` and a verified or assumed prerequisite are -not questions. Put them in the phase doc as they happen, and in the report. - -### When the workflow asks something - -Publish it with `post --wait`: a new question hands the turn over by itself -(status `waiting`). When the answer lands, collecting it -sets you `working` again; carry on. - -A question stops the build. Never post `"status": "working"` with a question -open, and never "carry on while you decide": the page reads `working` as "not -your turn", and the person is left looking at a question they cannot answer. -If there is other work the answer does not touch, finish it before you ask, -then ask and wait. +Publish it with `post --wait`. A question stops the build: never post `"status":"working"` with a question open, and finish any work the answer does not touch before you ask. | Moment | `kind` | Notes | | --- | --- | --- | -| Several phases can be picked | `choice` | One option per phase, `detail` = status and task count, `token` = the phase number. Put the "run another agent on a different phase" tip in `body`. | -| A phase is already in progress | `confirm` | "Resume Phase 3?" `yes` / `no`. | -| `SPEC CONFLICT` | `choice` or `text` | The conflict in `body`, the readings as options where there are clear ones. Never guess on architecture. | -| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first. | +| Several phases can be picked | `choice` | one option per phase, `detail` = status and task count, `token` = the phase number; put the "run another agent on a different phase" tip in `body` | +| A phase is in progress | `confirm` | "Resume Phase 3?" | +| `SPEC CONFLICT` | `choice` or `text` | the conflict in `body`, clear readings as options; never guess on architecture | +| Test failures | `choice` | `1` Fix now, `2` Document and proceed, `3` Investigate first | +| Shared ground touched | `choice` | run the full suite, run a wider named set, or approve without it; `body` says what was touched and why it is wide | | A small phase, continue with the next? | `confirm` | | | A spec gap only they can close | `text` | | -| Something learned for AGENTS.md | `confirm` | The proposed lines in `consequences`. | +| Something learned for AGENTS.md | `confirm` | proposed lines in `consequences` | -Titles stay plain: "Which phase next", "Tests are failing", "Keep going?". +Titles stay plain: "Which phase next", "Tests are failing", "Keep going?". In loop mode (`notes/loop.md`) a question is held or stopped by the app, never answered by it; the findings pick and fixes are `handledBy:"loop"` cards. ---- +## Stop during a build -## Stop requests during a build +Stop only arrives on the person's turn, never mid-task. On `__stop` (`console-stop.md`): -The Stop button only works on the person's turn, so it never lands mid-task. -When `__stop` arrives (`console-stop.md`): +- **implement / implement-review:** Implementation Mode's abort without the "are you sure": the phase stays `[/]`, list completed and remaining tasks, post `finish` with headline starting "Paused" and the resume command (`/plan2code-3-implement specs//overview.md`), no `dashboard`, then `stop`. +- **quick-task:** say in `finish.body` what was worked out and that nothing was saved unless built; `"command":"/plan2code-quick-task"`. -- **implement / implement-review:** Implementation Mode's abort, without the - "are you sure" (the page asked): the phase stays `[/]`, list completed and - remaining tasks, post `finish` with the resume command - (`/plan2code-3-implement specs//overview.md`), then `stop`. An - implement abort is a pause: a headline starting "Paused", no `dashboard`, - `stop` at once. -- **quick-task:** say in `finish.body` what was worked out, and that nothing was - saved unless it was built; `"command": "/plan2code-quick-task"`. - -A mid-build `__dashboard` (the top bar's triangle, `console-stop.md` → "Back -to the dashboard, mid-workflow") lands the same way, only on the person's -turn. Save exactly as for `__stop` above (an implement phase stays `[/]`), but -post no finish and do not `stop`: resume as the dashboard instead, with one -terminal line naming what was saved and the resume command. +A mid-build `__dashboard` lands the same way: save as for `__stop`, but post no finish and do not `stop`; resume as the dashboard, with one terminal line naming what was saved and the resume command. diff --git a/src/web-console/cmd-chat.mjs b/src/web-console/cmd-chat.mjs index 08ca54a..2340d18 100644 --- a/src/web-console/cmd-chat.mjs +++ b/src/web-console/cmd-chat.mjs @@ -3,11 +3,12 @@ import path from "node:path"; import { readJson } from "./files.mjs"; -import { healthOk, listHandles, pidAlive, terminalLine } from "./sessions.mjs"; +import { healthOk, listHandles, pidAlive } from "./sessions.mjs"; import { chatReplyLines, collectChat, deliverableChat } from "./inbox.mjs"; import { pendingWorkspaceChanges } from "./workspace.mjs"; import { changeLine } from "./public/workspace.js"; -import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace } from "./cmd-post-wait.mjs"; +import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace, chatSeqs, lineIfChanged, owedFlags, printOut } from "./cmd-post-wait.mjs"; +import { duePointers, pointersForSend, rememberPointers } from "./pointers.mjs"; // The CLI's own pieces, handed over by console.mjs through useCli() before // any command runs: console.mjs runs on import, so it cannot be imported back. @@ -32,13 +33,17 @@ export async function cmdChat() { const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {})); const changes = pendingWorkspaceChanges(dir); const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n"); - const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply }); + const [out, subCursor] = withSubagents(dir, { reply }); if (!entries.length && !changes.length && !subCursor) { - print({ chat: [] }); + print({}); process.exitCode = 10; return; } - print({ ...out, terminalLine: terminalLine(handle.url) }); + const seqs = chatSeqs(entries); + const topics = pointersForSend({}, readJson(path.join(dir, "state.json")) || {}, owedFlags(changes, subCursor), entries); + const due = duePointers(dir, topics); + printOut(dir, { ...out, ...(seqs.length ? { chat: seqs } : {}), ...(due.length ? { read: due } : {}), ...lineIfChanged(dir, handle.url) }); + rememberPointers(dir, topics); advanceCursor(dir, entries); advanceWorkspace(dir, changes); advanceSubagents(dir, subCursor); diff --git a/src/web-console/cmd-help.mjs b/src/web-console/cmd-help.mjs index 7cf05ea..ffce703 100644 --- a/src/web-console/cmd-help.mjs +++ b/src/web-console/cmd-help.mjs @@ -42,21 +42,26 @@ port, and the filesystem as transport; this CLI is the whole agent surface. open [--file ] [--workflow ] [--title ""] [--spec ] [--session|--resume ] [--no-open] [--idle-ms ] + [--loop] (desktop app only; implement or implement-review) Start or resume a session and its server. Prints { ok, sid, session, - url, terminalLine }, plus swept { sessions, scratch, handoffs } when - old sessions, scratch files or handoffs were removed. Run it FIRST, before + url, embed, port, pid, terminalLine }. Run it FIRST, before reading anything: the page shows a starting screen until your first post. --file is optional, and --title defaults to the project's folder name. Also prints workspace: { folders: [{ name, path, description?, original? }], missing? }, the folders this console session reads as context, addressed as @name. The list is remembered per folder and spec in workspaces.json beside looks.json. - May also print subagents: { state, revision, max, instruction, strength } and - a reply holding only its "Subagents: ..." lines, when a standing - instruction (the page's Subagents switch) is owed to you. + May also print a reply holding only its "Subagents: ..." lines, + when a standing instruction (the page's Subagents switch) is owed + to you. workspace only when more than one folder is listed. post --session --file [--wait ] - Merge a patch into the session. Prints terminalLine while the - server is live. Exit 3 = rejected; stderr says why. --wait + Merge a patch into the session. Prints { ok, open } (open = the + required questions still open), plus terminalLine only when the + link changed, read ([path], a topic file to open now) when a + pointer is due, and a warning when Quick questions are unanswered. + Exit 3 = rejected; stderr names the item id, the field and the + field done right. Exit 2 = unreadable patch; stderr gives the + line, column and a short excerpt. --wait then waits up to N seconds in the same command (two JSON lines; the exit code is the wait's). The patch may carry settle: true (or a list of item ids) to mark the latest send's cards answered @@ -71,17 +76,20 @@ port, and the filesystem as transport; this CLI is the whole agent surface. the Subagents tab (help subagents). wait --session [--seconds ] A bounded wait slice, sized below your shell timeout. Exit 0 = the - result is on stdout, 10 = still waiting ("Waiting on your answer - in the web console"; call again), 20 = server gone (open --resume - ), 30 = canceled. Exits 0 and 10 carry terminalLine. - Exit 0 may carry "chat" (Quick questions); with no card send it - is type: "chat" and actions is empty. Exit 0 may also carry - "workspace" (changes since you last heard, each once, with a - "Workspace: ..." line in reply); exit 10 counts them as - pendingWorkspace, and a change alone never ends a slice. - Exit 0 may also carry "subagents" (a console setting, not typed - by the person, with its "Subagents: ..." lines last in reply); a - setting change alone never ends a slice either. A hop + result is on stdout as { reply, session?, read?, ... }, 10 = still + waiting ({"waiting":true,"open":N}; call again), 20 = server gone + ({"gone":true,"fix":"open --resume --workflow "}), + 30 = canceled. terminalLine is printed only when the link changed. + reply holds the answers; session lists the "__" session actions + whole; read ([path]) names a topic file to open now, once per + session per topic and again after a resume. Exit 0 may carry "chat" (the seq of each Quick question + handed over, the ids a reply's re needs; the questions are in + reply, as "Quick question (): ..."); with no card send it + holds only reply and chat. Workspace changes arrive as + "Workspace: ..." lines in reply, each once, and a Subagents + setting change as its "Subagents: ..." lines last in reply (a + console setting, not typed by the person); a change alone never + ends a slice. A hop (__launch, __dashboard, __commit, __changelog) carries resume, the exact open --resume command, and skillFile when installed. Collecting a send sets the page to working; a wait with a question open @@ -89,10 +97,10 @@ port, and the filesystem as transport; this CLI is the whole agent surface. chat --session Collect Quick questions, workspace changes and a Subagents setting change now, never waiting, never touching card sends. - Exit 0 = { chat, workspace, subagents?, reply, terminalLine }, - 10 = none, 20 = server gone. - terminalLine is "→ Look at the web console: ": end your terminal - messages with it during a console session. + Exit 0 = { reply, chat? }, 10 = {} (none), 20 = server gone. + terminalLine is "→ Look at the web console: ": printed by open and + again only when the link changes. End your terminal messages with the + latest one during a console session. keep --session --upload --name --spec specs/ [--from ] Copy a cited note attachment into specs//attachments/. Prints { ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or @@ -120,8 +128,12 @@ port, and the filesystem as transport; this CLI is the whole agent surface. on a refusal. status [--session ] [--all] One session, or (--all) every session on this machine, every project. - stop --session | --all - Shut a session's server down. Always post finish first. + stop --session [--force] | --all + Shut a session's server down. Always post finish first: a named + session with no finish is refused (exit 3, stderr shows the + finish to post). --force stops a dead page or an abandoned session + anyway (the desktop app passes it on its own shutdowns); --all + never asks. ${workflowLines()} @@ -141,6 +153,7 @@ ${workflowLines()} export const HELP_TOPICS = { console: "console.md", building: "building.md", + docs: "console-docs.md", "building-review": "building-review.md", finish: "console-finish.md", stop: "console-stop.md", diff --git a/src/web-console/cmd-open.mjs b/src/web-console/cmd-open.mjs index ee760b1..59ee550 100644 --- a/src/web-console/cmd-open.mjs +++ b/src/web-console/cmd-open.mjs @@ -48,6 +48,7 @@ import { writeWorkspaceCursor, } from "./workspace.mjs"; import { readPrHosts, resetSubagentCursor } from "./settings.mjs"; +import { resetPointers } from "./pointers.mjs"; import { WORKFLOWS, isWorkflow } from "./public/skills.js"; import { startsClean } from "./public/hops.js"; import { snapshot } from "./git-repo.mjs"; @@ -62,6 +63,7 @@ import { awaitSubagentSync, withSubagents, advanceSubagents, + printOut, } from "./cmd-post-wait.mjs"; // The CLI's own pieces, handed over by console.mjs through useCli() before @@ -100,6 +102,9 @@ function leavePointer() { // embed mode, and the in-app signal). The app refuses a console without it. const EMBED_API = 1; +// The only workflows a loop drives (open --loop). +const LOOP_WORKFLOWS = ["implement", "implement-review"]; + export async function cmdOpen() { trace("open: start"); // A workflow the console does not know is refused first, before the pointer, @@ -109,6 +114,16 @@ export async function cmdOpen() { if (args.workflow !== undefined && !isWorkflow(args.workflow)) { die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2); } + // Loop mode (the desktop app's Implementation Loop) is asked for with + // --loop and refused everywhere else, again before the pointer or any + // session folder exists. + const loopMode = args.loop !== undefined && args.loop !== false; + if (loopMode) { + if (!inAppSignal()) die("Loop mode runs only inside the Plan2Code desktop app.", 3); + if (!LOOP_WORKFLOWS.includes(args.workflow)) { + die(`--loop goes only with --workflow ${LOOP_WORKFLOWS.join(" or --workflow ")}`, 2); + } + } leavePointer(); // Under the desktop app the page belongs in the app's window: never the // browser, and (unless a session was named) the app's own session, so one @@ -145,6 +160,9 @@ export async function cmdOpen() { if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1); state = readJson(path.join(dir, "state.json")); if (!state) die(`session "${sid}" has no state`, 1); + // A resume starts the reading over: each topic file is named again when + // its moment recurs (FR-11), whether or not this is a hop. + resetPointers(dir); // A resume can also be a hand-off: the dashboard launches another skill // into its own session, and the first thing that skill needs is for the // page to stop being a dashboard. Letting the flags restate these fields @@ -189,15 +207,44 @@ export async function cmdOpen() { const liveTopics = new Set(s.items.map((i) => i.topic)); s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id)); } + // A launch is a resume that names a workflow and keeps the page put + // (`--no-open`: Continue here, a dashboard pick, a pick-up). It starts a + // new run, so a real ending from the last one comes down with it. A hop + // to another skill already starts clean; this is the same skill again + // (Pathfinder into Pathfinder), where the old finish card would freeze + // every question the new run asks. A plain `open --resume` (no workflow) + // still keeps a real ending, so a re-shared link shows its card. + if (s.finish && args.workflow && args["no-open"]) { + delete s.finish; + delete s.stopWarning; + s.agent = { status: "working", since: nowIso() }; + } if (hop) { s = switchWorkflow(s, { workflow: args.workflow, title: typeof args.title === "string" ? args.title : path.basename(worktree), specDir: args.spec, }); - } else if (switching) s.workflow = args.workflow; + } else if (switching) { + s.workflow = args.workflow; + // An inline switch (into Review) is not a loop phase. + if (!LOOP_WORKFLOWS.includes(args.workflow)) { + delete s.loopOutcome; + delete s.loopEnd; + } + } if (args.title) s.title = args.title; if (args.spec) s.specDir = args.spec; + // The loop lock follows the flag: --loop locks the page, and a resume + // without it (Fix it by hand, from a stop screen) is an ordinary, + // unlocked session. + if (loopMode) s.loop = { driving: true }; + else { + delete s.loop; + // The loop's cards mean nothing without it, and validate() refuses + // handledBy outside a loop session, which would wedge every post. + s.items = (s.items || []).map(({ handledBy, ...item }) => item); + } // Every resume clears the wake-up flag: a server restart, a launch from // the dashboard, a Back-to-dashboard return. Cleared here rather than by // the page because the page cannot write state, and a replay on a return @@ -221,6 +268,8 @@ export async function cmdOpen() { }); // Only a freshly opened dashboard plays Planny's wake-up. if (args.workflow === "dashboard") state.wake = true; + // Locked from the first frame, before the state is first written. + if (loopMode) state.loop = { driving: true }; } // A first payload's meter and folder reports, as `post` takes them: checked @@ -230,8 +279,9 @@ export async function cmdOpen() { let openReread; let patch = null; if (args.file) { - patch = readPatch(args.file); - if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2); + const read = readPatch(args.file); + if (read.error) die(read.error, 2); + patch = read.patch; ({ run: openRun, folderIssue: openIssue } = patch); delete patch.run; delete patch.folderIssue; @@ -366,10 +416,6 @@ export async function cmdOpen() { const sweptSessions = staleSessions(SESSIONS_DIR, Date.now(), SESSION_MAX_AGE_MS, sid); const sweptScratch = staleScratch(HOME_DIR, Date.now(), SESSION_MAX_AGE_MS); const sweptHandoffs = staleHandoffs(Date.now(), SESSION_MAX_AGE_MS); - const swept = - sweptSessions.length || sweptScratch.length || sweptHandoffs.length - ? { swept: { sessions: sweptSessions, scratch: sweptScratch, handoffs: sweptHandoffs } } - : {}; const sweep = () => { sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {}); removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {}); @@ -377,32 +423,34 @@ export async function cmdOpen() { removeHandoffs(sweptHandoffs).catch(() => {}); }; - // A standing instruction the new agent is owed, as `subagents` and a - // `reply` holding only its lines; neither key when nothing is owed. + // A standing instruction the new agent is owed, as a `reply` holding only + // its lines; no key when nothing is owed. const subagentsOwed = () => { awaitSubagentSync(dir, state.workflow); const [out, cursor] = withSubagents(dir, { reply: "" }); - return [out.subagents ? out : {}, cursor]; + return [cursor ? out : {}, cursor]; }; + // What open tells the agent about the folders: only when there is more than + // the folder it started in. + const folders = workspace.folders && workspace.folders.length > 1 ? { workspace } : {}; + // Reuse a live server if one is already serving this session. if (existing && (await reusable)) { if (!args["no-open"]) openBrowser(existing.url); const inAppReport = await tellApp(inApp, { url: existing.url, sid, workflow: state.workflow }); const [owed, subCursor] = subagentsOwed(); - print({ + printOut(dir, { ok: true, sid, session: dir, url: existing.url, embed: EMBED_API, - reused: true, ...inAppReport, - pendingResult: carried, + ...(carried ? { pendingResult: true } : {}), terminalLine: terminalLine(existing.url), - workspace, + ...folders, ...owed, - ...swept, ...remoteWarning(), }); advanceSubagents(dir, subCursor); @@ -443,7 +491,7 @@ export async function cmdOpen() { notes.push(`The app did not take the page. Open ${handle.url} in a browser, or press Reload in the app.`); } const [owed, subCursor] = subagentsOwed(); - print({ + printOut(dir, { ok: true, sid, session: dir, @@ -452,11 +500,10 @@ export async function cmdOpen() { ...inAppReport, port: handle.port, pid: handle.pid, - pendingResult: carried, + ...(carried ? { pendingResult: true } : {}), terminalLine: terminalLine(handle.url), - workspace, + ...folders, ...owed, - ...swept, ...(remote.remote ? { remote: remote.remote } : {}), ...(notes.length ? { note: notes.join(" ") } : {}), }); @@ -542,7 +589,9 @@ async function startServer(project, worktree, sid, dir, { handoff = true } = {}) { // Detached, because harness-managed background tasks get killed at // assorted timeouts and on compaction, which would take the human's - // half-finished answers with them. Detached processes are immune. + // half-finished answers with them. Detached processes are immune to + // that, but not to the desktop app's Job Object on Windows: ending an + // agent there ends a server the agent opened (the app's window reconnects). detached: true, // Redirecting stdio to a file is what lets the child outlive us. The // IPC channel is only for the handover, and is closed straight after. diff --git a/src/web-console/cmd-post-wait.mjs b/src/web-console/cmd-post-wait.mjs index 4891b63..6363541 100644 --- a/src/web-console/cmd-post-wait.mjs +++ b/src/web-console/cmd-post-wait.mjs @@ -14,11 +14,12 @@ import { repoRoots, terminalLine, } from "./sessions.mjs"; -import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, validate } from "./patches.mjs"; +import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, rule, validate } from "./patches.mjs"; import { CHAT_FILE, chatReplyLines, collectChat, + currentConversation, deliverableChat, unansweredChat, readChat, @@ -32,6 +33,7 @@ import { handoffsDir, isHandoffId, markHandoffUsed, readHandoffMeta } from "./ha import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js"; import { blockFor, offered } from "./public/subagents.js"; import { changeLine } from "./public/workspace.js"; +import { duePointers, pointersForSend, rememberPointers } from "./pointers.mjs"; // The CLI's own pieces, handed over by console.mjs through useCli() before // any command runs: console.mjs runs on import, so it cannot be imported back. @@ -40,31 +42,132 @@ export function useCli(cli) { ({ args, print, die, mustSession, sessionProject } = cli); } +/* --------------------------------------------------------- printed line */ + +// The link line is printed by `open` and then only when it changes (a new URL +// after a restart or a resume). What was last printed lives in the session +// folder, never in state.json, which rides every frame to the page. +const PRINTED_FILE = "printed.json"; + +export function printedLine(dir) { + const saved = readJson(path.join(dir, PRINTED_FILE), {}); + return saved && typeof saved.terminalLine === "string" ? saved.terminalLine : ""; +} + +export function rememberLine(dir, line) { + try { + writeJsonAtomic(path.join(dir, PRINTED_FILE), { terminalLine: line }); + } catch {} +} + +// `{ terminalLine }` when the line for this link differs from the one last +// printed, else `{}`. Printing is printOut(), which stores the line after the +// print, the order advanceCursor() uses: a kill in between repeats a line, +// never loses one. +export function lineIfChanged(dir, url) { + if (!url) return {}; + const line = terminalLine(url); + return line === printedLine(dir) ? {} : { terminalLine: line }; +} + +export function printOut(dir, out) { + print(out); + if (typeof out.terminalLine === "string") rememberLine(dir, out.terminalLine); +} + /* ----------------------------------------------------------------- post */ // A patch from a file, or from stdin with `--file -`: a heredoc piped into // the command saves the agent writing a file first, one tool call a turn. // A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or // in UTF-16 (its `>`), and both are the documented Windows route, so both read. +// Indented and minified JSON read alike. Returns `{ patch }`, or `{ error }` +// saying what is wrong and where, for the caller to print with exit 2. export function readPatch(file) { + let text; try { const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file)); - let text; if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le"); else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le"); else text = buf.toString("utf8"); - // A patch is one JSON object: an array, string or number would merge - // into the state as junk keys ("0", "1"...) and still report ok. - const patch = JSON.parse(text.replace(/^\uFEFF/, "")); - return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null; - } catch { - return null; + } catch (e) { + return { error: `could not read --file ${file}: ${e.code === "ENOENT" ? "no such file" : e.message}` }; } + text = text.replace(/^\uFEFF/, ""); + if (!text.trim()) return { error: "the patch is empty (nothing arrived on stdin? use a quoted heredoc, <<'EOF')" }; + let patch; + try { + patch = JSON.parse(text); + } catch (e) { + return { error: parseErrorAt(text, e.message) }; + } + // A patch is one JSON object: an array, string or number would merge + // into the state as junk keys ("0", "1"...) and still report ok. + if (!patch || typeof patch !== "object" || Array.isArray(patch)) { + const what = patch === null ? "null" : Array.isArray(patch) ? "an array" : `a ${typeof patch}`; + return { error: `the patch must be one JSON object ({...}), not ${what}` }; + } + return { patch }; +} + +// Whether `prefix` could still grow into valid JSON: it parses, or it only +// fails by stopping short. +function viablePrefix(prefix) { + try { + JSON.parse(prefix); + return true; + } catch (e) { + if (/end of JSON input|Unterminated/.test(e.message)) return true; + const at = /(?:in|after) JSON at position (\d+)/.exec(e.message); + return Boolean(at) && Number(at[1]) >= prefix.length; + } +} + +// Where JSON.parse gave up, as a 0-based character index. Node 18 and Node 20+ +// word the message differently (and some messages carry no position at all), +// so the message's position is used when there is one and the spot is found +// by search when there is not. +function errorIndex(text, message) { + const at = /(?:in|after) JSON at position (\d+)/.exec(message); + if (at) return Math.min(Number(at[1]), text.length); + const lc = /position \d+ \(line (\d+) column (\d+)\)/.exec(message); + if (lc) { + const lines = text.split("\n"); + let index = 0; + for (let i = 0; i < Number(lc[1]) - 1 && i < lines.length; i++) index += lines[i].length + 1; + return Math.min(index + Number(lc[2]) - 1, text.length); + } + let lo = 0; + let hi = text.length; + while (lo < hi) { + const mid = Math.ceil((lo + hi) / 2); + if (viablePrefix(text.slice(0, mid))) lo = mid; + else hi = mid - 1; + } + return lo; +} + +// `line L, column C: `, then up to 30 characters either +// side of the spot (newlines shown as \n) and a caret under it. +export function parseErrorAt(text, message) { + const index = errorIndex(text, message); + const before = text.slice(0, index).split("\n"); + const line = before.length; + const column = before[before.length - 1].length + 1; + const show = (t) => t.replaceAll("\r", "").replaceAll("\n", "\\n"); + const left = show(text.slice(Math.max(0, index - 30), index)); + const right = show(text.slice(index, index + 31)); + const said = message + .replace(/ in JSON at position \d+( \(line \d+ column \d+\))?/, "") + .replace(/,\s.*is not valid JSON$/s, "") + .replace(/ at position \d+.*$/, ""); + return `line ${line}, column ${column}: ${said}\n${left}${right}\n${" ".repeat(left.length)}^`; } export function failValidation(problems) { process.stderr.write("console: the payload was rejected, nothing was written.\n"); - for (const p of problems) process.stderr.write(" - " + p + "\n"); + // A problem that runs over several lines stays under its own bullet. + for (const p of problems) process.stderr.write(" - " + String(p).replaceAll("\n", "\n ") + "\n"); // exitCode, not exit(): the agent has to read these lines to fix the patch, // and process.exit() can truncate a pipe Node has not flushed. process.exitCode = 3; @@ -87,8 +190,9 @@ function postOnce() { const dir = mustSession(); const file = args.file; if (!file) die("post needs --file ", 2); - let patch = readPatch(file); - if (!patch) die(`could not read --file ${file} as one JSON object`, 2); + const read = readPatch(file); + if (read.error) die(read.error, 2); + let patch = read.patch; const statePath = path.join(dir, "state.json"); const before = readJson(statePath); @@ -100,6 +204,13 @@ function postOnce() { die(e.message, 3); } + // A chat reply names the conversation it answers; the agent is no longer + // handed the entries, so a missing one means the current conversation. + if (patch.chat && Array.isArray(patch.chat.replies)) { + const { conversation } = currentConversation(readChat(dir)); + patch.chat.replies = patch.chat.replies.map((r) => (r && typeof r === "object" && !Array.isArray(r) && r.conversation === undefined ? { ...r, conversation } : r)); + } + // Meter and folder reports go to the ledger, never into state.json. Checked // here, before anything is written: a rejected post appends nothing. const { run, folderIssue } = patch; @@ -162,14 +273,18 @@ function postOnce() { const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").length; // Only a live server's link: no handle, no line, never a dead link. const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir)); - print({ + // The first patch carrying documents names the docs topic file; a refused + // post returned above and recorded nothing. + const topics = Array.isArray(patch.docs) && patch.docs.length ? ["docs"] : []; + const due = duePointers(dir, topics); + printOut(dir, { ok: true, - items: next.items.length, open, - phase: next.phase, + ...(due.length ? { read: due } : {}), ...unansweredNote(dir, next), - ...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}), + ...(handle && handle.url ? lineIfChanged(dir, handle.url) : {}), }); + rememberPointers(dir, topics); return true; } @@ -179,14 +294,14 @@ function postOnce() { * git session. state.git itself is the console's own: a patch never carries it. */ export function liftReread(patch, workflow) { - if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3); + if (Object.hasOwn(patch, "git")) die(rule("", "git", "is the console's own state; post reread instead", { reread: true }), 3); const { reread } = patch; delete patch.reread; if (reread === undefined) return undefined; const flagOnly = reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean"; - if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3); - if (workflow !== "git") die("reread only goes with the git workflow", 3); + if (reread !== true && !flagOnly) die(rule("", "reread", "must be true or { refreshFailed: true|false }", { reread: true }), 3); + if (workflow !== "git") die(rule("", "reread", "only goes with the git workflow", { reread: null }), 3); return reread; } @@ -218,16 +333,17 @@ export function ledgerFromPost(dir, run, issue, workflow) { const lines = []; if (run !== undefined) { const event = run && typeof run === "object" ? run.event : undefined; - if (!RUN_EVENTS.has(event)) die(`run: unknown event "${event}"`, 3); - if (typeof run.id !== "string" || !run.id.trim()) die("run: id required", 3); + const runRight = { run: { event: "implement-phase", id: "phase-2" } }; + if (!RUN_EVENTS.has(event)) die(rule("", "run", `unknown event "${event}" (one of: ${[...RUN_EVENTS].join(", ")})`, runRight), 3); + if (typeof run.id !== "string" || !run.id.trim()) die(rule("", "run", "needs an id", runRight), 3); if (run.tasks !== undefined) { - if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3); - if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3); + if (!TASK_EVENTS.has(event)) die(rule("", "run", `tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, { run: { event: [...TASK_EVENTS][0], id: "phase-2", tasks: 9 } }), 3); + if (!isTaskCount(run.tasks)) die(rule("", "run", `tasks must be a whole number from 1 to ${MAX_TASKS}`, { run: { event, id: run.id, tasks: 9 } }), 3); } if (run.commits !== undefined) { - if (event !== "git-commits") die("run: commits only goes with git-commits", 3); + if (event !== "git-commits") die(rule("", "run", "commits only goes with git-commits", { run: { event: "git-commits", id: "commits-1", commits: 2 } }), 3); const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS; - if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3); + if (!ok) die(rule("", "run", `commits must be a whole number from 1 to ${MAX_COMMITS}`, { run: { event, id: run.id, commits: 2 } }), 3); } lines.push({ kind: "run", @@ -242,8 +358,8 @@ export function ledgerFromPost(dir, run, issue, workflow) { const text = (v) => typeof v === "string" && v.trim() !== ""; const ok = issue && typeof issue === "object" && text(issue.name) && text(issue.reason) && (issue.hint === undefined || text(issue.hint)); - if (!ok) die("folderIssue must be { name, reason, hint? }, each a non-empty string", 3); - const problems = proseProblems(JSON.stringify([issue.reason, issue.hint || ""]), "folderIssue"); + if (!ok) die(rule("", "folderIssue", "must be { name, reason, hint? }, each a non-empty string", { folderIssue: { name: "api", reason: "..." } }), 3); + const problems = [...proseProblems(issue.reason, "folderIssue reason"), ...(issue.hint ? proseProblems(issue.hint, "folderIssue hint") : [])]; if (problems.length) die(problems.join("\n "), 3); lines.push({ kind: "folder-issue", @@ -282,7 +398,7 @@ export async function cmdWait() { const existing = readJson(resultPath); if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat()); const earlyChat = pendingChat(); - if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl()); + if (earlyChat.length) return deliverChat(dir, earlyChat, liveUrl()); markWaiting(dir); // A stat every 50ms, and a read only when the file has moved. The old tick @@ -324,7 +440,7 @@ export async function cmdWait() { if (chatStamp !== chatSeen) { chatSeen = chatStamp; const entries = pendingChat(); - if (entries.length) return deliverChat(dir, sid, entries, liveUrl()); + if (entries.length) return deliverChat(dir, entries, liveUrl()); } // The health check runs beside the polling, never in its way: awaited @@ -356,26 +472,15 @@ export async function cmdWait() { } const state = readJson(path.join(dir, "state.json")) || {}; - const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice"); - const answered = items.filter((i) => !isOpen(i)).length; - const draft = readJson(path.join(dir, "draft.json"), {}); - const staged = Object.keys(draft.staged || {}).length; + const open = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i)).length; const handle = listHandles(project).find((h) => h.sid === sid); - print({ - status: "waiting", - sid, - elapsed: fmtMs(Date.now() - Date.parse(state.created || nowIso())), - answered, - total: items.length, - staged, - url: handle ? handle.url : "", - message: "Waiting on your answer in the web console", - next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.", + // A workspace change alone never ends a slice: it rides on the next send. + printOut(dir, { + waiting: true, + open, ...unansweredNote(dir, state), - // A workspace change alone never ends a slice: it rides on the next send. - pendingWorkspace: pendingWorkspaceChanges(dir).length, - ...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}), + ...(handle && handle.url ? lineIfChanged(dir, handle.url) : {}), }); process.exitCode = 10; } @@ -390,25 +495,24 @@ function unansweredNote(dir, state) { } export function serverGone(sid) { - return { - status: "server-gone", - sid, - message: "The console server is not running. Start it again with `open --resume --workflow ` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.", - }; + return { gone: true, fix: `open --resume ${sid} --workflow ` }; } -// Quick questions and nothing else: an ordinary exit 0 with no card actions. -function deliverChat(dir, sid, entries, url) { - const [withWs, changes] = withWorkspace(dir, { - type: "chat", - at: nowIso(), - sid, - actions: [], - chat: entries, - reply: chatReplyLines(entries), - }); +// The seq numbers of the Quick questions handed over: the ids a `chat.replies` +// entry's `re` needs. The questions themselves travel in `reply`. +export function chatSeqs(entries) { + return entries.filter((e) => e.kind === "message").map((e) => e.seq); +} + +// Quick questions and nothing else: an ordinary exit 0 with no card send. +function deliverChat(dir, entries, url) { + const [withWs, changes] = withWorkspace(dir, { reply: chatReplyLines(entries) }); const [out, subCursor] = withSubagents(dir, withWs); - print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) }); + const seqs = chatSeqs(entries); + const topics = pointersForSend({}, readJson(path.join(dir, "state.json")) || {}, owedFlags(changes, subCursor), entries); + const due = duePointers(dir, topics); + printOut(dir, { ...out, ...(seqs.length ? { chat: seqs } : {}), ...(due.length ? { read: due } : {}), ...lineIfChanged(dir, url) }); + rememberPointers(dir, topics); advanceCursor(dir, entries); advanceWorkspace(dir, changes); advanceSubagents(dir, subCursor); @@ -416,12 +520,20 @@ function deliverChat(dir, sid, entries, url) { } // The workspace changes the agent is owed, added to what it is about to read: -// the list as `workspace`, and one line each at the end of `reply`. -function withWorkspace(dir, out) { +// one `Workspace:` line each at the end of `reply`, in words only. The second +// value is the changes, whose length is the "a change happened" flag +// (see owedFlags()); the cursor moves after the print. +export function withWorkspace(dir, out) { const changes = pendingWorkspaceChanges(dir); if (!changes.length) return [out, changes]; const reply = [out.reply, ...changes.map(changeLine)].filter(Boolean).join("\n"); - return [{ ...out, workspace: changes, reply }, changes]; + return [{ ...out, reply }, changes]; +} + +// Whether the standing instructions in a reply carried a change, for the +// pointers that name a topic file when one is delivered. +export function owedFlags(changes, subCursor) { + return { workspaceChanged: changes.length > 0, subagentsChanged: Boolean(subCursor) }; } // Print first, then this, as with the chat cursor: a kill in between can only @@ -454,7 +566,7 @@ export function awaitSubagentSync(dir, workflow) { } // The Subagents switch the agent is owed, added to what it is about to read: -// the setting as `subagents`, and its lines last in `reply`, after card lines, +// its lines last in `reply` (in words only), after card lines, // Quick questions and Workspace lines (FR-9). Read from the session's own // setting file only, which only the server writes (FR-7). A setting for // another workflow is the server not having caught up with a hop yet: it @@ -467,7 +579,7 @@ export function withSubagents(dir, out) { const block = blockFor(setting, readSubagentCursor(dir)); if (!block) return [out, null]; const reply = [out.reply, ...block.lines].filter(Boolean).join("\n"); - return [{ ...out, subagents: block.field, reply }, block.cursor]; + return [{ ...out, reply }, block.cursor]; } // After the print, like advanceWorkspace(): a kill in between repeats the @@ -507,15 +619,33 @@ export function advanceCursor(dir, entries) { */ function consume(dir, resultPath, result, url, chat = []) { const collected = { ...result, consumedAt: nowIso() }; - // The link, any chat and any workspace change ride on what the agent reads, - // never on result.json itself. - const withChat = { ...collected, chat }; - if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n"); + // What the agent reads is a trimmed view: `reply` (the card answers, any + // Quick question and any Workspace or Subagents line), the `__` session + // actions and the hop fields `reply` cannot carry. result.json keeps the + // whole send; the link, chat and standing lines never go into it. + const withChat = { reply: chat.length ? [result.reply, chatReplyLines(chat)].filter(Boolean).join("\n") : result.reply }; const [withWs, changes] = withWorkspace(dir, withChat); const [out, subCursor] = withSubagents(dir, withWs); const hop = hopFor(path.basename(dir), result); + const session = sessionActions(result); + const seqs = chatSeqs(chat); + // Read before markWorking() below: a __dashboard asks for the finish topic + // or the stop topic by whether a finish is up as the person pressed it. + const stateNow = readJson(path.join(dir, "state.json")) || {}; + const topics = pointersForSend(result, stateNow, owedFlags(changes, subCursor), chat); + const due = duePointers(dir, topics); markPickedUp(result); - print({ ...out, ...hop, ...handoffFor(result), ...(url ? { terminalLine: terminalLine(url) } : {}) }); + printOut(dir, { + ...(out.reply ? { reply: out.reply } : {}), + ...(session ? { session } : {}), + ...hop, + ...handoffFor(result), + ...(seqs.length ? { chat: seqs } : {}), + ...(due.length ? { read: due } : {}), + ...unansweredNote(dir, stateNow), + ...lineIfChanged(dir, url), + }); + rememberPointers(dir, topics); try { writeJsonAtomic(resultPath, collected); } catch {} @@ -632,6 +762,21 @@ function markPickedUp(result) { // data off disk or the wire, so the name is checked here and not trusted. const SAFE_SPEC = /^specs\/[^/\\"'`$;&|<>(){}*?!#~\r\n]+$/; +// The send's `__` actions, whole, for the agent: the docs dispatch on them by +// `i`. A `type` that only repeats `i` ("__stop" and "stop") is left out. The +// card answers, comments and skips are already in `reply`. +export function sessionActions(result) { + const actions = (result && Array.isArray(result.actions) && result.actions) || []; + const kept = actions + .filter((a) => a && typeof a.i === "string" && a.i.startsWith("__")) + .map((a) => { + if (a.type !== a.i.slice(2)) return a; + const { type, ...rest } = a; + return rest; + }); + return kept.length ? kept : undefined; +} + function hopFor(sid, result) { const actions = (result && Array.isArray(result.actions) && result.actions) || []; const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__")); @@ -668,10 +813,3 @@ function ledgerAnswers(dir, result) { } catch {} } -function fmtMs(ms) { - if (!Number.isFinite(ms) || ms < 0) return "0s"; - const s = Math.round(ms / 1000); - if (s < 60) return `${s}s`; - const m = Math.floor(s / 60); - return `${m}m ${s % 60}s`; -} diff --git a/src/web-console/cmd-small.mjs b/src/web-console/cmd-small.mjs index addb779..291887b 100644 --- a/src/web-console/cmd-small.mjs +++ b/src/web-console/cmd-small.mjs @@ -6,7 +6,7 @@ import path from "node:path"; import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs"; import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs"; import { removeSpec } from "./scan.mjs"; -import { isOpen } from "./patches.mjs"; +import { isOpen, rule } from "./patches.mjs"; import { pendingChatCount } from "./inbox.mjs"; import { forgetWorkspace, specKey } from "./workspace.mjs"; import { newHandoff, removeHandoff } from "./handoffs.mjs"; @@ -249,6 +249,24 @@ export async function cmdStop() { // the command runs from. const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null; const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot(); + // A stop with no finish posted leaves the page without an ending (FR-12). + // Refused for one named session unless --force; --all keeps its behavior. + if (named && !args.force) { + const state = readJson(path.join(named, "state.json")); + if (state && !state.finish) { + process.stderr.write( + rule( + "", + "finish", + "this session has no finish posted, so the page would be left without an ending. Post one first, then stop", + { finish: { headline: "Paused: ", command: "/" } }, + ) + `. To stop a dead page or an abandoned session anyway: stop --session ${path.basename(named)} --force +`, + ); + process.exitCode = 3; + return; + } + } const handles = listHandles(project); const targets = args.all ? handles diff --git a/src/web-console/console-attachments.md b/src/web-console/console-attachments.md index 837b124..30f69f6 100644 --- a/src/web-console/console-attachments.md +++ b/src/web-console/console-attachments.md @@ -1,17 +1,7 @@ # Keeping Attachments -Part of the web console contract (`console.md`). Read when a file you write -under `specs//` cites a note's attachment. +Read when a file you write under `specs//` cites a note's attachment. Attachments are swept with the session, so keep one first: -Note attachments are swept with the session. Before a file under `specs//` -cites one, keep it: - -``` -node "" keep --session --upload --name --spec specs/ --from -``` - -It prints `{ ok, path, link, image, reused }`: paste `link` as it is -(`![name](link)` for an image, `[name](link)` otherwise) and name the kept file -in your next update. Uncited and Quick-question attachments stay where they -are. Exit 3 means refused: say so, link nothing. +`node "" keep --session --upload --name --spec specs/ --from ` +It prints `{ok,path,link,image,reused}`: paste `link` as given (`![name](link)` for an image, `[name](link)` otherwise) and name the kept file in your next update. Uncited and Quick-question attachments stay where they are. Exit 3 means refused: say so and link nothing. diff --git a/src/web-console/console-chat.md b/src/web-console/console-chat.md index 58a028f..e65c311 100644 --- a/src/web-console/console-chat.md +++ b/src/web-console/console-chat.md @@ -1,170 +1,59 @@ -# Quick Questions on the Web Console +# Quick Questions (the Ask tab) -Part of the web console contract (`console.md`). Read the first time `wait` or -`chat` hands you a Quick question. +The console points here the first time a Quick question reaches you. The person can ask anything on the Ask tab at any time, about this project's files or in general, without waiting for a card. A message never blocks a card send and a card send never blocks a message. -The page has an **Ask** tab, always the last one, on every workflow. There the -person can ask anything, about this project's files or in general, at any -time, without waiting for a card. Their messages reach you at your next -check-in, through the `wait` you already run (and, in a build, the instant -`chat` check). Chat rides its own channel: a message never blocks a card send, -and a card send never blocks a message. The page handles its own refusals, so -you never see them: `too-long` past 4,000 characters, `limit` after 10 -messages, `offline` when no agent has checked in for a few minutes (a finish alone does -not end the chat: you may still be waiting on its buttons), -`stale` after a new conversation started. +## How they arrive -## How chat arrives +`wait` exit 0 (or `chat`) carries them in `reply`, after the card lines, plus `chat`: the seq number of each question, the ids your replies need as `re`. -- `wait` exit `0` may carry `chat: [...]` beside `actions`, or, when no card - was sent, be `type: "chat"` with `actions: []`. No exit code changes. -- `reply` gains one block per entry after the card lines: +``` +Quick question (12): Where does the export go? + About: Export format + Image: /home/sam/.plan2code/console/sessions//uploads/3f2b9c1e.jpg (shot.png) + File: /home/sam/.plan2code/console/sessions//uploads/9e4b2d7a.json (config.json) +Declined (14): edit r7 + Note: keep the old name working too +Approved (15): edit r9 +New conversation started. Treat earlier chat as closed. +``` - ``` - Quick question: Where does the export go? - About: Export format - Image: /home/sam/.plan2code/console/sessions//uploads/3f2b9c1e.jpg (shot.png) - File: /home/sam/.plan2code/console/sessions//uploads/9e4b2d7a.json (config.json) - Declined: edit r7 - Note: keep the old name working too (only a decline carries one) - New conversation started. Treat earlier chat as closed. - ``` - - Typed text past its first line is indented, so only a real entry ever - starts a line. -- Each `chat` entry carries `seq`, `conversation` and `kind`: `message` - (`text`, optional `about`, `images` and `files`), `decision` (`re`, - `decision` `approve` or `decline`, optional `text`) or `reset`. -- `about` is set only when the person attached it with **+ Add context**. The - page never adds one on its own, so a message without it is a general - question, not one about the card on screen. -- Open every `Image:` and `File:` path with your file-read tool before you - answer, as for notes. -- `node "" chat --session ` checks right now and never sleeps: - exit `0` with `{ chat, reply, terminalLine }`, `10` with `{ chat: [] }` when - nothing is waiting, `20` when the server is gone. It never reads or collects - card sends; those stay with `wait`. +- Open every `Image:` and `File:` path with your file-read tool before you answer. +- `About:` is set only when the person attached that context; without it the question is general, not about the card on screen. +- After "New conversation started" treat earlier chat as closed and do not raise it unless they do. +- `node "" chat --session ` checks now and never sleeps: exit 0 with the same `reply` and `chat`, 10 nothing waiting, 20 server gone. It never reads card sends. ## Answering -**Every message gets a reply, always.** The Ask tab is the person talking to -you, and the page shows "working on the answer" until a reply lands. Never -leave one unanswered, whatever it asks and whatever mid-task you are in. When -a message asks you to do something, do it if you can, then say what happened; if -you will not, the reply says so and why. `post` and `wait` print -`unansweredChat` with a `warning` for every message handed over and not yet -replied to: treat that as a stop-and-reply. +**Every message gets a reply**, whatever it asks and whatever you are mid-task on. `post` and `wait` print `unansweredChat` with a `warning` for each message not yet replied to: stop and reply. When a message asks you to do something, do it if you can, then say what happened; if you will not, say so and why. 1. Handle any card answers first, under the workflow's own rules. -2. Write the chat replies, in inbox order. -3. Send **one** `post` with the card updates and `chat: { replies: [...] }` - (`chat.replies`). +2. Write the replies, in order. +3. Send one `post` with the card updates and the replies. -```jsonc -{ "chat": { "replies": [ - { "re": 12, "conversation": 3, - "md": "The export is written by `src/export.js`, into `out/`." } -] } } -``` +`{"chat":{"replies":[{"re":12,"md":"The export is written by `src/export.js`, into `out/`."}]}}` -- `re` is the message's `seq`, `conversation` is copied from the entry, `md` is - markdown. `id` is optional: left out, it is `r`. Give one only when you - send two replies to the same message. -- Replies merge by `id`, so re-posting the same reply after a repeated - delivery replaces it (unlike `thread`, which appends). -- Print one terminal line per exchange: `Quick question: — answered in the console`. -- Answer questions about the project by reading files and read-only lookups - (search, `git log`, reading files); run no other commands. -- Questions about what a Plan2Code skill does, asks or writes: read that - skill's `SKILL.md` (`~/.agents/skills//SKILL.md`, or the table "What - each skill reads and writes" in `~/.agents/skills/plan2code/SKILL.md`) - before answering. Never answer from menu text, card blurbs or memory. Name - files exactly as the skill does; if the skill does not say, say you do not - know. -- When `about` is set, answer from that context: the card, doc section or - spec the person was looking at. +- `re` is the message's seq; `md` is markdown and non-empty. `id` is optional (default `r`): give one only for two replies to the same message. Replies merge by `id`, so re-posting the same reply replaces it. +- Print one terminal line per exchange: `Quick question: (answered in the console)`. +- Answer questions about the project from files and read-only lookups (search, `git log`, reading); run nothing else. +- For what a Plan2Code skill does, asks or writes, read that skill's `SKILL.md` (`~/.agents/skills//SKILL.md`, or the table "What each skill reads and writes" in `~/.agents/skills/plan2code/SKILL.md`) first. Name files exactly as it does; if it does not say, say you do not know. +- With `About:`, answer from that context. -## Prompts to carry away +## A prompt to carry away -Some questions are really a new task: the person asks for "a prompt", or the -right answer is work for a separate Plan, Quick Task or another skill rather -than something to do inside this session. Do not start that work here and do -not make them retype your answer. Reply with the explanation first, then ONE -self-contained prompt in a fenced block with no info string. The page draws -every fenced block with a **Copy** button, so the person copies it into a new -conversation. +When the right answer is a separate task (a new Plan, Quick Task or another skill), explain first, then give ONE self-contained prompt in a fenced block with no info string (the page adds a **Copy** button). The block: -A good prompt block: - -- opens with plain prose, never a command word. A block whose first line looks - like a terminal command (`git`, `npm`, `node`, `rm` and the like, or `#!`) - gets the muted "paste it into the Ask tab" hint, which is wrong for a prompt. - The check is case-insensitive and also catches everyday verbs that are shell - commands (Make, Go, Source, Export, Service, Cat, Echo, Zip, Tar, Cd, Ls), so - "Make the report export..." trips it. Start with "In this repo, ..." or "Using - the Quick Task skill, ...". A leading skill command (`/plan2code-quick-task ...`) - is fine: it gets none; -- names the skill to paste it into, the files to read first, and what to do; -- states what is out of scope, so the new conversation does not wander; -- stands alone: it assumes nothing said in this session, because the new - conversation has none of it. - -One block per reply, and only when the work is likely to move to a new -conversation. A plain answer stays a plain answer. +- opens with plain prose, never a command word: a first line that looks like a shell command (`git`, `npm`, `node`, `rm`, `#!`, or an everyday verb like Make, Go, Source, Export, Cat, Echo, Zip, Tar, Cd, Ls; case-insensitive) gets a "paste into the Ask tab" hint. Start with "In this repo, ..." or "Using the Quick Task skill, ...". A leading `/plan2code-quick-task ...` is fine. +- names the skill to paste it into, the files to read first, the task, and what is out of scope. +- stands alone: it assumes nothing said in this session. ## Never steer the workflow -A chat answer never changes a card's answer, a gate, or where the workflow -goes. If a message asks for that ("approve phase 2", "skip the tests -question"), reply by pointing to the card — its note box for a comment, its -answer for a change — and do not act on it. Chat never counts as an answer to -a card and is never recorded under `specs/`. +A chat message never answers a card, passes a gate or changes where the workflow goes ("approve phase 2"): point to the card (its note box, its answer) and do not act. Chat is never recorded under `specs/`. A conversation holds at most 10 typed messages; the page enforces it. -## A new conversation is a clean slate +## Edits need approval -After a `reset` entry (New conversation, or a skill switch through the -dashboard) treat earlier chat as closed, and do not bring it up unless the -person does. A conversation holds at most 10 typed messages; the page -enforces it, so never tell someone to keep asking past it. - -## Edits need approval first - -- A request to change files gets a reply carrying `proposal: { summary, - files }` — a plain-English summary and every file that will change — and - **no change yet**. The page shows it with Approve and Decline. -- Only after `Approved: edit `: make exactly the proposed change, then post - a reply (its `re` is the decision's `seq`) carrying `changed: [{ file, - added, removed }]`, with line counts from `git diff --numstat -- ` (or - counted by hand for an untracked file). Name the changed files in your next - progress update or `activity` line. -- `Declined:` (with any note): acknowledge it and change nothing. A revised - proposal is a new reply. -- Hard limits: never touch the running skill's own files under - `specs//` (`post` rejects a proposal that names them); run no commands - beyond read-only lookups, except one the person plainly asks you to run in - their message (a commit they spell out, a test run): run it, then report the - result in the reply; refuse anything else and say why, in the reply. -- Edits happen only at check-ins, never mid-task in a build. - -```jsonc -{ "chat": { "replies": [ - { "id": "r14", "re": 14, "conversation": 3, "md": "I can rename it.", - "proposal": { "summary": "Write the export to `out/audit.csv` instead of `out/export.csv`", - "files": ["src/export.js", "README.md"] } } -] } } -``` - -## What the server checks - -Each reply needs a unique `id` (or none, to take `r`), an `re` naming a real -message or decision `seq`, an integer `conversation` and non-empty `md`. A -`proposal` needs a `summary` and project-relative `files`, none under the -running skill's `specs//`. `changed` is a list of `{ file, added, -removed }`. The house rules on completion markers and metric-like words cover -reply text too. - -## The same chat twice - -Replies merge by `id`, so re-post the same reply if it is not on the page yet; -do not answer the question a second time. +- A request to change files gets a reply with `proposal` (a plain-English `summary` and every file that will change) and **no change yet**: `{"chat":{"replies":[{"re":14,"md":"I can rename it.","proposal":{"summary":"Write the export to `out/audit.csv`","files":["src/export.js","README.md"]}}]}}`. The page shows Approve and Decline. +- `Approved (): edit `: make exactly the proposed change, then reply (its `re` is that seq) with `changed:[{file,added,removed}]`, line counts from `git diff --numstat -- ` (counted by hand for an untracked file). Name the changed files in your next update. +- `Declined ()`, with any note: acknowledge and change nothing; a revised proposal is a new reply. +- Never touch the running skill's own files under `specs//` (a proposal naming them is refused). Run no commands beyond read-only lookups, except one they plainly ask for in their message (a commit they spell out, a test run): run it and report. Refuse anything else, saying why. +- Edits happen at check-ins, never mid-task in a build. diff --git a/src/web-console/console-docs.md b/src/web-console/console-docs.md new file mode 100644 index 0000000..32ce959 --- /dev/null +++ b/src/web-console/console-docs.md @@ -0,0 +1,27 @@ +# Documents on the Web Console + +The console points here at your first patch with `docs`. A doc is a tab of blocks the person reads beside the questions. + +`{"docs":[{"id":"map","title":"What we've agreed","note":"what changed in this version","saved":"specs/lunch-vote/pathfinder/map.md","blocks":[{"id":"b1","md":"## Where we're headed\n\n..."},{"id":"b2","state":"assumed","md":"### File format\n\nAssuming CSV..."},{"id":"b4","file":"specs/lunch-vote/overview.md"}]}]}` + +Docs and their blocks merge by `id`; a new id is added at the end. Patch blocks as decisions land: + +- `{"id":"b2","state":"settled"}` settles b2 and keeps its text; blocks you leave out stay. +- `{"id":"b3","_delete":true}` removes a block; a doc entry with `"_delete":true` removes the tab. + +## Block content: one of three + +- `md`: markdown you write. +- `file`: the console reads the text from that project file (inside the project, 512 KB at most). Re-send the block, or the doc with `"refresh":true`, after the file changes. `"select":"tasks"` keeps only its `- [ ] **Task N.M:**` lines. Never paste a file you can name. +- `image`: `{"id":"s1","image":"shots/run.png","alt":"..."}`: a PNG, JPEG or WebP (5 MB at most) saved directly in the session's `shots/` folder (the `session` path `open` printed), named with letters, digits, `.`, `_` or `-`. Anything else is exit 3. + +## State + +`state` is `settled` (decided; the default), `assumed` (picked to keep going, still open: shown dashed) or `draft` (dimmed). Mark assumptions honestly so a half-finished doc does not read as decisions. + +## Doc fields + +- `note`: one line saying what changed; write one whenever you change a doc. +- `stale`: `true` while answers the doc does not reflect have landed. +- `saved`: the path of the file the doc mirrors, when one exists; leave it off docs that exist only here. +- `version`: moves by itself when content changes and never goes back; leave it out. diff --git a/src/web-console/console-finish.md b/src/web-console/console-finish.md index 891d8a5..ed6680a 100644 --- a/src/web-console/console-finish.md +++ b/src/web-console/console-finish.md @@ -1,132 +1,47 @@ -# Finishing a Web Console Session +# Finishing a Session -Part of the web console contract (`console.md`). Read before your first `finish` -post, and when a send carries `__commit` or a finished screen's `__dashboard`. -A stop request or the mid-workflow way home is `console-stop.md`. +The console points here on `__commit`, or on `__dashboard` from a finished screen. Read it before your first `finish` post too. A stop request or the way home mid-workflow is `console-stop.md`. -Three steps, in this order. **Post the finish, keep waiting for a press — -there is no timeout — and stop the server when the session ends.** A pause -(below) still stops straight away. -Stopping first leaves the person staring at a page that says "leave this tab -open, the next question will appear here on its own" about a session that is -over, and the one thing they need is a command in a terminal they are not -looking at. Post it on every session end, not only the last one: an off-ramp -that routes elsewhere, a checkpoint that saves and stops, a stop request. +Three steps, in order: post the finish, keep waiting for a button (no timeout), `stop` the server. Every session end posts one, not only the last. A pause (below) stops at once. -**Nothing of yours may still be running.** Before the finish, every -subagent or background job you started this session must have reported -back. They run inside your terminal's process, not the console's: the page -cannot see them, and the moment it says the session ended, the person is -free to close that terminal and kill them mid-write. While you wait, post -`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}` -and update the count as each returns. Never write a `finish.body` that says -work "is running in the background" or "will finish on its own". Mark every -reported helper `done` or `failed` before the finish, so the Subagents tab -never ends on a row still running: post each one's `done` in the same turn its -notice arrives, and a `finish` is refused (exit `3`, naming the helper) while -any row is still `running`. +Every helper or background job you started must have reported back first. While you wait, post `{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`. Mark each reported helper `done` or `failed` in the turn its notice arrives: a `finish` is refused while any row is `running`. Never write a `finish.body` saying work "is running in the background". ## 1. Post the finish -The same closer you are about to print in the terminal, as data: +`{"settle":true,"finish":{"headline":"The map is written","body":"Everything is on disk under `specs/lunch-vote/pathfinder/`.","command":"/plan2code-0-pathfinder specs/lunch-vote/pathfinder","doc":"map","dashboard":true}}` -```jsonc -{ - "settle": true, - "finish": { - "headline": "The map is written", - "body": "Everything you decided is on disk under `specs/lunch-vote/pathfinder/`, one file per decision. The **The map** tab has the whole picture.", - "command": "/plan2code-0-pathfinder specs/lunch-vote/pathfinder", - "doc": "map", - "dashboard": true - } -} -``` - -| Field | | | -| --- | --- | --- | -| `headline` | required | What just happened, in plain words. Becomes the card's title. | -| `command` | optional | The exact thing they run next, when there is one — the same string as your Trail Footer's Form A. Rendered with a Copy button that is always on show. Leave it out when nothing is left to run: the page shows an "All done" line with `/plan2code` instead. **No placeholders**: a rendered command is copied and run verbatim, and a patch carrying `<` or `>` in it is rejected. | -| `dashboard` | optional | `true` puts a **Back to the dashboard** button on the finished screen. Set it on every ending except a pause, and keep waiting for the press (below). | -| `body` | optional | Markdown. Where the files landed, what to read first. | -| `where` | optional | Overrides "Run this in the terminal where you started Plan2Code, in a new conversation:". | -| `doc` | optional | Id of the document to offer as a Markdown download on the way out. Defaults to the first one. | -| `console` | optional | Whether the copied text asks the next session to use the web console. Leave it out: it follows from the command. | -| `commit` | optional | `true` on a finished `quick-task`, `implement`, `implement-review`, `review` or `finalize` whose finish prints a git command puts a **Commit it now** button on the finished screen. The press arrives as `__commit` (below). | -| `changelog` | optional | `true` on a finished `quick-task` or `finalize` that also carries `commit: true` puts an **Update CHANGELOG first** button beside **Commit it now**. Refused (exit 3) on any other workflow, `implement` included. The press arrives as `__changelog` (below). | -| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen (`notes/quick-task.md`, `building-review.md`). `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. | - -**Continue here.** Nothing to set: when `command` starts with a Plan2Code skill -(`/plan2code-2-document specs/lunch-vote/PLAN-DRAFT-20261019.md`, with or -without `--web`) and the finish is not a pause, the page puts a **Continue -here** button beside the Next step block, unless the session meter is red -(then the fresh-session advice stands alone). A finish whose command is a git -commit, or that has none, gets no button. You write nothing new; you only -handle the `__launch` it sends (below). The `spec` it carries is the -`specs/` folder the command mentions. - -**Write the bare command.** Every Plan2Code skill has a console — the -dashboard and every skill behind it — so for any of them the page -appends ` --web` to what it shows and copies, so someone who worked here -lands back here instead of being asked the interface question as though -they were new. Every one of those skills takes that flag in its argument as -the answer. Do not write `Use the web console for this session.` into the -command; if it is there, the page swaps it for `--web`. A command that is not -a Plan2Code skill gets nothing appended. Set `"console": false` if they have -asked to go back to the terminal. - -The page then says the session is finished rather than paused, offers the -command, tells them they can close the tab, and stops treating the server going -away as a fault. Send is disabled, and anything they staged and never sent is -named rather than quietly lost. - -Settle whatever the session ends on. An item still `open` when the finish -lands freezes exactly as it stands: a send it carries shows as the final word -on it, and one that was never answered shows as a question that ran out of -time. If their last send was a verdict you are closing on — the review's -`approve`, the plan's `yes`, the fixes pick — the finish post is the same post -that settles it (`"settle": true`). - -Post it even when you are also printing the footer in the terminal. Someone who -has spent the whole session in the browser has no reason to look anywhere else. - -The chat stays open after a finish for as long as you are still listening (the -review and dashboard buttons live as long as you do); the page only turns Send -off once you have gone quiet. So while you wait for a button press, answer any -chat `wait` delivers (`console-chat.md`). - -## 2. After the finish: the buttons - -A **pause** is an ending that keeps a place to come back to: a stop request, -an abort that keeps its place to resume, or a checkpoint that saves and ends -(Plan's Large checkpoint). A pause's headline starts with "Paused", it never -carries `dashboard`, and you post it without `--wait` and `stop` at once. - -Every other finish carries `"dashboard": true` and goes up with `post --wait`; -keep waiting in the usual slices. There is no timeout after a finish: the -buttons live exactly as long as you are listening, so a press an hour later -works like a press a minute later. - -| What arrives | What you do | +| Field | Use | | --- | --- | -| An action `{ "i": "__dashboard", "type": "dashboard" }` | Run the `resume` it carries (`open --resume --no-open --workflow dashboard`; it re-runs the project scan and clears the page, the finish included), read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its `menu` with `--wait` and carry on as the dashboard from its "Coming back from another skill", in this same conversation. | -| An action `{ "i": "__changelog", "type": "changelog" }` | Update CHANGELOG first: run the `resume` it carries (`open --resume --no-open --workflow changelog`; no `finish`, no `stop`; the hop gives Changelog a clean page, the finish included), then open the Changelog skill (`skillFile`, or `~/.agents/skills/plan2code-changelog/SKILL.md`) with your file-read tool and follow it from the top (`notes/changelog.md`). Its "Commit this now?" yes carries on to Git. Leave the commit command you printed in the finish where it is for the terminal. | -| An action `{ "i": "__launch", "type": "launch", "skill": ..., "workflow": ..., "spec": ... }` | Continue here: the same hop as a dashboard pick (`console-launches.md` → A pick). Run the `resume` it carries (the hop gives the next skill a clean page, the finish included), read its `skillFile` with your file-read tool (never a skill-invocation tool), and follow it from the top in this same conversation. No `stop`. A hop into a different skill gives it a clean page, the finish included; when the `resume` keeps your own workflow (a phase finish whose next step is the same Implement), nothing clears the page, so your first post of the new run carries `"finish": null`. | -| An action `__review` or `__done` | As `building-review.md` says (quick task only). | -| An action `{ "i": "__commit", "type": "commit" }` | Commit it now: run the `resume` it carries (`open --resume --no-open --workflow git`; no `finish`, no `stop`; the resume gives Git a clean page, the finish included, as a dashboard launch does), then open the Git skill (`skillFile`, or `~/.agents/skills/plan2code-git/SKILL.md`) with your file-read tool and follow it, starting with the commit flow over the board (the person pressed Commit it now), then the board with Push lit. Leave the commit command you printed in the finish where it is for the terminal. | -| `wait` exit `20` | The server is gone. `open --resume --workflow ` (it gets a new link: give it to them; the browser opens it), then keep waiting: their Ask messages and the dashboard button still need you. Give up only when the resume itself fails. | -| The session ends without a press (the terminal closes, the conversation ends) | The server sweeps itself once its idle window passes, and the page swaps the buttons for the matching commands — nothing pressable dies silently. A press that lands in the meantime is kept on disk (`pendingResult`) for a resumed session. | +| `headline` | required: what happened, in plain words | +| `command` | the exact next thing to run (your Trail Footer's Form A), copied verbatim: no `<` or `>` (refused). Leave it out when nothing is left to run. Write it bare: the page appends `--web` itself, and swaps a written `Use the web console for this session.` for it. `"console":false` if they asked to go back to the terminal | +| `dashboard` | `true` on every ending except a pause: the **Back to the dashboard** button | +| `body` | markdown: where files landed, what to read first | +| `where` | overrides "Run this in the terminal where you started Plan2Code, in a new conversation:" | +| `doc` | id of the doc to offer as a download (default: the first) | +| `commit` | `true` when the finish prints a git command (`quick-task`, `implement`, `implement-review`, `review`, `finalize`): **Commit it now** | +| `changelog` | `true` with `commit:true` on `quick-task` or `finalize`: **Update CHANGELOG first** (exit 3 on any other workflow) | +| `review` | `quick-task` only: `true` or `{"label":"..."}` puts **Review it now** on the screen (`building-review.md`) | + +A finish whose `command` starts with a Plan2Code skill and is not a pause gets a **Continue here** button (unless the meter is red). You only handle the `__launch` it sends. + +Settle whatever the session ends on in the same post (`"settle":true`): an item still `open` freezes as it stands. Post the finish even when you also print the footer in the terminal. Answer any chat `wait` delivers while you wait for a button (`console-chat.md`). + +## 2. The buttons + +A **pause** (a stop request, an abort that keeps its place, a checkpoint that saves and ends) has a headline starting "Paused", no `dashboard`, and is posted without `--wait`: `stop` at once. Every other finish goes up with `post --wait`; keep waiting in the usual slices. + +| Arrives | Do | +| --- | --- | +| `__dashboard` | Run its `resume` (it re-scans and clears the page, the finish included), read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), post its `menu` with `--wait`, and carry on as the dashboard in this conversation | +| `__changelog` | Run its `resume` (no `finish`, no `stop`), read the Changelog skill (`skillFile`, or `~/.agents/skills/plan2code-changelog/SKILL.md`) and follow it (`notes/changelog.md`). Leave the commit command where it is | +| `__launch` | Continue here: run its `resume`, read `skillFile` with your file-read tool (never a skill-invocation tool), follow it from the top. No `stop`. Into a different skill the page is cleared; when the `resume` keeps your own workflow (a phase finish into the same Implement), your first post of the new run carries `"finish":null` | +| `__review` or `__done` | `building-review.md` (quick task only) | +| `__commit` | Run its `resume` (`--workflow git`; no `finish`, no `stop`), read the Git skill (`skillFile`, or `~/.agents/skills/plan2code-git/SKILL.md`), start with its commit flow over the board (they pressed Commit it now), then the board with Push lit. Leave the printed commit command where it is | +| `wait` exit 20 | `open --resume --workflow `, give the new link, keep waiting; give up only if the resume fails | +| Session ends without a press | Nothing for you: an unfetched press stays on disk (`pendingResult`) for a resumed session | ## 3. Stop the server -``` -node "" stop --session -``` +`node "" stop --session ` -If you forget, it shuts itself down after 30 minutes of silence. Stop it anyway. -The page keeps the hand-off on screen after the server has gone: everything it -needs is already in `state.json`, and the Copy button is the one action that -still works on a page whose server has died. - -`node "" status` lists sessions for this project, including any whose -answers were submitted but never picked up. +A session with no finish is refused (exit 3); `--force` stops it anyway (`console-trouble.md`). `node "" status` lists this project's sessions, including any whose answers were never picked up. diff --git a/src/web-console/console-launches.md b/src/web-console/console-launches.md index 5909a6f..0bae337 100644 --- a/src/web-console/console-launches.md +++ b/src/web-console/console-launches.md @@ -1,113 +1,25 @@ -# Launches: the Dashboard on the Web Console +# Launches (the Dashboard) -Part of the web console contract (`console.md`). Read when you are the -dashboard. The dashboard skill's own prompt (`plan2code/SKILL.md`) has the -menu judgment and the launch steps; this is what the page does around them. +Read when you are the dashboard. The dashboard skill's own prompt (`plan2code/SKILL.md`) has the menu judgment and launch steps; this is what the page does around them. ## A launch -```jsonc -{ "type": "submit", - "actions": [{ "i": "__launch", "type": "launch", - "skill": "plan2code-3-implement", "workflow": "implement", - "spec": "specs/lunch-vote" }], - "reply": "Start Implement (/plan2code-3-implement) for specs/lunch-vote, right here in this session.", - "resume": "node \"…/console.mjs\" open --resume --no-open --workflow implement --spec specs/lunch-vote", - "skillFile": "…/plan2code-3-implement/SKILL.md" } -``` +A pick arrives with `session:[{"i":"__launch","skill":"plan2code-3-implement","workflow":"implement","spec":"specs/lunch-vote"}]`, plus `resume` and `skillFile`. `spec` is present only when the skill takes one and the person picked it. Run `resume` first, before reading anything: it reuses the live server and turns the page from the menu into the skill's starting screen while you read. Then read `skillFile` (absent outside an install: `~/.agents/skills//SKILL.md`) with your own file-read tool and follow it from the top. Never hand it to a skill-invocation tool: every skill below the dashboard ships `disable-model-invocation: true`, and the call errors out. -`spec` is the picker's selected spec dir, present only when the launched skill -takes a spec (or is Quick Task on a `diagnosed` spec) and the person picked one. `resume` is the one command to run -first, before reading anything: it reuses the live server and turns the page -from the menu into the skill's starting screen while you read. `skillFile` is -the skill to read next (absent outside an install: then -`~/.agents/skills//SKILL.md`). +A session handed to you is resumed, never re-opened (`--title` and `--spec` are honored on resume). A resume to or from `dashboard`, or into `git` from any skill, clears the page; a skill run inline from another (a quick task's review) never resumes. Its Interface step is already answered by the launch, and you have read the card: read only the notes or building files its Interface names. Post before anything slow. -**A session handed to you is resumed, never re-opened.** A fresh `open` would -strand the page the person is watching on the dashboard's session while your -questions went to a page nobody has open. `--title` and `--spec` are honored on -resume. A resume to or from `dashboard`, or into `git` from any skill, clears -the page: the last skill's questions, sections, docs, headline and finish are -dropped, so the new skill starts blank and posts its own. A skill run inline -from another (a quick task's review) never resumes, and keeps the page it was -handed. +## What the page knows -> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your -> own file-read tool and follow it from the top.** Every Plan2Code skill below -> the dashboard ships `disable-model-invocation: true` on purpose, and calling -> one through a skill-invocation tool errors out and strands the hand-off. +`state.scan` is `{hasAgents,isGit,pending,specs:[{dir,name,state,detail,touched}],handoffs,handoffsDir}`, a snapshot of the last `open` (a spec created mid-session appears at the next dashboard resume). `pending` is the count a commit would take (`null` when git cannot say). The `menu` you post (`note`, `recommend`, `details`) describes the initially selected spec; leave any field out and the page falls back to that spec's own next step, and derives them again when the person switches specs. Post it with `--wait`. -Its Interface step is already answered by having been launched. You have read -`console.md` already: do not read it again; read only the notes or building -files its Interface names. +A `__stop` before a pick ends the session the usual way: `finish` (headline "Paused", `"command":"/plan2code"`), then `stop` (`console-stop.md`). -From the click until the resume lands, the page shows a getting-ready screen; -from the resume until the skill's first payload, its starting screen. Resume -first, and post before anything slow. - -## What the page already knows - -`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }], handoffs, handoffsDir }`, -a snapshot of the last `open` (a spec created mid-session appears the next time -the session resumes as a dashboard). `pending` is how many files a commit would -take (`null` when git cannot say): the Git card never grays out, shows the count -when there is one, and outside a repository says Git can start one. The picker -grays the cards that do not fit the selected spec — or hides them, while the -**Hide unavailable workflows** switch under it is on (the default). - -The `menu` you post (`note`, `recommend`, `details`) describes the initially -selected spec; leave any field out and the page falls back to that spec's own -next step, and it derives both again from the scan when the person switches -specs or starts fresh. Post it with `--wait`; waiting on the menu is the -person's turn by itself. - -A `__stop` before a pick ends the session the usual way: `finish` (paused -headline, `"command": "/plan2code"`) then `stop` (`console-stop.md`). - -`handoffs` is this checkout's unused handoffs, newest first (`[{ id, title, -next, written, spec, skill, workflow }]`, read from `~/.plan2code/handoffs/` -by `open`, a dashboard only), and `handoffsDir` is that folder. The picker shows -them as dashed **Handoff** chips after the specs. +`handoffs` is this checkout's unused handoffs, newest first (`[{id,title,next,written,spec,skill,workflow}]`, read from `~/.plan2code/handoffs/`), shown as dashed Handoff chips. ## A pick-up -Selecting a handoff chip shows a preview and hides the skill cards. **Pick it up -here** sends a hop like a launch, naming only the id: - -```jsonc -{ "type": "submit", - "actions": [{ "i": "__pickup", "type": "pickup", "handoff": "2026-10-17-1152-handoff" }], - "reply": "Pick up the handoff \"Lunch vote\" right here in this session.", - "resume": "node \"…/console.mjs\" open --resume --no-open --workflow quick-task --spec specs/lunch-vote", - "skillFile": "…/plan2code-quick-task/SKILL.md", - "handoffFile": "~/.plan2code/handoffs/2026-10-17-1152-handoff.md" } -``` - -`wait` has already read the handoff's stored skill and spec, marked the handoff -used (the next scan no longer lists it) and put the command in `resume`. Run -`resume`, read `skillFile` with your file-read tool, then read `handoffFile`, -follow the skill from where its real work starts, and carry on from the -handoff's **Next task**. When the send carries `"fallback": true` the named -skill or spec was gone, or the Handoff skill wrote it: say so in one line, -since Quick Task is picking it up. -The handoff's document stays on disk until the 30-day sweep. +**Pick it up here** sends `session:[{"i":"__pickup","handoff":"2026-10-17-1152-handoff"}]` with `resume`, `skillFile` and `handoffFile`. `wait` already read the handoff's stored skill and spec and marked it used. Run `resume`, read `skillFile`, then `handoffFile`, follow the skill from where its real work starts, and carry on from the handoff's **Next task**. With `"fallback":true` (the named skill or spec was gone, or the Handoff skill wrote it) say so in one line, since Quick Task is picking it up. ## A delete -The ✕ on a picker chip, after the page's two-step confirm (what goes, then -the spec's name typed), sends `{ "i": "__delete", "type": "delete", "spec": -"specs/" }` with a `reply` saying it is for good. It is no hop: it -carries no `resume`, and you stay the dashboard. The console never writes into -a project, so the page only asks; delete through -`node "" delete-spec --spec `, never your own `rm`. It takes -only an existing `specs/` folder inside the worktree (never a link, -never deeper, never `specs--completed/`), exits 3 with `message` on a refusal -having touched nothing, and drops the workspace remembered for that spec. -Then `open --resume --no-open --workflow dashboard` to rescan, and post -the menu again with `--wait`, its note saying what went or why it did not. -The page shows the chip as "Deleting…" until that rescan lands. - -A handoff's **Delete** sends the same `__delete`, with `handoff` (its id) where a -spec has `spec`. Delete it through -`node "" delete-handoff --handoff ` (exit 3 with `message` when it -refuses, nothing touched), then rescan and post the menu as for a spec. +The ✕ on a chip (after the page's two-step confirm) sends `session:[{"i":"__delete","type":"delete","spec":"specs/"}]` (a handoff has `handoff` where a spec has `spec`). It is no hop: no `resume`, you stay the dashboard. Delete through `node "" delete-spec --spec ` or `delete-handoff --handoff `, never your own `rm`; exit 3 with `message` means refused with nothing touched. Then `open --resume --no-open --workflow dashboard` to rescan, and post the menu again with `--wait`, its note saying what went or why not. diff --git a/src/web-console/console-meter.md b/src/web-console/console-meter.md index 36a6b55..2ab96a9 100644 --- a/src/web-console/console-meter.md +++ b/src/web-console/console-meter.md @@ -1,56 +1,12 @@ -# The Session Meter on the Web Console +# The Session Meter -Part of the web console contract (`console.md`). Your workflow notes give the -exact `run` to post; read this only if one is refused. +Read only if a `run` was refused; your workflow notes give the exact `run` to post. -### Session meter +The meter is advice and never blocks. The console scores these launches itself when their session opens (post nothing for them): Plan, Revise plan, Document, Review, Quick task, Init, Init update, Finalize, Git, Changelog, X-ray, Diagnose. It also counts answers: every 2 cards answered in a send add a point; notes, Quick questions and buttons do not count. -The page's top bar shows a meter of how much work this console session has -done (green, yellow, red), so the person knows when a fresh session would be -sharper. It is advice only and never blocks anything. The console counts -launches itself: Plan, Revise plan, Document, Review, Quick task, Init, Init -update, Finalize, Git, Changelog, X-ray and Diagnose score when their session opens, and there is nothing to -post for them. +Per-unit work is yours: `{"run":{"event":"implement-phase","id":"phase-2","tasks":9}}`, one `run` per post, never reaching the page state. -It counts answers itself too: every card the person answers in a send adds to -the skill run's tally when `wait` hands the send to you, and every 2 answers -score a point, so a long back-and-forth weighs more than a short one. Notes, -Quick questions and buttons such as Stop or the dashboard do not count. - -Per-unit work is yours to report, with `run` in any post: - -```jsonc -{ "run": { "event": "implement-phase", "id": "phase-2", "tasks": 9 } } -``` - -- `event` is one of `pathfinder-chart`, `pathfinder-question` (scores - nothing now: answers count instead), `pathfinder-research`, `plan`, - `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, - `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, - `git`, `changelog`, `xray`, `diagnose`, `git-commits` and `git-conflict` (Git's own, see - `notes/git.md`). - An unknown event is exit `3`. Post only the events your notes name: a skill - that scores when its session opens (the list above this one) already has its - points, and a `run` for it scores the same work twice. -- `id` names the unit: a question's file slug, `phase-N`, `map`. The same id - posted again in the same skill run is ignored, so a repeated post never - counts twice. It must be non-empty. -- `tasks` goes only with `implement-phase` and `implement-review-phase`: the - number of tasks the phase completed (marked `[x]`; blocked `[!]` tasks do - not count), a whole number from 1 to 999. A built phase scores by its size, - one point per 3 tasks rounded up, and Implement + Review one more for the - review. Always send it: without it a phase scores a flat 2 (or 3), however - big it was. On any other event it is exit `3`. The console already counts a - build's tasks from `headline.cleared` as they are ticked off; the phase's - `run` takes that count over with the final score, so it never counts twice. -- `commits` goes only with `git-commits`: how many commits Git just made, a - whole number from 1 to 999. A Git run scores one point per 2 commits, - rounded down; on any other event it is exit `3`. -- One `run` per post. Which events a workflow reports is in its own notes - (`notes/pathfinder.md`, `notes/git.md`; `building.md` for Implement and for - the review run on the page after a build). - -`run` never reaches the page state: `post` (and `open --file`) lift it into the -session's ledger. - ---- +- `event`: `pathfinder-chart`, `pathfinder-question` (scores nothing now), `pathfinder-research`, `plan`, `revise-plan`, `document`, `implement-phase`, `implement-review-phase`, `review`, `quick-task`, `init`, `init-update`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`, `git-commits`, `git-conflict`. An unknown event is exit 3. Post only the events your notes name: a launch the console scores already has its points. +- `id`: the unit (a question's slug, `phase-N`, `map`), non-empty. The same id in the same skill run is ignored. +- `tasks`: only with `implement-phase` and `implement-review-phase`; the tasks completed (`[x]`, not blocked), a whole number 1 to 999. A phase scores one point per 3 tasks rounded up (Implement + Review one more for the review); without it, a flat 2 (or 3). It takes over the count from `headline.cleared`, never adding to it. +- `commits`: only with `git-commits`; commits made, 1 to 999, one point per 2 rounded down. diff --git a/src/web-console/console-stop.md b/src/web-console/console-stop.md index 973c106..8c2b5f2 100644 --- a/src/web-console/console-stop.md +++ b/src/web-console/console-stop.md @@ -1,132 +1,43 @@ -# Stop Requests on the Web Console +# Stop Requests -Part of the web console contract (`console.md`). Read when a send carries -`__stop` or `__dashboard`, or your workflow notes say to post a `stopWarning`. +The console points here when a send carries `__stop`, or `__dashboard` with no `finish` up. Your workflow notes also say when to post a `stopWarning`. -## Stop requests +## `__stop` -The page has a **Stop session** button. Pressing it sends, in one submit, any -answers the person had staged plus one more action: +The person is ending the session: act on it in this turn. It arrives in `session` (`[{"i":"__stop"}]`) with any answers they had staged in `reply`. -```jsonc -{ "type": "submit", - "actions": [ /* staged answers and notes, as usual */, - { "i": "__stop", "type": "stop" } ], - "reply": "...the answer lines...\nStop here and save my place, so I can pick this up later." } -``` +1. Handle the answers under the workflow's own rules and record only what is final: a confirmed recap, an approval verdict, a finished checklist. A pick that still owes its recap is not an answer yet: save it where the workflow keeps unfinished work (Pathfinder: the question's `## Evidence`, with the probes outstanding and your recommendation) and never write a provisional `## Answer`. Do not claim a question they picked from a menu in the same send. Settle only the final cards (`"settle":[...]`). +2. Save your place the way the workflow does when a session ends. +3. Post `finish` (`console-finish.md`) without `--wait`: a headline starting "Paused", a body naming what was saved and anything open (name a question left mid-way), and the resume command. If `stopWarning` is set, clear it in the same patch (`"stopWarning":""`): a finish posted while it is set is refused. +4. `stop` the server. -`__stop` is not an item and matches nothing; like every `__` action it is -about the session. It arrives through `wait` with exit `0`, like any send. It is -the person ending the session, so act on it in this turn: +Publish no new questions and do not ask whether they are sure: the page asked. Stop is only offered on their turn; the exception is an agent that stopped checking in, then the request waits on disk. -1. **Handle the answers under the workflow's own rules, and record only what is - final.** A confirmed recap, an approval verdict, a finished checklist with its - values. A pick that still owes its recap is not an answer yet: save it where - the workflow keeps unfinished work (Pathfinder: the question's `## Evidence`, - with the probes still outstanding and your recommendation for each) and never - write a provisional `## Answer`. Do not claim a question the person picked - from a menu in the same send. Settle only the final cards (`"settle": [...]`). -2. **Save your place** the way the workflow does when a session ends. -3. **Post `finish`** (`console-finish.md`) with a headline starting "Paused" - (the page and `open --resume` both key off that word), a body naming what - was saved and anything still open, and the resume command, without - `--wait`. Name a question that was left mid-way, so they can ask for it by - name next time. -4. **`stop`** the server. +## `__stop` with a handoff -Do not publish new questions and do not ask whether they are sure: the page -already asked. +`{"session":[{"i":"__stop","handoff":true}],"handoffSkill":"…/plan2code-handoff/SKILL.md"}`. In order: -The page only offers Stop on the person's turn. From the moment they press Send -until your reply lands, the button is disabled, so a stop never arrives while -you are halfway through writing their last answers. The one exception is an -agent that has stopped checking in: then Stop comes back, and the request waits -on disk for whichever session collects it next. +1. Handle the answers as above. +2. Save your place as above. +3. `node "" handoff new --workflow --skill [--spec ] --title "" --from-stop` prints the `path` to write. +4. Open `handoffSkill` with your file-read tool and write the document it describes to that `path`. Skip its questions and its "Where to write it" step: infer the Next task from where the work stands and say so in the document. With no `handoffSkill`, use `~/.agents/skills/plan2code-handoff/SKILL.md`. +5. Post `finish` as above, its body naming the handoff path and saying the dashboard will offer it; clear any `stopWarning` in the same patch. +6. `stop` the server. -## Stop with a handoff +## `__dashboard` with no finish up (home, mid-workflow) -Off the dashboard, the Stop dialog offers **Stop with a handoff** first and -**Just stop and save** second. The handoff choice sends the same `__stop`, with -`handoff: true`, and `wait` adds `handoffSkill` (the Handoff skill's `SKILL.md`, -present in a built skill): +Same rules as Stop: their turn only, staged answers ride along. -```jsonc -{ "type": "submit", - "actions": [ /* staged answers and notes, as usual */, - { "i": "__stop", "type": "stop", "handoff": true } ], - "reply": "...the answer lines...\nStop here, save my place and write a handoff, so the dashboard can pick this up later.", - "handoffSkill": "…/plan2code-handoff/SKILL.md" } -``` +1. Handle the answers as above. +2. Save your place as above. A workflow with nothing to save (a quick task not yet built) just goes home. +3. Run the `resume` the send carried, read the dashboard skill (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), post its `menu` with `--wait`, and carry on as the dashboard in this conversation. -Act on it in this turn, in this order: +No `finish` and no `stop`: the menu is the ending. Say what you saved in one terminal line. -1. **Handle the answers** exactly as in "Stop requests" step 1. -2. **Save your place** exactly as step 2 there. -3. **Make the handoff file:** - `node "" handoff new --workflow --skill [--spec ] --title "" --from-stop` - It prints the `path` to write. -4. **Write the handoff.** Open `handoffSkill` with your file-read tool (never a - skill-invocation tool) and write the document it describes to that `path`. - Skip its questions and its "Where to write it" step: infer the Next task - from where the work stands, and say in the document that it was inferred. -5. **Post `finish`** (`console-finish.md`) with a headline starting "Paused", a - `body` that names the handoff path and says the dashboard will offer it, and - the resume command, without `--wait`. -6. **`stop`** the server. +## `stopWarning` -With no `handoffSkill` (a source checkout), use the structure in -`~/.agents/skills/plan2code-handoff/SKILL.md`. Do not ask whether they are -sure: the page already asked. - -## Back to the dashboard, mid-workflow - -On every workflow but the dashboard, a triangle left of Stop session takes the -person back to the dashboard. It follows Stop's rules exactly: only on their -turn, a confirm first (with your `stopWarning`), and the staged answers ride -along in the same submit: - -```jsonc -{ "type": "submit", - "actions": [ /* staged answers and notes, as usual */, - { "i": "__dashboard", "type": "dashboard" } ], - "reply": "...the answer lines...\nSave my place and take me back to the dashboard, right here in this session.", - "resume": "node \"…/console.mjs\" open --resume --no-open --workflow dashboard" } -``` - -It is the same `__dashboard` a finished screen sends; with no `finish` on the -page it means "stop, then go home". Act on it in this turn: - -1. **Handle the answers** exactly as step 1 above. -2. **Save your place** exactly as step 2 above. -3. **Go home:** run the `resume` the send carried (it turns the page back into - the dashboard and drops this skill's page), read the dashboard skill - (`skillFile`, or `~/.agents/skills/plan2code/SKILL.md`), then post its - `menu` with `--wait` and carry on as the dashboard from its "Coming back - from another skill", in this same conversation. - -No `finish` and no `stop` in between: the menu is the ending. Say what you -saved in one terminal line, since no finish card will. A workflow with nothing -to save (a quick task not yet built) just goes home. - -## Saying what stopping would cost - -Some points in a workflow have nothing on disk yet, and stopping there loses the -answers given so far: Pathfinder before its map exists, Planning before a -checkpoint. The page cannot know where you are, so tell it: - -```jsonc -{ "stopWarning": "The map is not written yet, so stopping now loses today's answers." } -``` - -It is shown in the page's Stop dialog, and the button changes from "Stop and -save" to "Stop anyway". Post `"stopWarning": ""` once stopping is safe again. -For `plan` sessions the page assumes a warning until you post that empty string. +Where stopping loses answers (Pathfinder before its map exists, Plan before a checkpoint), post `{"stopWarning":"The map is not written yet, so stopping now loses today's answers."}`. The Stop dialog shows it and says "Stop anyway". Post `"stopWarning":""` once stopping is safe, or in the same patch as a paused `finish`. For `plan` the page assumes a warning until you post the empty string. ## Picking up a paused session -`open --resume ` (or `open --session `) clears a paused `finish` -itself, and the questions left open at the pause with it: the finish body -already said what was still open, so re-ask whatever the new session needs in -your own words rather than leaving the old asks on the page as duplicates. -Settled items stay. For any other ending you are deliberately taking back, post -`"finish": null` in your first patch. +`open --resume ` clears a paused `finish` and the questions left open at it; re-ask what you need in your own words. Settled items stay. For any other ending you are taking back, post `"finish":null` in your first patch. diff --git a/src/web-console/console-subagents.md b/src/web-console/console-subagents.md index cb64c4c..4b4af32 100644 --- a/src/web-console/console-subagents.md +++ b/src/web-console/console-subagents.md @@ -1,101 +1,39 @@ -# Standing Instructions: Helpers on the Web Console +# Helpers (Subagents) -Part of the web console contract (`console.md`). Read when a `Subagents:` block -arrives, or when your workflow notes say to report helpers. - -On the skills that offer it (`implement`, `implement-review`, `quick-task`, -`review`, `pathfinder`, `plan`, `revise-plan`), the person can turn **helpers** (subagents) on or off -from the top bar's Subagents button. Their pick is saved per project and per -skill, on until switched off, and reaches you as a standing instruction, only when it -changes. +The console points here when a `Subagents:` block reaches you. On the skills that offer it (`implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, `plan`, `revise-plan`) the person turns helpers on or off from the top bar's Subagents button, per project and skill. It reaches you as a standing instruction, only when it changes. ## What arrives -A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`, -after the card lines, the `Quick question:` blocks and the `Workspace:` lines. -It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting -change alone never ends a `wait` slice: it waits for the next send, or for -your next `chat` check. +`Subagents:` lines last in `reply` (on `wait` exit 0, `chat` exit 0 and `open`). A change alone never ends a slice. ``` -Subagents: on (revision 2) — a console setting, not typed by the person. - Hand independent work to helpers if your tools allow it; otherwise carry on alone. - Report each helper on the page (console-subagents.md); questions for the person stay with you. - If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it. - Match each helper's strength and effort to its job, as helper-strength.md says; when your tools cannot set them, start the helper without them. - Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you. Pick each helper's strength and effort from helper-strength.md's table: light for a 1-2 file task the task file spells out, standard for multi-file or debugging work. - Helper strength: balanced (the table in helper-strength.md as written). - At most 3 helpers at once. +Subagents: on, balanced strength, at most 3 helpers at once (a console setting, not typed by the person). + Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. ... ``` -beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…", "strength": "balanced" }`. -The `Helper strength:` line carries the person's profile, and replaces the -Balanced default when they pick another: +The indented lines are the skill's own instruction (or the person's); follow them. The latest block replaces an earlier one. Off arrives as one line: `Subagents: off. Start no new helpers for the rest of this session.` Nothing arrives: keep doing what the skill says. After a dashboard launch, no block means off for this skill. It never answers a card and is never recorded under `specs/`. -- `balanced`: the table in `helper-strength.md` as written (the default). -- `thrifty`: one step lighter in strength and effort; reviews never below standard. -- `best`: strongest and high effort for every helper except lookups, which stay light. -- `session`: set no model or effort on any helper. +The standing rules: -An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …` -with the whole block again; switching off arrives as one line: -`Subagents: off (revision 4) — don't start new helpers for the rest of this session.` - -It is a console setting, not something the person typed. It never answers a -card, and it is never recorded under `specs/`. - -## Obeying it - -- **On:** hand independent work to helpers if your tools allow it, at most - `max` at once, following the instruction lines. `max` is advisory: your - harness's own limit still applies. -- **Strength:** start each helper at the strength and effort - `helper-strength.md` (in the skill's `references/`) gives for its job, - following its fallback order. Read it when you first start a helper. -- **A higher revision replaces a lower one.** Follow the latest block only. -- **Off:** start no new helpers for the rest of the session. Let running ones - finish and report them. -- **Nothing arrives:** keep doing what the skill says. -- **Scope is the skill run it arrived in.** After a dashboard launch, no block - means the switch is off for this skill, even if an earlier skill in the same - conversation was told "on": `open` starts the count again, and a launch with - the switch off sends nothing. +- **On:** hand independent work to helpers if your tools allow it, at most the stated number at once (advisory: your harness's limit applies). If your tools cannot start helpers at all, report one working-alone entry (below). +- **Strength:** start each helper at the strength and effort `helper-strength.md` (in the skill's `references/`) gives for its job, following its fallback order; read it when you first start a helper. The word in the first line is the person's profile: + - `balanced`: the table as written (default). + - `thrifty`: one step lighter in strength and effort; reviews never below standard. + - `best`: strongest and high effort for every helper except lookups, which stay light. + - `session`: set no model or effort on any helper. + When your tools cannot set them, start the helper without. +- **Off:** start no new helpers; let running ones finish and report them. +- **Pathfinder:** research questions always use helpers and are always reported, whatever the switch says. The switch governs recon, sketches and lookups. +- Helpers add no session meter points: post no `run` for them. ## Reporting helpers -Post them, at your check-ins, so the page's Subagents tab can show them. The -page never hears from a helper directly: +Post them at your check-ins so the Subagents tab shows them (one post per change worth seeing, not a stream): -```jsonc -{ "helpers": [ - { "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" }, - { "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass.", "strength": "light", "effort": "low" } -] } -``` +`{"helpers":[{"id":"h1","title":"Read the store helpers","ask":"Find every caller of readSubagentSetting.","state":"running"},{"id":"h2","title":"Check the tests","ask":"Run the subagents tests.","state":"done","result":"All 9 pass.","strength":"light","effort":"low"}]}` -- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and - `state` (`running`, `done` or `failed`) are required; `result` (at most 200) - is the one line you add once a helper ends. `strength` (`light`, - `standard`, `strongest` or `inherit`) and `effort` (`low`, `medium` or - `high`) are optional: report what the helper actually ran with, and - `inherit` when its strength could not be set. Anything else is exit `3`, and - the house rules on completion markers and metric-like words cover `title`, - `ask` and `result`. -- Merged by `id`: post a helper again with its new `state` and `result` and it - updates in place. `"helpers": null` clears the list. A dashboard hop clears it - too; a resume into the same skill keeps it. -- One post per change worth seeing, not a stream. -- Questions for the person stay with you, never with a helper: most harnesses - give helpers no way to ask, and an answer only reaches the agent holding the - session. -- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }` - entry for the skill run instead. The tab then says you are working alone. - It is a claim about your tools, not about the moment — post it only when no - helper mechanism exists. Reporting a real helper removes it, so an early - `alone` can never hide a later helper. At most one `alone` entry. -- **Pathfinder:** research questions always use helpers and are always - reported, whatever the switch says. The switch governs recon, sketches and - lookups beside the conversation. -- Helpers add no session meter points. Post no `run` for them. -- Before any `finish`, mark every reported helper `done` or `failed` - (`console-finish.md`). +- Required: `id`, `title` (80 characters at most), `ask` (400), `state` (`running`, `done`, `failed`). `result` (200 at most) is the line you add once it ends. `strength` (`light`, `standard`, `strongest`, `inherit`) and `effort` (`low`, `medium`, `high`) are optional: report what it actually ran with, `inherit` when its strength could not be set. Anything else is exit 3. +- Merged by `id`: post it again with the new `state` and `result`. `"helpers":null` clears the list. A dashboard hop clears it; a resume into the same skill keeps it. +- Questions for the person stay with you: a helper cannot ask. +- No way to start helpers at all: post `{"helpers":[{"id":"alone","alone":true}]}` once for the skill run. Reporting a real helper removes it. At most one. +- Before any `finish`, mark every reported helper `done` or `failed` (`console-finish.md`). diff --git a/src/web-console/console-trouble.md b/src/web-console/console-trouble.md index 5036bb8..67beefa 100644 --- a/src/web-console/console-trouble.md +++ b/src/web-console/console-trouble.md @@ -1,20 +1,15 @@ -# When Things Go Wrong on the Web Console +# When Things Go Wrong -Part of the web console contract (`console.md`). Read when something goes wrong. - -| Situation | What to do | +| Situation | Do | | --- | --- | -| `open` fails | Say so in one line, carry on in the terminal. Never block on this. | -| `wait` returns `20` | `open --resume `, give them the new link. Nothing they typed is lost. | -| They close the tab | Nothing happens. Drafts are saved. Reopening the link restores everything. | -| Your session ends mid-flight | Their answers still land on disk. A fresh session runs `status` (or `open --resume`, which reports `pendingResult: true`), and `wait` returns them. An uncollected result is never discarded. | -| They ask to go back to the terminal | `stop` the session and continue. The files under `specs/` are unchanged. | -| The session ends and they are still in the browser | Post `finish` **before** `stop`, and wait for the dashboard button first unless it is a pause (`console-finish.md`). Without it their last screen says the next question is coming, and then says contact was lost. | -| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. | -| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. | -| Picking up a paused session | `open --resume ` clears a paused `finish` and the questions left open at it; re-ask what you still need (`console-stop.md` → Picking up a paused session). | -| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. | -| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. | -| A patch is refused (exit `3`) | stderr names every problem; nothing was written. Fix them and post again. A `version` refusal means the payload is stale: drop `version` and let it move by itself. | -| A doc block's `file` is refused | It must be a file inside the project, under 512 KB; `select` only takes `tasks`. | -| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. | +| `open` fails, or `node` is missing or older than 18 | Say so in one line and carry on in the terminal; install nothing | +| `wait` returns 20 | `open --resume `, give the new link; nothing they typed is lost | +| They close the tab | Nothing: drafts are saved and the link restores everything | +| Your session ends mid-flight | Their answers stay on disk; a fresh session runs `status` (or `open --resume`, which reports `pendingResult:true`) and `wait` returns them | +| They ask to go back to the terminal | `finish`, then `stop`, and continue; files under `specs/` are unchanged | +| The page is dead, the server will not answer, or the session is abandoned with no finish | `stop --session --force` (a plain `stop` with no finish is refused, exit 3) | +| Picking up a paused session | `open --resume ` clears the paused `finish` and its open questions; re-ask what you need (`console-stop.md`) | +| The same result arrives twice | Your harness killed `wait` after the hand-over. Handle it once; most of a repeated patch is harmless since items merge by id, but `thread` appends: leave out entries you already sent | +| The same chat arrives twice | Replies merge by `id`: re-post the same reply if it is not on the page yet; do not answer a second time | +| A patch is refused (exit 3) | stderr names the item, the field and the fix; nothing was written. Correct it and post again. A `version` refusal means a stale payload: drop `version` | +| A doc block's `file` is refused | It must be a file inside the project, under 512 KB; `select` only takes `tasks` | diff --git a/src/web-console/console-workspace.md b/src/web-console/console-workspace.md index 1719c33..5c47a7c 100644 --- a/src/web-console/console-workspace.md +++ b/src/web-console/console-workspace.md @@ -1,80 +1,25 @@ -# The Workspace on the Web Console +# The Workspace -Part of the web console contract (`console.md`). Read when `open` lists more -than one folder, a `Workspace:` line arrives, or someone writes `@name`. +The console points here when a `Workspace:` change arrives. Read it also when `open` lists more than one folder or someone writes `@name`. -The person can add folders beside the one the session started in (a shared -library, a design folder), from the footer's folder label. Together they are -the session's **workspace**: context for every skill run in this console -session, each folder addressed by a short `@name`. It outlives dashboard hops, -and it is remembered: every change is saved to `workspaces.json` beside -`looks.json` (never into the project), keyed by the folder the session runs -in and then by spec. A session with a spec opens on that spec's list, one with -none on the project's; a spec with nothing saved starts as a copy of the -project's list. The dashboard's picker swaps the list as the selection moves, -and a `specDir` you post mid-run takes the current list with it. There is -nothing for you to load: `open` prints the list, and a switch of spec on a -resume reaches you as ordinary workspace changes on your next `wait`. +The person can add folders beside the one the session started in (a shared library, a design folder). Together they are the session's workspace: context for every skill run in it, each folder addressed by a short `@name`. It follows dashboard hops. There is nothing to load: `open` prints the list, and a spec switch on a resume reaches you as ordinary changes. ## What you are told -`open` (fresh or `--resume`) prints the whole list under `workspace`: +`open` prints `workspace` when it holds more than the folder you started in: `{"folders":[{"name":"shop","path":"/home/sam/code/shop","original":true},{"name":"shared","path":"/home/sam/code/shared-ui","description":"Button and form styles"}],"missing":["old-docs"]}` (`missing` only when a folder is no longer on disk). -```jsonc -{ "ok": true, "sid": "…", "url": "…", - "workspace": { - "folders": [ - { "name": "shop", "path": "/home/sam/code/shop", "original": true }, - { "name": "shared", "path": "/home/sam/code/shared-ui", "description": "Button and form styles" } - ], - "missing": ["old-docs"] - } } -``` - -`missing` (only when there is one) names folders no longer on disk. After -`open`, you hear only of changes, each exactly once: - -- `wait` exit `0` carries them beside a send or chat as `workspace: [...]` - (`{ kind, name, path, description?, from? }`, `kind` one of `added`, - `renamed`, `described`, `removed`, `missing`, `found`), with one - `Workspace: …` line each at the end of `reply` - (`Workspace: added @shared — /home/sam/code/shared-ui`). A change alone never - ends a slice: exit `10` counts it as `pendingWorkspace` and it rides on the - next send. -- `chat` hands changes over at once, with or without a Quick question, as - `{ chat, workspace, reply }`. - -Act on a change in the same turn it arrives: drop a removed folder, use the -new name after a rename, note a missing one. No reply is needed unless the -person asked something. +After `open`, you hear only of changes, each once, as `Workspace:` lines last in `reply` of `wait` exit 0 or `chat`: `Workspace: added @shared`, then the folder path. The kinds are added, renamed, described, removed, missing and found. A change alone never ends a slice. Act on it in the same turn: drop a removed folder, use a new name, note a missing one. No reply is needed unless they asked something. ## Rules -- **Resolve `@name` from the workspace list.** `@shared` in an answer, a note - or a Quick question means that folder's `path`. An `@name` not in the list - is ordinary text. -- **Added folders are read-only reference.** Read them freely; edit one only - when the person asks for that change in this conversation. Chat edits still - need approval (`console-chat.md` → Edits need approval first). -- **Read an added folder's `AGENTS.md` before you first use it** (`CLAUDE.md` - when there is no `AGENTS.md`), once per folder per skill run. It says how - that folder is laid out; the original folder's `AGENTS.md` still governs - this project and the work. +- Resolve `@name` from the list: `@shared` in an answer, note or Quick question means that folder's `path`. An `@name` not in the list is ordinary text. +- Added folders are read-only reference. Edit one only when they ask for that change in this conversation (chat edits still need approval, `console-chat.md`). +- Read an added folder's `AGENTS.md` (`CLAUDE.md` without one) before first using it, once per folder per skill run. The original folder's `AGENTS.md` still governs the project. -## When a folder cannot be read +## A folder you cannot read -When a read of an added folder genuinely fails (refused, not found), post, once -per folder: +When a read of an added folder fails (refused, not found), post once per folder, and print one terminal line saying which and why: -```jsonc -{ "folderIssue": { "name": "shared", "reason": "Permission was refused", "hint": "/add-dir /home/sam/code/shared-ui" } } -``` +`{"folderIssue":{"name":"shared","reason":"Permission was refused","hint":"/add-dir /home/sam/code/shared-ui"}}` -and print one terminal line saying which folder and why. The page marks the -folder and tells the person once. `hint` is optional: an agent that knows it -is Claude Code puts `/add-dir ` there. Your harness asking the person -for permission is not a failure; report only a read that failed after it. - -A `folderIssue` needs non-empty `name` and `reason` strings, and `hint`, when -present, is one too; anything else is exit `3`. It goes to the session's -ledger, never into the page state. +`name` and `reason` are required non-empty strings; `hint` is optional (Claude Code: `/add-dir `). Your harness asking the person for permission is not a failure; report only a read that failed after it. diff --git a/src/web-console/console.md b/src/web-console/console.md index 31e52b6..4881cb7 100644 --- a/src/web-console/console.md +++ b/src/web-console/console.md @@ -1,431 +1,104 @@ -# The Web Console +# The Web Console (the card) -A local page in the person's browser where they answer your questions, read what -you have drafted, and approve things, instead of typing into the terminal. +A local page where the person answers your questions, reads your drafts and approves things. Read this card once per session. Read a topic file only when your workflow notes or the console's `read` output name it. -> **Not open yet?** `node "" open --workflow ` first (launched -> from the dashboard: its `resume` instead), then read on. +`` is `/references/web-console/console.mjs` (globally `~/.agents/skills//references/web-console/`; `~/.plan2code/console/console-dir` may hold the folder). Always quote the path. `node "" help ` prints any topic file. -**Read this file once per conversation.** Every Plan2Code skill ships the same -copy (`version.json` beside it says which). If you already read it in this -conversation — from the dashboard, or from another skill's copy — do not read it -again after a hop; carry on. The topic files below are read only when their -moment comes, also once each. +## Start -**``** means the directory holding this skill's `SKILL.md`, and -`` means `/references/web-console/console.mjs` (globally: -`~/.agents/skills//references/web-console/`; an earlier session may -have left the directory in `~/.plan2code/console/console-dir`). `node -"" help ` prints any topic file below. Always quote the path: -install paths contain spaces. Requires Node 18+; nothing to install. +`node "" open --workflow ` (add `--spec specs/` when known). `` is one of `dashboard`, `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, `document`, `implement`, `implement-review`, `review`, `finalize`, `handoff`, `git`, `changelog`, `xray`, `diagnose`. Launched from the dashboard? The session is open: run the `resume` command the launch carried instead. -**The console changes where you ask, not what you ask.** Every rule of this -workflow still applies: the same questions, the same order, the same gates, the -same cap of three questions at a time, the same recap before anything is recorded. -You are not allowed to answer your own questions just because a form makes it easy. +Keep `sid`: every later command takes `--session `. `open` failing: carry on in the terminal. When `open` adds `remote` and a `note`, give the link, ask whether it opened, and move to the terminal if not. Tell the person the link (with `"inApp":true`, never print it: only how many questions are waiting) and end every terminal message with the latest `terminalLine`, verbatim. -> **The one rule that keeps the page alive: while the session is open, every -> turn ends on a `wait` (or `post --wait`) call, never on text.** Exit `10` means -> "nobody has answered yet", not "done": relay one line and wait again in the -> same turn, as many times as it takes. A turn that ends without a `wait` -> running strands the person's next click. - -## What to read, and when - -All beside this file. Read one when its moment first comes, not before; when -several are due at once (a build's start), read them in one batch. - -| File (`help` topic) | Read it when | -| --- | --- | -| `building.md` (`building`) | You run `implement`, `implement-review` or `quick-task`: right after `open`, then `notes/implement.md` or `notes/quick-task.md`. | -| `building-review.md` (`building-review`) | A build's review is asked for on the page (a `review` verdict, `__review`, Implement + Review's Stage 2). | -| `notes/.md` (``) | Right after `open`: `init` (also init-update), `pathfinder`, `plan`, `revise-plan`, `document`, `implement` (also implement-review), `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`. The dashboard's is `console-launches.md`. | -| `console-launches.md` (`launches`) | You are the dashboard. | -| `console-finish.md` (`finish`) | Before your first `finish` post, and when a send carries `__commit`, or `__dashboard` from a finished screen. | -| `console-stop.md` (`stop`) | A send carries `__stop`, or `__dashboard` with no finish up; or your notes say to post a `stopWarning`. | -| `console-chat.md` (`chat`) | The first time `wait` or `chat` hands you a Quick question (`chat: [...]`). | -| `console-workspace.md` (`workspace`) | `open` lists more than one folder, a `Workspace:` line arrives, or someone writes `@name`. | -| `console-subagents.md` (`subagents`) | A `Subagents:` block arrives, or your workflow notes say to report helpers. | -| `console-meter.md` (`meter`) | Only if a `run` is refused: your notes give the exact `run` to post. | -| `console-attachments.md` (`attachments`) | A file you write under `specs/` cites a note's attachment. | -| `console-trouble.md` (`trouble`) | Something goes wrong: `open` fails, a repeat delivery, a dead server. | - ---- - -## Starting it - -It needs Node 18+ on PATH (anything older exits naming the version), the -person's own machine (the page is on `127.0.0.1`; in a cloud VM or remote -sandbox do not offer it), and a foreground command of a minute at a time. When -`open` thinks the machine is remote (SSH, a dev container, a Codespace) it adds -`"remote"` and a `note`: give them the link, ask whether it opened, and move to -the terminal if not. If anything fails, say so in one line and carry on in the -terminal — that path loses nothing, and they can switch either way at any time. - -1. `node "" open --workflow `, where `` is one of `dashboard`, - `init`, `init-update`, `pathfinder`, `quick-task`, `plan`, `revise-plan`, - `document`, `implement`, `implement-review`, `review`, `finalize`, - `handoff`, `git`, `changelog`, `xray`, `diagnose`. Get it right: the page decides from it what - to offer and what stopping costs. `--title` defaults to the folder name; - `--spec specs/` when you already know the spec. It prints - `{"ok":true,"sid":"...","session":"...","url":"...","terminalLine":"→ Look at the web console: ..."}` - and opens the browser itself. `swept` is housekeeping, `workspace` and - `subagents` are explained in their topic files. -2. Pass each patch on stdin with `--file -` (The turn, below). Where you cannot - (PowerShell), write it to a file in the `session` folder `open` printed — - never into the project or `~/.plan2code/console/` itself — and pass that - path. `open --file ` opens with a first payload the same way. -3. Post the first questions as soon as you have them. If getting there takes a - while, post `{"agent":{"status":"working","activity":"Reading the plan"}}` - first so the page says what you are doing. -4. Tell the person, in one line, the link and how many questions are waiting. - While the session is open, end every terminal message with the latest - `terminalLine`, verbatim. When `open` printed `"inApp":true` the page is - already in the desktop app's window: never print the link (here, after a - resume or anywhere else), only the count; `terminalLine` leaves it out too. - -Keep `sid`: every later command takes `--session `. - ---- +Right after `open`, read `building.md` (implement, implement-review, quick-task only) and `notes/.md`. ## The turn ``` node "" post --session --file - --wait 240 <<'EOF' -{ "settle": true, "items": [ ... ] } +{"settle":true,"items":[...]} EOF ``` -`--file -` reads the patch from stdin: in bash or zsh a quoted heredoc -(`<<'EOF'`) saves writing a file first. PowerShell has no heredoc and its pipe -can mangle non-ASCII text, so there write the patch to a file in the session -folder and pass `--file `. `post --wait ` posts, then waits up to `N` -seconds in the same command: use it for every post that hands the turn to the -person, so a turn costs one command. It prints the post's line (its `open` is -the required questions still open; optional cards and notices are not -counted), then the wait's; the exit code is the wait's, and exit `3` means the post was refused -and nothing waited. `--wait` with no number takes `--seconds`, else 240, so -always give one; slices under 5 seconds count as 5. Plain -`wait --session --seconds ` waits without posting. +Keep the heredoc quoted (`<<'EOF'`). PowerShell has no heredoc: write the patch to a file in the `session` folder `open` printed (never in the project) and pass `--file `. Size the `--wait` slice to your shell limit: 5 minutes or more `240` (tool timeout 300000 ms), about 2 minutes `90`, 60 seconds or unsure `45`. -**Size the slice to your shell timeout**, comfortably below its limit, so the -command returns by itself rather than being killed: +With nothing to post, `node "" wait --session --seconds 240` waits alone (same slice sizes). -| Your limit on one command | Use | -| --- | --- | -| 5 minutes or more | `240`, with the tool timeout set to 300000 ms | -| about 2 minutes | `90` | -| 60 seconds, or you cannot tell | `45` | +**Every turn ends on a `wait` (or `post --wait`), never on text.** -Killing a wait mid-slice loses nothing; a result is marked collected only after -it is printed, so the worst case is a repeat, never a lost answer. - -| Exit | Meaning | What you do | +| Exit | Meaning | Do | | --- | --- | --- | -| `0` | They pressed Send, asked a Quick question, or both. stdout is the result. | Handle it (below), then post once, with `--wait`. | -| `10` | Nobody has answered yet. | Relay one line, the `message` followed by the `terminalLine`, and wait again in the same turn. | -| `20` | The server is gone. | `open --resume --workflow ` (no `--no-open`: the restart has a new link, and the browser opens it), give them the new link, keep waiting. | -| `30` | They pressed Cancel. | Stop. Ask what they want, in the terminal. | -| `3` | (`post --wait` only) the post was refused; stderr says why. | Fix the patch and post again. | -| `2` | Bad usage: a flag missing its value, or a patch that is not one readable JSON object. Nothing was posted. | Fix the command or the patch and run it again. | +| 0 | A send arrived | Handle it (below), then one `post --wait` | +| 10 | Nobody answered yet | Relay one line of your own, ending with the latest `terminalLine`, and wait again, same turn, without limit | +| 20 | `{"gone":true,"fix":...}` | Run its `fix` (replace `` with your workflow), give the new link, keep waiting | +| 30 | They canceled | Stop; ask what they want in the terminal | +| 3 | Patch refused | stderr names the item, the field and the fix; correct it and post again | +| 2 | Patch unreadable | stderr gives line, column and the spot; fix it and post again | -Do not poll faster, do not spin on `status`, and never stop after some number -of slices: people step away and come back. After a finish, keep waiting the -same way (`console-finish.md`). **Collect promptly:** a sent question is locked -on the page, and a second send is blocked, until your next post lands. +## A send -### Handling a send +`reply` is what they would have typed: one line per question, parts joined with `; `. Act on it as their typed answer, in that turn, with no summary back. Open every `Image:` and `File:` path in it with your file-read tool before you answer. -```jsonc -{ "type": "submit", - "actions": [ - { "i": "q2", "type": "answer", "kind": "choice", "k": "A" }, - { "i": "q3", "type": "comment", "text": "Please keep the header row.", - "images": [{ "path": "/home/sam/.plan2code/console/sessions//uploads/3f2b9c1e.jpg", "name": "header.png" }] } - ], - "reply": "File format: a\nNote on What to call it: Please keep the header row.\n Image: /home/sam/.plan2code/console/sessions//uploads/3f2b9c1e.jpg (header.png)" } -``` +Other fields, when present: `session` (actions about the session, dispatch on `i`: `__launch` and `__pickup` run `resume`, then read `skillFile` and follow it in this conversation; `__stop`, `__dashboard`, `__commit`, `__changelog`, `__delete`, `__brief`, `__review`, `__done`, `__git` are covered by the topic file `read` names, or by your notes), `chat` (the seq numbers of Quick questions that need a reply), `read` (open each path now, before acting), `resume`, `skillFile`, `handoffFile`, `fallback` (hop fields: run `resume` as given). -**`reply` is the important field**: what they would have typed in the terminal, -one line per question, every part of an answer joined by `; `. Treat it as their -typed answer and follow the workflow from there; `actions` has the same with -structure. Collecting it already set the page to "working" for you: do not post -a status first. Act on it in that turn — no asking whether to proceed, no -summary back. +## A patch -A `comment` may carry `images` and `files` (`[{ path, name }]`), listed under the -note in `reply` as `Image:` / `File:` lines. **Open every path with your -file-read tool before you answer** — or say you could not read it. They live in -the session's `uploads/`; never copy one into the project yourself -(`console-attachments.md`). +One-line JSON, only what changed; the patch merges (`items`, `topics`, `docs` and blocks by `id`; `thread` appends; `null` deletes a key). The console fills `status:"open"`, `required:true`, `allowOther:true`, empty `options` and `thread`, and option keys `A`, `B`, `C` by position, so leave them out. -An action whose `i` starts with `__` is about the session, not a question: +`{"title":"Audit export","headline":{"stage":"Working","cleared":4,"total":9,"confidence":"One area still needs work."},"items":[...],"agent":{"status":"working","activity":"Reading the plan"}}` -| Action | Read | -| --- | --- | -| `__stop` (plain, or with `handoff: true`), `__dashboard` (no finish up) | `console-stop.md` | -| `__commit`, `__dashboard` (from a finished screen) | `console-finish.md` | -| `__launch` | `console-launches.md` | -| `__delete` | `console-launches.md` (the dashboard only) | -| `__brief` | `notes/pathfinder.md` | -| `__review`, `__done` | `building-review.md` | -| `__git` | `notes/git.md` | +`headline.cleared`/`total` drive the progress bar: always fill them. `agent.activity` is one plain sentence; add `quietMinutes` (1 to 60) when a stretch may go silent. Say `status:"working"` only while you work on with nothing for the person to answer. A new open question hands the turn over by itself; with only a doc or notice up, post `"agent":{"status":"waiting"}` yourself before you wait. -A hop (`__launch`, `__dashboard`, `__commit`) arrives with `resume`, the exact -command that resumes the session under the new workflow — run it as given — -and, in an installed skill, `skillFile`, the `SKILL.md` to follow next. +Every item: `id` (new for each question, whole session), `kind`, `title` (2 to 4 plain words), `body` (markdown: the question and why it matters), optional `topic`, `doc`, `required:false` (adds Skip), `token` (`{"A":"approved"}`: the typed word an answer stands for). -Then, in ONE post (with `--wait`): +- `choice`: `{"id":"q1","kind":"choice","title":"Export format","body":"Which format?","options":[{"text":"CSV","detail":"Opens in Excel","recommended":true},{"text":"JSON","detail":"For scripts"}]}`. Back: `{k}` or `{text}`; `allowOther:false` drops the free-text row. +- `text`: `{"id":"q2","kind":"text","title":"Who uses it","body":"Who, and for what?","placeholder":"For example: reviewers, in Excel every Monday."}`. Back: `{text}`. `pattern` plus `patternHint` checks shape (kebab-case). The placeholder is an offer, so write a whole answer. On the fresh-idea card in Pathfinder, Plan and Quick Task add `"templates":"idea"` (also when the idea came as the argument, with a one-line summary in `placeholder`; a resumed map, PLAN-DRAFT or checkpoint gets no idea card; never mention templates in the terminal); a Notebook tab fills a box marked `"fill":"note"`. +- `confirm`: `{"id":"q3","kind":"confirm","title":"Keep going","body":"Continue?","yesLabel":"Yes","noLabel":"Not yet"}`. Back: `{yes,text?}`. +- `recap`: `{"id":"q4","kind":"recap","title":"What we heard","body":"Is this right?","summary":"- ..."}`. Back: `{ok,text?}`. +- `menu`: `{"id":"q5","kind":"menu","title":"Next step","body":"What now?","options":[{"text":"Plan it"}],"command":"/plan2code-1-plan"}`. Back: `{k}`. -- settle what they answered: `"settle": true` (below) -- reply to every note in that item's `thread` -- reply to any Quick question (`console-chat.md`) -- publish the next batch of questions - -You never post the status for a turn: a post that asks a new question, and any -`wait` started with a question open (or a finish, the dashboard menu, the git -board), hands the turn over by itself (`agent.status` becomes `waiting`). Say -`"agent": { "status": "working" }` only while you work on with nothing for them -to answer, and `"agent": { "status": "waiting" }` yourself when you go back to -waiting with nothing open for them (only a doc or a notice on the page, a -brief just delivered): `wait` leaves a working agent working then, since -that is also how an agent waiting out its subagents looks. - -### Replying to a note - -```jsonc -{ "items": [{ "id": "p4", "thread": [ - { "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." } -] }] } -``` - -`{ "who": "agent", "text": "" }` — `text`, not `md`. The server already -wrote their note into the thread: send only your new entries (`thread` -appends). Answer what they asked in the thread, even when you also change a doc -or re-ask; "I've updated the doc" alone leaves their question unanswered. - -### Recording the answer - -`"settle": true` marks every card from their latest send `answered`, with the -answer they sent. `"settle": ["q2"]` names the cards instead — use it when only -some are final (a pick that still owes its recap stays open). A card the same -post reopens is never settled. To record a -reading of your own, also send the item with its `answer` (it wins): -`{ "k": "A" }`, `{ "ks": ["A","C"] }`, `{ "text": "audit-export" }`, -`{ "yes": true }`, `{ "verdict": "changes", "text": "..." }`, -`{ "done": [0,1], "state": "done" }`, `{ "rows": [...] }`. A settled card turns -into a record ("A · Continue without it"), so settle every card you are done -with — one left open stays on the page as a question still owed. - ---- - -## Posting an update - -``` -node "" post --session --file [--wait ] -``` - -The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / -`docs` and a doc's `blocks` merge by `id` (an unknown id is added), `thread` -appends. **Send only what changed.** Never write a timestamp: the server stamps -them. A refused patch is exit `3` with the reason on stderr; nothing is -written. - -While you work through a long stretch, say so: -`{"agent":{"status":"working","activity":"Reading the plan"}}` — one plain -sentence, shown in place of "thinking". The page calls a working agent stuck -after two silent minutes: expecting longer, add `"quietMinutes": <1-60>` to -`agent`. It only counts while you are working, so set it once. - -`run` (session meter, `console-meter.md`), `folderIssue` -(`console-workspace.md`) and `helpers` (`console-subagents.md`) are top-level -keys too; `run` and `folderIssue` go to the session's ledger, never the page. - ---- - -## The payload - -```jsonc -{ - "title": "Audit export", - "headline": { "stage": "Working", "cleared": 4, "total": 9, - "confidence": "Looking solid, but one area still needs work.", - "note": "optional sentence shown above the list" }, - "topics": [ { "id": "t2", "title": "How it behaves", "status": "current" } ], - "items": [ /* the kinds below */ ], - "docs": [ /* Documents, below */ ], - "finish": { /* only at the end: console-finish.md */ }, - "agent": { "status": "waiting" } -} -``` - -Fill in `headline.cleared` / `total`: the progress bar is the first thing anyone -looks at. `confidence` is a plain-English sentence, never raw scores. Post -`"specDir": "specs/"` once the folder exists (or pass `--spec` to -`open`): the page builds a resume command from it if you ever cannot answer a -stop. `stopWarning` is in `console-stop.md`. - -### Every item - -**Every new question gets a new `id`**, for the whole session. - -```jsonc -{ - "id": "q7", - "topic": "t2", - "kind": "choice", - "title": "Export format", // 2-4 plain words a newcomer understands - "body": "The question, in markdown, with why it matters.", - "required": true, // false adds a "Skip this one" link - "doc": "report", // optional: a "Read ... in full" button for that doc - "status": "open", // open | answered | reopened | skipped - "token": { "A": "approved" } // optional: the typed word an answer stands for -} -``` - -`token` is only needed where the terminal word differs from the option's `k` -or verdict `id`: without it, `reply` uses the key itself. - -### The kinds - -| `kind` | Use it for | Extra fields | You get back | +| Kind | Use | Extra fields | Back | | --- | --- | --- | --- | -| `choice` | one of several | `options[]`, `allowOther` | `{ k }` **or** `{ text }` | -| `multi` | any number of several | `options[]`, `presets[]` | `{ ks[], text? }` | -| `text` | free text | `placeholder`, `help`, `pattern`, `patternHint`, `templates` | `{ text }` | -| `confirm` | yes or no | `yesLabel`, `noLabel`, `danger`, `consequences` | `{ yes, text? }` | -| `recap` | play decisions back for agreement | `summary` (markdown) | `{ ok, text? }` | -| `review` | read something, then approve | `doc` (always), `summary`, `verdicts[]` (each `{ id, label, danger? }`: `label`, not `text`), `nothingYet` (the line under the buttons; defaults to "Nothing has been changed yet…", so `false` when the change is already on disk) | `{ verdict, text? }` | -| `checklist` | steps only they can do | `steps[]`, `valuesLabel` | `{ done?[], state?, text? }` (each left out when nothing was ticked or picked) | -| `menu` | what to do next | `options[]`, `command` | `{ k }` | -| `list` | reorder or edit a breakdown | `rows[{id,title,body}]` | `{ rows[] }`, or `{ text }` when they changed nothing; `reply` names renames, additions and removals | -| `notice` | something to read, no answer | — | nothing | +| `multi` | any number of several | `options`, `presets:[{label,ks}]` | `{ks,text?}` | +| `review` | read, then approve | `doc` (required), `summary`, `verdicts:[{id,label,danger?}]`, `nothingYet` (false once the change is on disk) | `{verdict,text?}` | +| `checklist` | steps only they can do | `steps`, `valuesLabel` | `{done?,state?,text?}` | +| `list` | reorder or edit a breakdown | `rows:[{id,title,body}]` | `{rows}` or `{text}` | +| `notice` | read, no answer | none | none | -An option is `{ "k": "A", "text": "short label", "detail": "the trade-off", "recommended": true }`. -`detail` is the difference between a person choosing and a person guessing. +Items show in the order sent: send them in the order you want them answered. -- **`choice`**: one of the two, never both. The page offers "Something else, in - your own words" in the same radio group; read `k` if it is there, otherwise - `text`. `"allowOther": false` drops it when the options are the whole set. -- **`multi`**: `text` joins the ticks rather than replacing them. `presets` - (`[{ "label": "Critical and warnings", "ks": ["1","2"] }]`) only tick boxes. -- **`pattern`** is a JavaScript regex checked as they type, with `patternHint` - shown when it fails. Use it for anything with a shape, above all kebab-case. -- **A placeholder is an offer.** The **Autofill suggestion** button drops it - into the box as a real answer (a lead-in like "For example:" is stripped), so - write a whole example in their voice, one that satisfies any `pattern`. -- **Starter templates:** on the `text` card that asks for a **fresh idea** in - Pathfinder, Plan and Quick Task, add `"templates": "idea"` (any other kind or - value is exit 3). Launched with notes or an idea as the argument? Still set - it, with a one-line summary in `placeholder`. A resumed map, PLAN-DRAFT or - checkpoint gets no idea card. Only the box's text comes back; never mention - templates in the terminal. -- **Fill from a Notebook tab:** on a `text` item, `"fill": "note"` (its only - value; any other kind or value is exit 3) has the page fill the first open one - once, with the tab's text and ticked pictures, when the person started from a - Notebook tab. You read it only when they send that box (Send, or Stop or - Back to the dashboard, which carry ready answers). -- **Recommend only when you genuinely know better and can say why.** "Which - format survives Excel?" is yours; "Who is this for?" is not — there a - recommendation is an anchor people rubber-stamp. At most one per question. +**Documents:** the first patch that carries `docs` is answered with a `read` pointer to `console-docs.md`. -Items appear in the order you send them, and the person walks the open ones with -Previous / Next: send them in the order you want them answered. +## Settling and notes -### Documents +`"settle":true` marks every card in their latest send answered with what they sent; `"settle":["q2"]` names cards. A card the same post reopens is never settled. To record your own reading, send the item with `answer` (`{k}`, `{ks}`, `{text}`, `{yes}`, `{verdict,text}`, `{rows}`). -```jsonc -"docs": [{ - "id": "map", "title": "What we've agreed", - "note": "what changed in this version", - "saved": "specs/lunch-vote/pathfinder/map.md", - "blocks": [ - { "id": "b1", "state": "settled", "md": "## Where we're headed\n\n..." }, - { "id": "b2", "state": "assumed", "md": "### File format\n\nAssuming CSV..." }, - { "id": "b3", "state": "draft", "md": "### Still to work out\n\n- ..." }, - { "id": "b4", "file": "specs/lunch-vote/overview.md" } - ] -}] -``` +Every note in an item's `thread` gets a reply: `{"id":"p4","thread":[{"who":"agent","text":"..."}]}`. Send only new entries. -Each doc is a tab. Patch blocks as decisions land: `{ "id": "b2", "state": -"settled" }` settles b2 and keeps its text, blocks you leave out stay, a new id -goes at the end, `{ "id": "b3", "_delete": true }` removes one (a doc entry -with `"_delete": true` removes the whole tab). +## What the console refuses (exit 3) -- **`state`**: `settled` (decided), `assumed` (picked to keep going, still open: - shown dashed, "Assumed for now"), `draft` (dimmed). Marking assumptions - honestly is what stops a half-finished doc reading as decisions. -- **`file`** instead of `md`: the console reads the block's text from that file - (relative to the project, never outside it). Re-send the block, or the doc - with `"refresh": true`, after the file changes. `"select": "tasks"` keeps only - its `- [ ] **Task N.M:**` lines. Never paste a file you could name. -- **`image`** instead of `md`: `{ "id", "image": "shots/run.png", "alt": "..." }` - shows a PNG, JPEG or WebP (5 MB at most) saved directly in the session's - `shots/` folder (the `session` path `open` printed), named with letters, - digits, `.`, `_` or `-`; anything else is exit `3`. -- **`version`** moves by itself: a known doc whose content changed is the next - version. Send one only to jump; it never goes back. Write a one-line `note` - when you change a doc, and `"stale": true` while answers it does not reflect - have landed. -- **`saved`** is the path of the file the doc mirrors, when one exists: the page - shows the path instead of a download. Leave it off docs that exist only here. +- more than three open required questions at once (optional cards and notices do not count) +- internal vocabulary in a title (grill, frontier, fog, HITL, AFK, durable, `Locked:`, `Blocked by:`, `State:`) +- more than one recommended option on a question +- loop completion markers (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest) +- a bare Requirements, Feasibility, Integration or Risk followed by a number (hyphenate or reword) +- a doc `version` that goes back (leave `version` out) +- a finish `command` with `<` or `>` in it +- a note left without a reply +- a `finish` while `stopWarning` is set or a helper is still `running` +- a `stop` with no `finish` (`stop --session --force` for a dead page) ---- +It cannot see these two: every turn ends on a `wait`, and no new open question after a `finish`. -## House rules the server enforces +Ending: every session end posts `finish` (`{"settle":true,"finish":{"headline":"Phase 3 is done","body":"...","command":"/plan2code-3-implement specs/x/overview.md","dashboard":true}}`, with `--wait`, then keep waiting for the button), then `stop`. A pause (headline starting "Paused") has no `dashboard` and stops at once. Your notes give your workflow's finish; read `console-finish.md` for every field. -A patch that breaks one is refused, exit `3`, with the reason: +## Read when -1. **At most three questions open at once.** -2. **No internal vocabulary in a title**: *grill*, *frontier*, *fog*, *HITL*, - *durable*, `Locked:`, `Blocked by:`. -3. **At most one recommended option per question.** -4. **No loop completion markers** (`TASK_COMPLETE`, `PHASE_COMPLETE` and the rest). -5. **No bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a - number** (the metrics collector scrapes that): hyphenate or reword. Rules 4 - and 5 skip `file` blocks: those words are already on disk. -6. **Chat replies hold together** (`console-chat.md`). -7. **`run`, `folderIssue` and `helpers` are well formed** (their topic files). -8. **A doc's `version` never goes back.** -9. **A finish `command` has no placeholders** (`<` or `>`). -10. **Every note gets a reply.** A card whose thread ends with the person's own - words stays that way until a patch adds an agent reply to it; settling or - reopening it does not count. Exempt once the item is deleted, or the whole - session is ending. - ---- - -## Ending - -Every session end — done, a pause, a stop request, an off-ramp — posts a -`finish` **before** `stop`, and every ending but a pause keeps waiting for the -person's last button. Read `console-finish.md` before your first finish post: -it has the fields, the dashboard button and the order. Before any finish, every -subagent or background job you started must have reported back. - ---- - -## Worked example - -The first questions of a pathfinder session, piped in with `post --file - --wait 240`: - -```json -{ - "title": "Audit export", - "headline": { "stage": "Charting", "cleared": 0, "total": 6 }, - "items": [ - { "id": "q1", "kind": "choice", "title": "What you end up with", - "body": "When this is done, what exists that does not exist now?", - "options": [ - { "k": "A", "text": "A plan, ready to build from", "detail": "We write the decisions down. Nothing is built yet.", "recommended": true }, - { "k": "B", "text": "A change already made", "detail": "Small enough to just do. We would skip planning entirely." } - ] }, - { "id": "q2", "kind": "text", "title": "Who uses it", - "body": "Who uses the result, and what do they do with it the day it lands?", - "placeholder": "For example: compliance reviewers, who open it in Excel every Monday." } - ] -} -``` - -It lands and waits in one command; the new questions make it the person's turn. +| File | When | +| --- | --- | +| `notes/.md` | right after `open` | +| `building.md` | right after `open`: implement, implement-review, quick-task | +| `console-launches.md` | you are the dashboard | +| `console-meter.md` | a `run` was refused | +| `console-attachments.md` | a file you write under `specs/` cites a note's attachment | +| `console-trouble.md` | something breaks (a failed `open`, a repeat delivery, a dead server) | diff --git a/src/web-console/inbox.mjs b/src/web-console/inbox.mjs index 9246296..5c4b550 100644 --- a/src/web-console/inbox.mjs +++ b/src/web-console/inbox.mjs @@ -4,7 +4,7 @@ import path from "node:path"; import { CHAT_LIMIT } from "./public/chat.js"; import { appendJsonLine, nowIso, readJson, readJsonLines, writeJsonAtomic } from "./files.mjs"; -import { isPlainObject, proseProblems } from "./patches.mjs"; +import { isPlainObject, proseProblems, rule } from "./patches.mjs"; /* ------------------------------------------------------- the chat inbox */ @@ -143,12 +143,12 @@ export function chatReplyLines(entries) { const lines = []; for (const e of entries) { if (e.kind === "message") { - lines.push(`Quick question: ${indent(e.text, " ")}`); + lines.push(`Quick question (${e.seq}): ${indent(e.text, " ")}`); if (e.about && e.about.label) lines.push(` About: ${indent(e.about.label, " ")}`); for (const img of e.images || []) lines.push(` Image: ${img.path} (${img.name})`); for (const f of e.files || []) lines.push(` File: ${f.path} (${f.name})`); } else if (e.kind === "decision") { - lines.push(`${e.decision === "approve" ? "Approved" : "Declined"}: edit ${e.re}`); + lines.push(`${e.decision === "approve" ? "Approved" : "Declined"} (${e.seq}): edit ${e.re}`); if (e.text) lines.push(` Note: ${indent(e.text, " ")}`); } else if (e.kind === "reset") { lines.push("New conversation started. Treat earlier chat as closed."); @@ -181,7 +181,8 @@ function underSpec(file, specDir) { export function validateChat(state, entries) { const replies = state?.chat?.replies; if (replies == null) return []; - if (!Array.isArray(replies)) return ['"chat.replies" must be an array']; + const right = { chat: { replies: [{ re: 12, md: "..." }] } }; + if (!Array.isArray(replies)) return [rule("", "chat.replies", "must be an array", right)]; const problems = []; const targets = new Set( entries.filter((e) => e.kind === "message" || e.kind === "decision").map((e) => e.seq) @@ -189,34 +190,36 @@ export function validateChat(state, entries) { const ids = new Set(); for (const r of replies) { if (!isPlainObject(r)) { - problems.push("every chat reply must be an object"); + problems.push(rule("", "chat.replies", "every reply must be an object", right)); continue; } const name = typeof r.id === "string" && r.id.trim() ? r.id : "(no id)"; - if (name === "(no id)") problems.push('every chat reply needs a non-empty string "id"'); - else if (ids.has(r.id)) problems.push(`duplicate chat reply id "${r.id}"`); + const at = `chat reply "${name}"`; + if (name === "(no id)") problems.push(rule(at, "id", 'needs a non-empty string "id" (or "re", which names it)', right)); + else if (ids.has(r.id)) problems.push(rule(at, "id", "is used twice", right)); ids.add(r.id); if (!Number.isInteger(r.re) || !targets.has(r.re)) { - problems.push(`chat reply "${name}" needs "re": the seq of the message or decision it answers`); + problems.push(rule(at, "re", "needs the seq of the message or decision it answers", right)); } - if (!Number.isInteger(r.conversation)) problems.push(`chat reply "${name}" needs an integer "conversation"`); - if (typeof r.md !== "string" || !r.md.trim()) problems.push(`chat reply "${name}" needs its answer in "md"`); + if (!Number.isInteger(r.conversation)) problems.push(rule(at, "conversation", "needs an integer", right)); + if (typeof r.md !== "string" || !r.md.trim()) problems.push(rule(at, "md", "needs the answer", right)); const p = r.proposal; if (p != null) { - if (!isPlainObject(p)) problems.push(`chat reply "${name}" "proposal" must be an object`); + const proposalRight = { chat: { replies: [{ re: 12, md: "...", proposal: { summary: "Rename the helper", files: ["src/util.mjs"] } }] } }; + if (!isPlainObject(p)) problems.push(rule(at, "proposal", "must be an object", proposalRight)); else { if (typeof p.summary !== "string" || !p.summary.trim()) { - problems.push(`chat reply "${name}" proposal needs a plain-English "summary"`); + problems.push(rule(at, "proposal.summary", "needs a plain-English summary", proposalRight)); } if (!Array.isArray(p.files) || !p.files.length) { - problems.push(`chat reply "${name}" proposal needs "files": the project files it would change`); + problems.push(rule(at, "proposal.files", "needs the project files it would change", proposalRight)); } else { for (const f of p.files) { if (!projectRelative(f)) { - problems.push(`chat reply "${name}" proposal file "${f}" must be a project-relative path`); + problems.push(rule(at, "proposal.files", `"${f}" must be a project-relative path`, proposalRight)); } else if (state.specDir && underSpec(f, state.specDir)) { - problems.push(`a chat edit cannot touch the running skill's own files under ${state.specDir}/`); + problems.push(rule(at, "proposal.files", `a chat edit cannot touch the running skill's own files under ${state.specDir}/`, proposalRight)); } } } @@ -226,12 +229,13 @@ export function validateChat(state, entries) { if (r.changed != null) { const count = (n) => Number.isInteger(n) && n >= 0; if (!Array.isArray(r.changed) || !r.changed.every((c) => isPlainObject(c) && typeof c.file === "string" && count(c.added) && count(c.removed))) { - problems.push(`chat reply "${name}" "changed" must be a list of { file, added, removed }`); + problems.push(rule(at, "changed", "must be a list of { file, added, removed }", { changed: [{ file: "src/util.mjs", added: 3, removed: 1 }] })); } } + + problems.push(...proseProblems(String(r.md ?? ""), `${at} md`)); + if (isPlainObject(p) && typeof p.summary === "string") problems.push(...proseProblems(p.summary, `${at} proposal.summary`)); } - const prose = JSON.stringify(replies.map((r) => [r && r.md, r && r.proposal && r.proposal.summary])); - problems.push(...proseProblems(prose, "a chat reply")); return problems; } diff --git a/src/web-console/loop-setup.mjs b/src/web-console/loop-setup.mjs new file mode 100644 index 0000000..63ec434 --- /dev/null +++ b/src/web-console/loop-setup.mjs @@ -0,0 +1,124 @@ +// Plan2Code Web Console - the Implementation Loop's setup, remembered per project. + +import path from "node:path"; + +import { ensureDir, HOME_DIR, readJson, withStateLock, writeJsonAtomic } from "./files.mjs"; +import { foldKey } from "./workspace.mjs"; + +// One file for the person, beside workspaces.json and looks.json, keyed by the +// folder a session runs in (FR-4: one entry per project, used for any spec): +// +// { "schema": 1, "projects": { "": { ...setup, "saved": "" } } } +// +// Never under specs/: the server never writes into a project. The quick check +// is stored text only; nothing in the console ever runs it. +export const LOOP_SETUP_FILE = path.join(HOME_DIR, "loop-setup.json"); +export const LOOP_SETUP_LOCK = "loop-setup.json.lock"; + +const LEVELS = ["critical", "warning", "suggestion"]; +const FIX_MODES = ["levels", "smart"]; +const ON_QUESTION = ["pause", "stop", "guess"]; +const AFTER_LAST = ["offer-finalize", "run-finalize"]; +const NOTIFY_KINDS = ["query", "discord", "slack", "teams", "google-chat", "json"]; +// The kinds where the person names the parameter or field that holds the message. +const NAMED_KINDS = ["query", "json"]; + +export const LOOP_DEFAULTS = Object.freeze({ + review: true, + fixMode: "smart", + fix: Object.freeze([...LEVELS]), + commit: true, + onQuestion: "guess", + afterLast: "offer-finalize", + quickCheck: "", + retryOnce: true, + silenceMinutes: 20, + notifyKind: "query", + notifyUrl: "", + notifyParam: "message", +}); + +/** An http or https address in printable ASCII, with a host and no user name or password (the app's `valid_url`). */ +function isNotifyUrl(text) { + if (text.length > 2000 || !/^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(text) || /[^!-~]/.test(text)) return false; + try { + return Boolean(new URL(text).hostname); + } catch { + return false; + } +} + +/** Problems with a setup entry, as sentences naming the field; empty when it is good. */ +export function loopSetupProblems(entry) { + if (entry === null || typeof entry !== "object" || Array.isArray(entry)) return ["the setup must be an object"]; + const problems = []; + for (const key of Object.keys(entry)) { + if (!Object.hasOwn(LOOP_DEFAULTS, key)) problems.push(`"${key}" is not a setup field`); + } + for (const key of ["review", "commit", "retryOnce"]) { + if (typeof entry[key] !== "boolean") problems.push(`"${key}" must be true or false`); + } + if (!Array.isArray(entry.fix) || !entry.fix.every((l) => LEVELS.includes(l)) || new Set(entry.fix).size !== entry.fix.length) { + problems.push(`"fix" must list distinct levels from ${LEVELS.join(", ")}`); + } + if (!FIX_MODES.includes(entry.fixMode)) problems.push(`"fixMode" must be one of ${FIX_MODES.join(", ")}`); + if (!ON_QUESTION.includes(entry.onQuestion)) problems.push(`"onQuestion" must be one of ${ON_QUESTION.join(", ")}`); + if (!AFTER_LAST.includes(entry.afterLast)) problems.push(`"afterLast" must be one of ${AFTER_LAST.join(", ")}`); + if (typeof entry.quickCheck !== "string" || /[\r\n]/.test(entry.quickCheck) || entry.quickCheck.length > 500) { + problems.push('"quickCheck" must be one line of at most 500 characters (empty for none)'); + } + if (!Number.isInteger(entry.silenceMinutes) || entry.silenceMinutes < 1 || entry.silenceMinutes > 60) { + problems.push('"silenceMinutes" must be a whole number from 1 to 60'); + } + if (typeof entry.notifyUrl !== "string" || (entry.notifyUrl !== "" && !isNotifyUrl(entry.notifyUrl))) { + problems.push('"notifyUrl" must be an http or https web address, without a user name or password (empty for none)'); + } + if (!NOTIFY_KINDS.includes(entry.notifyKind)) problems.push(`"notifyKind" must be one of ${NOTIFY_KINDS.join(", ")}`); + // The name only matters beside an address and for a kind that uses it: the field is hidden otherwise. + if (typeof entry.notifyParam !== "string" || (entry.notifyUrl && NAMED_KINDS.includes(entry.notifyKind) && !/^[A-Za-z0-9._~-]{1,64}$/.test(entry.notifyParam))) { + problems.push('"notifyParam" must be 1 to 64 letters, digits, or - _ . ~'); + } + return problems; +} + +function readStore() { + const saved = readJson(LOOP_SETUP_FILE, null); + const ok = saved && saved.schema === 1 && saved.projects && typeof saved.projects === "object" && !Array.isArray(saved.projects); + return ok ? saved : { schema: 1, projects: {} }; +} + +/** + * The setup for this project: the saved entry over the defaults, or the + * defaults alone. `remembered` says which, so the setup screen can tell a + * first visit from a returning one. A missing, unreadable or foreign-schema + * file reads as empty. An entry saved before `fixMode` existed fixed by level, + * so it keeps doing that rather than taking the newer default. + */ +export function readLoopSetup(project) { + const saved = readStore().projects[foldKey(project)]; + if (saved && typeof saved === "object") return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], fixMode: "levels", ...saved, remembered: true }; + return { ...LOOP_DEFAULTS, fix: [...LOOP_DEFAULTS.fix], remembered: false }; +} + +/** Validate and save this project's setup; throws an Error listing the problems. */ +export function saveLoopSetup(project, entry) { + const problems = loopSetupProblems(entry); + if (problems.length) { + const err = new Error(`the loop setup is not valid: ${problems.join("; ")}`); + err.problems = problems; + throw err; + } + ensureDir(path.dirname(LOOP_SETUP_FILE)); + return withStateLock( + path.dirname(LOOP_SETUP_FILE), + () => { + const store = readStore(); + // Only the known fields are kept, in the defaults' order. + const known = Object.fromEntries(Object.keys(LOOP_DEFAULTS).map((key) => [key, entry[key]])); + store.projects[foldKey(project)] = { ...known, saved: new Date().toISOString() }; + writeJsonAtomic(LOOP_SETUP_FILE, { schema: 1, projects: store.projects }); + return readLoopSetup(project); + }, + LOOP_SETUP_LOCK, + ); +} diff --git a/src/web-console/notes/changelog.md b/src/web-console/notes/changelog.md index 799dfb7..ba8157f 100644 --- a/src/web-console/notes/changelog.md +++ b/src/web-console/notes/changelog.md @@ -1,27 +1,14 @@ -# Changelog on the Web Console +# Changelog -Workflow notes for `changelog`, part of the web console contract (`console.md`). +`changelog`: post `activity` while you read the history and diff. One card per step, each only when needed: -Open with `--workflow changelog` (launched from the dashboard: resume the -session instead). Post `activity` while you read the history and the diff. One -card per step, each asked only when the step needs it: - -| Step | On the page | +| Step | Card | | --- | --- | -| Version | A `choice`, "Which version?": the computed version (recommended) with its reason in `body` (main is at X, the branch has Y), "Keep Y" when the branch's own entry could stay, and "Another version" (`allowOther`). A `choice` does not check what is typed, so check it yourself: anything that is not `X.Y.Z` gets the card again with a `thread` reply saying so. Left out when the entry is already right. | -| Entries | A `list` titled "Entries to add": one row per suggested entry, `title` the entry line itself (the part they can edit) and `body` its section (`Added`, `Fixed`…). Removable and reorderable; `reply` names renames, additions and removals. A row they add has no section: ask, or file it where it reads best and say so. | -| The result | The final entry as a doc (`id: "entry"`, marked `"saved": "CHANGELOG.md"` once written) plus a `review` card with verdicts `write` ("Write it"), `change` and `stop`. | -| package.json | A `confirm` with the `old → new` in `consequences`. | -| Commit this now? | A `confirm`, "Commit this now?". | +| Version | `choice` "Which version?": the computed version (recommended, reason in `body`), "Keep Y" when the branch's entry could stay, "Another version" (`allowOther`). Typed text is unchecked: anything but `X.Y.Z` gets the card again with a `thread` reply. Skipped when the entry is right. | +| Entries | `list` "Entries to add": `title` the entry line, `body` its section. `reply` names renames, additions, removals. A row they add has no section: ask, or file it and say so. | +| Result | Doc `entry` (`"saved":"CHANGELOG.md"` once written) plus a `review` with verdicts `write`, `change`, `stop`. | +| package.json | `confirm`, `old → new` in `consequences`. | +| Commit now? | `confirm` "Commit this now?" | -A yes to "Commit this now?" ends no session (no `finish`, no `stop`): settle -the card, resume as `git` (`open --resume --no-open --workflow git`), -then read `~/.agents/skills/plan2code-git/SKILL.md` with your file-read tool -and start with its commit flow, in this same session, as a dashboard launch -does (`console-launches.md`); the resume clears Changelog's page for it. -Entered from **Update CHANGELOG first** on a finished Quick Task or Finalize -(`console-finish.md`): the hop is the same as a dashboard launch, and nothing -else changes. The yes above is the exit to Git as always, so the person lands in -the commit flow with the CHANGELOG already updated. -Finish, on a no: `"dashboard": true` and the version and entries in `body`, -with no `command`. A stop's finish is the bare `/plan2code-changelog`. +A yes ends no session (no `finish`): settle the card, resume as `git` (`open --resume --no-open --workflow git`), read `~/.agents/skills/plan2code-git/SKILL.md` and start its commit flow. +A no finishes with `"dashboard":true`, version and entries in `body`, no `command`. A stop's `command` is `/plan2code-changelog`. diff --git a/src/web-console/notes/diagnose.md b/src/web-console/notes/diagnose.md index 1bcb7eb..0e91f47 100644 --- a/src/web-console/notes/diagnose.md +++ b/src/web-console/notes/diagnose.md @@ -1,83 +1,38 @@ -# Diagnose on the Web Console - -Workflow notes for `diagnose`, part of the web console contract (`console.md`). +# Diagnose ## The bug -A typed argument that already describes the bug skips the cards it answers. -Otherwise ask in one batch (at most three open), posted with `--wait`: +An argument that already describes the bug skips the cards it answers. Otherwise one `--wait` batch, no `templates`: ```jsonc -{ - "title": "Diagnose a bug", - "headline": { "stage": "The bug", "cleared": 0, "total": 3 }, - "items": [ - { "id": "bug", "kind": "text", "title": "What is wrong", - "body": "The bug, in a sentence or two.", - "placeholder": "The CSV export drops the last row when the report has more than 100 rows." }, - { "id": "expected", "kind": "text", "title": "Expected and actual", - "body": "What should happen, and what happens instead.", - "placeholder": "Expected 150 rows in the file; it has 149, and the last order is missing." }, - { "id": "see-it", "kind": "text", "title": "How to see it", - "body": "The steps, command, page or input that shows it, and since when if you know.", - "placeholder": "Run npm run export -- --month 2026-09 and count the rows. It worked last month." } - ] -} +{"title":"Diagnose a bug","headline":{"stage":"The bug","cleared":0,"total":3},"items":[{"id":"bug","kind":"text","title":"What is wrong","body":"The bug, in a sentence or two."},{"id":"expected","kind":"text","title":"Expected and actual","body":"What should happen, and what happens instead."},{"id":"see-it","kind":"text","title":"How to see it","body":"The steps, command, page or input that shows it, and since when if known."}]} ``` -No `"templates"` on these cards: the starter templates are for a fresh idea, -and a bug report is not one. A follow-up the answers leave open is a new card -with a new id. +A follow-up the answers leave open is a new card with a new id. ## The cause -Post the cause as a doc, `id` `"cause"`, as soon as there is something to show, -and grow it as evidence lands, with `"agent": { "status": "working", -"activity": "..." }` while you reproduce and narrow: +Doc `cause`, posted as soon as there is something to show and grown as evidence lands, with `agent` `working` while you reproduce: ```jsonc -"docs": [{ "id": "cause", "title": "The cause", "note": "Reproduced; narrowing", "blocks": [ - { "id": "repro", "state": "settled", "md": "## Reproduction\n\n`node scripts/export-check.mjs` fails: 149 rows, expected 150." }, - { "id": "found", "state": "settled", "md": "## The cause\n\n`src/export.ts` `writeRows()`: the loop stops at `rows.length - 1`. **Proven** by the reproduction." }, - { "id": "fix", "state": "settled", "md": "## Suggested fix\n\nLoop to `rows.length`. **Size:** Small (Quick Task)." } -]}] +{"docs":[{"id":"cause","title":"The cause","note":"Reproduced; narrowing","blocks":[{"id":"repro","state":"settled","md":"## Reproduction\n\n..."},{"id":"found","state":"settled","md":"## The cause\n\n..."},{"id":"fix","state":"settled","md":"## Suggested fix\n\n... **Size:** Small (Quick Task)."}]}]} ``` -- **Unproven** guesses are `assumed` blocks, one per guess, ranked, each with - its evidence and what would confirm it. A guess the evidence proves becomes - `settled`; one it rules out is removed (`"_delete": true`). -- Keeping a failing test inside the project is a `confirm` card pointing at - the doc (`"doc": "cause"`), `yesLabel` "Keep it", `noLabel` "Throw it away". +- Unproven guesses are `assumed` blocks, ranked, each with its evidence and what would confirm it. Proven: `settled`. Ruled out: `"_delete":true`. +- Keeping a failing test in the project: `confirm` with `"doc":"cause"`, `yesLabel` "Keep it", `noLabel` "Throw it away". ## The bug name -With the cause written, ask the folder name, posted with `--wait`: +After the cause, `--wait`: ```jsonc -{ "id": "name", "kind": "text", "title": "Name for the write-up", "doc": "cause", - "body": "The diagnosis is saved as `specs//DIAGNOSIS-.md`. Lowercase words joined by dashes.", - "placeholder": "csv-export-drops-rows", - "pattern": "^[a-z0-9]+(-[a-z0-9]+)*$", - "patternHint": "Lowercase letters, numbers and dashes, like csv-export-drops-rows." } +{"id":"name","kind":"text","title":"Name for the write-up","doc":"cause","body":"Saved as `specs//DIAGNOSIS-.md`. Lowercase words joined by dashes.","placeholder":"csv-export-drops-rows","pattern":"^[a-z0-9]+(-[a-z0-9]+)*$","patternHint":"Lowercase letters, numbers and dashes."} ``` -Once written, re-send the doc with -`"saved": "specs//DIAGNOSIS-.md"` and its blocks replaced by one -`file` block for that path (delete the old ids). +Once written, re-send `cause` with `"saved":"specs//DIAGNOSIS-.md"` and one `file` block for that path (delete the old block ids). ## The finish -`command` is `/plan2code-quick-task specs/` (small fix) or -`/plan2code-1-plan specs/` (big fix) with the real folder filled in -(`/plan2code-quick-task specs/csv-export-drops-rows`), never a placeholder: a -copied command must reach the diagnosis. `body` names the cause, how sure, and that the -next step reads the diagnosis first. `doc` is `"cause"`. `"dashboard": true`, -then keep waiting for the press (`console-finish.md`): back on the dashboard -the folder shows as "Bug diagnosed", with that card lit. +`command` is `/plan2code-quick-task specs/` (small fix) or `/plan2code-1-plan specs/` (big fix), real folder filled in. `body`: the cause, how sure, and that the next step reads the diagnosis first. `"doc":"cause"`, `"dashboard":true`. Nothing kept (did not reproduce, no guess held): no `command`, say so in `body`. -Nothing kept (the bug did not reproduce and no guess held up): leave -`command` out and say so in `body`. - -A stop before the file is written ends on a finish whose `body` says nothing -was kept (and names any throwaway script or kept test you wrote), with -`"command": "/plan2code-diagnose"` (`console-stop.md`). +A stop before the file is written: `body` says nothing was kept (and names any throwaway script or kept test), `"command":"/plan2code-diagnose"`. diff --git a/src/web-console/notes/document.md b/src/web-console/notes/document.md index 7bd6ed2..51b4036 100644 --- a/src/web-console/notes/document.md +++ b/src/web-console/notes/document.md @@ -1,12 +1,3 @@ -# Documentation on the Web Console +# Documentation -Workflow notes for `document`, part of the web console contract (`console.md`). - -The questions are few — which draft, a clarification, the sign-off — but the -docs are the point: post each phase file as a doc as it is written, so a -browser-only person watches the spec take shape. Each one mirrors a file on -disk, so carry its `saved` path, and post it as a `file` block -(`{ "id": "body", "file": "specs//phase-2.md" }`) rather than pasting -the text you just wrote. Pass `--spec specs/` once the folder is known; -it is what the resume command needs. Finish commands follow the pipeline: the -sign-off's is `/plan2code-3-implement specs//overview.md`. +Post each phase file as a doc as it is written, as a `file` block (`{"id":"body","file":"specs//phase-2.md"}`) carrying its `saved` path. Pass `--spec specs/` once the folder is known. The sign-off's finish `command` is `/plan2code-3-implement specs//overview.md`. diff --git a/src/web-console/notes/finalize.md b/src/web-console/notes/finalize.md index 8aefd52..9ef635b 100644 --- a/src/web-console/notes/finalize.md +++ b/src/web-console/notes/finalize.md @@ -1,34 +1,14 @@ -# Finalize on the Web Console +# Finalize -Workflow notes for `finalize`, part of the web console contract (`console.md`). - -Finalize is a run of reports and gates, and each maps onto a kind you already -know: - -| Step | On the page | +| Step | Card | | --- | --- | -| 1, Task Completion Audit | The audit table as a doc (`id: "audit"`). If incomplete or blocked tasks exist (`totals.incomplete + totals.blocked > 0`), a `choice` with the three options — return to implementation, mark partially complete, abandon — with the counts against the thresholds in `body`. | -| 2, Implementation Verification | The verification results as a doc. Nothing to ask unless an issue needs their decision. | -| 3, Implementation Summary | Written to `overview.md` as usual; mirror it as a doc (marked `saved`, as a `file` block on `overview.md`) so the page reader sees it land. | -| 4, Documentation Review | The proposed-updates table as a doc, and a `multi` naming the documents to update — every option ticked is "approve", unticked ones are skipped. A `review` works instead when the set is all-or-nothing. | -| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. | -| 6, Spec Cleanup | A `review` item before moving anything (`doc`: Step 3's summary), verdicts `yes` ("Archive it"), `show` ("Show me it working", token `show me`) and `no`, the archive paths in `body`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/` after the move). On `show`, run it as `notes/implement.md` → Show me it working says (the summary line goes into `overview.md`'s Completion Summary), then reopen the card without `show`. | +| 1, Audit | Table as doc `audit`. If `totals.incomplete + totals.blocked > 0`, a `choice` (return, mark partial, abandon) with counts against thresholds in `body`. | +| 2, Verification | Results as a doc; ask only on an issue. Unless Full Suite is `Never` or `At Phase N`: `confirm` "Run the full suite" (`yesLabel` "Run it", `noLabel` "Skip it", reason in `body`); a failure is the building notes' `choice`. | +| 3, Summary | Written to `overview.md`; mirror it as a doc (`saved`, `file` block). | +| 4, Docs review | Proposed-updates table as a doc, plus a `multi` of documents (ticked = approved); a `review` if all-or-nothing. | +| 5, Feedback | `required:false`: rating as `choice` 1 to 10 or `text`, three reasons as `text`, maintainer consent as `confirm`. | +| 6, Cleanup | `review` (`doc` Step 3's summary), verdicts `yes` ("Archive it"), `show` (token `show me`), `no`; archive paths in `body`, and a line that remembered workspace folders are forgotten too (`console.mjs forget --spec specs/` after the move). On `show`, see `notes/implement.md`, then reopen without `show`. | -Post `activity` as each step starts, before its doc or question lands — reading -the spec, running `specs.mjs status` or `archive --dry-run`, checking the -implementation — the same way Review does. A step with no card of its own -(2, 3) is otherwise a stretch of silence the page can only show as "Starting -Finalize". +Post `activity` as each step starts. Pass `--spec specs/` or post `specDir`. -Pass `--spec specs/` to `open`, or post `specDir` once you know it. -Stopping mid-finalize loses nothing — the specs are untouched until Step 3's -summary write — so a stop's finish just says where it paused and uses -`"command": "/plan2code-4-finalize specs//overview.md"`. On success -the finish's `command` is the suggested commit when Step 4 doc updates landed -(with `"where": "When you are happy with it, commit it from your terminal:"`), otherwise leave `command` out. -When the finish prints that suggested commit, it also carries `"commit": true`, -so the finished screen offers **Commit it now** (`console-finish.md`), and -`"changelog": true` beside it, for **Update CHANGELOG first** (it hops into -Changelog and on to Git). Both only when the finish prints a commit. The -completion summary is printed to a terminal the browser user is not watching, -so put it in `finish.body`. +Finish: the completion summary goes in `body`. `command` is the suggested commit when Step 4 updates landed (`"where":"When you are happy with it, commit it from your terminal:"`, `"commit":true`, `"changelog":true`), else none. A stop loses nothing before Step 3's write: `command` `/plan2code-4-finalize specs//overview.md`. diff --git a/src/web-console/notes/git.md b/src/web-console/notes/git.md index b4da3c0..2c7416b 100644 --- a/src/web-console/notes/git.md +++ b/src/web-console/notes/git.md @@ -1,124 +1,58 @@ -# Git on the Web Console +# Git -Workflow notes for `git`, part of the web console contract (`console.md`). +Launched from the dashboard or a hand-off: resume the session. The main column is the git board, from `state.git`. **Never post `git`** (exit 3). Your cards sit in the board's card slot. -Open with `--workflow git` (launched from the dashboard, or by a **Commit it -now** or Changelog hand-off: resume the session instead). Like the dashboard, -the main column is drawn by the page itself: the git board, from `state.git`, -which `open` and every `reread` snapshot through `git-repo.mjs`. **You never -post `git`** (exit 3: `state.git` is the console's own). Your cards sit in -the board's card slot, under its tab strip. - -**A click** arrives as one session action, one per send, and the board locks -until your next post lands: +A click arrives as one session action per send, and the board locks until your next post lands: ```jsonc -{ "type": "submit", - "actions": [{ "i": "__git", "type": "git", "op": "create", - "name": "feature/export-csv", "from": "origin/main", - "then": "commit", "files": ["src/a.js"], "ignore": ["dist/"] }], - "reply": "Create feature/export-csv from origin/main. ..." } +{"reply":"Create feature/export-csv from origin/main.","session":[{"i":"__git","op":"create","name":"feature/export-csv","from":"origin/main","then":"commit","files":["src/a.js"],"ignore":["dist/"]}]} ``` | `op` | Fields | | --- | --- | -| `refresh`, `pull`, `push`, `abort`, `continue`, `done` | none (a `refresh` with no remote is "look again": `plan refresh` gives no commands, so just post `reread`) | -| `publish` | `remote?` (left out when there are several: `plan publish` asks which) | -| `switch`, `delete` | `branch` (a remote-only row is `/`) | -| `create` | `name`, `from`; `then: "commit"` with `files` (and `ignore`, when any) when it came from the commit panel's branch offer | +| `refresh`, `pull`, `push`, `abort`, `continue`, `done` | none (`refresh` with no remote: `plan refresh` gives no commands, just post `reread`) | +| `publish` | `remote?` (absent with several: `plan publish` asks) | +| `switch`, `delete` | `branch` (remote-only row is `/`) | +| `create` | `name`, `from`; `then:"commit"` with `files` (and `ignore`) from the commit panel's branch offer | | `cleanup` | `branches[]` | -| `commit` | `files[]` (paths and untracked folders), `ignore[]` (folders to add to `.gitignore`). `files[]` may be empty when `ignore[]` is not: the board's held-back offer (**Add … to .gitignore**). Then add the paths to `.gitignore` and commit only `.gitignore`. | -| `pr-host` | `host`, `kind` (already saved by the page's `POST /pr-host`) | +| `commit` | `files[]`, `ignore[]` (folders for `.gitignore`). `files[]` may be empty when `ignore[]` is not (held-back offer): add the paths to `.gitignore` and commit only `.gitignore`. | +| `pr-host` | `host`, `kind` (already saved by `POST /pr-host`) | -`reply` is the plain instruction the terminal would get, so it reads like any -answer. `__git` names no question, like `__stop`. - -**After an action**, in ONE post (with `--wait`): +**After an action**, ONE post with `--wait`: ```jsonc -{ "reread": true, - "items": [{ "id": "git-result", "kind": "notice", "status": "open", - "title": "Pushed 2 commits to origin/feature/x", - "body": "a1b2c3d, e4f5a6b. [Open pull request](https://github.com/...)" }], - "board": { "describe": "export-csv-button" } } +{"reread":true,"items":[{"id":"git-result","kind":"notice","title":"Pushed 2 commits to origin/feature/x","body":"a1b2c3d, e4f5a6b. [Open pull request](https://github.com/...)"}],"board":{"describe":"export-csv-button"}} ``` -- `reread` is `true`, or `{ "refreshFailed": true }` after a Refresh that - failed (the board then says so beside the last refreshed time and keeps the - last data). It goes only with the `git` workflow; anywhere else, or in any - other shape, it is exit `3`. The console takes the snapshot inside the same - locked write as your cards, so the result line and the fresh board land - together. -- `git-result` is a `notice` replaced every action (same id). The board shows - it under its header, not in the card slot: what happened, with short hashes - and, after a push or publish, the `pr-url` link. On a failure it quotes - git's stderr verbatim with `classify-error`'s `next`. -- `board.describe` is yours: a short kebab-case description of the changes - still on the tree, which the Create prompt pre-fills. Post it with the - reread whenever changes remain; leave it out otherwise. -- The board is the person's to click whenever you wait, so `wait` hands the - turn back by itself; no `agent` status is needed. +- `reread` is `true`, or `{"refreshFailed":true}` after a failed Refresh. Only with the `git` workflow, else exit 3. +- `git-result` is one `notice` replaced every action: what happened, short hashes, the `pr-url` link after a push or publish. A failure quotes git's stderr verbatim with `classify-error`'s `next`. +- `board.describe`: short kebab-case description of the changes still on the tree (prefills Create); leave out when none remain. -**Cards per `plan`.** `git.mjs plan ` decides whether to ask: +**Cards per `plan`** (`git.mjs plan `): | `plan` says | On the page | | --- | --- | -| `confirm` | A `confirm` card with its `title`, `body`, `danger` and `consequences` verbatim (the consequences end with the exact command). Where the plan names files, add them as `files: [{ "path", "state" }]`. | -| `card.kind: "switch"` | A `choice`, "Bring your changes?": exactly the `options` given, labeled **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); the files in `body`, and `reason` when git would refuse (then there is no `bring`). `allowOther: false`. | -| `card.kind: "dirty"` | The same `choice` for a pull that needs a clean tree: **Commit first** / **Cancel**, `reason` in `body`. | -| `card.kind: "remote"` | A `choice`, "Publish to which remote?": one option per remote, `preset` recommended. Then `plan publish --remote ` and its `confirm`. | -| `ask: false` | No card: run it on the click. | -| exit 4 or 5 | No card and nothing run: the `message` and `next` as the `git-result` notice. | +| `confirm` | `confirm` with `title`, `body`, `danger`, `consequences` verbatim; named files as `files:[{"path","state"}]`. | +| `card.kind:"switch"` | `choice` "Bring your changes?", exactly the given `options`: **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); files in `body`, `reason` when git refuses (no `bring` then). `allowOther:false`. | +| `card.kind:"dirty"` | Same `choice`, **Commit first** / **Cancel**, `reason` in `body`. | +| `card.kind:"remote"` | `choice` "Publish to which remote?", one option per remote, `preset` recommended; then `plan publish --remote ` and its `confirm`. | +| `ask:false` | No card: run on the click. | +| exit 4 or 5 | Nothing run: `message` and `next` as the `git-result` notice. | -An `auth` failure gets a `notice` card saying the tool never handles logins, -with `next`. The commit flow's own cards (message, groups, `git init`, -`.gitignore`) are the rows below. +An `auth` failure: a `notice` saying the tool never handles logins, with `next`. | Commit step | On the page | | --- | --- | -| One commit | A `text` card whose `placeholder` is the drafted subject and whose `pattern` caps it at 100 characters, then a `confirm` "Commit this?" with the files in `consequences` and, as `files: [{ "path": "src/a.js", "state": "modified" }]` (states: modified, new, deleted, renamed), a collapsed **Show the N files** table on the card. With the subject given as the argument there is no card. | -| A split | The groups as a doc (`id: "commits"`: each group's subject and files, and any file that mixes concerns) plus a `review` card with verdicts `approve`, `change` and `single` ("One commit instead"). Asked even when the subject came as the argument. | -| Push | Not asked after a commit on the board: the board lights Push. `commit and push` (or a Push click) asks `plan push` / `plan publish`'s `confirm`. | -| `git init` | A `confirm` naming the folder and its first branch (`init-check`'s `branch`, `danger: false`), its `consequences` `init-check`'s `commands`. Run those, not a bare `git init`. | -| `.gitignore` | The proposed file, or the lines a `commit`'s `ignore[]` adds, as a doc plus a `review` card. | +| One commit | `text` card, `placeholder` the drafted subject, `pattern` capping it at 100 characters, then `confirm` "Commit this?" with files in `consequences` and `files:[{"path","state"}]` (modified, new, deleted, renamed). No card when the subject was the argument. | +| A split | Doc `commits` (each group's subject and files, files mixing concerns) plus `review` with verdicts `approve`, `change`, `single` ("One commit instead"). Asked even with a subject argument. | +| Push | Not asked after a board commit (the board lights Push). `commit and push` or a Push click asks `plan push` / `plan publish`'s `confirm`. | +| `git init` | `confirm` naming folder and first branch (`init-check`'s `branch`, `danger:false`), `consequences` its `commands`. Run those, not a bare `git init`. | +| `.gitignore` | The proposed file, or a `commit`'s `ignore[]` lines, as a doc plus `review`. | -Risky files (`sensitive`, `large`) are named in the card's `body`. On the -board there is no branch-offer card: the commit panel's **You're on main** -line asks it, and the answer arrives as `create` with `then: "commit"`. +Risky files (`sensitive`, `large`) go in the card's `body`. There is no branch-offer card: the commit panel's **You're on main** asks, answered as `create` with `then:"commit"`. -**Conflict help.** A pull, rebase or merge stopped on conflicts asks first, a -`choice` "Resolve them for me?": **Yes**, **I'll fix it**, **Abort pull**. -On yes, every stop is a doc (`id: "conflict"`, replaced per stop, its version moving by itself: step N of M, -the commit being replayed, each file with a one-line reason, then a per-file -diff) plus a `review` card, fresh id per stop, `"nothingYet": false` (the resolution is already on disk), with the verdicts `continue` -("Continue"), `change` ("Change it") and `abort` ("Abort pull", `danger`). -Only **Continue** runs `plan continue`'s commands; **Abort pull** runs -`plan abort` and the board is back on the exact original HEAD. A file you -cannot resolve with confidence is named and left with its markers; **I'll fix -it** leaves the markers too. The board's banner always offers Continue: a -`continue` click is the person saying the files are fixed, so run `plan -continue`; when it refuses (exit 5, markers left), post a `reread` with its -`message` as the `git-result` notice, which also refreshes the banner's file -list. Nothing is pushed during conflict help. At the end, a `notice` -summary (commits replayed, each resolved file with its reason, "N commits -ready to push"). +**Conflict help.** A pull, rebase or merge stopped on conflicts: `choice` "Resolve them for me?": **Yes**, **I'll fix it**, **Abort pull**. On yes, each stop is doc `conflict` (replaced per stop: step N of M, the commit replayed, each file with a one-line reason, per-file diff) plus a `review` with a fresh id per stop, `"nothingYet":false`, verdicts `continue`, `change`, `abort` ("Abort pull", `danger`). Only **Continue** runs `plan continue`'s commands; **Abort pull** runs `plan abort`. A file you cannot resolve confidently keeps its markers, as does **I'll fix it**. A `continue` click from the board's banner means the files are fixed: run `plan continue`; on exit 5 (markers left) post a `reread` with its `message` as the `git-result`. End with a `notice` summary (commits replayed, each resolved file with its reason, "N commits ready to push"). -**Meter events** (`console-meter.md`). Git scores on launch. -Post `run: { "event": "git-commits", "id": "", "commits": N }` -after each commit step (N commits made), and `run: { "event": "git-conflict", -"id": "conflict-" }` once per conflict help, resolved or aborted. +**Meter.** Post `run:{"event":"git-commits","id":"","commits":N}` after each commit step, and `run:{"event":"git-conflict","id":"conflict-"}` once per conflict help. -**Finishing** (`console-finish.md`). **Done with git** (`op: "done"`). A `done` -that arrives while one of your cards is still open is the person canceling it: -record that card as canceled (`{ "items": [{ "id": "", "status": -"answered", "answer": { "text": "Canceled by Done with git" } }] }`, not -`settle`, which refuses a card nothing was sent to) in the same post as the -finish, or, with nothing done, before resuming as the dashboard. Never run what -the card was asking for. With something done this session: a `finish` with a -headline, the commits with hashes, pushes and branches created or deleted in -`body`, no `command`, and `"dashboard": true`; keep waiting for the press. Done -with nothing done: no finish screen — resume as `dashboard` at once (`open ---resume --no-open --workflow dashboard`), read the dashboard skill -(`~/.agents/skills/plan2code/SKILL.md`), post its `menu` with `--wait` and -carry on from its "Coming back from another skill". A stop's finish is a pause, -headline "Paused …", the bare `/plan2code-git`, then `stop`. +**Finishing.** **Done with git** is `op:"done"`. A `done` while one of your cards is open cancels it: record it `{"items":[{"id":"","status":"answered","answer":{"text":"Canceled by Done with git"}}]}` (not `settle`) in the finish post, or, with nothing done, before resuming as the dashboard. Never run what that card asked. Something done: `finish` with a headline and the commits (hashes), pushes and branches created or deleted in `body`, no `command`, `"dashboard":true`. Nothing done: no finish screen; resume as `dashboard` (`open --resume --no-open --workflow dashboard`), read `~/.agents/skills/plan2code/SKILL.md`, post its `menu` with `--wait`, carry on from "Coming back from another skill". A stop's finish is a pause, "Paused ...", bare `/plan2code-git`. diff --git a/src/web-console/notes/handoff.md b/src/web-console/notes/handoff.md index 539e9c0..3f53d5e 100644 --- a/src/web-console/notes/handoff.md +++ b/src/web-console/notes/handoff.md @@ -1,11 +1,3 @@ -# Handoff on the Web Console +# Handoff -Workflow notes for `handoff`, part of the web console contract (`console.md`). - -One gate: the next-task confirmation, then the document itself as a doc — -that is what the person is there to download. Give it no `saved` and paste it -as `md`: the handoff file lives in `~/.plan2code/handoffs/`, outside the project, -where a `file` block is refused, and the download is the point. The finish carries no -`command`: the doc download is the point, and the dashboard button and the -"All done" line cover what comes next. Unless it is a pause, the finish carries -`"dashboard": true` and you keep waiting for the press (`console-finish.md`). +One gate (next-task confirmation), then the document as a doc with `md`, no `saved` (the file lives outside the project, where a `file` block is refused). The finish has no `command`; unless it is a pause it carries `"dashboard":true`. diff --git a/src/web-console/notes/implement.md b/src/web-console/notes/implement.md index a80596e..76c7f73 100644 --- a/src/web-console/notes/implement.md +++ b/src/web-console/notes/implement.md @@ -1,193 +1,63 @@ -# Implement on the Web Console +# Implement -Workflow notes for `implement` and `implement-review`, part of the web console -contract (`console.md`). Read `building.md` first. +`implement` and `implement-review`. Read `building.md` first. -## The first post of a phase +## First post of a phase ```jsonc -{ - "headline": { "stage": "Phase 3: API layer", "cleared": 0, "total": 9 }, - "docs": [ - { "id": "phase", "title": "Phase 3 tasks", "blocks": [ - { "id": "tasks", "file": "specs//phase-3.md", "select": "tasks" } - ]}, - { "id": "phasefile", "title": "phase-3.md", "blocks": [ - { "id": "body", "file": "specs//phase-3.md" } - ]} - ], - "agent": { "status": "working", "activity": "Checking the prerequisites", "quietMinutes": 15 } -} +{"headline":{"stage":"Phase 3: API layer","cleared":0,"total":9},"docs":[{"id":"phase","title":"Phase 3 tasks","blocks":[{"id":"tasks","file":"specs//phase-3.md","select":"tasks"}]},{"id":"phasefile","title":"phase-3.md","blocks":[{"id":"body","file":"specs//phase-3.md"}]}],"agent":{"status":"working","activity":"Checking the prerequisites","quietMinutes":15}} ``` -`phase` is the task list, `phasefile` the whole `phase-X.md` as its own tab — -the person can read the prerequisites and task specs while you build. Both are -read from disk by the console: never paste the file. It renders as markdown, so -the file's checkboxes show as ticks exactly as they stand on disk. - -A later phase in the same session posts the same two docs with the new phase's -title and file: their content changed, so their versions move up by themselves -(a doc's version never goes back, and you no longer have to track it). Leave -`version` out. +`phase` is the task list, `phasefile` the whole file. A later phase posts the same two docs with the new title and file. ## After every task -In the same breath as writing the task's checkbox to disk: +With the checkbox write: ```jsonc -{ - "headline": { "cleared": 4 }, - "docs": [ { "id": "phase", "refresh": true }, { "id": "phasefile", "refresh": true } ], - "agent": { "activity": "Task 5 of 9: the rate limiter" } -} +{"headline":{"cleared":4},"docs":[{"id":"phase","refresh":true},{"id":"phasefile","refresh":true}],"agent":{"activity":"Task 5 of 9: the rate limiter"}} ``` -`refresh` re-reads the file the checkbox write just changed, so both tabs tick -in place; the Phase Completion Summary lands in `phasefile` the same way at the -end. Then the `chat` check (`building.md` → Quick questions between tasks). - ---- +The Phase Completion Summary lands in `phasefile` the same way. Then the `chat` check. ## Sign-off -Put the Completion Report on the page as a doc, then ask for approval as a -`review` item pointing at it. The review offer rides on this card, as a verdict -ahead of the approval buttons — not on the finish after it, where it could -only ever be offered once nothing could come of it: +Loop mode (`notes/loop.md`) posts `loopOutcome` instead. Otherwise the Completion Report is a doc and the approval a `review` pointing at it; the review offer is a verdict here, not on the finish: ```jsonc -{ - "docs": [{ "id": "report", "title": "Completion report", "blocks": [ - { "id": "summary", "state": "settled", "md": "## Summary\n\n..." }, - { "id": "files", "state": "settled", "md": "## Files\n\n..." }, - { "id": "verify", "state": "settled", "md": "## How to check it\n\n..." } - ]}], - "items": [{ - "id": "signoff", "kind": "review", "title": "Approve this phase", "doc": "report", - "body": "Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.", - "verdicts": [ - { "id": "review", "label": "Review the code first" }, - { "id": "approve", "label": "Approve this phase" }, - { "id": "show", "label": "Show me it working" }, - { "id": "changes", "label": "I want changes" } - ], - "token": { "approve": "approved", "changes": "needs changes", "show": "show me" }, - "nothingYet": "Nothing is marked complete until you approve.", - "gate": { "id": "signoff", "authoritative": true } - }] -} +{"docs":[{"id":"report","title":"Completion report","blocks":[{"id":"summary","state":"settled","md":"## Summary\n\n..."},{"id":"files","state":"settled","md":"## Files\n\n..."},{"id":"verify","state":"settled","md":"## How to check it\n\n..."}]}],"items":[{"id":"signoff","kind":"review","title":"Approve this phase","doc":"report","body":"Phase 3 is built. Read the report, try the checks, then approve it, review the code first, see it running, or say what to change.","verdicts":[{"id":"review","label":"Review the code first"},{"id":"approve","label":"Approve this phase"},{"id":"show","label":"Show me it working"},{"id":"changes","label":"I want changes"}],"token":{"approve":"approved","changes":"needs changes","show":"show me"},"nothingYet":"Nothing is marked complete until you approve.","gate":{"id":"signoff","authoritative":true}}]} ``` -Posted with `--wait`. `reply` carries `Approve this phase: approved`, which is -the terminal's `approved`. If the note that came with an approval asks for a -change, treat it as "describe any issues": do the change first and ask again. -`changes` means exactly what it says: address it, update the report, and reopen -the item (`"status": "reopened"`) with a reply in its `thread`. `review` is the -person asking for the code review before they approve anything — read -`building-review.md`. `show` is the terminal's `show me`: see below. +Posted with `--wait`. An approval whose note asks for a change: do the change first and ask again. `changes`: address it, update the report, reopen the item with a `thread` reply. `review`: read `building-review.md`. `show`: below. + +A later phase in the same session asks with a new id (`signoff-phase-2`, title "Approve Phase 2"); the old card is a record. ### Show me it working -On `show`, run the workflow's **Show me it working** paragraph (start the app, -look at the change, stop it, one summary line in `phase-X.md`). Save each -screenshot under the session's `shots/` folder, never under `specs/`, and post -them as image blocks in a `shown` doc (`console.md` → Documents), with what was -run in a `md` block above them; no browser tool means that block alone says -what the command printed. Then reopen the same card (`"status": "reopened"`) -without the `show` verdict, a `thread` reply naming what was seen. The same -holds on Finalize's card and the one `building-review.md` reopens; Quick -Task's card is settled instead (`notes/quick-task.md`). - -`gate` marks the one approval that counts. The server refuses a second open -authoritative gate, which is what keeps a composed workflow from asking for -sign-off twice. A later phase in the same session asks with a new id -(`signoff-phase-2`, its title naming the phase, "Approve Phase 2", so the rail tells -the two apart), since the last phase's approved card is a record: the same -id posted again would only edit that record. - ---- +On `show`, run the workflow's **Show me it working** paragraph. Save screenshots under the session's `shots/`, never `specs/`, and post them as image blocks in a `shown` doc with what was run in a `md` block above (no browser tool: that block alone says what the command printed). Then reopen the same card without the `show` verdict, with a `thread` reply naming what was seen. Same on Finalize's card and the one `building-review.md` reopens; Quick Task's card is settled instead. ## After approval: the finish -Do everything the workflow does on approval (the checkboxes, the summary, the -upcoming phases, the commit command) and print it in the terminal as usual. -Then post the finish, wait for the dashboard button as `console-finish.md` -says, and `stop`: +Do what the workflow does on approval and print it in the terminal as usual, then: ```jsonc -{ - "settle": true, - "run": { "event": "implement-phase", "id": "phase-3", "tasks": 9 }, - "finish": { - "headline": "Phase 3 is done", - "body": "9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```", - "command": "/plan2code-3-implement specs/lunch-vote/overview.md", - "doc": "report", - "commit": true, - "dashboard": true - } -} +{"settle":true,"run":{"event":"implement-phase","id":"phase-3","tasks":9},"finish":{"headline":"Phase 3 is done","body":"9 of 9 tasks, all on disk.\n\n| Phase | Tasks | Goal |\n| --- | --- | --- |\n| Phase 4: ... | 6 | ... |\n\nCommit it with:\n\n```\ngit add -A && git commit -m \"...\" -m \"AI Assisted\"\n```","command":"/plan2code-3-implement specs/lunch-vote/overview.md","doc":"report","commit":true,"dashboard":true}} ``` -`"commit": true` is there because the body prints a git command: the finished -screen gets a **Commit it now** button, and its `__commit` press is handled as -`console-finish.md` says (resume as `git` and open its commit flow, same -session). Leave it out when the body prints no commit. +`commit:true` only when the body prints a commit. `command` is the next step: `/plan2code-3-implement specs//overview.md`, or `/plan2code-4-finalize specs//overview.md` after the last phase. No `review` on the finish. -`finish.command` is the next pipeline step, the same one the terminal names: -the next `/plan2code-3-implement specs//overview.md`, or -`/plan2code-4-finalize specs//overview.md` after the last phase. An `implement` finish never carries `review`: the offer was on the -sign-off card, and approving past it was the answer. `implement-review` ends -the same way; that phase was reviewed already. - -`run` gives the approved phase its final score on the session meter -(`console-meter.md`), in the same post that records the approval; it takes over -what the build already counted from `cleared`, never adds to it: -`implement-phase` for Implement, `implement-review-phase` for Implement + -Review, id `phase-N`, and `tasks`: how many of the phase's tasks were -completed (`[x]`, not blocked `[!]`). The phase scores by its size, so a -twelve-task phase weighs four times a three-task one; leave `tasks` out and -every phase weighs the same. A review run on the page after a build reports its -own (`building-review.md`). - ---- +`run` takes over what `cleared` counted, never adds: `implement-phase` (Implement) or `implement-review-phase` (Implement + Review), id `phase-N`, `tasks` the completed ones (`[x]`, not `[!]`); without `tasks` every phase weighs the same. ## Manual check-off (`next.action` is `checkoff`) -No phase to build: the open tasks under approved phases are asked about one -at a time, one `confirm` item each, posted with `--wait`: +Open tasks under approved phases, one `confirm` each, `--wait`: ```jsonc -{ - "headline": { "stage": "Manual check-off", "cleared": 0, "total": 2 }, - "items": [{ - "id": "checkoff-3.4", "kind": "confirm", "title": "Task 3.4", - "body": "**Configure the SSO app in Okta**\n\nBLOCKED: needs admin access. User action: create the app and paste its client id into `.env`.\n\nIs this done?", - "yesLabel": "Done, check it off", "noLabel": "Not yet" - }] -} +{"headline":{"stage":"Manual check-off","cleared":0,"total":2},"items":[{"id":"checkoff-3.4","kind":"confirm","title":"Task 3.4","body":"**Configure the SSO app in Okta**\n\nBLOCKED: needs admin access.\n\nIs this done?","yesLabel":"Done, check it off","noLabel":"Not yet"}]} ``` -`yes` → `specs.mjs tick`, then `"headline": { "cleared": N }` with the next -item. When the last one is answered, post the finish: `command` is -`/plan2code-4-finalize specs//overview.md` when `tick` said -`remaining` is empty, otherwise the same `/plan2code-3-implement` command, -and `body` lists what is still open. No `run` (nothing was built), no -`commit` unless a body prints one. - ---- +Yes: `specs.mjs tick`, `{"headline":{"cleared":N}}` with the next item. After the last: finish with `command` `/plan2code-4-finalize specs//overview.md` when `tick` said `remaining` is empty, else `/plan2code-3-implement ...`; `body` lists what is open. No `run`, no `commit` unless the body prints one. ## Implement + Review (`implement-review`) -The same build, then Stage 2 publishes the findings exactly as -`building-review.md` → The findings (the `review` doc and the `fixes` item). -Stage 3 fixes, with no "Check the fixes" item: Stage 4 is the only gate. The -post that starts Stage 2's review carries `"run": { "event": "review", "id": -"review" }`: in this workflow it scores the review stage's 1 point on the meter -as it begins, and the phase's final `run` leaves that point out. Stage 4 is the -sign-off above (`show` included) **without the review verdict** — the phase was already reviewed -— with the review results and unresolved findings in the report doc, header -"Reviewed and ready for sign-off" in the item's `body`. The finish never -carries `review`, and its post carries `"run": { "event": -"implement-review-phase", "id": "phase-N", "tasks": N }` with the count of -completed tasks. +Stage 2 publishes findings as in `building-review.md` (The findings). Stage 3 has no "Check the fixes" item. The post starting Stage 2 carries `"run":{"event":"review","id":"review"}` (scores 1 point; the final `run` leaves it out). Stage 4 is the sign-off above, `show` included, without the `review` verdict, with review results and unresolved findings in the report and "Reviewed and ready for sign-off" in `body`. Its finish `run` is `implement-review-phase`. diff --git a/src/web-console/notes/init.md b/src/web-console/notes/init.md index d3fae60..9364d92 100644 --- a/src/web-console/notes/init.md +++ b/src/web-console/notes/init.md @@ -1,14 +1,3 @@ -# Init and Init Update on the Web Console +# Init and Init Update -Workflow notes for `init` and `init-update`, part of the web console contract -(`console.md`). - -Setup conversations: every confirmation and Q&A item goes through the page. -For `init` and `init-update` the finished AGENTS.md also lands as a doc so a -browser-only person can read what was written — marked `"saved": "AGENTS.md"`, -since the file itself is already on disk (or as a `file` block: -`{ "id": "body", "file": "AGENTS.md" }`, instead of pasting it). A completed run -finishes with **no** `command`: the page shows the "All done" line. Nothing is -on disk to resume mid-run, so a stop's finish command is the bare -`/plan2code-init` or `/plan2code-init-update` — the skill starts over -either way. +Post the finished AGENTS.md as a doc (`"saved":"AGENTS.md"` or a `file` block). A completed run finishes with no `command`; a stop's is the bare `/plan2code-init` or `/plan2code-init-update`. diff --git a/src/web-console/notes/loop.md b/src/web-console/notes/loop.md new file mode 100644 index 0000000..7939bc7 --- /dev/null +++ b/src/web-console/notes/loop.md @@ -0,0 +1,168 @@ +# Loop Mode on the Web Console + +Workflow notes for Implement and Implement + Review started by the desktop app's +Implementation Loop with `--loop`, part of the web console contract +(`console.md`). Read `building.md` and `notes/implement.md` first: this note says +only where loop mode differs. The app judges the result, so you report and never +approve. + +## Flags + +- `--loop`: this run is one phase of an unattended loop. The skill's first step + already ran a plain `open`; run it again now, before any post, as + `node "" open --workflow --spec specs/ --loop`. + Inside the app it resumes the app's session and locks the page; without it, + `loopOutcome` and `handledBy` are refused. If it exits 3, the run is not inside + the app: say "Loop mode runs only inside the Plan2Code desktop app." in the + terminal and continue as an ordinary run with the person's sign-off. Skip + nothing below unless that `open` succeeded. +- `--fix `: a comma list from `critical`, `warning`, `suggestion`, the + levels to fix in the one fix round. Absent means findings are reported, not + fixed. +- `--fix smart`: Smart pick. A triage step chooses which findings to fix, in + place of a level list (see Triage). The one fix round and the fresh re-check + are unchanged. +- `--guess`: when a task needs a decision the spec does not make, take the best + guess, mark the task `[?]` with a one-line note as an indented line right under + it in the phase file (` - Assumed: what you chose and why`), and carry on. The + app copies that note into the person's report. Without `--guess`, ask the question as an ordinary open card + (see Questions and cards). + +## What changes in loop mode + +- Pick the phase without asking (Choosing the phase). +- No sign-off card, no "Approve this phase", no Show me it working, no Continue + offer. +- Never run `specs.mjs mark --to done`, and never set `[x]` on the phase in + `overview.md`. Tasks inside the phase file are still checked off as they + finish: `[x]`, `[!]` when blocked, `[?]` when assumed. +- Never run `git` in any form (no add, commit, stash, checkout), and never + `commit-msg.mjs`. +- No Stop-with-handoff, no `__dashboard`, no finish screen: the app ends the + session. +- Where the prompt would stop and ask, report instead of posting a card: + - A spec conflict: list it in `conflicts`, report `failed`, reason `conflict`. + - A blocked prerequisite or task: mark the task `[!]`, list it in + `tasks.blocked`, report `failed`, reason `blocked`. + - Failing tests: try one fix, then report `tests.passed: false`, `failed`, + reason `tests`. Never post the Fix now, Document or Investigate options. + - A waiting `**Plan change:**` line in the phase's Notes: do not ask Revise + first or Resume; report `failed`, reason `other`, and say so in `summary`. +- Run only the tests the phase file names, as the Implement prompt's tests rule + says: a phase task or a task's `Test:` line (a `## Phase Testing` block counts + when it lists them as tasks). Never the full suite unless the phase file names it. + +## Headline stages + +Post `headline.stage` as each begins, using only these words: `Build`, `Review`, +`Fixes`, `Re-check`, `Reporting`. The app's strip reads them, and any other word +shows as Build, so do not invent new ones in loop mode. Keep `cleared` and +`total` as in any build. + +## Choosing the phase + +Run `node "/specs.mjs" status specs/`. A phase whose checklist marker +is `[/]` goes first; otherwise take `next.phase.number` (the first of +`next.options` when `next.action` is `choose`). Never post the "Resume?" question +or the parallel-phase pick. Set the phase in progress with +`specs.mjs mark --phase N --to in-progress`, exactly as an ordinary run +does: that mark is allowed, and only `--to done` is the app's. When `next.action` +is `none` or `checkoff` (no open phase), post a `loopOutcome` with +`result: "failed"`, `reason: "other"` and +`summary: "No open phase left in this spec"`. + +## Questions and cards the loop handles + +- A real question (a decision the spec does not make, without `--guess`) is an + ordinary open card, waited on with `post --wait` as usual. The app sees it open + and holds or stops the loop. Do not mark it `handledBy`. +- The review stage's findings pick and the fix confirmation are answered by this + run itself from `--fix` (with `--fix smart`, from the triage). Post them for the record as settled items with + `"handledBy": "loop"` and the answer filled in, so the page shows "The loop + handles this", for example + `{ "id": "fixes", "kind": "multi", "title": "Which to fix", "options": [ ... ], "status": "answered", "answer": { "ks": ["1", "2"] }, "handledBy": "loop" }`. +- Ask (chat) questions do not arrive while the loop drives. If one does, answer + it briefly as usual. + +## Review, one fix round and the re-check + +Implement + Review only. Run the review as `building-review.md` describes. Fix +only the findings at the `--fix` levels, in one round. Then start one fresh +reviewer helper (a new subagent with no memory of the fix round, or a fresh read +when helpers are off) that re-checks only the fixes: each finding at a chosen +level is fixed, and nothing new was introduced. Count what is left, by level, +after the re-check. Suggestions left or newly found on the re-check are listed +but never fail the phase. Do not run a second fix round. + +## Triage (`--fix smart`) + +Implement + Review only, after the review lists its findings and before the fix +round. Start one fresh triage helper (a new subagent with no memory of the build +or the review, or a fresh read when helpers are off). Its brief holds the +findings, the phase's tasks in `phase-X.md` and the project's `AGENTS.md`. For +each finding it answers `fix` or `skip` with one line of reason, at most 200 +characters. Skip is for a finding that is not real once the code is read, is +outside this phase's tasks, contradicts `AGENTS.md` or the spec, or asks for a +change out of proportion to the gain. Every skip carries a reason. + +The app stops the phase on any skipped Critical, so the triage must not skip a +Critical it merely dislikes: skip one only when it is plainly not a defect, and +say why. Post the triage's answers for the record as the settled `fixes` item (its `ks` are the findings marked `fix`, posted before the fix round) +(`handledBy: "loop"`), with one `thread` entry per skip carrying its reason. + +Then run the one fix round on the findings marked `fix`, and the fresh re-check +of only those fixes, as above. `left` counts the picked findings still open after +the re-check. Smart pick always reports `triage.ran: true` and `review.recheck: true`, even when no finding was raised or none was picked (an empty re-check). The triage runs under the `Review` stage; the stage words do not +change. + +## Reporting the outcome + +At the end of the run, post once a top-level `loopOutcome`: + +```json +{ "loopOutcome": { + "phase": 2, "result": "passed", "reason": null, + "summary": "Built the setup screen; 6 of 6 tasks", + "tests": { "ran": true, "passed": true, "summary": "14 pass" }, + "decisions": ["Kept the old /votes route so existing callers still work"], + "review": { "ran": true, "recheck": true, + "fixed": [ { "level": "warning", "title": "Close the file handle", "file": "src/z.js" } ], + "triage": { "ran": true, "skipped": [ { "level": "warning", "title": "Rename the helper", "file": "src/y.js", "reason": "Outside this phase's tasks" } ] }, + "left": { "critical": 0, "warning": 0, "suggestion": 2 }, + "unfixed": [ { "level": "suggestion", "title": "Name the timer", "file": "src/x.js" } ] }, + "tasks": { "blocked": [], "assumed": ["2.4"] }, + "conflicts": [], + "subject": "Add the loop setup screen" } } +``` + +- `result` is `"passed"` only when every task is `[x]` (or `[?]` with `--guess`), + the named tests pass, and, with review, no Critical or Warning is left at a + chosen level (every level in Smart pick) after the re-check, and, in Smart pick, + the triage skipped no Critical (otherwise `failed`, reason `findings`). Otherwise `"failed"`, with the first matching + `reason`: `tests`, `findings`, `blocked`, `conflict` or `other`. A passed + outcome has `"reason": null`. +- `review.triage` is present only with `--fix smart`: `ran: true` and `skipped` listing + every skipped finding with its reason (an empty list when nothing was skipped). + A picked Critical or Warning still left after the re-check fails the phase with + reason `findings`. `unfixed` lists only picked findings still open after the + re-check; skipped findings go only in `triage.skipped` (the app adds them to the + summary), and the 50-entry limits of the two lists are separate. +- `review.fixed` lists every finding the fix round fixed (an empty list when none, + or with no review), at most 50. +- `decisions` lists, at most 50, one line of at most 200 characters each, every + other judgment call this run made on the person's behalf that the spec did not + settle and the `Assumed:` notes do not already cover: a library or approach + chosen between real options, scope left out or added, a behavior changed outside + the task. The person reads these to check the work, so say what you chose and + why, and leave nothing out because it seems small. Do not list the routine steps + of building. An empty list means you made none. +- `review.ran` and `review.recheck` are `false` when the run did no review or no + re-check (plain Implement, or no `--fix` level; never with `--fix smart`). `tasks.blocked` and + `tasks.assumed` list task ids like `"2.4"`. `conflicts` holds one line per + spec conflict. +- `subject` is one imperative line under 100 characters saying what changed (it + becomes the commit subject). `summary` is one line under 200 characters. + +Then post `{"agent":{"status":"waiting"}}` and keep waiting with the usual +bounded `wait` slices until the app ends the session. Never end the turn on text. +If the post is refused (exit 3), fix the field it names and post again. diff --git a/src/web-console/notes/pathfinder.md b/src/web-console/notes/pathfinder.md index 0fcd718..3eca751 100644 --- a/src/web-console/notes/pathfinder.md +++ b/src/web-console/notes/pathfinder.md @@ -1,77 +1,26 @@ -# Pathfinder on the Web Console +# Pathfinder -Workflow notes for `pathfinder`, part of the web console contract (`console.md`). - -- Every probe, recap and menu goes through the page. -- Post `"stopWarning"` while no map exists (Steps 0 to 4) and `"stopWarning": ""` - once it does, and `"specDir": "specs/"` when the folder is created - (`console-stop.md` → Saying what stopping would cost). -- The menu after a decision is a `menu` card: its `options` are `trail --form C`'s, and the `Start fresh` one keeps its `"fresh": true` (the page words it "Start New Session" under the desktop app and asks the app for one on Send). Set the card's `command` to the resume command printed under `OR START FRESH`: the page copies it first. A declined confirm leaves you the pick: carry on as for any `Start fresh`. -- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one. -- A doc that is a file exactly as written (the map once it is on disk, a - brief) goes up as a `file` block (`{ "id": "body", "file": - "specs//pathfinder/map.md" }`) rather than pasted. Keep `md` blocks - where a block's `assumed` / `draft` state carries meaning. -- Chart Step 8's research subagents must all report back before the - finish (`console-finish.md` → Nothing of yours may still be running); the - finish body then names what each one found. -- Report every research subagent as a helper, whatever the Subagents switch - says (`console-subagents.md` → Reporting helpers). -- At every session end, post `finish` (headline, `body`, and Form A's command as - `command`) BEFORE `stop`. Someone who spent the session in the browser never - sees the Trail Footer, and without this their last screen promises a question - that is never coming. -- Post `run` `pathfinder-chart` (id `map`) when a new map is first written, - and `pathfinder-research` (id = the question's file slug; on `github`, `q`) as each research - subagent reports back, or when you resolve a `research` question yourself - (`console-meter.md`). Other questions score through their answers, so there is - nothing to post for them. -- The scope probe is **Leave for later**: "Which of these features are we - leaving out this time?" as a `multi` with a recommended preset. Every option - names a feature, and its `detail` ends "(Leaving this out = …)". Never phrase - an option as a rule to keep. +- Post `"stopWarning"` while no map exists (Steps 0 to 4), `""` once it does, and `"specDir":"specs/"` when the folder is created. +- The menu after a decision is a `menu` card: `options` are `trail --form C`'s, the `Start fresh` one keeps `"fresh":true`. Set the card's `command` to the resume command printed under `OR START FRESH`. A declined confirm leaves you the pick: carry on as for `Start fresh`. +- The fresh-idea card carries `"templates":"idea"`, `"fill":"note"`. +- A doc that is a file as written (the map, a brief) is a `file` block (`{"id":"body","file":"specs//pathfinder/map.md"}`). Keep `md` where `assumed` / `draft` state matters. +- Step 8 research subagents all report before the finish; the finish `body` names what each found. Report every one as a helper, whatever the Subagents switch says. +- Every session end `finish`es with Form A's command as `command`. +- Post `run` `pathfinder-chart` (id `map`) when a map is first written, and `pathfinder-research` (id the question's file slug; on `github`, `q`) as each research subagent reports or when you resolve a `research` question yourself. Other questions score through answers. +- The scope probe is **Leave for later**: "Which of these features are we leaving out this time?" as a `multi` with a recommended preset. Each option names a feature, its `detail` ends "(Leaving this out = ...)". Never phrase an option as a rule to keep. ## Briefs -The page shows a **Write a brief** button when `workflow` is `pathfinder`, -because that is the workflow with a brief playbook. The person picks a range and -presses it; nothing else about the session changes. - -It arrives through the wait loop like any other send: +The page shows **Write a brief** for this workflow. It arrives as a send: ```jsonc -{ - "type": "submit", - "actions": [{ "i": "__brief", "type": "brief", "range": "since 2026-09-15" }], - "reply": "Write a brief covering everything since 2026-09-15." -} +{"reply":"Write a brief covering everything since 2026-09-15.","session":[{"i":"__brief","range":"since 2026-09-15"}]} ``` -`range` is one of `today`, `this week`, `since ` or `full`, which is -the range grammar the brief playbook already parses. `reply` says the same thing -in words, so a workflow that only reads `reply` needs no new code path. The -`__brief` id is not an item and matches nothing; it marks the action as being -about the session rather than about a question. - -Run your normal brief procedure, write the file where it belongs, and then put -the same report on the page as a doc, as a `file` block on the file you wrote: +`range` is `today`, `this week`, `since ` or `full`. `__brief` matches no item. Run your brief procedure, write the file, then post it as one `file` block in doc `brief` (reused, so a second replaces the first; Save as HTML appears only on that id): ```jsonc -{ - "docs": [{ - "id": "brief", - "title": "Brief", - "note": "Covers this week", - "blocks": [{ "id": "body", "file": "specs//pathfinder/briefs/.md" }] - }] -} +{"docs":[{"id":"brief","title":"Brief","note":"Covers this week","blocks":[{"id":"body","file":"specs//pathfinder/briefs/.md"}]}]} ``` -One block holding the whole report is right here: a brief is read start to -finish, not block by block, and it gets Save as HTML, Print and Download buttons -that work on the document as a whole. Save as HTML appears only on the doc with -the id `brief`. Reuse the id `brief` so a second brief replaces the first -rather than growing a row of tabs; its version moves up by itself. - -Say in chat where the file went, as you always would. The page is a second copy -for reading and printing, never the record. +Say in chat where the file went. diff --git a/src/web-console/notes/plan.md b/src/web-console/notes/plan.md index 9ddb6fd..91ae9c8 100644 --- a/src/web-console/notes/plan.md +++ b/src/web-console/notes/plan.md @@ -1,22 +1,6 @@ -# Planning on the Web Console +# Planning -Workflow notes for `plan`, part of the web console contract (`console.md`). - -- Open with `--workflow plan`, first thing. Every question and sign-off gate - goes through the page, phase breakdowns as an editable `list`. -- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one. -- Planning has no mid-session save before the Large checkpoint or Phase 7, so for - a stop before then say plainly in `finish.body` that nothing was kept, and use - `"command": "/plan2code-1-plan"`. After the checkpoint, post - `"stopWarning": ""` (`console-stop.md`). -- At every session end, post `finish` BEFORE `stop`; on completion that is - `"command": "/plan2code-2-document"`, and at the Large checkpoint it is - `/plan2code-1-plan`. The closing message is printed to a terminal the - browser user is not watching. -- The Large checkpoint finish is a pause: a headline starting "Paused", no - `dashboard`, and `stop` at once. -- Plan offers the Subagents switch. A `Subagents:` block may arrive on `open` - output or a `wait` / `chat` pickup: follow `console-subagents.md` and the - skill's Helpers section, and report each helper as `helpers`. Post a helper - as `done` or `failed` before the sign-off it feeds, and every one before a - `finish`. Questions, sign-offs and the PLAN-DRAFT stay with you. +- Phase breakdowns are an editable `list`. The fresh-idea card carries `"templates":"idea"`, `"fill":"note"`. +- Nothing is saved before the Large checkpoint or Phase 7: a stop before then has `finish.body` say nothing was kept, `"command":"/plan2code-1-plan"`. After the checkpoint post `"stopWarning":""`. +- Completion finish `command`: `/plan2code-2-document`. The Large checkpoint finish is a pause: headline starts "Paused", `command` `/plan2code-1-plan`, no `dashboard`. +- Helpers are reported as `helpers`, each `done` or `failed` before the sign-off it feeds. Questions, sign-offs and the PLAN-DRAFT stay with you. diff --git a/src/web-console/notes/quick-task.md b/src/web-console/notes/quick-task.md index e6148ad..b641379 100644 --- a/src/web-console/notes/quick-task.md +++ b/src/web-console/notes/quick-task.md @@ -1,106 +1,34 @@ -# Quick Task on the Web Console +# Quick Task -Workflow notes for `quick-task`, part of the web console contract -(`console.md`). Read `building.md` first. +Read `building.md` first. -## Quick task (`quick-task`) - -- Open with the first clarifying question. Clarifying questions go out as - `text` or `choice`, at most three at a time. The first, asking what to build, - carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one. -- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."` - at the start, and `"stopWarning": ""` once the build is under way. -- **Scope check:** a `choice`, "Too big for a quick task?", options - `1` Continue (lightweight format) and `2` Escalate to a full plan, with the - measured counts against the thresholds in `body`. -- **Feature name** (escalating): `text` with - `"pattern": "^[a-z0-9]+(-[a-z0-9]+)*$"` and a kebab-case placeholder. -- **The plan:** a `plan` doc titled "Plan", one block per section, with the - Steps written as a checklist so the build can tick them in place, and a - `review` item "Build this plan?" (`"doc": "plan"`) with verdicts `yes` - ("Build it"), `modify` ("Change the plan"), `escalate` ("Plan it properly - instead") and `abort` ("Stop here", `"danger": true`): +- Clarifying questions are `text` or `choice`. The first (what to build) carries `"templates":"idea"`, `"fill":"note"`. +- Post `"stopWarning":"A quick task saves nothing until it is built, so stopping now loses what we have worked out."` at the start and `""` once the build is under way. +- **Scope check:** `choice` "Too big for a quick task?": `1` Continue (lightweight format), `2` Escalate to a full plan; measured counts against thresholds in `body`. +- **Feature name** (escalating): `text`, `"pattern":"^[a-z0-9]+(-[a-z0-9]+)*$"`, kebab-case placeholder. +- **The plan:** doc `plan`, one block per section, Steps as a checklist, plus `review` "Build this plan?" (`"doc":"plan"`) with verdicts `yes` ("Build it"), `modify` ("Change the plan"), `escalate` ("Plan it properly instead"), `abort` ("Stop here", `danger`): ```jsonc - { "id": "plan", "title": "Plan", "blocks": [ - { "id": "summary", "state": "settled", "md": "## Summary\n\n..." }, - { "id": "files", "state": "settled", "md": "## Files to change\n\n- `src/a.ts` - ..." }, - { "id": "steps", "state": "settled", "md": "## Steps\n\n- [ ] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" }, - { "id": "verify", "state": "settled", "md": "## Verify\n\n- [ ] ..." } - ]} + {"id":"plan","title":"Plan","blocks":[{"id":"summary","state":"settled","md":"## Summary\n\n..."},{"id":"files","state":"settled","md":"## Files to change\n\n- `src/a.ts` - ..."},{"id":"steps","state":"settled","md":"## Steps\n\n- [ ] **1.** Step one\n- [ ] **2.** Step two"},{"id":"verify","state":"settled","md":"## Verify\n\n- [ ] ..."}]} ``` - A `modify` reposts the changed blocks, Steps still a checklist; the version - moves up by itself. -- **Building** after `yes`: the Plan tab is the build's live task list, the - way an Implement phase has its tasks tab. There is no separate progress tab. - Settle the verdict (`"settle": true`) in the post that starts the build; the - plan's steps are the tasks and `total` is their number: + A `modify` reposts the changed blocks. +- **Building** after `yes`: the Plan tab is the live task list; steps are the tasks. Settle the verdict in the post that starts it: ```jsonc - { - "stopWarning": "", - "settle": true, - "headline": { "stage": "Building", "cleared": 0, "total": 4 }, - "agent": { "status": "working", "activity": "Task 1 of 4: step one", "quietMinutes": 10 } - } + {"stopWarning":"","settle":true,"headline":{"stage":"Building","cleared":0,"total":4},"agent":{"status":"working","activity":"Task 1 of 4: step one","quietMinutes":10}} ``` - Then post after every step, as `building.md` → While you build says, in the - same breath as finishing it: repost the plan's `steps` block alone (blocks - merge by id, so Summary, Files and Verify stay as they are) with that step - ticked; raise `headline.cleared`; set `agent.activity` to the next step - ("Task 2 of 4: step two"). The plan lives only on the page, so this block is - `md`, not `file`: + After each step (`building.md` → While you build), repost the `steps` block alone, as `md` since the plan lives only on the page: ```jsonc - { - "headline": { "cleared": 1 }, - "docs": [{ "id": "plan", "blocks": [ - { "id": "steps", "state": "settled", "md": "## Steps\n\n- [x] **1.** Step one\n- [ ] **2.** Step two\n- [ ] **3.** Step three\n- [ ] **4.** Step four" } - ]}], - "agent": { "activity": "Task 2 of 4: step two" } - } + {"headline":{"cleared":1},"docs":[{"id":"plan","blocks":[{"id":"steps","state":"settled","md":"## Steps\n\n- [x] **1.** Step one\n- [ ] **2.** Step two"}]}],"agent":{"activity":"Task 2 of 4: step two"}} ``` - A step that cannot be done is `- [!]` with the reason after it, and is not - counted in `cleared`. A step added mid-build goes into the list and raises - `headline.total` in the same post. Tick each step the moment it is done, - never in a batch at the end: the person is watching the Plan tab fill in. - Check for a Quick question between steps, and do not call `wait` until the - build is done. Tick the Verify block's boxes too as the checks pass, in the - post that reports them. -- **See it running, before the finish:** a finished screen freezes every open - card, so ask first. Once the build is done, post a `review` item "See it - running" (`"doc": "plan"`, verdicts `show` ("Show me it working") and `fine` - ("No need, finish up"), token `show me` / `no`) with `--wait`. On `show`, run - it as `notes/implement.md` → Show me it working says, its one line going into - the work summary (the finish's `body`); then, or on `fine`, settle the card in - the same post as the finish. -- **Archive a fixed bug, before the finish:** launched on a diagnosed folder - and now Fixed with nothing past the diagnosis, post a `confirm` card - "Archive this bug?" in the same post as "See it running": the dry run's - `files` in `body`, `yesLabel` "Archive it", `noLabel` "Keep it in specs/", - and `consequences` naming `specs--completed//`. On yes, run - `node "/specs.mjs" archive ` (the skill file says where `` is), - and say where it went in the finish's `body`. On no, the - dashboard lists the folder as "Bug fixed", never pre-selected. -- **The finish after the build:** `command` is the commit command, filled in, - in the project's commit format (AGENTS.md), with - `"where": "When you are happy with it, commit it from your terminal:"`, and - `review` on offer — the **Review it now** button, since a quick task has no - sign-off card to put it on — `"commit": true` (the **Commit it now** button; - `console-finish.md`), `"changelog": true` (**Update CHANGELOG first**, beside - it; it hops into Changelog and on to Git) and `"dashboard": true`, so the finished screen - also offers **Back to the dashboard**. Review and dashboard are required: a finish without - `dashboard` leaves the person on a dead end. Keep waiting for whichever - button is pressed, and everything after that is `building-review.md`. -- **Escalated / aborted:** settle the verdict the same way in the finish post — - finish with `"command": "/plan2code-1-plan"` and the - PLAN-DRAFT's path in `body`, no review; or `"command": "/plan2code-quick-task"`. - Both set `"dashboard": true`: an abort of a quick task saves nothing to - resume, so it is not a pause. + A step that cannot be done is `- [!]` with the reason, not counted in `cleared`. A step added mid-build raises `headline.total` in the same post. Tick Verify boxes in the post that reports the checks. Do not `wait` until the build is done. +- **See it running, before the finish:** once built, post `review` "See it running" (`"doc":"plan"`, verdicts `show` ("Show me it working"), `fine` ("No need, finish up"), tokens `show me` / `no`) with `--wait`. On `show`, see `notes/implement.md` → Show me it working; its one line goes in the finish `body`. Settle the card in the finish post. +- **Archive a fixed bug:** launched on a diagnosed folder and now Fixed with nothing past the diagnosis, post `confirm` "Archive this bug?" in the same post as "See it running": dry run's `files` in `body`, `yesLabel` "Archive it", `noLabel` "Keep it in specs/", `consequences` naming `specs--completed//`. Yes: `node "/specs.mjs" archive `, and say where it went in the finish `body`. +- **Finish after the build:** `command` is the filled-in commit command in the project's format (AGENTS.md), `"where":"When you are happy with it, commit it from your terminal:"`, with `review` (**Review it now**), `"commit":true`, `"changelog":true` and `"dashboard":true`. Review and dashboard are required. Whichever button is pressed, what follows is `building-review.md`. +- **Escalated / aborted:** settle the verdict in the finish post: `"command":"/plan2code-1-plan"` with the PLAN-DRAFT's path in `body`, no review; or `"command":"/plan2code-quick-task"`. Both `"dashboard":true`. -## Stop requests during a build - -See `building.md` → Stop requests during a build. +Stop requests during a build: `building.md`. diff --git a/src/web-console/notes/review.md b/src/web-console/notes/review.md index 94f9045..76863c6 100644 --- a/src/web-console/notes/review.md +++ b/src/web-console/notes/review.md @@ -1,34 +1,9 @@ -# Review on the Web Console +# Review -Workflow notes for `review`, part of the web console contract (`console.md`). -A review run from a build's review button stays in the build's session, under -its workflow: `building-review.md` governs it instead. +Standalone with nothing named: first a `choice` "What should I review?" from a quick scan (branch changes, uncommitted changes, specs, files you name; each with its size). A build's review skips it. Launched from the dashboard: `open --resume --no-open --workflow review`. Post `activity` while you read. -Scope questions up front — run standalone with nothing named, the first is -a `choice`, "What should I review?", built from a quick scan (branch changes, -uncommitted changes, specs, files you name; each option with its size), -never an assumed target; a build's review skips it (`building-review.md`). Then the -findings report as a doc (`id: "report"`), then the pick-what-gets-fixed menu -as a `multi` or `choice` keyed by finding id, carrying `"doc": "report"` so the -card links straight to the findings. Settle that item (`"settle": true`) in the -same post that takes the picks up: left open it stays on the page as a question -still owed, next to whatever you ask next. Post `activity` while you read — a -real review is long stretches of you working, and the page should say so rather -than hint at questions. +Findings are doc `report`; the fix menu is a `multi` or `choice` keyed by finding id with `"doc":"report"`, settled (`"settle":true`) in the post that takes the picks up. -When the session was launched from the dashboard, resume the session you were -handed (`open --resume --no-open --workflow review`), never a fresh -`open`. +Closing gate: `review` "Check the fixes", `"doc":"report"`, `"nothingYet":false`, verdicts `approve`, `changes`. -Review Mode's closing gate ("Reply approved to commit, or request changes") -is a `review` item titled "Check the fixes", `doc: "report"`, `"nothingYet": -false` (the fixes are already on disk), verdicts `approve` and `changes`. - -On completion the finish's `command` is the suggested commit when fixes -landed — filled in, in the AGENTS.md format, with -`"where": "When you are happy with it, commit it from your terminal:"` — -otherwise leave `command` out; with one, `"commit": true` puts **Commit it -now** beside it. The completion finish carries `"dashboard": true` -so the finished screen offers **Back to the dashboard**; keep waiting for the -press. A stop mid-review loses nothing on disk, so its finish is the bare -`/plan2code-review` (a pause, so no dashboard button). +Completion finish: `command` is the suggested commit when fixes landed (AGENTS.md format, `"where":"When you are happy with it, commit it from your terminal:"`, `"commit":true`), else none; `"dashboard":true`. A stop's `command` is the bare `/plan2code-review`, no dashboard. diff --git a/src/web-console/notes/revise-plan.md b/src/web-console/notes/revise-plan.md index 59c073b..c29a346 100644 --- a/src/web-console/notes/revise-plan.md +++ b/src/web-console/notes/revise-plan.md @@ -1,26 +1,12 @@ -# Revision on the Web Console +# Revision -Workflow notes for `revise-plan`, part of the web console contract (`console.md`). - -Revision is a short run of gates, and each maps onto a kind you already know: - -| Step | On the page | +| Step | Card | | --- | --- | -| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. With none waiting, the first card is a `text` item titled "What should change", `"fill": "note"`, asking what to change; its answer feeds the "Is this the change?" recap. | -| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." | -| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. | -| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. | +| 1, Change Analysis | `recap` "Is this the change?", affected-areas table in `summary`. A waiting `**Plan change:**` brief is quoted atop `summary` and no "what should change" card goes first; with none, the first card is `text` "What should change", `"fill":"note"`. | +| 2, Impact | Doc `impact`, plus `review` "Approve the spec changes": verdicts `approve`, `refine`, `abort` (`danger`), `nothingYet` "No spec file changes until you approve." | +| 3 to 5 | Nothing to ask: `activity` while you edit, then the Revision Complete summary as a doc. | +| 6, Cleanup | `confirm` per rename or removal, paths in `consequences`. | -Revision's own rule holds on the page too: **no option, verdict or label ever -offers to execute or implement.** Pass `--spec specs/` to `open`, or -post `specDir` once you know it. The finish command is -`/plan2code-3-implement specs//overview.md`; an abort's is -`/plan2code-1b-revise-plan specs//overview.md`. +No option, verdict, label, or helper `title`, `ask` or `result` ever offers to execute or implement. Pass `--spec specs/` to `open` or post `specDir`. Finish `command`: `/plan2code-3-implement specs//overview.md`; abort: `/plan2code-1b-revise-plan specs//overview.md`. -Revision offers the Subagents switch. A `Subagents:` block may arrive on -`open` output or a `wait` / `chat` pickup: follow `console-subagents.md` and -the skill's Helpers section, and report each helper as `helpers`. Lookup -helpers report back before the Step 2 review item goes up; phase-file helpers -report back before the Step 4 check. Every gate stays with you, and a helper's -`title`, `ask` and `result` follow the same rule as every label: nothing -offers to execute or implement. +Helpers: lookup helpers report before the Step 2 review goes up; phase-file helpers before the Step 4 check. diff --git a/src/web-console/notes/xray.md b/src/web-console/notes/xray.md index 77e1cd0..74c64c6 100644 --- a/src/web-console/notes/xray.md +++ b/src/web-console/notes/xray.md @@ -1,73 +1,37 @@ -# X-ray on the Web Console - -Workflow notes for `xray`, part of the web console contract (`console.md`). +# X-ray ## The mode question -A typed argument that names the mode and area skips it. Otherwise ask both in -one batch, posted with `--wait`: +An argument naming mode and area skips it. Otherwise one `--wait` batch: ```jsonc -{ - "title": "Codebase X-ray", - "headline": { "stage": "Choosing", "cleared": 0, "total": 2 }, - "items": [ - { "id": "mode", "kind": "choice", "title": "What you want to know", "allowOther": false, - "body": "Explain one area, or rank what makes this code hard to change.", - "options": [ - { "k": "1", "text": "Explain an area", "detail": "How it works and why it is that way, citing files and the commits behind it." }, - { "k": "2", "text": "Find the rough spots", "detail": "Ranked spots that make change hard. You pick the ones worth fixing; they become a brief for Pathfinder or Plan." } - ] }, - { "id": "area", "kind": "text", "title": "Which area", "required": false, - "body": "A folder, file or feature. Needed to explain; leave it empty to survey the whole repository.", - "placeholder": "src/exporter, the code that builds the CSV reports" } - ] -} +{"title":"Codebase X-ray","headline":{"stage":"Choosing","cleared":0,"total":2},"items":[{"id":"mode","kind":"choice","title":"What you want to know","allowOther":false,"body":"Explain one area, or rank what makes this code hard to change.","options":[{"text":"Explain an area","detail":"How it works and why, citing files and commits."},{"text":"Find the rough spots","detail":"Ranked spots that make change hard. You pick the ones worth fixing; they become a brief for Pathfinder or Plan."}]},{"id":"area","kind":"text","title":"Which area","required":false,"body":"A folder, file or feature. Needed to explain; empty surveys the whole repository."}]} ``` -Explain picked with the area left empty: ask for it again as a required `text` -card. No recommendation on the mode: only the person knows what they came for. +Explain with the area empty: ask again as a required `text`. ## Explain mode -The answer is a doc, `id` `"answer"`, one block per section (`In one paragraph`, -`How it works`, `Why it is this way`, `Worth knowing`), with the `Sources:` line -at the top of the first. Then the save offer as a `confirm` card pointing at it: +Doc `answer`, one block per section (`In one paragraph`, `How it works`, `Why it is this way`, `Worth knowing`), `Sources:` line atop the first. Then: ```jsonc -{ "id": "keep", "kind": "confirm", "title": "Keep this answer", "doc": "answer", - "body": "Save it as `specs/exporter/XRAY-exporter-20261016.md`, as input for Pathfinder or Plan?", - "yesLabel": "Save it", "noLabel": "No, just reading" } +{"id":"keep","kind":"confirm","title":"Keep this answer","doc":"answer","body":"Save it as `specs/exporter/XRAY-exporter-20261016.md`, as input for Pathfinder or Plan?","yesLabel":"Save it","noLabel":"No, just reading"} ``` -Ask the folder name in the same batch as a `text` card with `pattern` -`^[a-z0-9]+(-[a-z0-9]+)*$` when it is not obvious. Once written, re-send the doc -with `"saved": "specs//XRAY--.md"`. +When the folder name is not obvious, ask it in the same batch as a `text` with `pattern` `^[a-z0-9]+(-[a-z0-9]+)*$`. Once written, re-send the doc with `"saved":"specs//XRAY--.md"`. ## Rough-spots mode -The ranked list is a doc, `id` `"spots"`, one block per spot (its files, why it -hurts, the "to change X today" example). The pick is one `multi` card pointing -at it, posted with `--wait`: +Doc `spots`, one block per spot (files, why it hurts, the "to change X today" example). Pick, `--wait`: ```jsonc -{ "id": "pick", "kind": "multi", "title": "Worth fixing", "doc": "spots", "required": false, - "body": "Tick the spots worth fixing. Add a note for any of them in the box (\"1: the exporter part only\"). Only ticked spots go into the brief.", - "options": [ - { "k": "1", "text": "Exporter and its formatter always change together", "detail": "src/export.ts, src/format.ts: together in 14 of 16 commits." } - ] } +{"id":"pick","kind":"multi","title":"Worth fixing","doc":"spots","required":false,"body":"Tick the spots worth fixing. Only ticked spots go into the brief.","options":[{"text":"Exporter and its formatter always change together"}]} ``` -Nothing ticked: nothing is written. Otherwise write the brief, then add it as a -second doc with `"saved": "specs//ARCHITECTURE-BRIEF-.md"` and a -`file` block. +Nothing ticked: nothing written. Otherwise write the brief and add it as a second doc with `"saved":"specs//ARCHITECTURE-BRIEF-.md"` and a `file` block. ## The finish -`command` is `/plan2code-0-pathfinder` (big or unclear) or `/plan2code-1-plan` -(settled), never with a placeholder; leave it out when nothing was kept. `doc` -is the brief or the saved answer when there is one. `"dashboard": true`, then -keep waiting for the press (`console-finish.md`). +`command` is `/plan2code-0-pathfinder` (big or unclear) or `/plan2code-1-plan` (settled); none when nothing was kept. `doc` is the brief or saved answer. `"dashboard":true`. -A stop before anything was written ends on a finish whose `body` says nothing -was kept, with `"command": "/plan2code-xray"` (`console-stop.md`). +A stop before anything was written: `body` says nothing was kept, `"command":"/plan2code-xray"`. diff --git a/src/web-console/patches.mjs b/src/web-console/patches.mjs index 2ac8c8f..4e51512 100644 --- a/src/web-console/patches.mjs +++ b/src/web-console/patches.mjs @@ -15,10 +15,24 @@ export function isPlainObject(v) { return v !== null && typeof v === "object" && !Array.isArray(v); } +/** + * One form for every refusal, so a retry can be written from the message alone: + * `item "q2" options: . Like this: ` for a + * card, `finish: . Like this: ...` for the rest. `where` is the + * thing named (`item "q2"`, `doc "report"`), or "" for a top-level field; + * `right` is a value, written as minified JSON, and left out when there is no + * sensible example. + */ +export function rule(where, field, wrong, right) { + const head = [where, field].filter(Boolean).join(" "); + const text = String(wrong).replace(/\.\s*$/, ""); + return `${head}: ${text}.${right === undefined ? "" : ` Like this: ${JSON.stringify(right)}`}`; +} + // Reject prototype-pollution attempts before they reach the merge. function guard(obj, where) { if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, "__proto__")) { - throw new Error(`"__proto__" is not a valid key (in ${where})`); + throw new Error(rule("", where, '"__proto__" is not a valid key')); } return obj; } @@ -40,7 +54,7 @@ function mergeKeyed(current, patchList, idKey, defaults, where) { for (const entry of patchList) { guard(entry, where); const id = entry[idKey]; - if (!id) throw new Error(`every ${where} entry needs "${idKey}"`); + if (!id) throw new Error(rule("", where, `every entry needs "${idKey}"`, { [idKey]: where === "items" ? "q7" : "a1" })); const i = out.findIndex((x) => x[idKey] === id); if (entry._delete) { if (i !== -1) out.splice(i, 1); @@ -50,6 +64,16 @@ function mergeKeyed(current, patchList, idKey, defaults, where) { return out; } +// Every default the console fills, so a patch leaves these out (overview.md, +// Data Model; the card in console.md lists the same ones, keep the two in step): +// new item status "open", required true, allowOther true, options [], thread [] +// new doc version 1, stale false, blocks [] (DOC_DEFAULTS, below) +// a block's state: the page reads a missing one as "settled" +// a review item's verdicts: the page offers approve / changes when it has none +// option k: "A", "B", "C"... by position, when no option of the item has +// one (letterOptions(), below) +// Not defaulted, by choice: a topic's status, and `settle: true` on every post +// (it would close a pick that still owes its recap). const ITEM_DEFAULTS = { status: "open", required: true, @@ -58,6 +82,36 @@ const ITEM_DEFAULTS = { thread: [], }; +// A, B, C... Z, then AA, AB... by position. +function optionKey(i) { + return i < 26 ? String.fromCharCode(65 + i) : String.fromCharCode(64 + Math.floor(i / 26)) + String.fromCharCode(65 + (i % 26)); +} + +/** + * Give the options a patch sends their keys by position when none has one. + * Every option keyed is left alone; some keyed and some not is refused, naming + * the item. Only the options in this patch: stored ones are never re-lettered. + */ +function letterOptions(patchList) { + return patchList.map((entry) => { + if (!isPlainObject(entry) || !entry.id || !Array.isArray(entry.options) || !entry.options.length) return entry; + if (!entry.options.every(isPlainObject)) return entry; + const keyed = entry.options.filter((o) => o.k != null && o.k !== "").length; + if (keyed === entry.options.length) return entry; + if (keyed > 0) { + throw new Error( + rule( + `item "${entry.id}"`, + "options", + 'some options have "k" and some do not. Give every option a "k", or none to have them lettered A, B, C', + { options: [{ text: "CSV" }, { text: "Excel" }] }, + ), + ); + } + return { ...entry, options: entry.options.map((o, i) => ({ ...o, k: optionKey(i) })) }; + }); +} + // The question a card asks. If a patch rewrites any of these on a known id, it // is a new question wearing an old id. const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"]; @@ -73,6 +127,28 @@ function dropStaleSubmissions(currentItems, before, patchList) { const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items"); for (const entry of patchList) { const prev = (before || []).find((x) => x.id === entry.id); + // A whole new question under an answered card's id is not a typo fix: the + // card would stay answered and nothing would be left for the person, who + // sees a dead page. Refuse it so the agent picks a new id on the spot. + if ( + prev && + (prev.status === "answered" || prev.status === "skipped") && + !("status" in entry) && + !("answer" in entry) && + "title" in entry && + entry.title !== prev.title && + (("body" in entry && entry.body !== prev.body) || + ("options" in entry && JSON.stringify(entry.options) !== JSON.stringify(prev.options))) + ) { + throw new Error( + rule( + `item "${entry.id}"`, + "id", + `was already used for the answered question "${prev.title}", so this new question ("${entry.title}") would stay answered and the person would see nothing to answer. Give it a new id, or set status to "reopened" to ask the old one again`, + { id: "q12", kind: entry.kind || prev.kind, title: entry.title }, + ), + ); + } if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue; const rewritten = QUESTION_FIELDS.some( (f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]), @@ -111,24 +187,23 @@ function dropStaleSubmissions(currentItems, before, patchList) { // at all is refused. The person's own notes are recorded by the server when // they send, so an agent that echoes one back is not shown it twice. const THREAD_TEXT_KEYS = ["text", "md", "body", "content"]; +const THREAD_RIGHT = { thread: [{ who: "agent", text: "..." }] }; function normalizeThreads(patchList, currentItems) { return patchList.map((entry) => { if (!isPlainObject(entry) || entry.thread == null) return entry; - if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`); + if (!Array.isArray(entry.thread)) throw new Error(rule(`item "${entry.id}"`, "thread", "must be an array", THREAD_RIGHT)); const prev = (currentItems || []).find((x) => x && x.id === entry.id); const said = new Set( ((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()), ); const thread = []; for (const m of entry.thread) { - if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`); + if (!isPlainObject(m)) throw new Error(rule(`item "${entry.id}"`, "thread", "entries must be objects", THREAD_RIGHT)); guard(m, "thread"); const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim()); if (!key) { - throw new Error( - `item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "" }; the page shows nothing else.`, - ); + throw new Error(rule(`item "${entry.id}"`, "thread", 'an entry has no "text"; the page shows nothing else', THREAD_RIGHT)); } const { from, role, md, body, content, ...rest } = m; const who = (m.who || from || role) === "user" ? "user" : "agent"; @@ -153,8 +228,12 @@ function mergeDocs(current, patchList) { const prev = (current || []).find((d) => d && d.id === entry.id); if (prev && typeof prev.version === "number" && entry.version < prev.version) { throw new Error( - `doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` + - "Versions only go up: bump it, and check the payload is the current one." + rule( + `doc "${entry.id}"`, + "version", + `the page is at version ${prev.version}; this patch sends ${entry.version}. Versions only go up: leave it out, or bump it, and check the payload is the current one`, + { version: prev.version + 1 }, + ), ); } } @@ -186,7 +265,7 @@ function mergeDocs(current, patchList) { function settleItems(items, settle, patchItems, collected) { if (settle === undefined || settle === false) return items; if (settle !== true && !(Array.isArray(settle) && settle.every((id) => typeof id === "string"))) { - throw new Error('"settle" must be true or a list of item ids'); + throw new Error(rule("", "settle", "must be true or a list of item ids", { settle: ["q2"] })); } const sent = (items || []).filter((i) => i && i.submitted && typeof i.submitted === "object"); let ids; @@ -202,7 +281,7 @@ function settleItems(items, settle, patchItems, collected) { // The same patch reopening it has already let go of what was sent; the // reopen wins below, so naming it is not an error. const reopening = (patchItems || []).some((e) => e && e.id === id && (e.status === "open" || e.status === "reopened")); - if (!reopening && !sent.some((i) => i.id === id)) throw new Error(`settle: "${id}" has nothing sent to settle`); + if (!reopening && !sent.some((i) => i.id === id)) throw new Error(rule("", "settle", `"${id}" has nothing sent to settle`, { settle: true })); } ids = settle; } @@ -267,14 +346,16 @@ export function resolveDocFiles(patch, state, worktree) { if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch; const root = path.resolve(worktree || state.worktree || process.cwd()); const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p); - const read = (file, select, docId) => { - if (typeof file !== "string" || !file.trim()) throw new Error(`doc "${docId}": a block's "file" must be a path`); + const FILE_RIGHT = { id: "b4", file: "specs//overview.md" }; + const read = (file, select, docId, blockId) => { + const bad = (wrong) => new Error(rule(`doc "${docId}" block "${blockId}"`, "file", wrong, FILE_RIGHT)); + if (typeof file !== "string" || !file.trim()) throw bad("must be a path"); const abs = path.resolve(root, file); let real; try { real = fs.realpathSync.native(abs); } catch { - throw new Error(`doc "${docId}": no file at ${file}`); + throw bad(`no file at ${file}`); } const rootReal = (() => { try { @@ -286,15 +367,15 @@ export function resolveDocFiles(patch, state, worktree) { // path.relative, not a prefix test: a worktree at a drive root ends in a // separator already, and win32's relative() folds case itself. const rel = path.relative(fold(rootReal), fold(real)); - if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`doc "${docId}": ${file} is outside the project`); + if (rel.startsWith("..") || path.isAbsolute(rel)) throw bad(`${file} is outside the project`); const stat = fs.statSync(real); - if (!stat.isFile()) throw new Error(`doc "${docId}": ${file} is not a file`); - if (stat.size > DOC_FILE_MAX) throw new Error(`doc "${docId}": ${file} is larger than ${DOC_FILE_MAX / 1024} KB`); + if (!stat.isFile()) throw bad(`${file} is not a file`); + if (stat.size > DOC_FILE_MAX) throw bad(`${file} is larger than ${DOC_FILE_MAX / 1024} KB`); const text = fs.readFileSync(real, "utf8").replace(/\r\n/g, "\n"); if (select === undefined) return text; - if (select !== "tasks") throw new Error(`doc "${docId}": "select" only takes "tasks"`); + if (select !== "tasks") throw new Error(rule(`doc "${docId}" block "${blockId}"`, "select", 'only takes "tasks"', { id: blockId, file, select: "tasks" })); const tasks = text.split("\n").filter((l) => TASK_LINE_RE.test(l)).map((l) => l.trim()); - if (!tasks.length) throw new Error(`doc "${docId}": ${file} has no task lines to select`); + if (!tasks.length) throw new Error(rule(`doc "${docId}" block "${blockId}"`, "select", `${file} has no task lines to select`, { id: blockId, file })); return tasks.join("\n"); }; const docs = patch.docs.map((entry) => { @@ -307,9 +388,9 @@ export function resolveDocFiles(patch, state, worktree) { const again = ((prev && prev.blocks) || []) .filter((b) => b && typeof b.file === "string" && !named.has(b.id)) .map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) })); - if (!again.length && !blocks) throw new Error(`doc "${entry.id}": "refresh" found no file blocks to re-read`); + if (!again.length && !blocks) throw new Error(rule(`doc "${entry.id}"`, "refresh", "found no file blocks to re-read", { id: entry.id, blocks: [FILE_RIGHT] })); blocks = [...(blocks || []), ...again]; - } else if (refresh !== undefined) throw new Error(`doc "${entry.id}": "refresh" must be true`); + } else if (refresh !== undefined) throw new Error(rule(`doc "${entry.id}"`, "refresh", "must be true", { id: entry.id, refresh: true })); if (!blocks) return rest; const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || []; return { @@ -325,7 +406,7 @@ export function resolveDocFiles(patch, state, worktree) { // A file named again without `select` is the whole file, now and on // every refresh: an older select must not linger in the merge. const select = "select" in b ? b.select : null; - return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id) }; + return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id, b.id) }; }), }; }); @@ -358,14 +439,16 @@ export function resolveDocImages(patch, state, dir) { if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch; const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p); const shotsDir = path.join(path.resolve(dir), SHOTS_DIR_NAME); - const check = (image, docId) => { - if (typeof image !== "string" || !image.trim()) throw new Error(`doc "${docId}": an image block's "image" must be a path`); - const where = `doc "${docId}": image ${image}`; + const IMAGE_RIGHT = { id: "b5", image: "shots/run.png", alt: "..." }; + const check = (image, docId, blockId) => { + const at = `doc "${docId}" block "${blockId}"`; + if (typeof image !== "string" || !image.trim()) throw new Error(rule(at, "image", "must be a path", IMAGE_RIGHT)); + const bad = (wrong) => new Error(rule(at, "image", `${image} ${wrong}`, IMAGE_RIGHT)); let real; try { real = fs.realpathSync.native(path.resolve(dir, image)); } catch { - throw new Error(`${where} does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first.`); + throw bad(`does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first`); } let realShots; try { @@ -375,15 +458,15 @@ export function resolveDocImages(patch, state, dir) { } const name = path.basename(real); if (fold(path.dirname(real)) !== fold(realShots)) { - throw new Error(`${where} is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown.`); + throw bad(`is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown`); } - if (!SHOT_NAME.test(name)) throw new Error(`${where}: name it with letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp`); + if (!SHOT_NAME.test(name)) throw bad("needs a plain name: letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp"); const stat = fs.statSync(real); - if (!stat.isFile()) throw new Error(`${where} is not a file`); - if (stat.size > SHOT_MAX) throw new Error(`${where} is larger than ${SHOT_MAX / 1024 / 1024} MB`); + if (!stat.isFile()) throw bad("is not a file"); + if (stat.size > SHOT_MAX) throw bad(`is larger than ${SHOT_MAX / 1024 / 1024} MB`); const ext = path.extname(name).slice(1).toLowerCase(); const want = ext === "jpg" ? "jpeg" : ext; - if (shotType(fs.readFileSync(real)) !== want) throw new Error(`${where} is not a ${want.toUpperCase()} image (its bytes say otherwise)`); + if (shotType(fs.readFileSync(real)) !== want) throw bad(`is not a ${want.toUpperCase()} image (its bytes say otherwise)`); return `${SHOTS_DIR_NAME}/${name}`; }; const docs = patch.docs.map((entry) => { @@ -399,10 +482,10 @@ export function resolveDocImages(patch, state, dir) { return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b; } if (("md" in b && b.md != null) || ("file" in b && b.file != null)) { - throw new Error(`doc "${entry.id}": block "${b.id}" is an image; it cannot also carry "md" or "file"`); + throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "image", 'an image block cannot also carry "md" or "file"', IMAGE_RIGHT)); } - if (b.alt != null && typeof b.alt !== "string") throw new Error(`doc "${entry.id}": block "${b.id}" "alt" must be text`); - return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id), md: null, file: null }; + if (b.alt != null && typeof b.alt !== "string") throw new Error(rule(`doc "${entry.id}" block "${b.id}"`, "alt", "must be text", IMAGE_RIGHT)); + return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id, b.id), md: null, file: null }; }), }; }); @@ -418,12 +501,18 @@ export function resolveDocImages(patch, state, dir) { * back into the agent's context on every turn, and the state grows with the * session. */ +const HELPERS_RIGHT = { helpers: [{ id: "h1", title: "Read the plan", ask: "Summarize the plan", state: "running" }] }; +const CHAT_RIGHT = { chat: { replies: [{ re: 12, md: "..." }] } }; + export function applyPatch(state, patch) { guard(patch, "patch"); patch = liftActivity(patch); const { settle, ...rest } = patch; patch = rest; const next = { ...state }; + // `loop` is the page lock and the in-app gate: only `open` (--loop) sets or + // clears it, never a patch. + if (Object.hasOwn(patch, "loop")) throw new Error(rule("", "loop", "is set by open --loop, not by a patch")); for (const [k, v] of Object.entries(patch)) { if (v === null) { delete next[k]; @@ -435,18 +524,18 @@ export function applyPatch(state, patch) { next[k] = mergeOne(next[k], v, k); break; case "items": - if (!Array.isArray(v)) throw new Error('"items" must be an array'); - next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items)); + if (!Array.isArray(v)) throw new Error(rule("", "items", "must be an array", { items: [{ id: "q7", kind: "text", title: "Name" }] })); + next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(letterOptions(v), state.items)); break; case "topics": - if (!Array.isArray(v)) throw new Error('"topics" must be an array'); + if (!Array.isArray(v)) throw new Error(rule("", "topics", "must be an array", { topics: [{ id: "t2", title: "How it behaves", status: "current" }] })); next.topics = mergeKeyed(next.topics, v, "id", {}, "topics"); break; case "helpers": // The agent's report of its helpers, for the page's Subagents tab. // Only `post` writes it; the server's /submit never touches it. - if (!Array.isArray(v)) throw new Error('"helpers" must be an array'); - if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }'); + if (!Array.isArray(v)) throw new Error(rule("", "helpers", "must be an array", HELPERS_RIGHT)); + if (!v.every(isPlainObject)) throw new Error(rule("", "helpers", "entries must be objects, each { id, title, ask, state }", HELPERS_RIGHT)); next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers"); // A real helper report supersedes the working-alone marker, whether it // arrives after one or beside one. @@ -454,19 +543,19 @@ export function applyPatch(state, patch) { next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true)); break; case "docs": - if (!Array.isArray(v)) throw new Error('"docs" must be an array'); + if (!Array.isArray(v)) throw new Error(rule("", "docs", "must be an array", { docs: [{ id: "report", title: "Report", blocks: [{ id: "b1", md: "..." }] }] })); next.docs = mergeDocs(next.docs, v); break; case "chat": { // The agent's side of the Quick question chat. The person's side is // the inbox, which only the server writes; nothing else lives here. - if (!isPlainObject(v)) throw new Error('"chat" must be an object'); + if (!isPlainObject(v)) throw new Error(rule("", "chat", "must be an object", CHAT_RIGHT)); guard(v, "chat"); const extra = Object.keys(v).filter((key) => key !== "replies"); - if (extra.length) throw new Error(`"chat" only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`); + if (extra.length) throw new Error(rule("", "chat", `only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`, CHAT_RIGHT)); const chat = { ...(next.chat || {}) }; if (v.replies != null) { - if (!Array.isArray(v.replies)) throw new Error('"chat.replies" must be an array'); + if (!Array.isArray(v.replies)) throw new Error(rule("", "chat.replies", "must be an array", CHAT_RIGHT)); // A reply with no id is named for the message it answers (`r`), // so a repeat delivery re-posted the same way replaces, never doubles. const named = v.replies.map((r) => @@ -477,11 +566,28 @@ export function applyPatch(state, patch) { next.chat = chat; break; } + case "loopOutcome": + // The skill's one report of a phase built under the loop. The shape is + // checked by validate(); here only who may send it, and how often. + if (!state.loop?.driving) throw new Error(rule("", "loopOutcome", "is only accepted in a loop session")); + if (state.loopOutcome !== undefined) throw new Error(rule("", "loopOutcome", "was already posted for this session")); + next.loopOutcome = v; + break; + case "loopEnd": + // The app's word on how the loop ended; a later one replaces the earlier. + next.loopEnd = v; + break; default: next[k] = v; } } if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected); + // A question put to the person over a standing ending means the work went + // on past it: the finish card would grey the form out, and the person has + // no way to answer. The ending comes down unless this patch posts its own. + if (next.finish && !Object.hasOwn(patch, "finish") && asksSomething(patch.items, state.items)) { + delete next.finish; + } return stampTimes(state, settleAgent(next, patch, state)); } @@ -570,105 +676,154 @@ const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1, // reaches state.json (a post's `run` / `folderIssue`). Problems as sentences. export function proseProblems(prose, subject = "text") { const problems = []; - if (FORBIDDEN_TOKENS.test(prose)) { - problems.push(`${subject} contains a loop completion marker (${prose.match(FORBIDDEN_TOKENS)[0]}); the loop scans for these`); - } - if (METRICS_BAIT.test(prose)) { + const marker = prose.match(FORBIDDEN_TOKENS); + if (marker) { problems.push( - `${subject} contains "${prose.match(METRICS_BAIT)[0]}" — the metrics collector scrapes that pattern. ` + - `Hyphenate it (Requirements-clarity 22/25) or reword.` + rule("", subject, `contains a loop completion marker (${marker[0]}); the loop scans for these. Reword it`, marker[0].toLowerCase().replaceAll("_", " ")), + ); + } + const bait = prose.match(METRICS_BAIT); + if (bait) { + problems.push( + rule("", subject, `contains ${JSON.stringify(bait[0])}; the metrics collector scrapes that pattern. Hyphenate it or reword`, `${bait[1]}-score ${bait[0].match(/\d+$/)[0]}`), ); } return problems; } +// Every string under a value, with where it sits: `${base}` then .key and [i] +// steps, so a scan can say which field an offending word is in. +function walkStrings(value, base, visit) { + if (typeof value === "string") visit(value, base); + else if (Array.isArray(value)) value.forEach((v, i) => walkStrings(v, `${base}[${i}]`, visit)); + else if (isPlainObject(value)) for (const [k, v] of Object.entries(value)) walkStrings(v, base ? `${base}.${k}` : k, visit); +} + export const MAX_OPEN_REQUIRED = 3; +const OPTIONS_RIGHT = { options: [{ text: "CSV" }, { text: "Excel" }] }; +const OPTION_RIGHT = { text: "CSV", detail: "Opens in any spreadsheet" }; +const VERDICTS_RIGHT = { + verdicts: [ + { id: "approve", label: "Approve" }, + { id: "changes", label: "Request changes" }, + ], +}; +const TITLE_RIGHT = { title: "Export format" }; +const FINISH_RIGHT = { finish: { headline: "Paused: waiting on you", command: "/plan2code-1-plan" } }; +const HELPER_RIGHT = { helpers: [{ id: "h1", title: "Read the plan", ask: "Summarize the plan", state: "running" }] }; + +// `problem` with the field done right appended, for a message that came from +// shared code (public/subagents.js) and has no example of its own. +const likeThis = (problem, right) => rule("", "", problem, right).replace(/^: /, ""); + /** * Validate a merged state before it is written. * - * Returns an array of human-readable problems. An empty array means the patch - * is good. These checks turn four prose rules into mechanical ones. + * Returns an array of human-readable problems, each in rule()'s form: the item + * or field it is about, what is wrong, and the field done right. An empty array + * means the patch is good. These checks turn four prose rules into mechanical + * ones. */ export function validate(state) { const problems = []; - if (!Array.isArray(state.items)) return ['"items" must be an array']; + if (!Array.isArray(state.items)) { + return [rule("", "items", "must be an array", { items: [{ id: "q7", kind: "text", title: "Name" }] })]; + } const ids = new Set(); for (const item of state.items) { - if (!item.id) problems.push("every item needs an id"); - if (ids.has(item.id)) problems.push(`duplicate item id "${item.id}"`); + const at = `item "${item.id}"`; + if (!item.id) problems.push(rule("", "items", 'an entry has no "id". Every new question gets a new id', { id: "q7" })); + if (ids.has(item.id)) problems.push(rule(at, "id", "is used twice. Every new question gets a new id", { id: "q8" })); ids.add(item.id); if (!ITEM_KINDS.has(item.kind)) { - problems.push(`item "${item.id}" has unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`); + problems.push(rule(at, "kind", `unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`, { kind: "choice" })); } if (typeof item.title !== "string" || !item.title.trim()) { - problems.push(`item "${item.id}" needs a plain-English title`); + problems.push(rule(at, "title", "needs a plain-English title", TITLE_RIGHT)); } else { for (const re of JARGON) { if (re.test(item.title)) { problems.push( - `item "${item.id}" title contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow.` + rule( + at, + "title", + `contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow`, + TITLE_RIGHT, + ), ); break; } } } if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) { - problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`); + problems.push(rule(at, "options", `is a ${item.kind} and needs "options"`, OPTIONS_RIGHT)); } if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) { - for (const o of item.options) { - if (!o || typeof o.k !== "string" || !o.k.trim()) { - problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`); + item.options.forEach((o, i) => { + if (!isPlainObject(o) || typeof o.k !== "string" || !o.k.trim()) { + problems.push( + rule(at, "options", `option ${i + 1} has no usable "k" (its key, a string like "A"). Give every option a "k", or none to have them lettered A, B, C`, OPTIONS_RIGHT), + ); } else if (typeof o.text !== "string" || !o.text.trim()) { problems.push( - `item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".` + rule(at, "options", `option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc"`, OPTION_RIGHT), ); } - } + }); } if (item.verdicts != null) { if (!Array.isArray(item.verdicts) || !item.verdicts.length) { - problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`); + problems.push(rule(at, "verdicts", "must be a non-empty array of { id, label }", VERDICTS_RIGHT)); } else { for (const v of item.verdicts) { if (!v || typeof v.id !== "string" || !v.id.trim()) { - problems.push(`item "${item.id}" has a verdict with no "id"`); + problems.push(rule(at, "verdicts", 'a verdict has no "id"', VERDICTS_RIGHT)); } else if (typeof v.label !== "string" || !v.label.trim()) { - problems.push( - `item "${item.id}" verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text".` - ); + problems.push(rule(at, "verdicts", `verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text"`, VERDICTS_RIGHT)); } } } } if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) { - problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`); + problems.push(rule(at, "templates", 'only a text item can carry it, and its only value is "idea"', { kind: "text", templates: "idea" })); } // The box the page fills from a Notebook tab picked at Start. if (item.fill != null && (item.kind !== "text" || item.fill !== "note")) { - problems.push(`item "${item.id}" has "fill": only a text item can carry it, and its only value is "note".`); + problems.push(rule(at, "fill", 'only a text item can carry it, and its only value is "note"', { kind: "text", fill: "note" })); } // The page compiles it as the person types, and a pattern that does not // compile throws there, on every keystroke, with nothing on screen to say why. if (item.pattern != null) { + const patternRight = { pattern: "^[a-z0-9-]+$", patternHint: "kebab-case" }; if (typeof item.pattern !== "string") { - problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`); + problems.push(rule(at, "pattern", "must be a string holding a JavaScript regular expression", patternRight)); } else { try { new RegExp(item.pattern); } catch (e) { - problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`); + problems.push(rule(at, "pattern", `is not a valid JavaScript regular expression: ${e.message}`, patternRight)); } } } - const recs = (item.options || []).filter((o) => o.recommended); - if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`); + const recs = (item.options || []).filter((o) => o && o.recommended); + if (recs.length > 1) { + problems.push(rule(at, "options", `${recs.length} options are marked recommended; at most one`, [{ text: "A", recommended: true }, { text: "B" }])); + } + // Which cards the Implementation Loop answers itself; the page draws them. + if (item.handledBy != null) { + if (item.handledBy !== "loop") problems.push(rule(at, "handledBy", 'can only be "loop"', { handledBy: "loop" })); + else if (!state.loop?.driving) problems.push(rule(at, "handledBy", "is only valid in a loop session", { handledBy: null })); + } } + // The loop's two reports: the skill's outcome and the app's ending. + if (state.loopOutcome !== undefined) problems.push(...loopOutcomeProblems(state.loopOutcome)); + if (state.loopEnd !== undefined) problems.push(...loopEndProblems(state.loopEnd, state)); + // A note on a card is unanswered the moment no agent words follow it in its // thread. Once that is true, no patch may move past it except one that // finally replies: deleting the item drops it from state.items before this @@ -679,7 +834,12 @@ export function validate(state) { const thread = Array.isArray(item.thread) ? item.thread : []; const last = thread[thread.length - 1]; if (isPlainObject(last) && last.who === "user") { - problems.push(`item "${item.id}" has an unanswered note from the person; reply in its thread before this patch`); + problems.push( + rule(`item "${item.id}"`, "thread", "has an unanswered note from the person; reply in its thread in this patch", { + id: item.id, + thread: [{ who: "agent", text: "..." }], + }), + ); } } } @@ -688,7 +848,9 @@ export function validate(state) { // yet counts as open (and keeps Stop live for a question nobody can see). if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) { problems.push( - 'The dashboard draws no question cards: post its "menu" (and "agent"), and launch the skill a question belongs to.' + rule("", "items", "the dashboard draws no question cards. Post its menu (and agent), and launch the skill a question belongs to", { + menu: { note: "...", recommend: "plan2code-init" }, + }), ); } @@ -697,9 +859,13 @@ export function validate(state) { const openRequired = state.items.filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i)); if (openRequired.length > MAX_OPEN_REQUIRED) { problems.push( - `${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` + - `(the ceiling is the person's attention, not the screen's). ` + - `Send the rest after these are answered, or mark some "required": false.` + rule( + "", + "items", + `${openRequired.length} questions are open at once (${openRequired.map((i) => i.id).join(", ")}). The cap is ${MAX_OPEN_REQUIRED} ` + + `(the ceiling is the person's attention, not the screen's). Send the rest after these are answered, or mark some "required": false`, + { id: openRequired[openRequired.length - 1].id, required: false }, + ), ); } @@ -709,55 +875,68 @@ export function validate(state) { // and the page points at the dashboard instead of a next step. const fin = state.finish; if (fin != null) { + // The page would warn about losing work after the session ended (FR-13). + if (typeof state.stopWarning === "string" && state.stopWarning.trim()) { + problems.push( + rule("", "finish", `"stopWarning" is still set ("${state.stopWarning}"), so the page would warn about losing work after the session ended. Clear it in the same patch`, { + stopWarning: "", + finish: { headline: "Paused: ", command: "/" }, + }), + ); + } if (typeof fin !== "object" || Array.isArray(fin)) { - problems.push('"finish" must be an object'); + problems.push(rule("", "finish", "must be an object", FINISH_RIGHT)); } else { if (typeof fin.headline !== "string" || !fin.headline.trim()) { - problems.push('"finish" needs a plain-English "headline" saying what just happened'); + problems.push(rule("", "finish.headline", "needs a plain-English headline saying what just happened", { finish: { headline: "Phase 3 is done" } })); } if (fin.command != null && (typeof fin.command !== "string" || !fin.command.trim())) { - problems.push('"finish.command" must be a non-empty string, or left out when there is nothing to run'); + problems.push(rule("", "finish.command", "must be a non-empty string, or left out when there is nothing to run", { finish: { command: "/plan2code-1-plan" } })); } else if (fin.command != null && (fin.command.includes("<") || fin.command.includes(">"))) { // A rendered command is copied and run verbatim. A leftover // placeholder reaches someone who has no way to know what fills it. - problems.push(`"finish.command" still has a placeholder in it ("${fin.command}"). Fill it in.`); + problems.push( + rule("", "finish.command", `still has a placeholder in it ("${fin.command}"). Fill it in`, { + finish: { command: "/plan2code-3-implement specs/lunch-vote/overview.md" }, + }), + ); } if (fin.console != null && typeof fin.console !== "boolean") { - problems.push('"finish.console" must be true or false (or left out, to follow the command)'); + problems.push(rule("", "finish.console", "must be true or false (or left out, to follow the command)", { finish: { console: true } })); } if (fin.dashboard != null && typeof fin.dashboard !== "boolean") { - problems.push('"finish.dashboard" must be true or false (or left out: no dashboard button)'); + problems.push(rule("", "finish.dashboard", "must be true or false (or left out: no dashboard button)", { finish: { dashboard: true } })); } if (fin.commit != null && typeof fin.commit !== "boolean") { - problems.push('"finish.commit" must be true or false (or left out: no commit button)'); + problems.push(rule("", "finish.commit", "must be true or false (or left out: no commit button)", { finish: { commit: true } })); } // (The pause test is the page's finishPaused() in public/answers.js: keep them in step.) // Update CHANGELOG first: only the builds that end on a commit and have // no sign-off to put it on. An implementation phase never offers it. A // pause ignores it. if (fin.changelog != null && typeof fin.changelog !== "boolean") { - problems.push('"finish.changelog" must be true or false (or left out: no changelog button)'); + problems.push(rule("", "finish.changelog", "must be true or false (or left out: no changelog button)", { finish: { changelog: true } })); } else if (fin.changelog === true && !/^\s*paused\b/i.test(String(fin.headline || "")) && !["quick-task", "finalize"].includes(state.workflow)) { - problems.push('"finish.changelog" is only for a finished quick-task or finalize'); + problems.push(rule("", "finish.changelog", "is only for a finished quick-task or finalize", { finish: { changelog: null } })); } // The review offer on a finished build: true, or an object carrying the // button's heading. The heading is read by the person, so it faces the // same vocabulary check as a title. if (fin.review != null && typeof fin.review !== "boolean") { if (typeof fin.review !== "object" || Array.isArray(fin.review)) { - problems.push('"finish.review" must be true, false, or { "label": "..." }'); + problems.push(rule("", "finish.review", 'must be true, false, or { "label": "..." }', { finish: { review: { label: "Review the code" } } })); } else if (fin.review.label != null) { if (typeof fin.review.label !== "string") { - problems.push('"finish.review.label" must be a string'); + problems.push(rule("", "finish.review.label", "must be a string", { finish: { review: { label: "Review the code" } } })); } else { const hit = JARGON.find((re) => re.test(fin.review.label)); - if (hit) problems.push(`"finish.review.label" contains internal vocabulary (${hit.source})`); + if (hit) problems.push(rule("", "finish.review.label", `contains internal vocabulary (${hit.source})`, { finish: { review: { label: "Review the code" } } })); } } } for (const re of JARGON) { if (typeof fin.headline === "string" && re.test(fin.headline)) { - problems.push(`"finish.headline" contains internal vocabulary (${re.source})`); + problems.push(rule("", "finish.headline", `contains internal vocabulary (${re.source})`, { finish: { headline: "Phase 3 is done" } })); break; } } @@ -769,15 +948,15 @@ export function validate(state) { // huge number would hide a session that really has died. const quiet = state.agent && state.agent.quietMinutes; if (quiet != null && (typeof quiet !== "number" || !(quiet > 0) || quiet > 60)) { - problems.push('"agent.quietMinutes" must be a number of minutes between 1 and 60 (or null to clear it)'); + problems.push(rule("", "agent.quietMinutes", "must be a number of minutes between 1 and 60 (or null to clear it)", { agent: { quietMinutes: 15 } })); } // The page reads exactly two: anything else would leave it guessing whose // turn it is. if (state.agent && state.agent.status != null && !["working", "waiting"].includes(state.agent.status)) { - problems.push(`"agent.status" must be "working" or "waiting" (not "${state.agent.status}")`); + problems.push(rule("", "agent.status", `must be "working" or "waiting" (not "${state.agent.status}")`, { agent: { status: "working" } })); } if (state.agent && state.agent.activity != null && typeof state.agent.activity !== "string") { - problems.push('"agent.activity" must be a short sentence saying what you are doing'); + problems.push(rule("", "agent.activity", "must be a short sentence saying what you are doing", { agent: { activity: "Reading the plan" } })); } // Open gates only: an approval already given (last phase's sign-off) is a @@ -785,9 +964,12 @@ export function validate(state) { const gates = state.items.filter((i) => i.gate && i.gate.authoritative && isOpen(i)); if (gates.length > 1) { problems.push( - `${gates.length} authoritative approval gates are open (${gates - .map((g) => g.id) - .join(", ")}). Only one workflow may own sign-off at a time.` + rule( + "", + "items", + `${gates.length} authoritative approval gates are open (${gates.map((g) => g.id).join(", ")}). Only one workflow may own sign-off at a time`, + { id: gates[gates.length - 1].id, gate: null }, + ), ); } @@ -797,35 +979,43 @@ export function validate(state) { for (const b of (isPlainObject(d) && Array.isArray(d.blocks) ? d.blocks : [])) { if (!isPlainObject(b) || typeof b.image !== "string" || typeof b.alt !== "string") continue; const hit = JARGON.find((re) => re.test(b.alt)); - if (hit) problems.push(`doc "${d.id}" image "${b.id}" alt text contains internal vocabulary (${hit.source})`); + if (hit) { + problems.push( + rule(`doc "${d.id}" block "${b.id}"`, "alt", `contains internal vocabulary (${hit.source})`, { id: b.id, image: b.image, alt: "The finished screen" }), + ); + } } } // Scan what the AGENT wrote, never what the person typed. `submitted` is the // server's record of an answer someone pressed Send on; if their own words // happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch - // would be rejected and the session would wedge with no way out. - const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({ - ...rest, - thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread, - })); + // would be rejected and the session would wedge with no way out. Scanned one + // string at a time so a refusal names the item and field it found the word in. + const scan = (value, prefix) => + walkStrings(value, "", (str, where) => problems.push(...proseProblems(str, [prefix, where].filter(Boolean).join(" ")))); + for (const { submitted, sentNote, thread, ...rest } of state.items) { + const item = { + ...rest, + thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread, + }; + scan(item, `item "${item.id}"`); + } // A doc block read from a file (`file`) is the file's own words, already on // disk: the agent cannot reword it, and refusing it would wedge every post // that refreshes it. Only what the agent typed is scanned. - const typedDocs = (state.docs || []).map((d) => - isPlainObject(d) && Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d - ); - const prose = - JSON.stringify(authored) + - JSON.stringify(typedDocs) + - JSON.stringify(state.finish || {}) + - JSON.stringify(state.menu || {}); - problems.push(...proseProblems(prose)); + for (const d of state.docs || []) { + if (!isPlainObject(d)) continue; + const typed = Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d; + scan(typed, `doc "${d.id}"`); + } + scan(state.finish || {}, "finish"); + scan(state.menu || {}, "menu"); // The agent's report of its helpers: the shape the page draws from // (subagents.js), then the same prose scan as everything else it writes. if (state.helpers != null) { - problems.push(...checkHelpers(state.helpers)); + problems.push(...checkHelpers(state.helpers).map((p) => likeThis(p, HELPER_RIGHT))); for (const helper of Array.isArray(state.helpers) ? state.helpers : []) { if (!isPlainObject(helper)) continue; for (const field of ["title", "ask", "result"]) { @@ -839,9 +1029,13 @@ export function validate(state) { // A finish ends the session, and a helper still shown as running would sit // on the Subagents tab, spinning, after everything is over. if (state.finish != null && Array.isArray(state.helpers)) { - const running = state.helpers.filter((h) => isPlainObject(h) && h.state === "running").map((h) => `"${h.id}"`); + const running = state.helpers.filter((h) => isPlainObject(h) && h.state === "running").map((h) => h.id); if (running.length) { - problems.push(`"finish" while helper ${running.join(", ")} still shows as running: post each one as done or failed first, or in the same patch`); + problems.push( + rule("", "finish", `helper ${running.map((id) => `"${id}"`).join(", ")} still shows as running: post each one as done or failed first, or in the same patch`, { + helpers: [{ id: running[0], state: "done" }], + }), + ); } } @@ -852,6 +1046,182 @@ export function isOpen(item) { return item.status === "open" || item.status === "reopened"; } +/* ------------------------------------------------------ the loop's reports */ + +const LOOP_LEVELS = ["critical", "warning", "suggestion"]; +const LOOP_REASONS = ["tests", "findings", "blocked", "conflict", "other"]; +const LOOP_CAN = ["resume", "fix", "finalize"]; +const TASK_ID = /^\d+\.\d+$/; + +// A one-line path that stays inside the project: not absolute, no `..` step. +const relativePath = (f) => + typeof f === "string" && f.length > 0 && !/[\r\n]/.test(f) && !path.isAbsolute(f) && !/^[A-Za-z]:/.test(f) && !f.replaceAll("\\", "/").split("/").includes(".."); +const isNonNegInt = (n) => Number.isInteger(n) && n >= 0; +const isPosInt = (n) => Number.isInteger(n) && n > 0; +// One line of 1..max characters. +const oneLine = (s, max) => typeof s === "string" && s.length >= 1 && s.length <= max && !/[\r\n]/.test(s); + +/** + * Problems with a `loopOutcome` (what the skill reports after building a phase + * under the loop), as sentences naming the field; an empty array when it is + * good. Rules are the overview's API section; house rules 4 and 5 apply to + * every string. + */ +export function loopOutcomeProblems(o) { + const p = []; + const bad = (field, rule) => p.push(`loopOutcome.${field} ${rule}`); + if (!isPlainObject(o)) return ["loopOutcome must be an object"]; + const prose = (field, s) => { + if (typeof s === "string") p.push(...proseProblems(s, `loopOutcome.${field}`)); + }; + if (!isPosInt(o.phase)) bad("phase", "must be a positive integer"); + if (o.result !== "passed" && o.result !== "failed") bad("result", 'must be "passed" or "failed"'); + if (o.result === "passed") { + if (o.reason !== null) bad("reason", "must be null when the phase passed"); + } else if (o.result === "failed" && !LOOP_REASONS.includes(o.reason)) { + bad("reason", `must be one of ${LOOP_REASONS.join(", ")} when the phase failed`); + } + if (!oneLine(o.summary, 200)) bad("summary", "must be one line of 1 to 200 characters"); + else prose("summary", o.summary); + + if (!isPlainObject(o.tests)) bad("tests", "must be an object { ran, passed, summary }"); + else { + if (typeof o.tests.ran !== "boolean") bad("tests.ran", "must be true or false"); + if (typeof o.tests.passed !== "boolean") bad("tests.passed", "must be true or false"); + if (typeof o.tests.summary !== "string" || /[\r\n]/.test(o.tests.summary)) bad("tests.summary", "must be a one-line string"); + else prose("tests.summary", o.tests.summary); + } + + if (!isPlainObject(o.review)) bad("review", "must be an object { ran, recheck, left, unfixed }"); + else { + const r = o.review; + if (typeof r.ran !== "boolean") bad("review.ran", "must be true or false"); + if (typeof r.recheck !== "boolean") bad("review.recheck", "must be true or false"); + if (!isPlainObject(r.left)) bad("review.left", "must be an object { critical, warning, suggestion }"); + else for (const level of LOOP_LEVELS) if (!isNonNegInt(r.left[level])) bad(`review.left.${level}`, "must be a non-negative integer"); + if (r.triage !== undefined) { + const t = r.triage; + if (!isPlainObject(t)) bad("review.triage", "must be an object { ran, skipped } when present"); + else { + if (typeof t.ran !== "boolean") bad("review.triage.ran", "must be true or false"); + if (!Array.isArray(t.skipped)) bad("review.triage.skipped", "must be an array"); + else { + if (t.skipped.length > 50) bad("review.triage.skipped", "can hold at most 50 entries"); + t.skipped.forEach((u, i) => { + const at = `review.triage.skipped[${i}]`; + if (!isPlainObject(u)) return bad(at, "must be an object { level, title, file, reason }"); + if (!LOOP_LEVELS.includes(u.level)) bad(`${at}.level`, `must be one of ${LOOP_LEVELS.join(", ")}`); + if (typeof u.title !== "string" || !u.title.trim() || /[\r\n]/.test(u.title)) bad(`${at}.title`, "must be a non-empty one-line string"); + else prose(`${at}.title`, u.title); + if (typeof u.file !== "string" || /[\r\n]/.test(u.file)) bad(`${at}.file`, "must be a one-line string"); + else prose(`${at}.file`, u.file); + if (!oneLine(u.reason, 200)) bad(`${at}.reason`, "must be one line of 1 to 200 characters"); + else prose(`${at}.reason`, u.reason); + }); + } + } + } + if (!Array.isArray(r.fixed)) bad("review.fixed", "must be an array (empty when nothing was fixed)"); + else { + if (r.fixed.length > 50) bad("review.fixed", "can hold at most 50 entries"); + r.fixed.forEach((u, i) => { + if (!isPlainObject(u)) return bad(`review.fixed[${i}]`, "must be an object { level, title, file? }"); + if (!LOOP_LEVELS.includes(u.level)) bad(`review.fixed[${i}].level`, `must be one of ${LOOP_LEVELS.join(", ")}`); + if (typeof u.title !== "string" || !u.title.trim() || /[\r\n]/.test(u.title)) bad(`review.fixed[${i}].title`, "must be a non-empty one-line string"); + else prose(`review.fixed[${i}].title`, u.title); + if (u.file !== undefined && (typeof u.file !== "string" || /[\r\n]/.test(u.file))) bad(`review.fixed[${i}].file`, "must be a one-line string when present"); + else prose(`review.fixed[${i}].file`, u.file); + }); + } + if (!Array.isArray(r.unfixed)) bad("review.unfixed", "must be an array"); + else { + if (r.unfixed.length > 50) bad("review.unfixed", "can hold at most 50 entries"); + r.unfixed.forEach((u, i) => { + if (!isPlainObject(u)) return bad(`review.unfixed[${i}]`, "must be an object { level, title, file? }"); + if (!LOOP_LEVELS.includes(u.level)) bad(`review.unfixed[${i}].level`, `must be one of ${LOOP_LEVELS.join(", ")}`); + if (typeof u.title !== "string" || !u.title.trim()) bad(`review.unfixed[${i}].title`, "must be a non-empty string"); + else prose(`review.unfixed[${i}].title`, u.title); + if (u.file !== undefined && typeof u.file !== "string") bad(`review.unfixed[${i}].file`, "must be a string when present"); + else prose(`review.unfixed[${i}].file`, u.file); + }); + } + } + + if (!isPlainObject(o.tasks)) bad("tasks", "must be an object { blocked, assumed }"); + else { + for (const key of ["blocked", "assumed"]) { + const list = o.tasks[key]; + if (!Array.isArray(list) || !list.every((t) => typeof t === "string" && TASK_ID.test(t))) { + bad(`tasks.${key}`, 'must be an array of task ids like "2.4"'); + } + } + } + + if (!Array.isArray(o.conflicts) || !o.conflicts.every((c) => typeof c === "string" && !/[\r\n]/.test(c))) { + bad("conflicts", "must be an array of one-line strings"); + } else o.conflicts.forEach((c, i) => prose(`conflicts[${i}]`, c)); + + if (!Array.isArray(o.decisions)) bad("decisions", "must be an array of one-line strings (empty when there were none)"); + else { + if (o.decisions.length > 50) bad("decisions", "can hold at most 50 entries"); + o.decisions.forEach((d, i) => { + if (!oneLine(d, 200)) bad(`decisions[${i}]`, "must be one line of 1 to 200 characters"); + else prose(`decisions[${i}]`, d); + }); + } + + if (!oneLine(o.subject, 100)) bad("subject", "must be one line of 1 to 100 characters"); + else prose("subject", o.subject); + return p; +} + +/** + * Problems with a `loopEnd` (the app's word on how the loop ended), given the + * merged state so `evidence` can be checked against the docs on the page. + */ +export function loopEndProblems(e, state) { + const p = []; + const bad = (field, rule) => p.push(`loopEnd.${field} ${rule}`); + if (!isPlainObject(e)) return ["loopEnd must be an object"]; + const prose = (field, s) => { + if (typeof s === "string") p.push(...proseProblems(s, `loopEnd.${field}`)); + }; + if (e.kind !== "stopped" && e.kind !== "finished") bad("kind", 'must be "stopped" or "finished"'); + if (!oneLine(e.line, 200)) bad("line", "must be one line of 1 to 200 characters"); + else prose("line", e.line); + if (e.evidence !== undefined) { + if (typeof e.evidence !== "string" || !(state?.docs || []).some((d) => d && d.id === e.evidence)) { + bad("evidence", "must be the id of a doc on the page"); + } + } + if (!Array.isArray(e.phases)) bad("phases", "must be an array"); + else { + e.phases.forEach((ph, i) => { + if (!isPlainObject(ph)) return bad(`phases[${i}]`, "must be an object { n, name, commit, unfixed, retries }"); + if (!isPosInt(ph.n)) bad(`phases[${i}].n`, "must be a positive integer"); + if (typeof ph.name !== "string" || /[\r\n]/.test(ph.name)) bad(`phases[${i}].name`, "must be a one-line string"); + else prose(`phases[${i}].name`, ph.name); + if (ph.commit !== null && !(typeof ph.commit === "string" && /^[0-9a-f]{4,40}$/i.test(ph.commit))) bad(`phases[${i}].commit`, "must be a short hex hash or null"); + if (!isNonNegInt(ph.unfixed)) bad(`phases[${i}].unfixed`, "must be a non-negative integer"); + if (!isNonNegInt(ph.retries)) bad(`phases[${i}].retries`, "must be a non-negative integer"); + for (const key of ["fixed", "skipped", "left", "assumed", "decisions"]) { + if (ph[key] !== undefined && !isNonNegInt(ph[key])) bad(`phases[${i}].${key}`, "must be a non-negative integer when present"); + } + }); + } + if (!Array.isArray(e.uncommitted) || !e.uncommitted.every(relativePath)) { + bad("uncommitted", "must be an array of relative paths (no leading slash or drive, no .. step, one line each)"); + } else if (e.uncommitted.length > 200) bad("uncommitted", "can hold at most 200 paths"); + else e.uncommitted.forEach((f, i) => prose(`uncommitted[${i}]`, f)); + if (!Array.isArray(e.can) || !e.can.every((c) => LOOP_CAN.includes(c))) { + bad("can", `must be an array with entries from ${LOOP_CAN.join(", ")}`); + } + return p; +} + +// Loop mode adds three optional keys that a blank state does not hold (absent, +// not null): `loop: { driving: true }` (set by `open --loop`), `loopOutcome` +// (the skill's report) and `loopEnd` (the app's). export function blankState({ sid, workflow, title, project, specDir }) { return { schema: SCHEMA, @@ -877,10 +1247,17 @@ export function blankState({ sid, workflow, title, project, specDir }) { * starts from a blank page: the last skill's questions, sections, docs, * helpers, headline and ending are its record on disk, not the next skill's * opening. - * Only the session's identity carries across. `workspace.json`, - * `ledger.ndjson` and the cursors live beside `state.json`, so the workspace - * and the meter outlive every hop. + * Only the session's identity and the Ask tab's conversation carry across: + * the agent's chat replies stay beside the messages in `chat.ndjson`, which + * a hop never touches, or every question asked before it would read as + * unanswered. `workspace.json`, `ledger.ndjson` and the cursors live beside + * `state.json`, so the workspace and the meter outlive every hop. */ export function switchWorkflow(state, { workflow, title, specDir }) { - return { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created }; + const next = { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created }; + // A blank state holds no `loop`, `loopOutcome` or `loopEnd`, so a hop never + // carries them over; `open --loop` stamps `loop` again after the switch. + for (const key of ["loop", "loopOutcome", "loopEnd"]) delete next[key]; + if (state.chat) next.chat = state.chat; + return next; } diff --git a/src/web-console/pointers.mjs b/src/web-console/pointers.mjs new file mode 100644 index 0000000..becc966 --- /dev/null +++ b/src/web-console/pointers.mjs @@ -0,0 +1,101 @@ +// Plan2Code Web Console - pointers: which topic file the console names, and when. +// +// The card (console.md) leaves a topic out and the console's own output names +// its file at the moment that topic is due: `read: []`, once per +// session per topic, and again after a resume. What was printed lives in the +// session folder (pointers.json), never in state.json, which rides every frame +// to the page, and never on the page's stream. + +import fs from "node:fs"; +import path from "node:path"; + +import { HERE, readJson, writeJsonAtomic } from "./files.mjs"; + +const POINTERS_FILE = "pointers.json"; + +// Topic -> the file that explains it, beside console.mjs. +export const POINTER_FILES = { + finish: "console-finish.md", + stop: "console-stop.md", + docs: "console-docs.md", + chat: "console-chat.md", + workspace: "console-workspace.md", + subagents: "console-subagents.md", + review: "building-review.md", +}; + +function printedTopics(dir) { + const saved = readJson(path.join(dir, POINTERS_FILE), {}); + return saved && Array.isArray(saved.printed) ? saved.printed.filter((t) => typeof t === "string") : []; +} + +/** + * The absolute paths of the topic files in `topics` not yet printed in this + * session, in the order given and each once. An unreadable or missing memory + * reads as nothing printed yet. + */ +export function duePointers(dir, topics) { + const done = new Set(printedTopics(dir)); + const out = []; + for (const topic of new Set(topics || [])) { + if (Object.hasOwn(POINTER_FILES, topic) && !done.has(topic)) out.push(path.join(HERE, POINTER_FILES[topic])); + } + return out; +} + +/** + * Record that these topics were printed. Called after the print, the order + * advanceCursor() uses: a kill in between repeats a pointer, never loses one. + * Never fatal. + */ +export function rememberPointers(dir, topics) { + const known = (topics || []).filter((t) => Object.hasOwn(POINTER_FILES, t)); + if (!known.length) return; + try { + const printed = [...new Set([...printedTopics(dir), ...known])]; + writeJsonAtomic(path.join(dir, POINTERS_FILE), { printed }); + } catch {} +} + +/** Forget what was printed (a resume starts the reading over). */ +export function resetPointers(dir) { + try { + fs.rmSync(path.join(dir, POINTERS_FILE), { force: true }); + } catch {} +} + +// The verdict a review card was answered with, wherever the action keeps it. +function verdictOf(action) { + if (typeof action.verdict === "string" && action.verdict) return action.verdict; + const answer = action.answer; + return answer && typeof answer === "object" && typeof answer.verdict === "string" && answer.verdict ? answer.verdict : ""; +} + +/** + * The topics a collected send makes due. Pure: no I/O. + * + * `result` is the send (result.json; an empty object for a chat-only pickup), + * `state` the session state as read before the page is set back to working, + * `changes` the standing-instruction flags from owedFlags(), and `chat` the + * Quick question entries delivered with it. + */ +export function pointersForSend(result, state, changes, chat = []) { + const topics = []; + const actions = (result && Array.isArray(result.actions) && result.actions) || []; + const items = (state && Array.isArray(state.items) && state.items) || []; + for (const a of actions) { + if (!a || typeof a !== "object") continue; + if (a.i === "__commit") topics.push("finish"); + else if (a.i === "__dashboard") topics.push(state && state.finish ? "finish" : "stop"); + else if (a.i === "__stop") topics.push("stop"); + else if (a.i === "__review") topics.push("review"); + else if (a.type === "answer" && typeof a.i === "string" && !a.i.startsWith("__")) { + const item = items.find((x) => x && x.id === a.i); + if (item && item.kind === "review" && verdictOf(a)) topics.push("review"); + } + } + if ((chat || []).some((e) => e && e.kind === "message")) topics.push("chat"); + if (changes && changes.workspaceChanged) topics.push("workspace"); + if (changes && changes.subagentsChanged) topics.push("subagents"); + return [...new Set(topics)]; +} diff --git a/src/web-console/public/answers.js b/src/web-console/public/answers.js index f7fd44d..9420c33 100644 --- a/src/web-console/public/answers.js +++ b/src/web-console/public/answers.js @@ -10,7 +10,7 @@ // No DOM, no `local`, no fetch. If a function in here needs any of those, it // belongs in app.js instead. -import { FIXED_REASON, SKILLS, labelFor, skillByName, skillFor } from "./skills.js"; +import { FIXED_REASON, FLOW_SKILLS, SKILLS, labelFor, skillByName, skillFor } from "./skills.js"; import { SPEC_STATES, stateFor } from "./spec-states.js"; /* ----------------------------------------------------- the sent answer */ @@ -257,7 +257,7 @@ export function suggestionFrom(item) { // The badge each workflow wears. Shared with the server, which writes it into // the page it serves so the first paint already names the session instead of // flashing a placeholder until the script arrives. Derived from skills.js. -export const WORKFLOW_LABEL = Object.fromEntries(SKILLS.map((s) => [s.workflow, s.label])); +export const WORKFLOW_LABEL = Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.label])); export function workflowLabel(workflow) { return labelFor(workflow) || workflow || "Session"; @@ -267,7 +267,7 @@ export function workflowLabel(workflow) { // skill as `additionalReferences`). Any other next step has no browser page // to open, and asking for one would send the next session looking for // something that is not there. Derived from skills.js: every entry is one. -export const CONSOLE_WORKFLOWS = SKILLS.map((s) => s.command); +export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command); // Rides on the end of the command as part of the skill's argument. Every // console skill takes it as the answer to "web console or terminal?" instead @@ -550,7 +550,7 @@ export const CATALOG_GROUPS = [ // action so the launched skill knows which spec it was picked for. Derived from // skills.js: the entries with a card, in their order, each card's fields // beside the skill's name, command and workflow. -export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({ +export const SKILL_CATALOG = FLOW_SKILLS.filter((s) => s.card).map((s) => ({ skill: s.skill, command: s.command, workflow: s.workflow, @@ -558,6 +558,15 @@ export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({ ...s.card, })); +// The desktop app's Implementation Loop card: not a skill, so not in +// SKILL_CATALOG. The dashboard draws it after its group's other cards, and its +// click opens the setup screen instead of launching anything. +const LOOP_SKILL = SKILLS.find((s) => s.appOnly && s.card); +export const LOOP_ENTRY = LOOP_SKILL + ? { skill: LOOP_SKILL.skill, command: "Desktop app only", workflow: null, appOnly: true, ...LOOP_SKILL.card } + : null; +export const OUTSIDE_APP_LINE = "Runs only in the Plan2Code desktop app."; + // A workflow by the name its dashboard card gives it ("Implement"), for the // screens that speak of it as a thing being started rather than as a badge. export function workflowTitle(workflow) { @@ -674,7 +683,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) { const hasAgents = Boolean(scan && scan.hasAgents); const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null; const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder"; - const rule = skillByName(entry.skill); + const rule = skillByName(entry.skill) || (entry.appOnly ? LOOP_SKILL : null); if (!rule || !rule.states) return ON; // The three cards whose rules read the scan rather than the spec. diff --git a/src/web-console/public/app-bridge.js b/src/web-console/public/app-bridge.js index a4e010a..fa6fe36 100644 --- a/src/web-console/public/app-bridge.js +++ b/src/web-console/public/app-bridge.js @@ -36,6 +36,40 @@ export function onAppMessage(kind, handler) { }); } +/** + * Hear the app's answers to the Implementation Loop's named requests: + * `loop-facts` (what agent a loop would use), `loop-start-result`, + * `loop-notify-test-result` and the three stop-screen results. `store` is the page object and `redraw` its + * render; they are handed in so this file keeps importing nothing. + */ +export function wireLoopMessages(store, redraw) { + onAppMessage("loop-facts", (data) => { + store.loopFacts = data.facts && typeof data.facts === "object" ? data.facts : null; + redraw(); + }); + onAppMessage("loop-start-result", (data) => { + // Cancel in the app's confirm: nothing started, so the setup is as it was. + if (data.ok === true && data.started === false) { + store.loopStart = null; + if (store.loopSetup) store.loopSetup.starting = false; + redraw(); + return; + } + store.loopStart = { ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app did not start the loop.") }; + redraw(); + }); + onAppMessage("loop-notify-test-result", (data) => { + store.loopNotifyTest = { waiting: false, ok: data.ok === true, sent: data.sent === true, error: data.ok === true ? null : String(data.error || "The app could not send the test.") }; + redraw(); + }); + for (const kind of ["loop-resume-result", "loop-fix-result", "loop-finalize-result"]) { + onAppMessage(kind, (data) => { + store.loopAction = { kind, ok: data.ok === true, error: data.ok === true ? null : String(data.error || "The app could not do that.") }; + redraw(); + }); + } +} + /** * Ask the app for what its bar's New Session button does, confirm and all. * `command`, when there is one, goes on the clipboard first so it can be diff --git a/src/web-console/public/app.js b/src/web-console/public/app.js index ac892db..7dd4199 100644 --- a/src/web-console/public/app.js +++ b/src/web-console/public/app.js @@ -22,7 +22,8 @@ import { adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter, renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope, wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding, - wireActivities, wireHelp, wireLooks, wireNotepad, wireWorkspace, + wireActivities, wireLoopSetup, wireHelp, launchSkill, openHelpOn, openLoopSetup, wireLooks, wireNotepad, wirePrefs, wireWorkspace, + openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, } from "./screens/core.js"; import { sound } from "./sound.js"; @@ -34,7 +35,10 @@ import { sound } from "./sound.js"; // last the session itself (its first state and the stream). The draft's save // and the few calls a screen makes into another are handed to state.js first. onSave(save); -useHooks({ banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope }); +useHooks({ + launchSkill, openHelpOn, openLoopSetup, banner, fitGrowBox, markSent, maybeWelcome, renderFooter, renderSidebar, renderWhere, stagedPayload, syncWorkspaceScope, + openPrefs, markSaved, confirmUnsaved, loadAgentsView, wireAgentsView, hasUnsaved, unsavedName, saveOpen, discardOpen, focusOpen, +}); const boot = bootData(); startLooks(boot); @@ -46,11 +50,13 @@ wireHelp(); wireDashboard(); wireEnding(); wireLooks(); +wirePrefs(); wireCleanup(); wireDocs(); wireAsk(); wireNotepad(); wireActivities(); +wireLoopSetup(); wireChrome(); startClock(); diff --git a/src/web-console/public/chat.js b/src/web-console/public/chat.js index e35825b..d93ab07 100644 --- a/src/web-console/public/chat.js +++ b/src/web-console/public/chat.js @@ -210,6 +210,24 @@ export function shouldChime(prevDot, nextDot) { // The page's own "has drifted away" threshold for an agent that is waiting. const ADRIFT_MS = 3 * 60 * 1000; +// How long an agent answering an Ask message may go without checking in. It +// is out of `wait` while it answers, and an approved edit can run for minutes. +export const ASK_BUSY_MS = 10 * 60 * 1000; + +/** + * Whether the agent has picked up an Ask message (or an edit decision) and + * not replied to it yet: busy with it, not gone. + */ +export function chatAnswering(frameChat) { + const chat = chatOf(frameChat); + const messages = Array.isArray(chat.messages) ? chat.messages : []; + const pickedUp = Number.isInteger(chat.pickedUp) ? chat.pickedUp : 0; + for (const [seq, answered] of answeredFlags(messages)) { + if (!answered && seq <= pickedUp) return true; + } + return false; +} + /** * Whether nobody is there to answer a chat message. A finished session's agent * is often still listening through its last wait (the review and dashboard @@ -217,10 +235,10 @@ const ADRIFT_MS = 3 * 60 * 1000; * not end the chat — going quiet does. Offline once the agent has been silent * longer than the page would tolerate before calling it stuck (working) or * adrift (anything else), which is also the only signal left once the server - * is gone. + * is gone. An Ask message in hand (`answering`) stretches either to ASK_BUSY_MS. */ -export function chatOffline({ finish, agent, agentLastSeenMs, now }) { +export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false }) { const silent = now - agentLastSeenMs; - if (agent && agent.status === "working") return silent > quietLimitMs(agent, STALE_MS); - return silent > quietLimitMs(agent, ADRIFT_MS); + const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS); + return silent > (answering ? Math.max(limit, ASK_BUSY_MS) : limit); } diff --git a/src/web-console/public/help.js b/src/web-console/public/help.js index 70b01f2..87f456c 100644 --- a/src/web-console/public/help.js +++ b/src/web-console/public/help.js @@ -22,6 +22,7 @@ export const HELP_TABS = Object.freeze([ tab("dashboard", "The dashboard", true), tab("meter", "Session meter", false), tab("build", "Watching a build", false), + tab("loop", "Implementation Loop", true), tab("git", "The git board", false), tab("subagents", "Helpers (subagents)", false), tab("ask", "Ask a quick question", false), @@ -53,20 +54,6 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, return "about"; } -// The tab index a key moves to, or -1 when the key is not a tab key. -export function helpKeyTarget(key, index, count) { - switch (key) { - case "ArrowDown": - case "ArrowRight": - return (index + 1) % count; - case "ArrowUp": - case "ArrowLeft": - return (index - 1 + count) % count; - case "Home": - return 0; - case "End": - return count - 1; - default: - return -1; - } -} +// The tab index a key moves to, or -1 when the key is not a tab key: the +// shared tab helper's, under the name Help and the git board import. +export { tabKeyTarget as helpKeyTarget } from "./tabs.js"; diff --git a/src/web-console/public/index.html b/src/web-console/public/index.html index 32b0e42..533a4cf 100644 --- a/src/web-console/public/index.html +++ b/src/web-console/public/index.html @@ -30,6 +30,8 @@ + + @@ -45,6 +47,8 @@ + + @@ -144,20 +148,6 @@
- + + + + + @@ -1104,8 +1112,8 @@ A simplified outline of this page with six numbered areas, in the same order as the sections below: 1, the top bar, with the title on - the left, the progress bar in the middle, the question mark and - gear buttons on the right, and Stop session under the title; + the left, the progress bar in the middle, the gear and question + mark buttons on the right, and Stop session under the title; 2, Planny and the outline down the left; 3, the view tabs, on the top bar's second row at the right; 4, the question card in the middle with Previous and Next under it; 5, the notes panel on the @@ -1117,9 +1125,9 @@ - ? + - + ? Stop session Questions @@ -1163,9 +1171,10 @@ "4 of 9 done" while something is being built.
  • - The ? button opens this Help, and the gear button - beside it opens User Preferences: your role first, - then your colors, theme, card width, sounds and whether Activities shows. + The gear button opens User Preferences, and the + ? button beside it opens this Help. Preferences has four tabs: + your theme, card width, colors and role, then agents and models, + cleanup, and sounds and whether Activities shows.
  • The megaphone button opens GitHub in a @@ -1972,6 +1981,139 @@

    +
    +

    Implementation Loop

    +

    + In the desktop app, the Implementation Loop builds every remaining + phase of a documented spec for you, one after another, while you do + something else. The dashboard's Implementation Loop card starts it. +

    +
    + + One pass of the loop + + You answer the setup once. Then, for each phase, the loop builds it, + reviews it, fixes the findings, re-checks, runs the quick check and + commits it. When the last phase is done, a summary is written. + + + + + + + + + + + + + + + Setup + Build + Review + Fixes + Re-check + Check + Commit + Summary + + + + + + + + + once for every phase + +
    Review, fixes and re-check are on only when you choose them in the setup.
    +
    +

    What it does

    +
      +
    • + It runs on its own, one fresh agent session per phase, + and, when you leave commits on, commits each phase locally to the + branch you are on. It never pushes. +
    • +
    • + Review fixes are chosen with Smart pick by a fresh agent + that skips what is not worth fixing and records each skip, or + by level (Critical, Warning, Suggestion). +
    • +
    • + It uses the launch agent and model the app is running, and it needs + permission checks off: with them on, an agent would + wait on a prompt nobody sees, so Start stays grayed out. +
    • +
    +

    What is locked while it runs

    +

    + Answers, sign-offs, launches, Workspace, Helpers and + Back are read-only, starting a new session is held + back, and Ask is off, except for a question the loop is waiting on. Still + open: Activities, Notebook, Help, Preferences, the docs and the code + review. +

    +

    Stopping it

    +
      +
    • + Stop after this phase, on the banner at the top of the window, lets the + phase finish its review, mark and commit, then ends the loop. +
    • +
    • + Stop now ends the agent at once, after you confirm. +
    • +
    • Quitting the app ends the loop too.
    • +
    +

    When a phase asks a question

    +

    + By default the agent takes its best guess and records the + assumption. If you chose to pause instead, the loop holds, with + no time limit, and nothing is lost. The app calls you back + with the taskbar dot, a flash of the window and the question sound. Answer, + and it carries on. +

    +

    Being told when it needs you

    +

    + Fill in Send a notification in the setup and the app sends a message + when the loop waits on your answer or ends, unless you stopped it yourself. Send it to a + Discord, Slack, Microsoft Teams or Google Chat webhook, or to any http or + https address, with the message in its query string or a JSON body. + Send a test tries it right away. One that fails during a loop does not + change what the loop does; the finish line or the stop screen says so. +

    +

    When it stops by itself

    +
      +
    • + Failing tests or a failing quick check, Critical or Warning findings + left over at a level you chose to fix, a blocked task, a conflict in the spec, a commit that was + refused, or a Critical finding the Smart pick skipped. +
    • +
    • + A crashed or silent agent gets one retry per phase, if you left that on. After that + the loop stops. +
    • +
    • + A stop screen says what failed and shows the evidence. + Resume the loop carries on from that phase; + Fix it by hand opens an ordinary Implement session + on it. +
    • +
    +

    The report

    +

    + One report follows the whole build, across stops and Resume: what each + phase built and committed, the findings it fixed, the findings it chose + not to fix and why, the findings left open, each assumption, any other + decisions the agent reported, and every retry and stop. The agent writes + most of it, so it holds what the agent noticed. The finish screen counts + each kind, and Read the full report opens it, saved as + specs/<feature>/LOOP-SUMMARY-<date>.md. After a + stop, the stop screen shows the report so far. +

    +
    +

    The git board

    @@ -2292,10 +2434,18 @@

    The die in the top bar opens Activities: small games to play while you wait, say - through a long build. Two games ship: Snake and - Mini golf. Pick one with the buttons above the board; - the window opens on your last pick next time. Nothing you do in it - reaches Plan2Code. + through a long build. Twelve games ship: Snake, + Mini golf, Light Trails, + Bug Hunt, Sunset Drive, + Stack Deploy, Bumper Ring, + Rapids Run, Hot Potato, + Crossing Rush, Bounce Road and + Ghoul Rush. The window opens on a card for each game, with its best score; click one + (or walk them with the arrows and press Space) to play it, + and All games takes you back. One game plays at a + time: a round left for the cards waits, paused, on its card, and + picking a different game ends it. Nothing you do in it reaches + Plan2Code.

    The games

      @@ -2303,7 +2453,7 @@ Snake: steer to the food and grow. The snake speeds up as it grows, and a wall, a rock, a comet or your own tail ends the round. Food eaten quickly builds a combo of up to x5. Every 5 - foods is a new level, and each of the first few brings something + foods is a new level, which starts in Slow-mo, and each of the first few brings something new: rocks (a flashing cell turns to stone), mystery boxes, portals, comets that cut your tail, then chaos. Power-ups turn up on their own: Shield, Turbo, Slow-mo, Magnet, Ghost and Scissors, and a @@ -2311,12 +2461,18 @@ and end screens count how many of them you have found so far.
    • - Mini golf: eighteen silly holes seen from above. - The front nine is Pirate Cove, greens afloat in a - shark sea with cannonballs, barrels, a kraken and a ghost ship. The - back nine is the Caves of Doom, lit only around - your ball, with lava, a bottomless pit, mine carts and stone - crushers. The aim follows your mouse. Click (or press + Mini golf: six themed courses of eighteen silly + holes, seen from above. Its card opens a dashboard of the courses, + each with a picture of one of its holes, its par and your best on + it: Pirate Cove (a shark sea, cannonballs, a + kraken and a ghost ship), the Caves of Doom (lit + only around your ball, with lava, a bottomless pit, mine carts and + stone crushers), Dino Valley, Candy + Carnival, Cosmic Glow (where black holes + bend your putt) and Frosty Peaks (where the ball + glides on ice). Pick one to play its eighteen holes, and + All courses takes you back. The aim starts on the cup and follows your mouse once you + move it, and a click putts where the arrow points. Click (or press Space) to start the power meter, then click again to set the power: the gold MAX band near the top gives a boosted putt, but go past it into the red and you shank it. @@ -2337,6 +2493,252 @@ Spyglass shows where it will roll while the meter runs. You hold one at a time, and it carries over to the next hole.
    • +
    • + Light Trails: you and your rivals each leave a + glowing wall behind, and the last rider still moving wins the heat. + A wall, any trail (yours too), a crystal or another rider is out, + though you hold in place for a split second first, so a quick + turn still gets you clear. + Win a heat to move on through nine arenas; a crash costs one of + three lives and runs the heat again. The arenas bring more rivals, + power-up pads (Boost, Phase through trails, an Eraser, Slow-mo for + the rivals, coins and a 1UP), crystals, portals, and walls that + close in a ring at a time, flashing red first. A rival out scores, + and more if it hit your trail. +
    • +
    • + Bug Hunt: fly Planny's ship along the bottom and + squash waves of bugs before they dive at you. New bugs join as you + go: Beetles that split in two, zigzagging Race conditions, + Exceptions that throw things, Null pointers your shots pass + through while they fade, and Firewalls that take five shots. Every + fifth wave is a boss: the Memory Leak, the Spaghetti Monster (shoot + its tentacles off first) and the Heisenbug. Squashed bugs drop + coins and power-ups (Spread shot, Rapid fire, Shield, Slow-mo, + Magnet, Refactor and a 1UP), and quick kills build a combo. +
    • +
    • + Sunset Drive: race Planny's convertible down an + endless road against the clock. Each stage ends at a checkpoint + that adds time, and just before it the road splits: the side you + keep to picks the next road, and the harder one scores more. + Six roads to find: Sunset Coast, Canyon Road, Maple Valley, + Snowcap Pass, Neon City and Starlight Highway. Traffic, roadside + props and the median slow you down; coins, clocks (+5 seconds) + and nitro cans line the road, and passing a car close at speed + scores a close call. The round ends when the time runs out. +
    • +
    • + Stack Deploy: one button. A block slides back and + forth above the tower; drop it, and whatever hangs over the edge + is sliced off, so the next block is narrower. Miss the tower and + the round is over. Land one dead on for a + Perfect: nothing is sliced, a run of them scores + more (up to x5), and every third in a row grows the block back. + Gold blocks turn up from floor 15, worth more and growing it + twice as much. The floors speed up from 10 and bring twists: + blocks from either side that may turn back at 20, lag spikes that + freeze a block for a beat at 30, wind at 40, a rush through the + middle at 70 and everything faster at 90. The tower goes + from server racks to office floors, glass towers and rockets, and + a dashed line marks the highest floor you have ever reached. +
    • +
    • + Bumper Ring: sumo in bumper cars, on a ring over + the void. Push into your rivals and the harder hit wins; a car + whose middle goes past the edge falls, and the last car on the + ring wins the heat. A rival lets go and revs before it dashes: + that is your moment to step aside, and a rival that misses near + the edge may fly off on its own. Win a heat to move on through + nine arenas, from the Training Mat to the + Grand Final, then Finals that keep getting + sharper; a fall costs one of three lives and runs the heat again. + After a while the ring shrinks a band at a time (the band flashes + red first), and a heat that drags on past the smallest ring goes + to sudden death, shrinking on until two cars no longer fit. The arenas bring rivals (the Bully, the heavy Turtle, + the Sniper, the Scrapper and the Mirror, who copies your moves), + power pads (Heavy, Spring, Charge, Shield, Grow, Ghost and + Slick), bumpers, ice, a turntable, holes, a magnet and a ring + that turns square. A knockout scores for the last car to touch + the one that fell, and quick knockouts build a combo of up to x5. +
    • +
    • + Rapids Run: pilot Planny's jet-skimmer up a + winding river that scrolls down the board, its banks narrowing and + splitting around islands. Hold Space to fire. The + battery drains all the while, a little faster at full speed: run + over a green charge buoy to top it up, or shoot it for a few + points if you can spare it. A bank, an island, a foe, a bolt or a + flat battery costs one of three lives, and you start the stretch + again from the last dam (or, once you have reached a mini-boss, + from the mouth of its basin); a dam you blasted stays open. Each + stretch ends at a dam across the river: shoot it open to pass + (slow down to give yourself time). + Eight named stretches, from Willow Run to + Old Lock, then Night Water again and again, + quicker. Patrol skiffs drift from bank to bank and bob mines sit + still from the start; gull drones swoop across from stretch 2, + bank sentries shoot back from stretch 3, whirlpools tug you from + stretch 5 and darters swerve into your lane from stretch 6. Every + fourth dam a mini-boss holds the basin before it (the river stops + and your battery holds while you fight): the Dredger, Ironclad and + Old Leviathan. Crates hold Spread shot, a Shield (one crash of any + kind but a flat battery), a Magnet for charge buoys and a Surge + (a full battery). Points: 1 for every 5 units of river, 2 at full + speed; 5 for every quarter second you skim a bank at speed (10 at + full speed); 20 to 60 for each foe, times your combo (sinks within + 1.6 seconds of each other, up to x5); 10 for a buoy shot; 100 + times the dam's number for each dam, 50 times it more for a + stretch with no life lost; and 400 for each of the first three + mini-bosses (800 each the next time around, and so on), each of + which also gives a life back. +
    • +
    • + Hot Potato: one fizzing bomb (a merge conflict, + its <<<<<<< markers showing) and a + fuse that keeps getting shorter. Whoever holds it passes it on by + touching someone, and whoever holds it when the fuse runs out is + blown out of the match. Someone just handed the bomb cannot pass + it on for a moment (it flashes white), and while three or more are + left nobody can hand it straight back to the one who just passed + it (a white ring at their feet shows who is safe). Handed the bomb + at its last moment, you still get time to pass it: a pass tops the + fuse up to 1.4 seconds, once a fuse for each runner. The holder runs a little faster, so a chase can end, and a + rival crouches before it lunges: that is your moment to dodge. The + last one standing wins the match and moves on through nine venues, + from the Break Room to the + Finale, then Finales that keep getting sharper; + being blown up costs one of three lives and runs the match again. + The venues bring rivals (the Sprinter, the Hider, the Trickster, + who feints before it dashes, the Pal and the Clingy), pickups + (Freeze, which stops every fuse for 2 seconds, Sneakers, Extra + Fuse, which adds 2 seconds to every fuse, and Swap, which trades + places with a random runner), long rows of server racks, a roof + with no wall at the bottom (off it is out), ice, conveyor belts, a + blackout and two bombs at once. Points: 10 times the venue for + every fuse that ends on someone else, 2 for each pass you make, 15 + more for a hot pass (under a second left) times your streak of hot + passes in a row (up to x5; a pass that is not hot ends it, and so + does a life lost), and 50 times the venue for a match won. +
    • +
    • + Crossing Rush: hop Planny up a strip of lanes, + racing two rival hoppers to the top: roads of cars and trucks, + rivers where you ride the logs and turtles (the water, or riding + off the edge, sends you back), train tracks that flash red and + ring before a train, and grass with bushes and rocks in the way. A + car, a train or the water sends you back down to the last grass + row, never out. Space shoves the hopper in front of you a cell, so + a well-timed shove puts a rival in the traffic (they will do the + same to you). First to the top wins the heat and moves on through + nine zones, from Side Street to + Rush Hour, then Rush Hours that keep getting + quicker; second or third costs one of three lives and runs the + heat again, though in the first two zones second place still gets + you through. The zones bring logs, trains, diving turtles, trucks + and lanes that speed up, a night lit only by headlights, rivers + that turn round and icy lanes that slide you a cell on, and rivals + (the Hopper, who waits for a clear gap, the Daredevil, who takes + the tight ones, the Bruiser, who shoves, and the Tagalong, who + follows you up and shoves near the top). Pickups sit on the + grass: Spring (your next hop goes two cells), Shield (the next hit + does not send you back), Coin and Horn (the nearest road stops for + a moment). Points: 1 for each row higher than you had got in the + heat, 50 times the zone for a heat won, times your streak of clean + wins (a win where you were never sent back adds one to it, up to + x3; any other win, a second place or a lost heat ends it), plus 3 + for each row the runner-up still had to go, 15 for a rival you + shoved that is sent back, 5 for a close call (a car or a train + through the cell you just left within a tenth of a second), and 10 + for a coin. +
    • +
    • + Bounce Road: race Planny's springy toy car up a + road laid across a giant's house and yard, with rival toy cars on + it that mean to stop you. Bump one sideways off the road, and press + Space to jump (you need a little speed, and a faster jump + goes further). Land on a rival to flatten it and bounce up again, + and land on another before your wheels touch the road to build the + bounce chain, up to x8. Every stunt in quick succession (a crush, a + rival bumped off, a hole, train, ball or barrier jumped, a ramp's + big air, a close shave, a boost strip) steps the combo: every + third in a row multiplies your points once more, up to x4, until + you go 2.6 seconds without one. In the air, a ring in your + highlight shows where you will come down, and a red one where a + rival will. Water or a hole under your wheels, a crash (a + flowerbed or a toy block nose first, a train, a truck's back), or + anything landing on you costs one of three lives. Ten stages, each + bringing something new: + Chalk Lane (cracks, boost strips and cones), + Hose Creek (broken bridges, a sprinkler, the Frog, + who hops), Kitchen Floor (oil slicks, a rolling + orange, the Sneak, who drops cones), Flowerbed Fork + (the road splits, ramps, falling flowerpots, the Nudge, who swipes + at you), Sandbox Run (road that crumbles behind + you, the Hauler too heavy to bump, the Bruiser, who shoves), + Toy Room (a toy train crossing, toy-block + chicanes, the Racer to catch), Garden Pond + (swaying bridges, drawbridges, the Cop, who chases you and pushes + you toward the edge), Rooftop Gutter (gusts of + wind), Night Lights (everything, in the dark) and + Monster Mash, where the Monster truck hops at + you: land on its roof five times to beat it. Then the road goes + round again from Kitchen Floor, quicker and meaner. Every hole has + a warning sign and a straight run-up, and can be cleared at 80% of + the top speed. Power-ups lie on the road from Hose Creek: Spring + (your next jump goes further), Bubble (one free save), Nitro (a + burst of speed) and Mega wheels (bigger and heavier: flatten + whatever you touch). Points: 1 for every 10 units of new road (a car + is 7 long); each rival's own points when you land on it (100 to + 300, the Racer most), times the chain; 60 for a rival that leaves + the road within a second and a half of your bump; 25 a hole and 40 + a train, ball or barrier jumped; 60 for a ramp's big air; 30 for a + close shave; 10 a star and a boost strip, all times the combo; + 250 a stomp on the Monster and 2,000 for beating it, with a life + back. At each stage line: 100 times the stage, 15 for every second + under the stage's par, and, with no life lost, 250 more and a life + back, up to five. +
    • +
    • + Ghoul Rush: blast Planny through a haunted + mansion, a room at a time, seen side on with the view scrolling + along with him. His flashlight blaster fires the way he faces, and + a bolt tilts a little toward a monster ahead near his height. It + heats up as it fires: after about three seconds of shooting it + slows, down to one bolt a second, a HEAT pill shows + how hot it is, and letting go of fire cools it. Rapid fire never + heats it. Grab + each room's key, then reach its door; a boss guards every fourth + room, and beating it opens the door. Zombies + shamble out of doors in the wall and lurch when you are close (two + bolts), crawlers come up through loose boards, + bats swoop down to your height in passes, + ghosts drift through walls and can only be hit, + and only hurt, while they are solid, and + skeletons throw bones you can shoot down. A bolt + to the head or a stomp from above doubles a kill, and kills in + quick succession build a chain that multiplies them, up to x8, but + it runs out in a second and a half. The rooms bring pits, shelves to jump up + through (down drops through one), boards that crumble and + chandeliers that come down on whatever is under them. Eight rooms, + the Foyer, Portrait Gallery, + Library, Ballroom (the + Great Gourd, which hops to where you stood: + watch its shadow), Kitchen, + Conservatory, Attic and + Crypt (Old Rattlebones, whose + shockwaves you jump), then round again, quicker and tougher. + Power-ups: Spread shot, Rapid fire, a Garlic shield (shrugs off one + hit) and a 1UP. A hit or a fall costs one of seven lives and puts + you back at the room's start (in a boss fight, the arena's), safe + for a moment. Points: 100 a zombie, 75 a crawler, 50 a bat, 150 a + ghost, 200 a skeleton, 40 a gourdling, all times the chain, 25 a bone shot down, 10 + a candy, 50 a power-up; through a door, 300 times the room number + plus the time bonus left (1500, dropping 30 a second; once it runs + out, zombies shamble in from the edges) and 500 more with no life + lost; and 2000 for the Gourd and 2500 for Rattlebones, times the + lap, with a life back. +

    It never hides your turn

      @@ -2354,7 +2756,7 @@
    • Nothing resumes by itself. Any game key plays on, and so does a - click on the Mini golf board. Playing on puts the banner away until + click on the Mini golf or Stack Deploy board. Playing on puts the banner away until the next new question.
    • @@ -2374,27 +2776,102 @@ again to set the power, and hold Space while the ball rolls to speed it up.
    • +
    • + Light Trails: the arrow keys, or W A + S D, steer, and Space spends a + boost charge for a burst of speed (two a heat, up to three). +
    • +
    • + Bug Hunt: the arrow keys, or W A S + D, fly the ship, and hold Space to fire. +
    • +
    • + Sunset Drive: hold up (or W) to drive and down (or + S) to brake, left and right steer, and Space + burns a nitro can for a burst of speed (two to start, up to three). +
    • +
    • + Stack Deploy: Space, up (or W) or a click + on the board drops the block. +
    • +
    • + Bumper Ring: hold the arrow keys, or W A + S D, to push your car that way (two at once + push on the diagonal), and Space dashes (two charges a + heat, one back every few seconds, up to three). +
    • +
    • + Rapids Run: left and right (or A and D) + steer, hold up (or W) to speed up and down (or + S) to slow down, and hold Space to fire. +
    • +
    • + Hot Potato: hold the arrow keys, or W A + S D, to run that way (two at once run on the + diagonal), and Space dashes: a lunge for a tag while you + hold the bomb, a dodge while you do not (two charges, one back + every 4 seconds). +
    • +
    • + Crossing Rush: the arrow keys, or W A + S D, hop one cell, one hop a press (a press + during a hop waits its turn), and Space shoves the + hopper in front of you a cell the way you face (once every 3 + seconds). +
    • +
    • + Bounce Road: hold up (or W) to drive and down (or + S) to brake, left and right steer (only a little in the + air), and Space jumps, once a press. A ramp launches you + on its own. +
    • +
    • + Ghoul Rush: hold left and right (or A D) to + run, up (or W) jumps, once a press (let go early for a + short hop), down (or S) drops through a shelf, and hold + Space to fire (in bursts: the blaster slows as it heats + and cools once you let go). +
    • Space starts a round, and plays again after a pause.
    • P pauses and plays.
    • -
    • Esc closes the window, with the game paused where it was.
    • +
    • R starts the round over, from the countdown.
    • +
    • + F, or Full screen under the board, gives + the game the whole screen: the board as big as the screen allows, + black bars where its shape leaves room, and a panel over it for the + game's name, your score and best, the game's Music slider, and Exit full screen. + The panel sits in a black bar when one is wide enough; otherwise it + floats in the top corner and, while you play and the pointer is + still, shrinks to your score in the bottom corner. The pointer hides while you are not + moving it. F or Esc + puts it back. A question, a sign-off or a finish puts it back too, + as it pauses the game. + It uses the browser's own full screen where the browser allows one. +
    • +
    • Enter does both: it starts a round, pauses it and plays on.
    • +
    • Esc closes the window, with the game paused where it was (in full screen, the first Esc leaves full screen).

    Activities need a keyboard: on a touch-only screen the window says so instead of showing the board.

    Best scores

    The window's title shows the best for the game on screen, and the - line under the board shows it beside your score. For Snake the best - is your highest score; for Mini golf it is your lowest full round of - eighteen holes, and a round left halfway never counts. - Reset best scores, at the bottom of the window, - clears both after a second click to confirm. + line under the board shows it beside your score, and each card shows + its game's. For Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush the best is + your highest score; for Mini golf it is your lowest full round of eighteen holes, + kept for each course on its own, and a round left halfway never counts. Reset best + scores, at the bottom of the window, clears them all after a + second click to confirm.

    Hiding it

    Don't want the die? Untick Show Activities in User - Preferences (the gear) and it is gone from every screen. + Preferences (the gear) and it is gone from every screen. To play + without sound, untick Play game sounds beside it. + A game with music (turn on Play game music there) has + its own Music slider under the board for how loud it plays.

    - Best scores, Snake's surprises found, your last pick and that switch are saved privately on + Best scores, Snake's surprises found, Light Trails' furthest arena, Bug Hunt's 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 furthest room, each game's music volume, your last pick and that switch are saved privately on this machine, with your other preferences, and never sent anywhere.

    @@ -2542,6 +3019,10 @@ Arrow keys, Home, End in Help Move between topics. + + Arrow keys, Home, End in User Preferences + Move between its tabs: up and down in the side list, left and right in the strip on a narrow window. +

    @@ -2551,26 +3032,46 @@

    Your preferences

    The gear button at the top, beside ?, opens - User Preferences: + User Preferences, always on its first tab. Its four + tabs sit in a side list, or in a strip along the top on a narrow + window:

    • - Role: Engineer, Product lead / PM, Architect / tech - lead, Designer (UX), QA / test engineer or Engineering manager, or - Not set / none of these (the default). It puts the - starter templates and Ask starter questions most useful to you first, - and never changes the questions a skill asks. + Appearance: Theme, Card width, Highlight color and + Role.
    • +
    • + Agents & models: the agents you can start and + the models each one offers. +
    • +
    • + System: Cleanup, and Desktop + app. +
    • +
    • + Sounds & activities: Sounds and Activities. +
    • +
    +

    + On Appearance and Sounds & activities, each change is saved the + moment you make it, and a small Saved mark shows + beside it. Close (or Esc) shuts the dialog. +

    +

    Appearance

    +
    • Theme: Follow my system (the default), Light or Dark.
    • - Card width: how wide the question and documents are. + Card width: how wide the questions, documents and dashboard are. Narrow (720 px), Comfortable - (880 px, the default) or - Wide (1,080 px). + (880 px, the default), + Wide (1,080 px) or + Ultra wide (1,440 px), + for an ultrawide monitor. On a smaller window they fit the space there is.
    • @@ -2579,19 +3080,52 @@ what is yours to do, and Planny's star uses it while he works.
    • - Sounds: Play sounds switches every - sound on or off at once. Below it, each moment has its own box: - Planny snoring and waking up, starting a skill from the dashboard, - the session opening, a started skill being ready, the session - ending, new questions for you, a reply on the Ask tab and a new tab - joining the strip. Keep only the ones you want; ticking a box plays - its sound. + Role: Engineer, Product lead / PM, Architect / tech + lead, Designer (UX), QA / test engineer or Engineering manager, or + Not set / none of these (the default). It puts the + starter templates and Ask starter questions most useful to you first, + and never changes the questions a skill asks. +
    • +
    +

    Agents & models

    +

    + Most people never need to change this: Plan2Code finds the agents + installed on this machine and ships an up-to-date model list with + every release. The tab opens on a table of every agent, with its + models and whether it was found on this machine. Edit + opens one agent's form, and Add agent a blank one. +

    +
      +
    • + Models: each built-in agent (Claude, Devin, Codex) + shows the models that come with Plan2Code, which every update + refreshes, and below them Models you added: a model + id and the name shown in the menu. Models you added stay through + updates. Restart plan2code to see a change in its model + menu.
    • - Activities: Show Activities puts - the die in the top bar, which opens small games to play while you - wait. Untick it to hide the die on every screen. + Agents: an agent you add is another command-line + tool the plan2code launcher can start, beside the + built-in ones. Give it a name, the command to run and, if you like, + a start prompt and models. Test checks the command + is on your PATH. The Command-line arguments fold + holds the arguments it is started with, the ones that skip its + permission prompts, and the ones that pick a model, where + {prompt} and {model} are filled in for you. + Added agents are saved in ~/.plan2code/agents.json; + Delete agent removes one.
    • +
    +

    + Nothing here is saved as you type. Each form has its own + Save and Discard, and an + Unsaved badge while it holds a change. Leaving a form + with an unsaved change (another tab, Back to summary, Close) asks + first: save it, discard it, or keep editing. +

    +

    System

    +
    • Cleanup: Find files to clean up lists what Plan2Code doesn't need in your @@ -2606,13 +3140,47 @@ handoffs/ folder is Plan2Code's own, so it is never offered for removal.
    • -
    • - Back to default puts everything back as it was, and - sets Role back to Not set. Your Activities best scores stay: only - Reset best scores, in the Activities window, clears - them. +
    • + Desktop app: shown only in the desktop app. + Show on the taskbar when Plan2Code needs me puts a + green dot on the taskbar button on Windows when it is your move and + a red one when it needs you, or a red badge on the dock icon on + macOS when it needs you. +
    • +
    • + Desktop app: shown only inside the desktop app, + where a switch puts a dot on the taskbar button when Plan2Code + needs you.
    +

    Sounds & activities

    +
      +
    • + Sounds: Play sounds switches every + sound on or off at once. Below it, each moment has its own box: + Planny snoring and waking up, starting a skill from the dashboard, + the session opening, a started skill being ready, the session + ending, new questions for you, a reply on the Ask tab and a new tab + joining the strip. Keep only the ones you want; ticking a box plays + its sound. +
    • +
    • + Activities: Show Activities puts + the die in the top bar, which opens small games to play while you + wait. Untick it to hide the die on every screen. + Play game sounds turns the games' sounds on or + off, leaving every other sound as it is; with Play sounds off, the + games are silent too. +
    • +
    +

    + Back to default resets only the tab on screen: + Appearance's four settings (Role goes back to Not set), or every sound + and the two Activities switches. Agents & models and System have + nothing to reset, so it is not shown there. Your Activities best + scores stay: only Reset best scores, in the + Activities window, clears them. +

    Your choices are remembered on this machine and carry over to every session you open here. @@ -2725,124 +3293,112 @@

    User Preferences

    - - - - - - - - - - - - +
    @@ -2976,16 +3532,32 @@ - -
    - -
    + + +
    +
    + +
    +
    +

    diff --git a/src/web-console/public/looks.js b/src/web-console/public/looks.js index 783a950..448f88f 100644 --- a/src/web-console/public/looks.js +++ b/src/web-console/public/looks.js @@ -9,7 +9,7 @@ import { normalizeRole, ROLE_NOT_SET } from "./starters.js"; import { bootData, hooks } from "./state.js"; import { el } from "./render.js"; import { tellApp } from "./app-bridge.js"; -import { ACTIVITIES, bestKey, memoKey } from "./activities.js"; +import { ACTIVITIES, bestKeys, memoKey, musicKey, musicLevel } from "./activities.js"; const $ = (id) => document.getElementById(id); @@ -31,13 +31,20 @@ export const DEFAULT_LOOKS = { ...soundPrefs(null), width: DEFAULT_CARD_WIDTH, hideUnavailable: true, - // Activities: the top bar's die, the game last picked, and one best score - // per listed game (activityBestSnake), each a flat key for cleanLooks(). + // Activities: the top bar's die, whether its games play sounds (under Play + // sounds, which silences them too), the game last picked, and one best score + // per listed game (activityBestSnake) or, for a game with courses, per + // course (activityBestGolfPirate), each a flat key for cleanLooks(). hideActivities: false, + activitySounds: true, + // Whether a game plays its chiptune music too: off until asked for. + gameMusic: false, lastActivity: "", - ...Object.fromEntries(ACTIVITIES.map((a) => [bestKey(a.id), 0])), + ...Object.fromEntries(ACTIVITIES.flatMap((a) => bestKeys(a).map((key) => [key, 0]))), // And one memo per game (activityMemoSnake): Snake's surprises found. ...Object.fromEntries(ACTIVITIES.map((a) => [memoKey(a.id), 0])), + // And, for a game with music, its music volume (activityMusicDrive), 0 to 100. + ...Object.fromEntries(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [musicKey(a.id), a.music])), }; export let looks = { ...DEFAULT_LOOKS }; @@ -55,14 +62,18 @@ export function adoptLooks(saved) { if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable; looks.width = cardWidth(looks.width); if (typeof looks.hideActivities !== "boolean") looks.hideActivities = DEFAULT_LOOKS.hideActivities; + if (typeof looks.activitySounds !== "boolean") looks.activitySounds = DEFAULT_LOOKS.activitySounds; + if (typeof looks.gameMusic !== "boolean") looks.gameMusic = DEFAULT_LOOKS.gameMusic; if (typeof looks.lastActivity !== "string") looks.lastActivity = DEFAULT_LOOKS.lastActivity; // A best score is a whole number of points, never below none. for (const a of ACTIVITIES) { - const key = bestKey(a.id); - const n = Number(looks[key]); - looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0; + for (const key of bestKeys(a)) { + const n = Number(looks[key]); + looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0; + } const memo = Number(looks[memoKey(a.id)]); looks[memoKey(a.id)] = Number.isFinite(memo) && memo > 0 ? Math.floor(memo) : 0; + if (a.music !== undefined) looks[musicKey(a.id)] = Math.round(musicLevel(a, looks[musicKey(a.id)]) * 100); } if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role); else delete looks.role; @@ -117,8 +128,9 @@ export async function syncLooks() { setTimeout(hooks.maybeWelcome, 0); } -// Fire-and-forget mirror. A failed POST costs nothing the next session would -// notice on this port; the localStorage copy still covers the reload case. +// The mirror on the server. A failed POST costs nothing the next session would +// notice on this port; the localStorage copy still covers the reload case. It +// resolves with whether the write landed, for Preferences' Saved mark. function pushLooks() { try { // Only what this tab changed since it last synced, so a tab with stale @@ -127,19 +139,29 @@ function pushLooks() { for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v; const before = syncedLooks; const partial = Boolean(before); - if (partial && !Object.keys(set).length) return; + if (partial && !Object.keys(set).length) return Promise.resolve({ ok: true }); syncedLooks = { ...looks }; const body = partial ? { set } : { looks }; // A write that did not land must be sent again with the next change. const undo = () => (syncedLooks = before); - fetch("/looks", { + const failed = (error) => { + undo(); + return { ok: false, error: error || "Could not save." }; + }; + return fetch("/looks", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body), }) - .then((res) => res.ok || undo()) - .catch(undo); - } catch {} + .then(async (res) => { + if (res.ok) return { ok: true }; + const reply = await res.json().catch(() => ({})); + return failed(reply.error); + }) + .catch(() => failed()); + } catch { + return Promise.resolve({ ok: false, error: "Could not save." }); + } } const systemDark = () => matchMedia("(prefers-color-scheme: dark)").matches; @@ -174,16 +196,26 @@ export function applyLooks() { ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i])); } +// Resolves { ok: true } once the server has it (or there was nothing new to +// send), or { ok: false, error } when the write did not land. export function saveLooks() { try { localStorage.setItem(LOOKS_KEY, JSON.stringify(looks)); } catch {} - pushLooks(); + const pushed = pushLooks(); applyLooks(); // A width change reflows the card without resizing the column, so the // column's observer never hears of it: refit the growing box here. hooks.fitGrowBox(); renderSwatches(); + return pushed; +} + +// Told of each swatch's save, for Preferences' Saved mark: set by the dialog's +// screen, since this module never imports one. +let swatchSaved = null; +export function onSwatchSaved(fn) { + swatchSaved = fn; } // Built once, repainted in place. Rebuilding the row on every choice destroyed @@ -200,7 +232,8 @@ export function renderSwatches() { b.setAttribute("aria-label", a.name); b.addEventListener("click", () => { looks.accent = id; - saveLooks(); + const saved = saveLooks(); + if (swatchSaved) swatchSaved(saved); }); box.appendChild(b); } @@ -231,15 +264,27 @@ export function renderSwatches() { } $("looks-role").value = looks.role ?? ROLE_NOT_SET; $("looks-activities").checked = !looks.hideActivities; + // Like a cue, the game sounds keep their tick while Play sounds is off. + $("looks-activity-sounds").checked = looks.activitySounds; + $("looks-activity-sounds").disabled = !looks.sound; + $("looks-game-music").checked = looks.gameMusic; + $("looks-game-music").disabled = !looks.sound; } // "Back to default": every look returns to its default, but the role is // marked as asked, the welcome stays seen, and the Activities' best scores -// and last pick stay (only Reset best scores clears those). -export function resetLooks() { +// and last pick stay (only Reset best scores clears those). Given `keys` (one +// Preferences tab's, prefsResetScope() in prefs.js), only those change: the +// role is cleared but marked as asked, the rest take their defaults, and +// every other key stays as it is. +export function resetLooks(keys) { + if (keys) { + for (const key of keys) looks[key] = key === "role" ? ROLE_NOT_SET : DEFAULT_LOOKS[key]; + return; + } const kept = { lastActivity: looks.lastActivity }; for (const a of ACTIVITIES) { - kept[bestKey(a.id)] = looks[bestKey(a.id)]; + for (const key of bestKeys(a)) kept[key] = looks[key]; kept[memoKey(a.id)] = looks[memoKey(a.id)]; } looks = { ...DEFAULT_LOOKS, ...kept, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen }; diff --git a/src/web-console/public/meter.js b/src/web-console/public/meter.js index 207bd51..852ea27 100644 --- a/src/web-console/public/meter.js +++ b/src/web-console/public/meter.js @@ -6,7 +6,7 @@ // access at module scope, and its one import is the data-only skills.js: the // server, console.mjs, the page and `node --test` all import this file. -import { SKILLS, isMetered, isPhased } from "./skills.js"; +import { FLOW_SKILLS, isMetered, isPhased } from "./skills.js"; // The weights (FR-12): the events that are not a skill's own launch live // here, and each skill's weight is its `weight` in skills.js. Tune there or here. @@ -24,7 +24,7 @@ const EVENT_WEIGHTS = { "git-conflict": 1, }; // A skill's fields as a table by workflow, leaving out the entries without one. -const bySkill = (field) => Object.fromEntries(SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]])); +const bySkill = (field) => Object.fromEntries(FLOW_SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]])); export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") }); // Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder, @@ -32,7 +32,7 @@ export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") }) // reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on // launch (Git then adds its commit tally and conflict help). Derived from // skills.js (`metered`). -export const LAUNCH_COUNTED = Object.freeze(new Set(SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow))); +export const LAUNCH_COUNTED = Object.freeze(new Set(FLOW_SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow))); // Git's commits weigh what they add up to: each `git-commits` run carries // `commits`, and a skill run scores one point per COMMITS_PER_POINT commits, @@ -65,7 +65,7 @@ export const MAX_TASKS = 999; // bonus. The phase's `run` then takes the row over with its final score, so // the total only ever climbs. Workflows whose headline counts tasks, derived // from skills.js (`phased`): -export const PROGRESS_WORKFLOWS = Object.freeze(new Set(SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow))); +export const PROGRESS_WORKFLOWS = Object.freeze(new Set(FLOW_SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow))); // Implement + Review reviews every phase as a stage of the build. A `review` // run inside it is that stage, so it scores the phase's TASK_BONUS when it @@ -120,7 +120,7 @@ export const ANSWERS_PER_POINT = 2; // The skill names the answers row uses ("7 answers in Plan"), derived from // skills.js (`name`). -const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(SKILLS.map((s) => [s.workflow, s.name]))); +const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(FLOW_SKILLS.map((s) => [s.workflow, s.name]))); // The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3"). const launchOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(0, id.indexOf(":")) : "L0"); diff --git a/src/web-console/public/palette.js b/src/web-console/public/palette.js index c4c91e4..42f225b 100644 --- a/src/web-console/public/palette.js +++ b/src/web-console/public/palette.js @@ -240,6 +240,7 @@ export const CARD_WIDTHS = { narrow: { label: "Narrow", px: 720 }, comfortable: { label: "Comfortable", px: 880 }, wide: { label: "Wide", px: 1080 }, + ultrawide: { label: "Ultra wide", px: 1440 }, }; export const DEFAULT_CARD_WIDTH = "comfortable"; diff --git a/src/web-console/public/prefs.js b/src/web-console/public/prefs.js new file mode 100644 index 0000000..f04cab4 --- /dev/null +++ b/src/web-console/public/prefs.js @@ -0,0 +1,31 @@ +// Plan2Code Web Console - what the User Preferences dialog is. +// +// Its tabs in order, which one opens, and what Back to default resets on +// each. No DOM access at module scope, and its one import is the data-only +// palette.js: the page and `node --test` both import this file. + +import { SOUND_EVENTS, soundKey } from "./palette.js"; + +const tab = (id, label, hint, sections) => Object.freeze({ id, label, hint, sections: Object.freeze(sections) }); + +// Each section id names one fieldset in the dialog (its data-section). +export const PREFS_TABS = Object.freeze([ + tab("appearance", "Appearance", "Theme, width, color, role", ["theme", "width", "accent", "role"]), + tab("agents", "Agents & models", "Your CLIs and models", ["agents"]), + tab("system", "System", "Cleanup, desktop app", ["cleanup", "desktop"]), + tab("sounds", "Sounds & activities", "What plays", ["sounds", "activities"]), +]); + +// The tab the dialog opens on: the one asked for when there is such a tab, +// else Appearance. Nothing is remembered between opens. +export function prefsOpenTab(asked) { + return PREFS_TABS.some((t) => t.id === asked) ? asked : "appearance"; +} + +// The looks keys Back to default resets on a tab, or null where it has +// nothing to reset (and is hidden). +export function prefsResetScope(tab) { + if (tab === "appearance") return ["theme", "width", "accent", "role"]; + if (tab === "sounds") return ["sound", ...Object.keys(SOUND_EVENTS).map(soundKey), "hideActivities", "activitySounds", "gameMusic"]; + return null; +} diff --git a/src/web-console/public/render.js b/src/web-console/public/render.js index 38f37d6..4530270 100644 --- a/src/web-console/public/render.js +++ b/src/web-console/public/render.js @@ -406,7 +406,7 @@ export function isMac() { // backdrop is the itself to the event, and so is its own padding, so // the point has to fall outside its box -- for the press as well as the // release, or selecting text inside and letting go outside would close it. -export function lightDismiss(dlg) { +export function lightDismiss(dlg, beforeClose) { const outside = (e) => { const r = dlg.getBoundingClientRect(); return e.target === dlg && (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom); @@ -414,7 +414,11 @@ export function lightDismiss(dlg) { let pressedOutside = false; dlg.addEventListener("pointerdown", (e) => (pressedOutside = outside(e))); dlg.addEventListener("click", (e) => { - if (pressedOutside && outside(e)) dlg.close(); + if (pressedOutside && outside(e)) { + // `beforeClose` may hold the close: false, or a Promise of false. + if (!beforeClose) dlg.close(); + else Promise.resolve(beforeClose()).then((go) => go !== false && dlg.close()); + } pressedOutside = false; }); } diff --git a/src/web-console/public/screens/agents-view.js b/src/web-console/public/screens/agents-view.js new file mode 100644 index 0000000..95a3071 --- /dev/null +++ b/src/web-console/public/screens/agents-view.js @@ -0,0 +1,713 @@ +// Plan2Code Web Console - User Preferences' Agents & models tab. +// +// A summary table of every agent (the built-in CLIs, the ones the person +// added, and a row kept for the v3 orchestrator) whose Edit opens that agent's +// full form. Nothing saves as it changes: a form edits a draft, and its Save +// sends the saved list with only that draft swapped in, so a half-typed +// command line never reaches agents.json or models.json. + +import { el } from "../render.js"; +import { hooks } from "../state.js"; + +const $ = (id) => document.getElementById(id); + +// The CLIs the launcher reads a model list for, in table order (routes.mjs MODEL_CLIS). +const MODEL_CLIS = ["claude", "devin", "codex"]; + +// What the table calls each built-in, and the command it runs (the launcher's CLIS ids). +const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" }; + +// The last server reply for each list. Unknown keys on an agent ride along untouched. +let saved = { agents: [], user: emptyLists(), shipped: emptyLists() }; + +// At most one per form being edited: "cli:" for a built-in's own models, +// "agent:" for an added agent, "agent:new" for one being added. +const drafts = new Map(); + +// The form on screen (a drafts key), or null while the summary shows. +let openKey = null; + +// The server's complaint about the open form, { field, error }, and a 409's +// warnings while Save anyway is on offer. +let formError = null; +let formReplace = null; + +// Delete agent waiting for its second click; the arguments fold's state, kept across redraws. +let confirming = false; +let argsOpen = false; + +// The badge each summary row last showed, by row key: { command, state }. +const found = new Map(); + +// Each open of the tab loads afresh: only the newest load's answers are drawn. +let loadSeq = 0; + +function emptyLists() { + return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []])); +} + +// Whether the status line says "Deleted.", which the next form opened clears +// (load warnings stay until the next open). +let deletedNote = false; + +function setAgentsStatus(text, isError, { deleted = false } = {}) { + const status = $("agents-status"); + status.textContent = text; + status.classList.toggle("error", Boolean(isError)); + deletedNote = deleted; +} + +function newAgent() { + return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] }; +} + +function normalizeAgent(agent) { + for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = []; + return agent; +} + +const cliOf = (key) => key.slice("cli:".length); +const agentId = (key) => key.slice("agent:".length); + +function savedEntry(key) { + if (key.startsWith("cli:")) return saved.user[cliOf(key)] || []; + if (key === "agent:new") return newAgent(); + return saved.agents.find((a) => a.id === agentId(key)); +} + +// JSON with object keys sorted, so a label removed and typed back counts as unchanged. +function canonical(value) { + return JSON.stringify(value, (_, v) => + v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v + ); +} + +function isDirty(key) { + return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(key)); +} + +function nameOf(key) { + if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)]; + const draft = drafts.get(key); + return String((draft && draft.name) || "").trim() || savedEntry(key)?.name || "a new agent"; +} + +const modelNames = (list) => list.map((m) => m.label || m.id); + +/* ------------------------------------------------------------- summary */ + +// One row per agent, in order: the built-ins, the added agents, the orchestrator. +function summaryRows() { + return [ + ...MODEL_CLIS.map((cli) => ({ + key: "cli:" + cli, + name: BUILT_IN[cli], + command: cli, + models: [...saved.shipped[cli], ...saved.user[cli]], + noneShip: saved.shipped[cli].length === 0, + })), + ...saved.agents.map((a) => ({ key: "agent:" + a.id, name: a.name, command: a.command, models: a.models })), + ]; +} + +function renderSummary() { + const body = $("agents-table").tBodies[0]; + body.replaceChildren(); + const check = []; + for (const row of summaryRows()) { + const tr = el("tr"); + tr.dataset.key = row.key; + const name = el("td", "prefs-agents-name"); + name.append(el("span", null, row.name), el("code", null, row.command)); + if (row.noneShip) name.append(el("span", "help", `No models ship for ${row.name} yet; add your own in Edit.`)); + const models = el("td", "prefs-agents-models"); + const names = modelNames(row.models); + models.textContent = names.length ? `${names.length}: ${names.join(", ")}` : "None"; + const badge = el("span", "prefs-badge"); + const last = found.get(row.key); + if (last && last.command === row.command) drawBadge(badge, last.state); + else { + badge.textContent = "Checking..."; + check.push(row); + } + const edit = el("button", "btn small", "Edit"); + edit.type = "button"; + edit.setAttribute("aria-label", "Edit " + row.name); + edit.addEventListener("click", () => openForm(row.key)); + const editCell = el("td", "prefs-agents-edit"); + editCell.append(edit); + const badgeCell = el("td"); + badgeCell.append(badge); + tr.append(name, models, badgeCell, editCell); + body.appendChild(tr); + } + const soon = el("tr", "prefs-agents-soon"); + const soonName = el("td", "prefs-agents-name"); + soonName.append(el("span", null, "v3 orchestrator"), el("span", "help", "Nothing to set yet.")); + soon.append(soonName, el("td", "prefs-agents-models"), el("td"), el("td")); + body.appendChild(soon); + if (check.length) checkFound(check, loadSeq); +} + +const BADGES = { + ok: "Found", + missing: "Not found on PATH", + unknown: "Not checked", +}; + +function drawBadge(badge, state) { + badge.textContent = BADGES[state]; + badge.classList.remove("ok", "missing"); + if (state !== "unknown") badge.classList.add(state); +} + +// Whether each row's command is on PATH, all at once. /agents/test only +// resolves the command and never runs it. +async function checkFound(rows, seq) { + await Promise.all( + rows.map(async (row) => { + let state = "unknown"; + try { + const res = await fetch("/agents/test", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ command: row.command }), + }); + if (res.ok) state = (await res.json()).found ? "ok" : "missing"; + } catch {} + if (seq !== loadSeq) return; + found.set(row.key, { command: row.command, state }); + const badge = $("agents-table").querySelector(`tr[data-key="${CSS.escape(row.key)}"] .prefs-badge`); + if (badge) drawBadge(badge, state); + }) + ); +} + +/* ------------------------------------------------------------- the form */ + +function showSummary(on) { + $("agents-table").hidden = !on; + $("agents-add").hidden = !on; + $("agents-intro").hidden = !on; + $("agents-form").hidden = on; +} + +function openForm(key) { + if (deletedNote) setAgentsStatus("", false); + openKey = key; + formError = null; + formReplace = null; + confirming = false; + argsOpen = key === "agent:new"; + if (!drafts.has(key)) drafts.set(key, structuredClone(key === "agent:new" ? newAgent() : savedEntry(key))); + showSummary(false); + drawForm(); + $("agents-form").querySelector("input")?.focus(); +} + +// Back on the summary, focus goes to the row just left (its Edit), or to Add +// agent when that row is gone (a new agent not saved, one just deleted). +function closeForm() { + const left = openKey; + if (openKey) drafts.delete(openKey); + openKey = null; + formError = null; + formReplace = null; + confirming = false; + $("agents-form").replaceChildren(); + showSummary(true); + renderSummary(); + const row = left && $("agents-table").querySelector(`tr[data-key="${CSS.escape(left)}"] .prefs-agents-edit button`); + (row || $("agents-add")).focus(); +} + +function edited() { + if (openKey) renderDirty(openKey); +} + +function agentField(label, field, child) { + const wrap = el("div", "agent-field"); + wrap.dataset.field = field; + wrap.append(el("span", null, label), child); + return wrap; +} + +function agentInput(agent, key, label, placeholder, trim) { + const input = el("input"); + input.value = agent[key] || ""; + input.placeholder = placeholder; + input.setAttribute("aria-label", label); + input.dataset.field = key; + input.addEventListener("input", () => { + agent[key] = trim ? input.value.trim() : input.value; + edited(); + }); + return input; +} + +// A list of text rows (arguments), with Remove on each and an Add under them. +function agentArgsEditor(agent, key, label, placeholder, addLabel) { + const box = el("div", "agent-rows"); + box.dataset.field = key; + const draw = () => { + box.replaceChildren(); + agent[key].forEach((value, i) => { + const row = el("div", "agent-row"); + const input = el("input"); + input.value = value; + input.placeholder = placeholder; + input.setAttribute("aria-label", label); + input.dataset.field = key; + input.addEventListener("input", () => { + agent[key][i] = input.value.trim(); + edited(); + }); + const remove = el("button", "btn small ghost", "Remove"); + remove.type = "button"; + remove.addEventListener("click", () => { + agent[key].splice(i, 1); + draw(); + edited(); + }); + row.append(input, remove); + box.appendChild(row); + }); + const add = el("button", "btn small ghost", addLabel); + add.type = "button"; + add.addEventListener("click", () => { + agent[key].push(""); + draw(); + edited(); + box.querySelector(".agent-row:last-of-type input")?.focus(); + }); + box.appendChild(add); + }; + draw(); + return agentField(label, key, box); +} + +// A models list: an id and a name for the menu on each row. An added agent's +// rows drop a blank name; a built-in's keep it, as models.json does. +function agentModelsEditor(list, { label: fieldLabel = "Models", optionalName = true } = {}) { + const box = el("div", "agent-rows"); + box.dataset.field = "models"; + const draw = () => { + box.replaceChildren(); + list.forEach((m, i) => { + const row = el("div", "agent-row model"); + const id = el("input"); + id.value = m.id || ""; + id.placeholder = optionalName ? "Model id, for {model}" : "Model id"; + id.setAttribute("aria-label", "Model id"); + id.dataset.field = "models"; + const label = el("input"); + label.value = m.label || ""; + label.placeholder = optionalName ? "Name shown in the menu (optional)" : "Name shown in the menu"; + label.setAttribute("aria-label", "Name shown in the menu"); + label.dataset.field = "models"; + const remove = el("button", "btn small ghost", "Remove"); + remove.type = "button"; + id.addEventListener("input", () => { + m.id = id.value.trim(); + edited(); + }); + label.addEventListener("input", () => { + const text = label.value.trim(); + if (text || !optionalName) m.label = text; + else delete m.label; + edited(); + }); + remove.addEventListener("click", () => { + list.splice(i, 1); + draw(); + edited(); + }); + row.append(id, label, remove); + box.appendChild(row); + }); + const add = el("button", "btn small ghost", "Add a model"); + add.type = "button"; + add.addEventListener("click", () => { + list.push(optionalName ? { id: "" } : { id: "", label: "" }); + draw(); + edited(); + box.querySelector(".agent-row:last-of-type input")?.focus(); + }); + box.appendChild(add); + }; + draw(); + return agentField(fieldLabel, "models", box); +} + +// The command's Test: where it would run from. Never saves. +function agentTest(agent) { + const wrap = el("div", "prefs-agents-test"); + const test = el("button", "btn small", "Test"); + test.type = "button"; + const result = el("span", "help agent-test-result"); + result.setAttribute("role", "status"); + test.addEventListener("click", async () => { + const command = String(agent.command || "").trim(); + if (!command) { + result.textContent = "Type a command first."; + return; + } + result.textContent = "Looking..."; + try { + const res = await fetch("/agents/test", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ command }), + }); + const body = await res.json(); + if (!res.ok) result.textContent = body.error || "Could not test."; + else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH"; + } catch { + result.textContent = "Could not test."; + } + }); + wrap.append(test, result); + return wrap; +} + +function builtInFields(cli, draft) { + const shipped = el("div", "models-list prefs-agents-shipped"); + shipped.setAttribute("aria-label", "Comes with Plan2Code"); + for (const m of saved.shipped[cli]) { + const row = el("div", "models-row locked"); + row.append(el("span", null, m.id), el("span", null, m.label || "")); + shipped.appendChild(row); + } + const note = el("div", "models-note"); + note.innerHTML = + "
      " + + "
    • Restart plan2code to see a change in its model menu.
    • " + + "
    • At any time, run plan2code --model <id>, or pick your model inside your agent before running a skill.
    • " + + "
    • Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.
    • " + + "
    • Devin models are limited to Low, Medium and High effort.
    • " + + "
    "; + const comes = el("div", "agent-field"); + comes.append(el("span", null, "Comes with Plan2Code")); + if (saved.shipped[cli].length) comes.append(shipped); + else comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`)); + return [note, comes, agentModelsEditor(draft, { label: "Models you added", optionalName: false })]; +} + +function addedFields(draft) { + const command = agentField("Command", "command", agentInput(draft, "command", "Command", "Program to run, such as myagent", true)); + command.append(agentTest(draft)); + const fold = el("details", "prefs-agents-args"); + fold.open = argsOpen; + fold.addEventListener("toggle", () => (argsOpen = fold.open)); + fold.append( + el("summary", null, "Command-line arguments"), + agentArgsEditor(draft, "args", "Arguments", "--message={prompt}", "Add an argument"), + agentArgsEditor(draft, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"), + agentArgsEditor(draft, "modelArgs", "Model arguments", "--model={model}", "Add an argument"), + ); + return [ + agentField("Name", "name", agentInput(draft, "name", "Name", "Name shown in the menu", true)), + command, + agentField("Start prompt", "prompt", agentInput(draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)), + agentModelsEditor(draft.models), + fold, + ]; +} + +// Save, Discard and the Unsaved badge (shown only while the draft differs), +// the Saved mark's spot, Save anyway after a 409, and Delete agent with its +// confirm on the form itself (never the browser's confirm()). +function formFoot(key) { + const foot = el("div", "agent-foot prefs-agents-foot"); + const save = el("button", "btn small primary prefs-agents-save", "Save"); + save.type = "button"; + save.addEventListener("click", () => saveForm(key)); + const discard = el("button", "btn small ghost prefs-agents-discard", "Discard"); + discard.type = "button"; + discard.addEventListener("click", () => discardOpen()); + const badge = el("span", "prefs-unsaved-badge", "Unsaved"); + foot.append(save, discard, badge); + if (formReplace) { + const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway"); + anyway.type = "button"; + anyway.addEventListener("click", () => saveForm(key, { replace: true })); + foot.append(anyway); + } + if (key.startsWith("agent:") && key !== "agent:new") { + if (confirming) { + const yes = el("button", "btn small danger", "Yes, delete"); + yes.type = "button"; + yes.addEventListener("click", () => deleteAgent(key)); + const keep = el("button", "btn small ghost", "Keep"); + keep.type = "button"; + keep.addEventListener("click", () => { + confirming = false; + drawForm(); + }); + foot.append(el("span", "help", "Delete this agent?"), yes, keep); + } else { + const del = el("button", "btn small ghost danger prefs-agents-delete", "Delete agent"); + del.type = "button"; + del.addEventListener("click", () => { + confirming = true; + drawForm(); + }); + foot.append(del); + } + } + return foot; +} + +function renderDirty(key) { + const foot = $("agents-form").querySelector(".prefs-agents-foot"); + if (!foot || key !== openKey) return; + const dirty = isDirty(key); + for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty; +} + +// Which field or button has focus, so a redraw (an id assigned, an error +// marked) puts the person back where they were: { nth, start, end }. What +// they typed is already in the draft the redraw reads. +const FORM_FOCUSABLE = "input, button, summary"; + +function formFocus(form) { + const active = document.activeElement; + if (!active || !form.contains(active)) return null; + const at = { nth: [...form.querySelectorAll(FORM_FOCUSABLE)].indexOf(active) }; + if (active instanceof HTMLInputElement) Object.assign(at, { start: active.selectionStart, end: active.selectionEnd }); + return at; +} + +function restoreFormFocus(form, at) { + if (!at) return; + const target = form.querySelectorAll(FORM_FOCUSABLE)[at.nth]; + // A button the redraw hid (Save, once saved) hands focus to the heading. + if (!target || target.closest("[hidden]")) return form.querySelector(".prefs-agents-title")?.focus(); + target.focus(); + if (target instanceof HTMLInputElement && at.start !== undefined) { + try { + target.setSelectionRange(at.start, at.end); + } catch {} + } +} + +function drawForm() { + const form = $("agents-form"); + const key = openKey; + const draft = drafts.get(key); + const focus = formFocus(form); + form.replaceChildren(); + const back = el("button", "btn small ghost prefs-agents-back", "Back to summary"); + back.type = "button"; + back.addEventListener("click", async () => { + if (await hooks.confirmUnsaved()) closeForm(); + }); + const title = el("h3", "prefs-agents-title"); + title.tabIndex = -1; + if (key.startsWith("cli:")) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key))); + else title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(key).name)); + const fields = el("div", "prefs-agents-fields"); + fields.append(...(key.startsWith("cli:") ? builtInFields(cliOf(key), draft) : addedFields(draft))); + form.append(back, title, fields); + if (formError) { + for (const input of form.querySelectorAll("input")) { + if (input.dataset.field === formError.field) input.classList.add("invalid"); + } + form.append(el("p", "agent-error", formError.error)); + } + if (formReplace) form.append(el("p", "agent-error", formReplace.join(" "))); + form.append(formFoot(key)); + renderDirty(key); + restoreFormFocus(form, focus); +} + +/* ------------------------------------------------------------- saving */ + +// The list as the server wants it: blank rows and models without an id dropped. +function cleanAgent(a) { + return { + ...a, + args: a.args.filter((v) => v !== ""), + bypassArgs: a.bypassArgs.filter((v) => v !== ""), + modelArgs: a.modelArgs.filter((v) => v !== ""), + models: a.models.filter((m) => m.id), + }; +} + +async function postJson(url, payload) { + const res = await fetch(url, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify(payload), + }); + return { res, body: await res.json() }; +} + +// The form's foot, for the Saved mark (or the error in its place). +const formMark = (result) => hooks.markSaved($("agents-form").querySelector(".prefs-agents-foot"), result); + +// Fresh from what was just saved: the form redraws on a clean draft. +function savedAs(key) { + drafts.delete(openKey); + openKey = key; + drafts.set(key, structuredClone(savedEntry(key))); + formError = null; + formReplace = null; + drawForm(); +} + +async function saveModelsFor(cli) { + const sent = drafts.get("cli:" + cli).filter((m) => m.id); + try { + const { res, body } = await postJson("/models", { models: { ...saved.user, [cli]: sent } }); + if (!res.ok) { + formMark({ ok: false, error: body.error || "Could not save." }); + return false; + } + saved.user[cli] = (body.user && body.user[cli]) || sent; + } catch { + formMark({ ok: false, error: "Could not save." }); + return false; + } + savedAs("cli:" + cli); + formMark({ ok: true, text: "Saved. Restart plan2code to use it." }); + return true; +} + +async function saveAgentFor(key, { replace = false } = {}) { + const draft = drafts.get(key); + const isNew = key === "agent:new"; + if (isNew && (!String(draft.name || "").trim() || !String(draft.command || "").trim())) { + formError = { field: String(draft.name || "").trim() ? "command" : "name", error: "Give it a name and a command first." }; + drawForm(); + return false; + } + const at = isNew ? saved.agents.length : saved.agents.findIndex((a) => a.id === agentId(key)); + const agents = saved.agents.map((a) => cleanAgent(a)); + agents.splice(at, isNew ? 0 : 1, cleanAgent(draft)); + try { + const { res, body } = await postJson("/agents", replace ? { agents, replace: true } : { agents }); + if (res.status === 409) { + formError = { field: null, error: body.error || "Not saved." }; + formReplace = Array.isArray(body.warnings) ? body.warnings : []; + drawForm(); + return false; + } + if (!res.ok) { + formError = { field: body.index === at ? body.field : null, error: body.error || "Could not save." }; + formReplace = null; + drawForm(); + return false; + } + saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent); + } catch { + formMark({ ok: false, error: "Could not save." }); + return false; + } + const id = saved.agents[at].id; + found.delete(key); + found.delete("agent:" + id); + savedAs("agent:" + id); + formMark({ ok: true }); + return true; +} + +function saveForm(key, options) { + return key.startsWith("cli:") ? saveModelsFor(cliOf(key)) : saveAgentFor(key, options); +} + +async function deleteAgent(key) { + const agents = saved.agents.filter((a) => a.id !== agentId(key)).map(cleanAgent); + confirming = false; + try { + const { res, body } = await postJson("/agents", { agents }); + if (!res.ok) { + formError = { field: null, error: body.error || "Could not delete." }; + drawForm(); + return; + } + saved.agents = (Array.isArray(body.agents) ? body.agents : agents).map(normalizeAgent); + } catch { + formError = { field: null, error: "Could not delete." }; + drawForm(); + return; + } + found.delete(key); + closeForm(); + setAgentsStatus("Deleted.", false, { deleted: true }); +} + +/* ------------------------------------------------------------- the dialog's side */ + +// An open form whose draft differs from what is saved. +export function hasUnsaved() { + return openKey !== null && isDirty(openKey); +} + +// What the unsaved prompt calls the open form. +export function unsavedName() { + return openKey ? nameOf(openKey) : ""; +} + +export function saveOpen() { + return openKey ? saveForm(openKey) : Promise.resolve(true); +} + +export function discardOpen() { + if (!openKey) return; + if (openKey === "agent:new") return closeForm(); + drafts.set(openKey, structuredClone(savedEntry(openKey))); + formError = null; + formReplace = null; + confirming = false; + drawForm(); +} + +// Back into the form after Keep editing or a failed Save: the marked field, else the first. +export function focusOpen() { + const form = $("agents-form"); + (form.querySelector("input.invalid") || form.querySelector("input"))?.focus(); +} + +// Each time the dialog opens: the summary, from the server. +export async function loadAgentsView() { + const seq = ++loadSeq; + openKey = null; + drafts.clear(); + found.clear(); + formError = null; + formReplace = null; + confirming = false; + $("agents-form").replaceChildren(); + showSummary(true); + setAgentsStatus("", false); + const [agents, models] = await Promise.all([ + fetch("/agents").then((r) => (r.ok ? r.json() : null)).catch(() => null), + fetch("/models").then((r) => (r.ok ? r.json() : null)).catch(() => null), + ]); + if (seq !== loadSeq) return; + const problems = []; + if (agents) { + saved.agents = (Array.isArray(agents.agents) ? agents.agents : []).map(normalizeAgent); + if (Array.isArray(agents.warnings)) problems.push(...agents.warnings); + } else { + saved.agents = []; + problems.push("Agents could not be loaded."); + } + saved.user = emptyLists(); + saved.shipped = emptyLists(); + if (models) { + for (const cli of MODEL_CLIS) { + if (Array.isArray(models.user?.[cli])) saved.user[cli] = models.user[cli]; + if (Array.isArray(models.shipped?.[cli])) saved.shipped[cli] = models.shipped[cli]; + } + } else { + problems.push("Models could not be loaded."); + } + setAgentsStatus(problems.join(" "), problems.length > 0); + renderSummary(); +} + +export function wireAgentsView() { + $("agents-add").addEventListener("click", () => openForm("agent:new")); +} diff --git a/src/web-console/public/screens/ask.js b/src/web-console/public/screens/ask.js index 0ffb682..10cff84 100644 --- a/src/web-console/public/screens/ask.js +++ b/src/web-console/public/screens/ask.js @@ -1,8 +1,8 @@ // Plan2Code Web Console - the Ask chat, the Subagents tab, and attaching files to notes. import { page, saveNow, redraw, freshChat, hooks, scrollMemory, setDraft } from "../state.js"; -import { chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js"; -import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen } from "../selectors.js"; +import { chatAnswering, chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js"; +import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen, loopAskLocked, loopDriving } from "../selectors.js"; import { el, md, isMac, lightDismiss, shortTime } from "../render.js"; import { startersFor } from "../starters.js"; import { looks } from "../looks.js"; @@ -37,6 +37,7 @@ function askFrame() { agent: page.S.agent, agentLastSeenMs: Date.parse(page.agentLastSeen), now: Date.now(), + answering: chatAnswering(base), }); return { ...base, offline }; } @@ -45,7 +46,13 @@ export function askState() { const frame = askFrame(); const shown = chatView(frame, { pendingSends: page.local.chat.pending, agentActivity: activity() }); const pendingSendCount = shown.rows.filter((r) => r.pending && !r.failed).length; - return { frame, view: shown, send: chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount }) }; + const send = chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount }); + // The Implementation Loop locks Ask like everything else it drives (FR-15), + // unless a question waits for the person (FR-14). + if (send.canType && loopAskLocked()) { + return { frame, view: shown, send: { state: "ok", text: "Ask is off while the loop builds.", canType: false } }; + } + return { frame, view: shown, send }; } // The conversation a send belongs to. The page's own record wins over the @@ -760,7 +767,8 @@ export function renderSubagentsButton() { btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on))); btn.title = label; btn.setAttribute("aria-label", label); - btn.disabled = page.gone; + // The Subagents switch is the person's setting for the next agent; the loop's phases are already started. + btn.disabled = page.gone || loopDriving(); } // The Subagents dialog, filled from the frame each time it opens. A null diff --git a/src/web-console/public/screens/cards.js b/src/web-console/public/screens/cards.js index d527926..20316fe 100644 --- a/src/web-console/public/screens/cards.js +++ b/src/web-console/public/screens/cards.js @@ -16,6 +16,8 @@ import { byId, docs, isGitBoard, + loopDriving, + loopWaiting, } from "../selectors.js"; import { lastOpenCard, @@ -316,14 +318,38 @@ function inFlightFor(item) { return sub ? { value: sub, summary: "" } : null; } +// While the Implementation Loop drives, an open card is a record, not a form +// (FR-15): "handled" when the loop answers it itself, "locked" otherwise. The +// one exception (FR-14) is a required question the loop does not handle, which +// stays a live form while it waits for the person. +function loopLockFor(item) { + if (!loopDriving() || !isOpen(item) || finish()) return null; + if (item.handledBy === "loop") return "handled"; + return loopWaiting() && item.required !== false ? null : "locked"; +} + +function renderLoopLocked(card, item, why) { + const box = el("div", "answered is-loop " + (why === "handled" ? "is-handled" : "is-locked")); + if (why === "handled") { + box.appendChild(el("p", "answered-head loop-tag", "The loop handles this")); + box.appendChild(el("p", "answered-lock", "The Implementation Loop answers this one itself, so there is nothing to do here.")); + } else { + box.appendChild(el("p", "answered-lock", "The Implementation Loop is building. This unlocks by itself if it needs you.")); + } + card.appendChild(box); + lockedOptions(card, item, []); +} + export function renderCard(item) { const staged = page.local.staged[item.id]; const flight = inFlightFor(item); + const loopLock = loopLockFor(item); const card = el( "article", "card question" + (!isOpen(item) || finish() ? " is-answered" : staged ? " is-staged" : "") + - (flight ? " is-inflight" : "") + (flight ? " is-inflight" : "") + + (loopLock ? " is-loop-" + loopLock : "") ); // Which question this card is for, so a render can tell whether the card it @@ -348,6 +374,8 @@ export function renderCard(item) { // send can no longer go anywhere and the form would be a trap. if (!isOpen(item) || finish()) { renderSettled(card, item); + } else if (loopLock) { + renderLoopLocked(card, item, loopLock); } else if (flight) { renderInFlight(card, item, flight); } else { @@ -355,7 +383,7 @@ export function renderCard(item) { if (build) build(card, item, staged); } - if (item.required === false && isOpen(item) && !flight && !finish()) { + if (item.required === false && isOpen(item) && !flight && !finish() && !loopLock) { const skipped = Boolean(staged && staged.skipped); // A small accent chip, like a comment box's quick answer ("No changes"), // rather than an underlined link that reads as fine print. @@ -372,7 +400,7 @@ export function renderCard(item) { } } - if (isOpen(item) && !flight && !finish()) markGrowBox(card); + if (isOpen(item) && !flight && !finish() && !loopLock) markGrowBox(card); return card; } @@ -835,6 +863,28 @@ function buildChoice(card, item, staged) { } otherOption(list, item, staged, name); card.appendChild(list); + clearRow(card, item); +} + +// Takes a one-answer question back to how it arrived: no pick, and nothing in +// "Something else" (its draft too, or the render would put the words straight +// back). A radio group cannot be unticked by clicking it again, so without +// this a stray pick could only be swapped for another one. Only the builders +// call it, and they only run for a form that has not been sent. +function clearRow(card, item) { + const row = el("div", "btn-row options-clear"); + const b = el("button", "btn small ghost", "Clear"); + b.type = "button"; + // An id so focus survives the render the click sets off (see withFocus). + b.id = "clear-" + item.id; + b.setAttribute("aria-label", "Clear your answer to this question"); + b.addEventListener("click", () => { + const other = "other-" + item.id; + if (page.local.drafts[other]) setDraft(other, ""); + stage(item.id, null); + }); + row.appendChild(b); + card.appendChild(row); } function buildMulti(card, item, staged) { @@ -1335,6 +1385,7 @@ function buildMenu(card, item, staged) { list.appendChild(li); } card.appendChild(list); + clearRow(card, item); if (item.command) { const note = el("div", "card-note"); diff --git a/src/web-console/public/screens/cleanup.js b/src/web-console/public/screens/cleanup.js index d80cb83..ed2e8f6 100644 --- a/src/web-console/public/screens/cleanup.js +++ b/src/web-console/public/screens/cleanup.js @@ -1,4 +1,4 @@ -// Plan2Code Web Console - User Preferences, Cleanup tab. +// Plan2Code Web Console - User Preferences, the Cleanup section on the System tab. import { formatBytes } from "../answers.js"; import { el } from "../render.js"; @@ -123,7 +123,7 @@ async function deleteCleanup() { setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed)); } -// The Cleanup tab's buttons, and starting over whenever Preferences closes. +// The Cleanup section's buttons, and starting over whenever Preferences closes. export function wireCleanup() { $("cleanup-scan").addEventListener("click", scanCleanup); $("cleanup-delete").addEventListener("click", deleteCleanup); diff --git a/src/web-console/public/screens/core.js b/src/web-console/public/screens/core.js index 424a5d2..832dd2f 100644 --- a/src/web-console/public/screens/core.js +++ b/src/web-console/public/screens/core.js @@ -50,7 +50,7 @@ import { faviconState, setFavicon } from "../favicon.js"; import { helperRows, showTab } from "../subagents.js"; import { FOOTER_TIERS, footerLabel } from "../workspace.js"; import { - activity, agentAdrift, agentWorking, asked, awaitingReply, byId, dashboardLive, docs, doingNow, + activity, agentAdrift, agentWorking, askBusy, loopDriving, loopWaiting, loopWaitingKey, asked, awaitingReply, byId, dashboardLive, docs, doingNow, finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems, patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded, topics, workingMs, WORKING_GRACE_MS, @@ -58,6 +58,7 @@ import { } from "../selectors.js"; import { sound } from "../sound.js"; import { renderConfirm, renderDashboard } from "./dashboard.js"; +import { renderLoopSetup } from "./loop-setup.js"; import { renderLaunching, renderWaiting } from "./starting.js"; import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js"; import { closeMentions } from "../mention-box.js"; @@ -69,13 +70,13 @@ import { renderWorkspace, tellFolderIssues } from "./workspace.js"; import { openHelpOn } from "./help-dialog.js"; import { linkLeavesPage, startNewSession, tellApp } from "../app-bridge.js"; import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js"; -import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js"; +import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js"; import { renderNotepadButton } from "./notepad.js"; import { renderActivities } from "./activities.js"; // What the entry needs from the screens at start-up, handed on from here: only // the core imports a screen. -export { wakeHoldsChime, wireDashboard } from "./dashboard.js"; +export { launchSkill, wakeHoldsChime, wireDashboard } from "./dashboard.js"; export { fillSky } from "./starting.js"; export { fitGrowBox, wireCards } from "./cards.js"; export { wireDocs } from "./docs.js"; @@ -84,9 +85,12 @@ export { syncWorkspaceScope, wireWorkspace } from "./workspace.js"; export { maybeWelcome, openHelpOn, wireHelp } from "./help-dialog.js"; export { wireCleanup } from "./cleanup.js"; export { startLooks, wireLooks } from "./looks.js"; +export { confirmUnsaved, markSaved, openPrefs, wirePrefs } from "./prefs-dialog.js"; +export { discardOpen, focusOpen, hasUnsaved, loadAgentsView, saveOpen, unsavedName, wireAgentsView } from "./agents-view.js"; export { wireEnding } from "./ending.js"; export { wireNotepad } from "./notepad.js"; export { wireActivities } from "./activities.js"; +export { openLoopSetup, wireLoopSetup } from "./loop-setup.js"; const $ = (id) => document.getElementById(id); @@ -293,6 +297,11 @@ export function adopt(body) { page.inApp = Boolean(body.inApp); // Help's `.for-app` / `.for-browser` wording switches on this (help.css). document.documentElement.classList.toggle("in-app", page.inApp); + // The Implementation Loop's lock: `loop: { driving: true }` on the state, + // ended by the app's `loopEnd`. Screens ask loopDriving(); the class is for + // the stylesheet. + page.loop = (body.state && body.state.loop && body.state.loop.driving === true) || body.loop === true ? { driving: true } : null; + document.documentElement.classList.toggle("loop-driving", loopDriving()); // Always replaced: an absent key means no update. page.updateFrame = body.update || null; // Always replaced too: an older server sends none, and then there is no switch. @@ -318,8 +327,9 @@ export function adopt(body) { // session; what this page kept for the last skill -- the question on // screen, the open tab, anything staged or typed against its item ids -- // goes too. The launch in flight and the dashboard's spec pick are about the - // hand-off itself, so they stay. A skill run inline from another (a quick - // task's review) keeps all of it. + // hand-off itself, so they stay, and so does the Ask tab: the conversation + // outlives the hop. A skill run inline from another (a quick task's review) + // keeps all of it. if (startsClean(prevWorkflow, page.S.workflow)) { // The pick rides into the skill it launched, never back home: arriving at // the dashboard, the picker starts on the most recently touched spec still @@ -331,13 +341,15 @@ export function adopt(body) { const keepNote = Boolean(ns) && page.S.workflow !== "dashboard" && page.S.workflow === ns.workflow; page.local = { ...fresh(), + chat: page.local.chat, launching: page.local.launching, ...(keepPick ? { specSel: page.local.specSel } : {}), ...(keepNote ? { noteSend: ns } : {}), }; save(); page.selected = null; - page.view = "questions"; + // Someone reading the Ask tab across the hop stays on it. + if (page.view !== "ask") page.view = "questions"; // And forget which tab is drawn, or the next render would store the old // skill's offset straight back under a tab id the new one may reuse. scrollMemory.clear(); @@ -394,7 +406,10 @@ export function adopt(body) { // session under its own workflow, so `dashboard` stops being what the state // says it is. A finish while still on the dashboard is the launch declined // or the session ended; either way the menu is not mid-handoff any more. - if (!isDashboard() || finish()) page.dashPick = null; + if (!isDashboard() || finish()) { + page.dashPick = null; + page.loopSetup = null; + } // A launch (or an ending) mid wake-up: cut it short rather than play on // over a page that is no longer the menu. if (page.wake && (!isDashboard() || finish())) page.wake.abort.abort(); @@ -505,7 +520,7 @@ export function adopt(body) { } // The chat's half of adopt(). A new conversation (New conversation pressed in -// any tab, or a skill switch) is a clean page: nothing typed or waiting for +// any tab) is a clean page: nothing typed or waiting for // the old one carries over. Conversations only ever count up, so a frame that // names an older one than this page already moved to is a late frame, not a // switch. Sends the server has now echoed stop being pending. @@ -515,8 +530,7 @@ function adoptChat() { if (page.local.chat.conversation == null) page.local.chat.conversation = conv; else if (conv > page.local.chat.conversation) { // What they were typing, and what they had attached to it, is theirs: - // a new conversation started elsewhere (another tab, a skill switch) - // must not wipe a message they have not sent yet. + // a new conversation started elsewhere (another tab) must not wipe a message they have not sent yet. page.local.chat = { ...freshChat(), history: page.local.chat.history, draft: page.local.chat.draft, images: page.local.chat.images, about: null, conversation: conv }; page.chatError = ""; page.askRowCount = 0; @@ -996,13 +1010,20 @@ function renderMeter() { // a command to copy into a new conversation. const fresh = $("meter-fresh"); fresh.hidden = page.meterFrame.level === "green"; + // The loop's agents run on; a new session mid-loop is the loop banner's Stop. + const built = fresh.querySelector(".meter-fresh-btn"); + if (built) { + built.disabled = loopDriving(); + built.title = loopDriving() ? "The loop is building. Stop it from the banner at the top of the window." : ""; + } if (fresh.hidden || fresh.dataset.built) return; fresh.dataset.built = "1"; if (page.inApp) { // The same press as the app bar's New Session, confirm and all. const press = el("button", "btn small primary meter-fresh-btn", "Start a New Session"); press.type = "button"; - press.addEventListener("click", () => tellApp("new-session")); + press.addEventListener("click", () => !loopDriving() && tellApp("new-session")); + press.disabled = loopDriving(); fresh.append(press); return; } @@ -1050,7 +1071,9 @@ function renderChrome() { // The menu has no questions to count: an empty bar there reads as a stall. document.querySelector(".progress-block").hidden = (isDashboard() || page.S.workflow === "git") && !finish(); $("progress-text").textContent = total - ? `${done} of ${total} ${building ? "done" : "answered"}` + ? loopDriving() && building + ? `${done} of ${total} tasks in this phase` + : `${done} of ${total} ${building ? "done" : "answered"}` : h.stage || "Getting started"; $("confidence").textContent = h.confidence || ""; $("progress-fill").style.width = pct + "%"; @@ -1087,6 +1110,10 @@ let moodVar = 0; const STRANDED_LINE = "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."; +// The agent is out of `wait` answering an Ask message (askBusy()), so a send +// waits for it to finish that first. +const ASK_BUSY_LINE = "Plan2Code is answering your Ask message. Your answers are saved, and it picks them up after that."; + // A finished screen's press that nothing is collecting (pressStranded()). const PRESS_STRANDED_LINE = "Plan2Code is not running. Your choice is saved and waiting for it. If the terminal is idle, type **continue** there and it will pick it up; it may also be waiting for your permission approval."; @@ -1252,6 +1279,9 @@ export function renderStatus() { const hint = quiet && page.inApp ? APPROVAL_HINT_IN_APP : quiet; return say("work", hint || activity() || "Plan2Code is thinking…", fmtMs(workingMs()), true, Boolean(hint)); } + // Only once something is waiting on it, and nothing else is theirs to answer: + // with a card still open, "Sent. N still for you" is the truer line. + if (askBusy() && !myTurn().length && (page.pendingResult || awaitingReply().length)) return say("work", ASK_BUSY_LINE, "", true); // Between pressing Send and the agent picking it up, the agent's own status // is still "waiting" because it has not started yet. Reading that as "your // turn" told someone who had just answered everything that the ball was back @@ -1520,6 +1550,7 @@ function paintMain(main) { // falls through to the ordinary path below, which hands it the card. if (isDashboard() && !finish()) { if (page.local.launching) renderLaunching(main); + else if (page.loopSetup) renderLoopSetup(main); else if (page.dashPick) { // A spec-switch under an open confirm can gray the pick out. Rather // than offer START on a card that cannot launch, drop back to the @@ -1559,6 +1590,15 @@ function paintMain(main) { return; } + // How the Implementation Loop ended, from the app's `loopEnd`: its own + // screen, ahead of any card the last phase left behind. + if (page.S.loopEnd && !finish()) { + const card = renderLoopEnd(page.S.loopEnd); + card.classList.add("is-primary"); + main.appendChild(card); + return; + } + const list = asked(); if (!list.length) { // A session can end before it asked anything at all (a build that needed @@ -1620,6 +1660,9 @@ export function renderFooter() { if (foot) foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish())); // A finished dashboard keeps its summary line but still has nothing to send. if (foot) foot.classList.toggle("is-dash-done", Boolean(isDashboard() && finish())); + // A loop at work has nothing for the person to send, so no Send to suggest + // otherwise; it comes back the moment a question waits. + if (foot) foot.classList.toggle("is-loop-idle", loopDriving() && !loopWaiting() && !finish()); const summary = $("footer-summary"); const notes = pendingNotes(); @@ -1904,13 +1947,16 @@ export async function send() { e.status = res.status; throw e; } + // Ask locks again once the loop's question is answered (FR-14); it opens + // for the next, different one. + if (loopWaiting()) page.local.askLockedAfterSend = loopWaitingKey(); markSent(payload); banner("Sent. Plan2Code is picking it up now.", "good"); setTimeout(() => banner(null), 4000); // A menu option the agent marked `fresh` is a clean start, which under the // app is the bar's New Session; the agent still gets the pick, so a // declined confirm carries on with its usual finish. - const freshMenu = page.inApp ? freshMenuPick(actions) : null; + const freshMenu = page.inApp && !loopDriving() ? freshMenuPick(actions) : null; if (freshMenu) startNewSession(freshMenu.command ? handoffText({ command: freshMenu.command }) : ""); } catch (err) { if (err && err.pending) { @@ -2108,8 +2154,9 @@ export function wireChrome() { // Escape is the confirm pane's Back — but not while a dialog has it. Native // dialogs close themselves on the same key; backing out of the pick at the // same time would be two undos for one press. - if (e.key === "Escape" && page.dashPick && isDashboard() && !finish() && !document.querySelector("dialog[open]")) { + if (e.key === "Escape" && (page.dashPick || page.loopSetup) && isDashboard() && !finish() && !document.querySelector("dialog[open]")) { page.dashPick = null; + page.loopSetup = null; redraw(); } }); diff --git a/src/web-console/public/screens/dashboard.js b/src/web-console/public/screens/dashboard.js index a06a64d..e856fde 100644 --- a/src/web-console/public/screens/dashboard.js +++ b/src/web-console/public/screens/dashboard.js @@ -9,11 +9,12 @@ import { handoffList, loadOverview, finish, + loopDriving, } from "../selectors.js"; import { hooks, page, redraw, saveNow } from "../state.js"; import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js"; import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js"; -import { looks, renderSwatches, saveLooks } from "../looks.js"; +import { looks, saveLooks } from "../looks.js"; import { RED_BANNER, RED_BANNER_IN_APP } from "../meter.js"; import { dashNoteKind, @@ -23,6 +24,8 @@ import { CATALOG_GROUPS, SKILL_CATALOG, catalogEntry, + LOOP_ENTRY, + OUTSIDE_APP_LINE, launchVariant, SPEC_STATE_LABELS, chipDetail, @@ -74,7 +77,6 @@ function roleNudge() { const setUp = el("button", "btn small primary", "Set up preferences"); setUp.type = "button"; setUp.addEventListener("click", () => { - renderSwatches(); // Closed without a role is a "Not now" too: having been to the dialog, // they were asked, and the banner does not come back (Help says so). $("looks-modal").addEventListener( @@ -88,7 +90,7 @@ function roleNudge() { }, { once: true } ); - $("looks-modal").showModal(); + hooks.openPrefs("appearance"); }); const notNow = el("button", "btn tiny ghost", "Not now"); notNow.type = "button"; @@ -243,12 +245,16 @@ export function renderDashboard(main) { let shown = 0; for (const g of CATALOG_GROUPS) { const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e))); - if (!entries.length) continue; - shown += entries.length; + // The desktop app's Implementation Loop card closes its group. Outside the + // app it is always drawn, grayed, so the feature can be found. + const loopCard = LOOP_ENTRY && LOOP_ENTRY.group === g.id && (!page.inApp || !hide || available(LOOP_ENTRY)); + if (!entries.length && !loopCard) continue; + shown += entries.length + (loopCard ? 1 : 0); const section = el("section", "dash-group"); section.appendChild(el("h3", "dash-group-title", g.title)); const grid = el("div", "dash-grid"); for (const e of entries) grid.appendChild(dashCard(e, menu)); + if (loopCard) grid.appendChild(dashCard(LOOP_ENTRY, menu)); section.appendChild(grid); wrap.appendChild(section); } @@ -664,7 +670,7 @@ async function readHandoff(h) { } function dashCard(entry, menu) { - const presentation = cardPresentation(entry, scan(), selSpec(), menu); + const presentation = entry.appOnly ? loopPresentation(entry, menu) : cardPresentation(entry, scan(), selSpec(), menu); // The agent's `recommend` and detail describe the initially selected spec. // Other picker choices derive both from the scan, so stale context never // follows a person to a different spec or to "start from scratch". A grayed @@ -675,7 +681,7 @@ function dashCard(entry, menu) { "dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "") ); b.type = "button"; - b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on; + b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || loopDriving() || !presentation.on; if (!presentation.on && presentation.reason) b.title = presentation.reason; const head = el("span", "dash-card-head"); @@ -693,12 +699,39 @@ function dashCard(entry, menu) { b.appendChild(foot); b.addEventListener("click", () => { + // The loop card opens its own setup screen instead of a confirm pane. + if (entry.appOnly) return hooks.openLoopSetup(selSpec()); page.dashPick = entry; redraw(); }); + if (entry.appOnly) b.appendChild(loopHelpLink()); return b; } +// The loop card is lit only inside the desktop app and, there, by the same +// rule as Implement (a documented or building spec). Never recommended or +// pre-selected: a person opts into running unattended. +function loopPresentation(entry, menu) { + if (!page.inApp) return { on: false, reason: OUTSIDE_APP_LINE, recommended: false, detail: "" }; + return { ...cardPresentation(entry, scan(), selSpec(), menu), recommended: false }; +} + +// "How the loop works" on the card: a link inside a button is not allowed, so +// it is a span that acts like one and keeps the click from opening the setup. +function loopHelpLink() { + const a = el("span", "dash-card-link", "How the loop works"); + a.setAttribute("role", "link"); + a.tabIndex = 0; + const open = (e) => { + e.stopPropagation(); + e.preventDefault(); + hooks.openHelpOn("loop"); + }; + a.addEventListener("click", open); + a.addEventListener("keydown", (e) => (e.key === "Enter" || e.key === " ") && open(e)); + return a; +} + // "Start with a note from your Notebook": the switch a lit card's confirm // pane offers when noteSwitchShows() says so. The pane is rebuilt on every // state frame, so what the person did lives here, keyed to the card and the @@ -806,8 +839,18 @@ function drawNoteBox(entry, box, cmdNote) { again(); if (state.on && (state.tabs === null || state.failed)) refreshNoteTabs(state, true); }); - label.append(toggle, el("span", null, "Start with a note from your Notebook")); - box.appendChild(label); + label.append(toggle, el("span", "confirm-note-switch-text", "Start with a note from your Notebook")); + // A callout row, so the switch stands out under the card's long text; the + // hint sits outside the label to keep the checkbox's name short. + const head = el("div", "confirm-note-head" + (state.on ? " is-on" : "")); + head.appendChild(label); + if (!state.on) { + const hint = el("span", "confirm-note-hint", "Hand it a tab you wrote earlier, with its pictures."); + hint.id = "confirm-note-hint"; + toggle.setAttribute("aria-describedby", hint.id); + head.appendChild(hint); + } + box.appendChild(head); const picked = state.on && state.tabs ? state.tabs.find((t) => t.id === state.picked && t.read) : null; cmdNote.textContent = picked ? " + note: " + picked.name : ""; @@ -834,11 +877,11 @@ function drawNoteBox(entry, box, cmdNote) { b.setAttribute("aria-pressed", String(t.id === state.picked)); b.appendChild(el("span", "confirm-note-tab-name", t.name)); if (t.sent) { - const badge = el("span", "notepad-sent-badge", "sent"); + const badge = el("span", "notepad-sent-badge", "previously sent"); badge.setAttribute("aria-hidden", "true"); b.appendChild(badge); } - b.setAttribute("aria-label", t.name + (t.sent ? ", sent" : "") + (empty ? ", empty" : "")); + b.setAttribute("aria-label", t.name + (t.sent ? ", previously sent" : "") + (empty ? ", empty" : "")); if (empty) b.title = t.read ? "This tab has no text or pictures." : "This tab could not be read."; b.addEventListener("click", () => { if (state.picked === t.id) return; @@ -985,7 +1028,6 @@ export function renderConfirm(main, entry) { const cmdNote = el("span", "confirm-cmd-note"); cmdNote.hidden = true; if (noteSwitchShows(entry, scan(), selSpec())) { - pane.appendChild(el("hr", "confirm-rule")); const box = el("div", "confirm-note-box"); // Which control in the box has the focus, so a rebuild of the whole pane // can hand it back (see the end of this function). @@ -1032,7 +1074,7 @@ export function renderConfirm(main, entry) { // A pick is a send like a brief or a stop: it names no question, so `__launch` // marks the action as being about the session, and it reaches the agent // through the same wait loop. The dashboard reads `skill` off it. -async function launchSkill(entry) { +export async function launchSkill(entry) { if (page.gone || page.pendingResult || page.local.launching || finish()) return; const target = launchTarget(entry, selSpec()); // The card was clickable, so this should never fire — but a spec picked in diff --git a/src/web-console/public/screens/ending.js b/src/web-console/public/screens/ending.js index cc7a175..520cf1b 100644 --- a/src/web-console/public/screens/ending.js +++ b/src/web-console/public/screens/ending.js @@ -42,9 +42,14 @@ import { agentWorking, awaitingReply, isDashboard, + loopDriving, } from "../selectors.js"; + +// What the session buttons say while the Implementation Loop drives: its own +// strip in the app's top bar stops it, not this page. +const LOOP_LOCK_TITLE = "The loop is building. Stop it from the banner at the top of the window."; import { docSavedNote, downloadDoc } from "../doc-files.js"; -import { startNewSession } from "../app-bridge.js"; +import { startNewSession, tellApp } from "../app-bridge.js"; import { pendingNotes } from "../uploads.js"; // The end of the session, and the only screen in this page whose job is to @@ -152,7 +157,110 @@ function closeGuideHeld() { return ["review", "commit", "changelog", "dashboard", "launch"].includes(page.local.afterBuild) || reviewPending() === "asked"; } +// Which stop-screen button was pressed and is waiting on the app's answer, so a +// second press cannot send the same request twice. +let loopPressed = null; + +const LOOP_BUTTONS = [ + ["resume", "loop-resume", "Resume the loop", "primary"], + ["fix", "loop-fix", "Fix it by hand", ""], + ["finalize", "loop-finalize", "Finalize", "primary"], +]; + +function shortHash(h) { + return typeof h === "string" ? h.slice(0, 7) : ""; +} + +/** + * How the Implementation Loop ended, drawn from the app's `loopEnd`: a stop + * (why, what was committed, what is left uncommitted, what can be done next) or + * a finish (every phase built, its commit, and a count of each kind of decision + * its agent made; the report behind the button holds them all). + */ +export function renderLoopEnd(end) { + const card = el("article", "card handoff loop-end"); + const finished = end.kind === "finished"; + card.appendChild(el("p", "card-kicker", finished ? "Loop finished" : "Loop stopped")); + card.appendChild(el("h2", null, finished ? "Every phase is built" : end.line)); + if (finished && end.line) card.appendChild(el("p", "loop-line", end.line)); + + const evidence = end.evidence && docs().find((d) => d.id === end.evidence); + if (evidence) { + const read = el("button", "btn small", finished ? "Read the full report" : "Read why, and the report so far"); + read.type = "button"; + read.addEventListener("click", () => { + page.view = "doc:" + evidence.id; + redraw(); + }); + card.appendChild(read); + } + + const phases = Array.isArray(end.phases) ? end.phases : []; + if (phases.length) { + const table = el("table", "loop-end-phases"); + const head = el("tr"); + const cols = finished ? ["Phase", "Commit", "Fixed", "Not fixed", "Left open", "Assumed", "Other decisions", "Retries"] : ["Phase", "Commit"]; + for (const c of cols) head.appendChild(el("th", null, c)); + table.appendChild(head); + for (const ph of phases) { + const row = el("tr"); + row.appendChild(el("td", null, `Phase ${ph.n}: ${ph.name}`)); + const commit = el("td"); + if (ph.commit) commit.appendChild(el("code", null, shortHash(ph.commit))); + else commit.textContent = "not committed"; + row.appendChild(commit); + if (finished) { + for (const count of [ph.fixed, ph.skipped, ph.left, ph.assumed, ph.decisions, ph.retries]) { + row.appendChild(el("td", null, String(count ?? 0))); + } + } + table.appendChild(row); + } + card.appendChild(table); + } + + const files = Array.isArray(end.uncommitted) ? end.uncommitted : []; + if (files.length) { + card.appendChild(el("h3", null, "Uncommitted in this phase")); + const list = el("ul", "loop-end-files"); + const fill = (items, into) => items.forEach((f) => into.appendChild(el("li", null, f))); + fill(files.slice(0, 10), list); + if (files.length > 10) { + const more = el("details"); + more.appendChild(el("summary", null, `${files.length - 10} more files`)); + const rest = el("ul", "loop-end-files"); + fill(files.slice(10), rest); + more.appendChild(rest); + card.append(list, more); + } else { + card.appendChild(list); + } + } + + const can = Array.isArray(end.can) ? end.can : []; + const actions = el("div", "loop-end-actions"); + for (const [key, message, label, kind] of LOOP_BUTTONS) { + if (!can.includes(key)) continue; + const b = el("button", "btn" + (kind ? " " + kind : ""), label); + b.type = "button"; + b.disabled = page.gone || (loopPressed === message && !page.loopAction); + b.addEventListener("click", () => { + loopPressed = message; + page.loopAction = null; + tellApp(message); + redraw(); + }); + actions.appendChild(b); + } + if (actions.childElementCount) card.appendChild(actions); + if (page.loopAction && !page.loopAction.ok) { + card.appendChild(el("p", "loop-error", page.loopAction.error)); + } + return card; +} + export function renderHandoff(fin) { + if (page.S && page.S.loopEnd) return renderLoopEnd(page.S.loopEnd); const card = el("article", "card handoff"); card.appendChild(el("p", "card-kicker", finishPaused(fin) ? "Session paused" : "Session ended")); card.appendChild(el("h2", null, fin.headline)); @@ -586,8 +694,8 @@ export function renderStopButton() { const gate = turnGate({ gone: page.gone, pendingResult: page.pendingResult, waiting: agentHasTheBall() }); // A way home in flight holds Stop back too, unless the agent went quiet // after collecting it: Stop's resume screen is then the only way out. - b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift()); - b.title = { + b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift()) || loopDriving(); + b.title = loopDriving() ? LOOP_LOCK_TITLE : { gone: "Not connected right now.", pending: "Your last answers are still being picked up. You can stop once they have been.", waiting: "Plan2Code is working on your answers. You can stop once it replies.", @@ -617,8 +725,8 @@ export function renderHomeButton() { warned: Boolean(page.S) && Boolean(stopWarning()), }); b.hidden = st.hidden; - b.disabled = st.disabled; - b.title = st.title; + b.disabled = st.disabled || loopDriving(); + b.title = loopDriving() ? LOOP_LOCK_TITLE : st.title; } function openHomeConfirm() { diff --git a/src/web-console/public/screens/help-dialog.js b/src/web-console/public/screens/help-dialog.js index 45c56aa..482dc04 100644 --- a/src/web-console/public/screens/help-dialog.js +++ b/src/web-console/public/screens/help-dialog.js @@ -4,7 +4,8 @@ import { looksReady, looks, saveLooks } from "../looks.js"; import { page } from "../state.js"; import { isDashboard, finish, agentAdrift } from "../selectors.js"; import { releasesLink, el, copyButton, lightDismiss } from "../render.js"; -import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js"; +import { HELP_TABS, helpTabFor } from "../help.js"; +import { wireTabs } from "../tabs.js"; import { CATALOG_GROUPS, SKILL_CATALOG } from "../answers.js"; const $ = (id) => document.getElementById(id); @@ -196,6 +197,8 @@ function renderAppWording(root) { } let helpBuilt = false; +// The tabs, wired by tabs.js once the content is built. +let helpTabs = null; async function renderHelpVersion() { const slot = $("help-version"); @@ -261,43 +264,31 @@ function buildHelp() { const code = row.querySelector("code"); row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code)); } - for (const t of HELP_TABS) { - const btn = el("button", "help-tab"); - btn.type = "button"; - btn.id = "help-tab-" + t.id; - btn.setAttribute("role", "tab"); - btn.setAttribute("aria-controls", "help-panel-" + t.id); - btn.setAttribute("aria-selected", "false"); - btn.tabIndex = -1; - const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); - svg.setAttribute("class", "help-tab-icon"); - svg.setAttribute("aria-hidden", "true"); - const use = document.createElementNS("http://www.w3.org/2000/svg", "use"); - use.setAttribute("href", "#hi-" + t.id); - svg.appendChild(use); - btn.appendChild(svg); - btn.appendChild(el("span", null, t.label)); - btn.addEventListener("click", () => selectHelpTab(t.id)); - tabs.appendChild(btn); - const panel = panels.querySelector(`section.help-panel[data-tab="${t.id}"]`); - panel.id = "help-panel-" + t.id; - panel.setAttribute("role", "tabpanel"); - panel.setAttribute("aria-labelledby", "help-tab-" + t.id); - panel.tabIndex = 0; - panel.hidden = true; - } + helpTabs = wireTabs({ + tabs: HELP_TABS, + list: tabs, + panels, + prefix: "help", + tabClass: "help-tab", + renderTab: (t, btn) => { + const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); + svg.setAttribute("class", "help-tab-icon"); + svg.setAttribute("aria-hidden", "true"); + const use = document.createElementNS("http://www.w3.org/2000/svg", "use"); + use.setAttribute("href", "#hi-" + t.id); + svg.appendChild(use); + btn.appendChild(svg); + btn.appendChild(el("span", null, t.label)); + }, + onSelect: () => { + $("help-panels").scrollTop = 0; + }, + }); helpBuilt = true; } export function selectHelpTab(id) { - for (const t of HELP_TABS) { - const on = t.id === id; - const btn = $("help-tab-" + t.id); - btn.setAttribute("aria-selected", String(on)); - btn.tabIndex = on ? 0 : -1; - $("help-panel-" + t.id).hidden = !on; - } - $("help-panels").scrollTop = 0; + helpTabs.select(id); } export function openHelp() { @@ -372,14 +363,6 @@ export function wireHelp() { if ((e.metaKey || e.ctrlKey) && e.key === "Enter") { e.preventDefault(); e.stopPropagation(); - return; } - if (!e.target.classList || !e.target.classList.contains("help-tab")) return; - const current = HELP_TABS.findIndex((t) => "help-tab-" + t.id === e.target.id); - const n = helpKeyTarget(e.key, current, HELP_TABS.length); - if (n < 0) return; - e.preventDefault(); - selectHelpTab(HELP_TABS[n].id); - $("help-tab-" + HELP_TABS[n].id).focus(); }); } diff --git a/src/web-console/public/screens/looks.js b/src/web-console/public/screens/looks.js index d362deb..de73fbb 100644 --- a/src/web-console/public/screens/looks.js +++ b/src/web-console/public/screens/looks.js @@ -1,444 +1,19 @@ -// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus. +// Plan2Code Web Console - User Preferences: the look and sound controls. The +// Agents & models tab is agents-view.js's. -import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js"; +import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, saveLooks, syncLooks } from "../looks.js"; import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.js"; +import { hushTones, tone, unlockTones } from "../tones.js"; +import { hushMusic } from "../music.js"; import { SOUND_EVENTS, soundKey } from "../palette.js"; import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, needsRoleNudge, normalizeRole } from "../starters.js"; import { isDashboard } from "../selectors.js"; -import { el, lightDismiss } from "../render.js"; -import { page, redraw } from "../state.js"; +import { el } from "../render.js"; +import { hooks, page, redraw } from "../state.js"; import { framed, onAppMessage, tellApp } from "../app-bridge.js"; const $ = (id) => document.getElementById(id); -function setModelsStatus(text, isError) { - const status = $("models-status"); - status.textContent = text; - status.classList.toggle("error", Boolean(isError)); -} - -// Models: the launcher's menu. The built-in list ships with every install and is read-only -// here; what the person adds is saved to the server, which the launcher reads on its next run. -let modelsData = null; - -// The CLIs the launcher reads a model list for, in tab order (routes.mjs MODEL_CLIS). -const MODEL_CLIS = ["claude", "devin", "codex"]; - -let modelsTab = "claude"; - -function renderModels() { - for (const cli of MODEL_CLIS) { - $("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab)); - } - const shipped = $("models-shipped"); - const user = $("models-user"); - shipped.replaceChildren(); - user.replaceChildren(); - if (!modelsData) { - setModelsStatus("Models could not be loaded.", true); - return; - } - for (const m of modelsData.shipped[modelsTab] || []) { - const row = el("div", "models-row locked"); - row.append(el("span", null, m.id), el("span", null, m.label || "")); - shipped.appendChild(row); - } - const mine = modelsData.user[modelsTab]; - mine.forEach((m, i) => { - const row = el("div", "models-row"); - const id = el("input"); - id.value = m.id; - id.placeholder = "Model id"; - id.setAttribute("aria-label", "Model id"); - const label = el("input"); - label.value = m.label; - label.placeholder = "Name shown in the menu"; - label.setAttribute("aria-label", "Name shown in the menu"); - const remove = el("button", "btn small ghost", "Remove"); - remove.type = "button"; - id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); }); - label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); }); - remove.addEventListener("click", () => { - mine.splice(i, 1); - saveModels(); - renderModels(); - }); - row.append(id, label, remove); - user.appendChild(row); - }); -} - -async function saveModels() { - try { - const res = await fetch("/models", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ models: modelsData.user }), - }); - const body = await res.json(); - if (!res.ok) return setModelsStatus(body.error || "Could not save.", true); - setModelsStatus("Saved. Restart plan2code to use it.", false); - } catch { - setModelsStatus("Could not save.", true); - } -} - -async function loadModelsData() { - try { - const res = await fetch("/models"); - if (res.ok) modelsData = await res.json(); - } catch {} - renderModels(); -} - -// Agents: CLIs Plan2Code did not find on its own, saved whole to ~/.plan2code/agents.json. -// Each card edits its entry in place (unknown keys ride along untouched); every change -// saves the whole list. A new card is not sent until it has a name and a command. -let agentsData = []; - -// The server's complaint about one card, drawn on it: { index, field, error } (index into agentsData). -let agentsError = null; - -// The entry whose Delete is waiting for a second click. -let agentsConfirming = null; - -// Every change saves, so two saves can be in flight at once: only the newest one's answer is drawn. -let agentsSaveSeq = 0; - -// The list as last loaded or saved, as sent: a change that leaves it the same (a field of a new -// card still held back) sends nothing. -let agentsLastSent = null; - -function setAgentsStatus(text, isError) { - const status = $("agents-status"); - status.textContent = text; - status.classList.toggle("error", Boolean(isError)); -} - -function newAgent() { - return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] }; -} - -function agentField(label, field, child) { - const wrap = el("div", "agent-field"); - wrap.dataset.field = field; - wrap.append(el("span", null, label), child); - return wrap; -} - -function agentInput(agent, key, label, placeholder, trim) { - const input = el("input"); - input.value = agent[key] || ""; - input.placeholder = placeholder; - input.setAttribute("aria-label", label); - input.dataset.field = key; - input.addEventListener("change", () => { - agent[key] = trim ? input.value.trim() : input.value; - saveAgents(); - }); - return input; -} - -// A list of text rows (arguments), with Remove on each and an Add under them. -function agentArgsEditor(agent, key, label, placeholder, addLabel) { - const box = el("div", "agent-rows"); - box.dataset.field = key; - const draw = () => { - box.replaceChildren(); - agent[key].forEach((value, i) => { - const row = el("div", "agent-row"); - const input = el("input"); - input.value = value; - input.placeholder = placeholder; - input.setAttribute("aria-label", label); - input.dataset.field = key; - input.addEventListener("change", () => { agent[key][i] = input.value.trim(); saveAgents(); }); - const remove = el("button", "btn small ghost", "Remove"); - remove.type = "button"; - remove.addEventListener("click", () => { - agent[key].splice(i, 1); - draw(); - saveAgents(); - }); - row.append(input, remove); - box.appendChild(row); - }); - const add = el("button", "btn small ghost", addLabel); - add.type = "button"; - add.addEventListener("click", () => { - agent[key].push(""); - draw(); - box.querySelector(".agent-row:last-of-type input")?.focus(); - }); - box.appendChild(add); - }; - draw(); - return agentField(label, key, box); -} - -// The models list: an id and an optional name for the menu on each row. -function agentModelsEditor(agent) { - const box = el("div", "agent-rows"); - box.dataset.field = "models"; - const draw = () => { - box.replaceChildren(); - agent.models.forEach((m, i) => { - const row = el("div", "agent-row model"); - const id = el("input"); - id.value = m.id || ""; - id.placeholder = "Model id, for {model}"; - id.setAttribute("aria-label", "Model id"); - id.dataset.field = "models"; - const label = el("input"); - label.value = m.label || ""; - label.placeholder = "Name shown in the menu (optional)"; - label.setAttribute("aria-label", "Name shown in the menu"); - label.dataset.field = "models"; - const remove = el("button", "btn small ghost", "Remove"); - remove.type = "button"; - id.addEventListener("change", () => { m.id = id.value.trim(); saveAgents(); }); - label.addEventListener("change", () => { - const text = label.value.trim(); - if (text) m.label = text; - else delete m.label; - saveAgents(); - }); - remove.addEventListener("click", () => { - agent.models.splice(i, 1); - draw(); - saveAgents(); - }); - row.append(id, label, remove); - box.appendChild(row); - }); - const add = el("button", "btn small ghost", "Add a model"); - add.type = "button"; - add.addEventListener("click", () => { - agent.models.push({ id: "" }); - draw(); - box.querySelector(".agent-row:last-of-type input")?.focus(); - }); - box.appendChild(add); - }; - draw(); - return agentField("Models", "models", box); -} - -// Test, and Delete with its confirm step on the card itself (never the browser's confirm()). -function agentFoot(agent) { - const foot = el("div", "agent-foot"); - const test = el("button", "btn small", "Test"); - test.type = "button"; - const result = el("span", "help agent-test-result"); - result.setAttribute("role", "status"); - test.addEventListener("click", async () => { - const command = String(agent.command || "").trim(); - if (!command) { - result.textContent = "Type a command first."; - return; - } - result.textContent = "Looking..."; - try { - const res = await fetch("/agents/test", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify({ command }), - }); - const body = await res.json(); - if (!res.ok) result.textContent = body.error || "Could not test."; - else result.textContent = body.found ? "Found at " + body.path : "Not found on PATH"; - } catch { - result.textContent = "Could not test."; - } - }); - foot.append(test); - if (agentsConfirming === agent) { - const ask = el("span", "help", "Delete this agent?"); - const yes = el("button", "btn small danger", "Yes, delete"); - yes.type = "button"; - const keep = el("button", "btn small ghost", "Keep"); - keep.type = "button"; - yes.addEventListener("click", async () => { - agentsConfirming = null; - agentsData.splice(agentsData.indexOf(agent), 1); - agentsError = null; - renderAgents(); - await saveAgents(); - }); - keep.addEventListener("click", () => { - agentsConfirming = null; - renderAgents(); - }); - foot.append(ask, yes, keep); - } else { - const del = el("button", "btn small ghost danger", "Delete"); - del.type = "button"; - del.addEventListener("click", () => { - agentsConfirming = agent; - renderAgents(); - }); - foot.append(del); - } - foot.append(result); - return foot; -} - -// Which field or button has focus, so a redraw (an id assigned, an error marked) puts the -// person back where they were, with what they had typed: { card, nth, value, start, end }. -const AGENT_FOCUSABLE = "input, button"; - -function agentsFocus(list) { - const active = document.activeElement; - const card = active && list.contains(active) ? active.closest(".agent-card") : null; - if (!card) return null; - const at = { card: [...list.children].indexOf(card), nth: [...card.querySelectorAll(AGENT_FOCUSABLE)].indexOf(active) }; - if (active instanceof HTMLInputElement) Object.assign(at, { value: active.value, start: active.selectionStart, end: active.selectionEnd }); - return at; -} - -function restoreAgentsFocus(list, at) { - const card = at && list.children[at.card]; - const target = card && card.querySelectorAll(AGENT_FOCUSABLE)[at.nth]; - if (!target) return; - if (!(target instanceof HTMLInputElement) || at.value === undefined) { - target.focus(); - return; - } - const drawn = target.value; - target.value = at.value; - target.focus(); - try { - target.setSelectionRange(at.start, at.end); - } catch {} - // Text typed before the redraw is not in agentsData yet, and the browser fires no change - // for a value set from script, so leaving the field sends it on. - if (at.value !== drawn) target.addEventListener("blur", () => target.dispatchEvent(new Event("change")), { once: true }); -} - -function renderAgents() { - const list = $("agents-list"); - const focus = agentsFocus(list); - list.replaceChildren(); - agentsData.forEach((agent, i) => { - for (const key of ["args", "bypassArgs", "modelArgs", "models"]) { - if (!Array.isArray(agent[key])) agent[key] = []; - } - const card = el("div", "agent-card"); - const top = el("div", "agent-top"); - top.append( - agentField("Name", "name", agentInput(agent, "name", "Name", "Name shown in the menu", true)), - agentField("Command", "command", agentInput(agent, "command", "Command", "Program to run, such as myagent", true)), - ); - card.append( - top, - agentArgsEditor(agent, "args", "Arguments", "--message={prompt}", "Add an argument"), - agentField("Start prompt", "prompt", agentInput(agent, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)), - agentArgsEditor(agent, "bypassArgs", "Bypass arguments", "--yes-always", "Add an argument"), - agentArgsEditor(agent, "modelArgs", "Model arguments", "--model={model}", "Add an argument"), - agentModelsEditor(agent), - ); - if (agentsError && agentsError.index === i) { - card.classList.add("invalid"); - for (const input of card.querySelectorAll("input")) { - if (input.dataset.field === agentsError.field) input.classList.add("invalid"); - } - card.appendChild(el("p", "agent-error", agentsError.error)); - } - card.appendChild(agentFoot(agent)); - list.appendChild(card); - }); - restoreAgentsFocus(list, focus); -} - -// The list as the server wants it: blank rows dropped, and a new card without both a name and -// a command (one still being typed) left out, so its first field is not refused as half an -// agent. `kept` maps each sent entry back to its place. -function agentsPayload() { - const kept = []; - const agents = []; - agentsData.forEach((a, i) => { - if (!a.id && (!String(a.name || "").trim() || !String(a.command || "").trim())) return; - kept.push(i); - agents.push({ - ...a, - args: a.args.filter((v) => v !== ""), - bypassArgs: a.bypassArgs.filter((v) => v !== ""), - modelArgs: a.modelArgs.filter((v) => v !== ""), - models: a.models.filter((m) => m.id), - }); - }); - return { kept, agents }; -} - -// `replace` is the person's Save anyway, over a file holding entries this page could not read. -async function saveAgents({ replace = false } = {}) { - const { kept, agents } = agentsPayload(); - const sent = JSON.stringify(agents); - if (!replace && agentsError === null && sent === agentsLastSent) return; - const seq = ++agentsSaveSeq; - try { - const res = await fetch("/agents", { - method: "POST", - headers: { "content-type": "application/json" }, - body: JSON.stringify(replace ? { agents, replace: true } : { agents }), - }); - const body = await res.json(); - if (seq !== agentsSaveSeq) return; - if (res.status === 409) { - const warnings = Array.isArray(body.warnings) ? body.warnings : []; - setAgentsStatus([body.error || "Not saved.", ...warnings].join(" "), true); - $("agents-replace").hidden = false; - return; - } - $("agents-replace").hidden = true; - if (!res.ok) { - const at = Number.isInteger(body.index) ? kept[body.index] : undefined; - agentsError = at === undefined ? null : { index: at, field: body.field, error: body.error || "Could not save." }; - setAgentsStatus(at === undefined ? body.error || "Could not save." : "Not saved. Fix the marked agent.", true); - renderAgents(); - return; - } - // Ids are assigned on the first save: take the server's entries, and redraw only then - // (or to clear a mark), so typing in another card is not interrupted. - const fresh = agents.some((a) => !a.id) || agentsError !== null; - agentsError = null; - agentsLastSent = sent; - setAgentsStatus("Saved.", false); - if (fresh) { - kept.forEach((at, n) => { agentsData[at] = body.agents[n]; }); - agentsLastSent = JSON.stringify(agentsPayload().agents); - renderAgents(); - } - } catch { - if (seq === agentsSaveSeq) setAgentsStatus("Could not save.", true); - } -} - -async function loadAgents() { - agentsError = null; - agentsConfirming = null; - agentsLastSent = null; - $("agents-replace").hidden = true; - try { - const res = await fetch("/agents"); - if (res.ok) { - const body = await res.json(); - agentsData = Array.isArray(body.agents) ? body.agents : []; - for (const agent of agentsData) { - for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = []; - } - agentsLastSent = JSON.stringify(agentsPayload().agents); - const warnings = Array.isArray(body.warnings) ? body.warnings : []; - setAgentsStatus(warnings.join(" "), warnings.length > 0); - } else { - setAgentsStatus("Agents could not be loaded.", true); - } - } catch { - setAgentsStatus("Agents could not be loaded.", true); - } - renderAgents(); -} - // Following the system, the saved looks painted before anything is drawn, and // the sound cues let go on the next touch. `boot` is the page's boot data. export function startLooks(boot) { @@ -461,25 +36,15 @@ export function startLooks(boot) { } } -// Preferences' buttons and fields. +// The fieldset a control sits in, for the Saved mark beside its legend. +const fieldsetOf = (node) => node.closest("fieldset"); + +// Preferences' look and sound fields. Opening and closing the dialog, its tabs +// and Back to default are prefs-dialog.js's. export function wireLooks() { - lightDismiss($("looks-modal")); - $("btn-looks").addEventListener("click", () => { - renderSwatches(); - setModelsStatus("", false); - loadModelsData(); - loadAgents(); - $("looks-modal").showModal(); - }); - $("looks-done").addEventListener("click", () => $("looks-modal").close()); $("looks-modal").addEventListener("close", () => { if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) redraw(); }); - $("looks-reset").addEventListener("click", () => { - resetLooks(); - saveLooks(); - redraw(); - }); for (const [value, label] of [[ROLE_NOT_SET, ROLE_NOT_SET_LABEL], ...ROLES.map((r) => [r.id, r.label])]) { const option = el("option", null, label); option.value = value; @@ -487,7 +52,7 @@ export function wireLooks() { } $("looks-role").addEventListener("change", (e) => { looks.role = normalizeRole(e.target.value); - saveLooks(); + hooks.markSaved(fieldsetOf(e.target), saveLooks()); // The dashboard banner, and the starter templates and Ask starters on any // page, all order themselves by the role. if (page.S) redraw(); @@ -495,13 +60,13 @@ export function wireLooks() { for (const radio of document.querySelectorAll('input[name="looks-theme"]')) { radio.addEventListener("change", () => { looks.theme = radio.value; - saveLooks(); + hooks.markSaved(fieldsetOf(radio), saveLooks()); }); } for (const radio of document.querySelectorAll('input[name="looks-width"]')) { radio.addEventListener("change", () => { looks.width = radio.value; - saveLooks(); + hooks.markSaved(fieldsetOf(radio), saveLooks()); }); } $("looks-sound").addEventListener("change", (e) => { @@ -509,15 +74,31 @@ export function wireLooks() { // Held cues are moments, not mail: muted, they are dropped rather than // saved up to fire all at once the next time sound comes back on. if (!looks.sound) dropHeldSound(); - saveLooks(); + hooks.markSaved(fieldsetOf(e.target), saveLooks()); // Turning them on is the one change you can hear: the question chime, or // the first cue still ticked when that one is not. const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn); if (preview) sound(preview); }); + // The games' sounds: off silences a game playing now; on plays a blip. + $("looks-activity-sounds").addEventListener("change", (e) => { + looks.activitySounds = e.target.checked; + if (!looks.activitySounds) hushTones(); + hooks.markSaved(fieldsetOf(e.target), saveLooks()); + if (looks.activitySounds) { + unlockTones(); + tone("go"); + } + }); + // The games' music: off stops a track playing now. + $("looks-game-music").addEventListener("change", (e) => { + looks.gameMusic = e.target.checked; + if (!looks.gameMusic) hushMusic(); + hooks.markSaved(fieldsetOf(e.target), saveLooks()); + }); $("looks-activities").addEventListener("change", (e) => { looks.hideActivities = !e.target.checked; - saveLooks(); + hooks.markSaved(fieldsetOf(e.target), saveLooks()); // The die comes and goes with the next render, which also closes an open // Activities window, paused. redraw(); @@ -527,40 +108,12 @@ export function wireLooks() { const event = box.dataset.sound; looks[soundKey(event)] = box.checked; if (!box.checked) dropHeldSound(event); - saveLooks(); + hooks.markSaved(fieldsetOf(box), saveLooks()); // Ticking one plays it, so the label has a sound to go with it. if (box.checked) sound(event); }); } - for (const cli of MODEL_CLIS) { - $("models-tab-" + cli).addEventListener("click", () => { - modelsTab = cli; - renderModels(); - }); - } - $("models-add").addEventListener("click", () => { - if (!modelsData) return; - modelsData.user[modelsTab].push({ id: "", label: "" }); - renderModels(); - $("models-user").querySelector(".models-row:last-child input")?.focus(); - }); - $("agents-add").addEventListener("click", () => { - agentsData.push(newAgent()); - renderAgents(); - $("agents-list").querySelector(".agent-card:last-child input")?.focus(); - }); - $("agents-replace").addEventListener("click", () => { - $("agents-replace").hidden = true; - saveAgents({ replace: true }); - }); - $("models-reset").addEventListener("click", () => { - if (!modelsData) return; - modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []])); - saveModels(); - renderModels(); - }); - // Desktop app: the taskbar switch, kept by the app in its own app.json. The // app says what it holds once the page is up; checked until it does. if (framed()) { diff --git a/src/web-console/public/screens/loop-setup.js b/src/web-console/public/screens/loop-setup.js new file mode 100644 index 0000000..f9b4821 --- /dev/null +++ b/src/web-console/public/screens/loop-setup.js @@ -0,0 +1,550 @@ +// Plan2Code Web Console - the Implementation Loop's setup screen, drawn by the page from the console's saved setup and the app's facts; defines only. +// +// The dashboard's loop card opens this in place of the cards. Nothing here +// runs an agent: Start saves the setup through POST /loop-setup, then asks the +// desktop app (`loop-start { spec }`), which reads the setup itself and +// confirms in its own window. The quick check is typed text the page never +// runs or sends to the app. + +import { el } from "../render.js"; +import { hooks, page, redraw } from "../state.js"; +import { SKILL_CATALOG } from "../answers.js"; +import { postJson } from "../net.js"; +import { tellApp, wireLoopMessages } from "../app-bridge.js"; + +const LEVELS = [ + ["critical", "Critical"], + ["warning", "Warning"], + ["suggestion", "Suggestion"], +]; + +const ON_QUESTION = [ + ["guess", "Take the agent's best guess", "The agent picks the likeliest answer and records the assumption."], + ["pause", "Pause and wait for me", "The loop holds and calls you; nothing is lost while you are away."], + ["stop", "Stop the loop", "The loop ends at that phase and tells you what it asked."], +]; + +const AFTER_LAST = [ + ["offer-finalize", "Stop and offer Finalize", "You press Finalize when you have looked it over."], + ["run-finalize", "Run Finalize automatically", "Finalize starts by itself once every phase is built."], +]; + +const DEFAULT_NOTIFY_PARAM = "message"; +// What the setup can send a notification to. `name` is the label for the field +// the person names, on the kinds that have one. +const NOTIFY_KINDS = [ + { id: "query", label: "A web address, with the message in its query string", placeholder: "https://example.com/hook", hint: "The app calls this address with a GET.", name: "Query string name for the message" }, + { id: "discord", label: "Discord webhook", placeholder: "https://discord.com/api/webhooks/...", hint: "In Discord: Edit Channel, Integrations, Webhooks, then Copy Webhook URL." }, + { id: "slack", label: "Slack webhook", placeholder: "https://hooks.slack.com/services/...", hint: "An Incoming Webhook URL from your Slack app's settings." }, + { id: "teams", label: "Microsoft Teams webhook", placeholder: "https://...", hint: 'In Teams: Workflows, the template "Post to a channel when a webhook request is received", then copy its URL.' }, + { id: "google-chat", label: "Google Chat webhook", placeholder: "https://chat.googleapis.com/v1/spaces/...", hint: "In the space: Apps & integrations, Webhooks, then copy the URL." }, + { id: "json", label: "A web address, with the message in a JSON body", placeholder: "https://example.com/hook", hint: "The app sends a POST with a JSON object holding the message, for any other service.", name: "JSON field name for the message" }, +]; +const SMART_DETAIL = "A fresh agent reads the review's findings and fixes the ones worth fixing. A skipped Critical stops the phase."; + +/** Called by the page's start-up: hear the app's answers to the loop's requests. */ +export function wireLoopSetup() { + wireLoopMessages(page, redraw); +} + +/** + * Open the setup screen for `spec` (the picker's selected spec object). The + * saved setup and the read-only facts come from the console; the agent, model + * and permission facts come from the app. + */ +export async function openLoopSetup(spec) { + if (!spec || !spec.dir || page.gone || page.pendingResult || page.local.launching) return; + const dir = spec.dir; + page.loopStart = null; + page.loopNotifyTest = null; + page.loopSetup = { spec: dir, loaded: false, failed: false, form: null, facts: null, problems: [], starting: false }; + tellApp("loop-facts"); + redraw(); + const mine = page.loopSetup; + let res; + try { + res = await fetch("/loop-setup?spec=" + encodeURIComponent(dir), { cache: "no-store" }); + } catch { + res = null; + } + if (page.loopSetup !== mine) return; + if (!res || !res.ok) { + mine.failed = true; + redraw(); + return; + } + const answer = await res.json().catch(() => null); + if (page.loopSetup !== mine) return; + if (!answer) { + mine.failed = true; + redraw(); + return; + } + const { phasesLeft, branch, pending, suggestedQuickCheck, remembered, saved, ...setup } = answer; + mine.form = { + review: setup.review !== false, + fixMode: setup.fixMode === "levels" ? "levels" : "smart", + fix: Array.isArray(setup.fix) ? [...setup.fix] : LEVELS.map(([k]) => k), + commit: setup.commit !== false, + onQuestion: setup.onQuestion || "guess", + afterLast: setup.afterLast || "offer-finalize", + quickCheck: typeof setup.quickCheck === "string" ? setup.quickCheck : "", + retryOnce: setup.retryOnce !== false, + silenceMinutes: Number.isInteger(setup.silenceMinutes) ? setup.silenceMinutes : 20, + notifyKind: NOTIFY_KINDS.some((k) => k.id === setup.notifyKind) ? setup.notifyKind : "query", + notifyUrl: typeof setup.notifyUrl === "string" ? setup.notifyUrl : "", + notifyParam: setup.notifyParam || DEFAULT_NOTIFY_PARAM, + }; + // A first visit with nothing typed starts from the project's own check. + if (!remembered && !mine.form.quickCheck && suggestedQuickCheck) mine.form.quickCheck = suggestedQuickCheck; + mine.facts = { + phasesLeft: Array.isArray(phasesLeft) ? phasesLeft : [], + branch: typeof branch === "string" ? branch : "", + pending: Number.isInteger(pending) ? pending : null, + }; + mine.loaded = true; + redraw(); +} + +function close() { + page.loopSetup = null; + page.loopStart = null; + redraw(); +} + +/** + * Why Start is grayed, or "" when it can go (FR-5), in the spec's order. + * Exported for the page's unit tests. + */ +export function startBlock(form, facts, appFacts) { + if (!form || !facts) return "Loading the setup..."; + if (form.commit && facts.pending !== null && facts.pending > 0) { + return `Commit each phase needs a clean tree: ${facts.pending} uncommitted ${facts.pending === 1 ? "change" : "changes"}.`; + } + if (!appFacts) return "Asking the app..."; + if (appFacts.permissionMode === "checked") return "The loop needs permission checks off. Start a New Session with checks off first."; + if (appFacts.promptSupport === false) return "This agent cannot be started with a first prompt."; + if (!facts.phasesLeft.length) return "Nothing left to build in this spec."; + return ""; +} + +/** + * What is wrong with the web address fields as typed, or "". The server checks + * again on save; this is the line that shows while typing. + */ +export function notifyProblem(url, param, kind = "query") { + const address = url.trim(); + if (!address) return ""; + if (!/^https?:\/\//i.test(address)) return "The web address must start with http:// or https://."; + let good = /^https?:\/\/[^/?#@]+([/?#][!-~]*)?$/i.test(address) && !/[^!-~]/.test(address); + if (good) { + try { + good = Boolean(new URL(address).hostname); + } catch { + good = false; + } + } + if (!good) return "That is not a web address the app can call. Leave out any user name or password, and percent-encode spaces and accents."; + const named = NOTIFY_KINDS.some((k) => k.id === kind && k.name); + if (named && !/^[A-Za-z0-9._~-]{1,64}$/.test(param.trim() || DEFAULT_NOTIFY_PARAM)) return "The name can only use letters, digits, and - _ . ~"; + return ""; +} + +/** + * The chat service a pasted address belongs to, or "". A webhook needs a POST: + * a GET to a Discord webhook answers 200 and posts nothing, so staying on the + * query string kind would look like it worked. + */ +export function kindForUrl(url) { + let parsed; + try { + parsed = new URL(url.trim()); + } catch { + return ""; + } + const host = parsed.hostname.toLowerCase(); + const under = (domain) => host === domain || host.endsWith(`.${domain}`); + if ((under("discord.com") || under("discordapp.com")) && parsed.pathname.startsWith("/api/webhooks/")) return "discord"; + if (host === "hooks.slack.com") return "slack"; + if (host === "chat.googleapis.com") return "google-chat"; + if (under("logic.azure.com") || under("powerplatform.com") || under("powerautomate.com")) return "teams"; + return ""; +} + +function field(label, hint) { + const box = el("div", "loop-field"); + box.appendChild(el("p", "loop-label", label)); + if (hint) box.appendChild(el("p", "loop-hint", hint)); + return box; +} + +function toggle(id, text, checked, onChange) { + const label = el("label", "loop-switch"); + const input = el("input"); + input.type = "checkbox"; + input.id = id; + input.checked = checked; + input.addEventListener("change", () => onChange(input.checked)); + label.append(input, el("span", null, text)); + return label; +} + +function radios(name, options, current, onChange) { + const group = el("div", "loop-radios"); + group.setAttribute("role", "radiogroup"); + for (const [value, text, detail] of options) { + const label = el("label", "loop-radio"); + const input = el("input"); + input.type = "radio"; + input.name = name; + input.id = `loop-${name}-${value}`; + input.checked = current === value; + input.addEventListener("change", () => input.checked && onChange(value)); + const body = el("span", "loop-radio-body"); + body.appendChild(el("span", "loop-radio-text", text)); + if (detail) body.appendChild(el("span", "loop-radio-detail", detail)); + label.append(input, body); + group.appendChild(label); + } + return group; +} + +function factRow(list, label, value) { + const row = el("div", "loop-fact"); + row.appendChild(el("dt", null, label)); + row.appendChild(el("dd", null, value)); + list.appendChild(row); +} + +function agentLine(facts, doing) { + if (!facts) return "Asking the app..."; + const bits = [facts.agentLabel || facts.agent || "the app's agent"]; + bits.push(facts.model ? `model ${facts.model}` : "default model"); + bits.push(facts.effort ? `effort ${facts.effort}` : "default effort"); + return `${bits.join(", ")} (the app's launch choice, for ${doing})`; +} + +export function renderLoopSetup(main) { + const s = page.loopSetup; + const pane = el("div", "dash-confirm loop-setup"); + pane.appendChild(el("p", "card-kicker", "Step 3 · Implementation Loop")); + pane.appendChild(el("h2", "dash-title", "Set up the loop")); + const specLine = el("p", "confirm-spec"); + specLine.append(el("span", null, "for "), el("code", null, s.spec)); + pane.appendChild(specLine); + + if (s.failed) { + pane.appendChild(el("p", "loop-error", "The setup could not be read. Go back and try again.")); + } else if (!s.loaded) { + const wait = el("p", "dash-working"); + wait.append(el("span", "spinner tiny"), el("span", null, "Loading the setup...")); + pane.appendChild(wait); + } else { + drawBody(pane, s); + } + + const actions = el("div", "confirm-actions"); + const back = el("button", "btn ghost", "Back"); + back.type = "button"; + back.addEventListener("click", close); + actions.appendChild(back); + const help = el("button", "linky loop-help", "How the loop works"); + help.type = "button"; + help.addEventListener("click", () => hooks.openHelpOn("loop")); + actions.appendChild(help); + pane.appendChild(actions); + main.appendChild(pane); +} + +function drawBody(pane, s) { + const f = s.form; + const redo = () => { + s.problems = []; + redraw(); + }; + + // What the app will do, in three plain lines (FR-3). + const lines = el("div", "loop-lines"); + for (const text of [ + "The app builds each remaining phase in a fresh agent session, one after another, while you are away.", + "After each phase it checks the work, marks it done and, if you chose, commits it to this branch. It never pushes.", + "You can watch, play an Activity or stop it at any time from the banner at the top of the window.", + ]) { + lines.appendChild(el("p", "loop-line", text)); + } + pane.appendChild(lines); + + // The read-only facts (FR-3). + const facts = el("dl", "loop-facts"); + const left = s.facts.phasesLeft; + factRow(facts, "Phases left", left.length ? left.map((p) => `Phase ${p.n}: ${p.name}`).join("\n") : "None"); + factRow(facts, "Building", agentLine(page.loopFacts, "building")); + factRow(facts, "Reviewing", f.review ? agentLine(page.loopFacts, "reviewing") : "Review is off"); + factRow(facts, "Branch", s.facts.branch || "unknown"); + factRow(facts, "Uncommitted changes", s.facts.pending === null ? "unknown" : String(s.facts.pending)); + pane.appendChild(facts); + + // The fields (FR-2, FR-4). + const form = el("div", "loop-form"); + + const review = field("Review"); + review.appendChild(toggle("loop-review", "Review each phase with a fresh agent before it counts", f.review, (v) => ((f.review = v), redo()))); + form.appendChild(review); + + if (f.review) { + const fix = field("Fix findings"); + fix.appendChild( + radios( + "fixmode", + [ + ["smart", "Smart pick", SMART_DETAIL], + ["levels", "By level", "The agent fixes every finding at the levels you tick."], + ], + f.fixMode, + (v) => ((f.fixMode = v), redo()) + ) + ); + if (f.fixMode === "levels") { + const row = el("div", "loop-ticks"); + for (const [key, text] of LEVELS) { + row.appendChild( + toggle(`loop-fix-${key}`, text, f.fix.includes(key), (on) => { + f.fix = LEVELS.map(([k]) => k).filter((k) => (k === key ? on : f.fix.includes(k))); + redo(); + }) + ); + } + fix.appendChild(row); + } + form.appendChild(fix); + } + + const ask = field("When a phase asks something"); + ask.appendChild(radios("onquestion", ON_QUESTION, f.onQuestion, (v) => ((f.onQuestion = v), redo()))); + form.appendChild(ask); + + const after = field("After the last phase"); + after.appendChild(radios("afterlast", AFTER_LAST, f.afterLast, (v) => ((f.afterLast = v), redo()))); + form.appendChild(after); + + const notify = field( + "Send a notification", + "When the loop waits on your answer or ends, except when you stop it yourself, the app sends a short message saying which. Leave the address empty to send nothing." + ); + const kindLabel = el("label", "loop-number"); + kindLabel.appendChild(el("span", null, "Send to")); + const kindSelect = el("select", "loop-text"); + kindSelect.id = "loop-notify-kind"; + for (const kind of NOTIFY_KINDS) { + const option = el("option", null, kind.label); + option.value = kind.id; + kindSelect.appendChild(option); + } + kindSelect.value = f.notifyKind; + kindLabel.appendChild(kindSelect); + const kindHint = el("p", "loop-hint"); + const notifyInput = el("input", "loop-text"); + notifyInput.type = "text"; + notifyInput.inputMode = "url"; + notifyInput.id = "loop-notify-url"; + notifyInput.value = f.notifyUrl; + notifyInput.maxLength = 2000; + notifyInput.setAttribute("aria-label", "Web address to call"); + const paramRow = el("div"); + const paramLabel = el("label", "loop-number"); + const paramText = el("span"); + paramLabel.appendChild(paramText); + const paramInput = el("input", "loop-text loop-param"); + paramInput.type = "text"; + paramInput.id = "loop-notify-param"; + paramInput.value = f.notifyParam; + paramInput.placeholder = DEFAULT_NOTIFY_PARAM; + paramInput.maxLength = 64; + paramLabel.appendChild(paramInput); + paramRow.appendChild(paramLabel); + const notifyWarn = el("p", "loop-warn"); + const testRow = el("div", "loop-test"); + const testButton = el("button", "btn", "Send a test"); + testButton.type = "button"; + testButton.id = "loop-notify-test"; + testButton.addEventListener("click", () => sendTest(s)); + testRow.appendChild(testButton); + const testLine = notifyTestLine(); + if (testLine) testRow.appendChild(testLine); + const showNotify = () => { + const kind = NOTIFY_KINDS.find((k) => k.id === f.notifyKind); + kindSelect.value = kind.id; + kindHint.textContent = kind.hint; + notifyInput.placeholder = kind.placeholder; + paramText.textContent = kind.name || ""; + paramRow.hidden = !kind.name || f.notifyUrl.trim() === ""; + const problem = notifyProblem(f.notifyUrl, f.notifyParam, kind.id); + notifyWarn.textContent = problem; + notifyWarn.hidden = !problem; + testButton.disabled = Boolean(problem) || f.notifyUrl.trim() === "" || Boolean(page.loopNotifyTest && page.loopNotifyTest.waiting) || s.starting; + }; + // What a test said was about the address as it was. + const forgetTest = () => { + if (page.loopNotifyTest && !page.loopNotifyTest.waiting) { + page.loopNotifyTest = null; + testRow.querySelector("p")?.remove(); + } + }; + notifyInput.addEventListener("input", () => { + f.notifyUrl = notifyInput.value; + forgetTest(); + // A pasted webhook picks its own kind, unless the person chose one here. + const service = kindForUrl(f.notifyUrl); + if (service && f.notifyKind === "query" && !s.notifyKindChosen) f.notifyKind = service; + showNotify(); + }); + kindSelect.addEventListener("change", () => { + f.notifyKind = kindSelect.value; + forgetTest(); + s.notifyKindChosen = true; + showNotify(); + }); + paramInput.addEventListener("input", () => { + f.notifyParam = paramInput.value; + forgetTest(); + showNotify(); + }); + showNotify(); + notify.append(kindLabel, notifyInput, kindHint, paramRow, notifyWarn, testRow); + form.appendChild(notify); + + const check = field("Quick check", "A command the app runs after each phase, such as npm run build. The page never runs it."); + const checkInput = el("input", "loop-text"); + checkInput.type = "text"; + checkInput.id = "loop-quickcheck"; + checkInput.value = f.quickCheck; + checkInput.placeholder = "npm run build"; + checkInput.maxLength = 500; + checkInput.setAttribute("aria-label", "Quick check command"); + const checkWarn = el("p", "loop-warn", "No check runs after each phase."); + checkWarn.hidden = f.quickCheck.trim() !== ""; + checkInput.addEventListener("input", () => { + f.quickCheck = checkInput.value.replace(/[\r\n]+/g, " "); + checkWarn.hidden = f.quickCheck.trim() !== ""; + }); + check.append(checkInput, checkWarn); + form.appendChild(check); + + const retry = field("If a phase crashes or goes quiet"); + retry.appendChild(toggle("loop-retry", "Retry it once", f.retryOnce, (v) => ((f.retryOnce = v), redo()))); + const silence = el("label", "loop-number"); + silence.appendChild(el("span", null, "Count the agent as stuck after this many minutes with no activity")); + const silenceInput = el("input", "loop-text loop-narrow"); + silenceInput.type = "number"; + silenceInput.id = "loop-silence"; + silenceInput.min = "1"; + silenceInput.max = "60"; + silenceInput.step = "1"; + silenceInput.value = String(f.silenceMinutes); + silenceInput.addEventListener("input", () => { + f.silenceMinutes = Number(silenceInput.value); + }); + silence.appendChild(silenceInput); + retry.appendChild(silence); + retry.appendChild(el("p", "loop-hint", "No activity means no file changes, in the project or the agent's session, so allow for your slowest build or test run. Waiting on your answer does not count.")); + form.appendChild(retry); + + const commit = field("Commit"); + commit.appendChild(toggle("loop-commit", "Commit each phase to the current branch", f.commit, (v) => ((f.commit = v), redo()))); + form.appendChild(commit); + + pane.appendChild(form); + + // Start and the one line saying why it is grayed (FR-5). + const block = startBlock(f, s.facts, page.loopFacts); + const gated = Boolean(block); + const foot = el("div", "loop-start"); + if (gated) { + const why = el("p", "loop-why", block); + why.setAttribute("role", "status"); + foot.appendChild(why); + if (f.commit && s.facts.pending > 0) foot.appendChild(gitButton()); + } + if (s.problems.length) { + const bad = el("ul", "loop-problems"); + for (const p of s.problems) bad.appendChild(el("li", null, p)); + foot.appendChild(bad); + } + const waiting = s.starting && !page.loopStart; + if (waiting) foot.appendChild(el("p", "loop-why", "Waiting for the app's confirm...")); + if (page.loopStart && !page.loopStart.ok) foot.appendChild(el("p", "loop-error", page.loopStart.error)); + if (page.loopStart && page.loopStart.ok) foot.appendChild(el("p", "loop-why", "The loop is starting...")); + const start = el("button", "btn primary", "Start the loop"); + start.type = "button"; + start.id = "loop-start"; + start.disabled = gated || waiting || page.gone || page.pendingResult || Boolean(page.loopStart && page.loopStart.ok); + start.addEventListener("click", () => startLoop(s)); + foot.appendChild(start); + pane.appendChild(foot); +} + +/** The line beside Send a test, or null with nothing to say. */ +function notifyTestLine() { + const test = page.loopNotifyTest; + if (!test) return null; + if (test.waiting) return el("p", "loop-why", "Waiting for the app's confirm..."); + if (!test.ok) return el("p", "loop-error", test.error); + if (test.sent) return el("p", "loop-why", "Sent, and the address answered OK. Check that the message arrived."); + return null; +} + +function gitButton() { + const b = el("button", "btn", "Open the Git board"); + b.type = "button"; + b.addEventListener("click", () => { + const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git"); + if (entry) hooks.launchSkill(entry); + }); + return b; +} + +/** The form as the console saves it. */ +function setupBody(f) { + return { ...f, quickCheck: f.quickCheck.trim(), notifyUrl: f.notifyUrl.trim(), notifyParam: f.notifyParam.trim() || DEFAULT_NOTIFY_PARAM }; +} + +/** + * Send a test: save, so the app can read what is on screen, then ask it. The + * message names nothing: the app takes the address from the saved setup and + * confirms it in its own dialog, as it does for Start. + */ +async function sendTest(s) { + const f = s.form; + if (!f.notifyUrl.trim() || notifyProblem(f.notifyUrl, f.notifyParam, f.notifyKind) || (page.loopNotifyTest && page.loopNotifyTest.waiting)) return; + s.problems = []; + page.loopNotifyTest = { waiting: true }; + redraw(); + const { status, body: answer } = await postJson("/loop-setup", setupBody(f)); + if (page.loopSetup !== s) return; + if (status !== 200 || !answer || answer.ok !== true) { + page.loopNotifyTest = null; + s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."]; + redraw(); + return; + } + tellApp("loop-notify-test"); +} + +async function startLoop(s) { + const f = s.form; + if (startBlock(f, s.facts, page.loopFacts) || (s.starting && !page.loopStart)) return; + s.problems = []; + page.loopStart = null; + s.starting = true; + redraw(); + const { status, body: answer } = await postJson("/loop-setup", setupBody(f)); + if (page.loopSetup !== s) return; + if (status !== 200 || !answer || answer.ok !== true) { + s.starting = false; + s.problems = Array.isArray(answer && answer.problems) && answer.problems.length ? answer.problems : ["The setup could not be saved. Try again."]; + redraw(); + return; + } + tellApp("loop-start", { spec: s.spec }); + redraw(); +} diff --git a/src/web-console/public/screens/prefs-dialog.js b/src/web-console/public/screens/prefs-dialog.js new file mode 100644 index 0000000..ab72cc0 --- /dev/null +++ b/src/web-console/public/screens/prefs-dialog.js @@ -0,0 +1,206 @@ +// Plan2Code Web Console - the User Preferences dialog: its tabs, the one way +// to open and close it, the Saved mark, Back to default for the tab on screen +// and the prompt that stops an unsaved agent edit being lost. + +import { onSwatchSaved, renderSwatches, resetLooks, saveLooks } from "../looks.js"; +import { PREFS_TABS, prefsOpenTab, prefsResetScope } from "../prefs.js"; +import { wireTabs } from "../tabs.js"; +import { el, lightDismiss } from "../render.js"; +import { hooks, redraw } from "../state.js"; + +const $ = (id) => document.getElementById(id); + +let prefsTabs = null; + +// Back to default only where the tab has looks to reset. +function showResetFor(id) { + $("looks-reset").hidden = prefsResetScope(id) === null; +} + +// The small mark at the top right of a fieldset, level with its legend: +// "Saved", fading, or the error in its place, kept until that fieldset saves +// again. `result` is what saveLooks() resolves, or a Promise of it; a `text` +// in it replaces the word Saved. +const markTimers = new WeakMap(); + +function clearMark(mark) { + clearTimeout(markTimers.get(mark)); + if (mark.classList.contains("is-saved")) mark.textContent = ""; +} + +export async function markSaved(fieldset, result) { + if (!fieldset) return; + let mark = fieldset.querySelector(":scope > .prefs-saved"); + if (!mark) { + mark = el("span", "prefs-saved"); + mark.setAttribute("role", "status"); + // Gone after the fade, or after the same time when motion is reduced and + // no animation runs to say so (the timer below). + mark.addEventListener("animationend", () => clearMark(mark)); + fieldset.appendChild(mark); + } + const { ok, error, text } = (await result) || { ok: true }; + // A newer save owns the mark: an earlier one's timer must not blank it. + clearTimeout(markTimers.get(mark)); + mark.classList.remove("is-saved", "error"); + // Restart the fade when the same fieldset saves twice in a row. + void mark.offsetWidth; + if (ok) { + mark.textContent = text || "Saved"; + mark.classList.add("is-saved"); + markTimers.set(mark, setTimeout(() => clearMark(mark), 2200)); + } else { + mark.textContent = error || "Could not save."; + mark.classList.add("error"); + } +} + +// Every way in: the gear, the dashboard's Set up preferences, or a caller +// naming the tab it wants. Agents and models load each time it opens. +export function openPrefs(tab) { + renderSwatches(); + hooks.loadAgentsView(); + prefsTabs.select(prefsOpenTab(tab)); + $("looks-modal").showModal(); + $("prefs-tab-" + prefsTabs.current()).focus(); +} + +// The unsaved prompt on screen: { resolve, promise, from }, or null. `from` +// is what had focus when it asked (the tab, Close, Back to summary, a field). +let asking = null; + +// Everything in the dialog but the prompt, kept out of reach while it asks. +const behindPrompt = () => [$("looks-title"), $("looks-modal").querySelector(".prefs-body"), $("looks-modal").querySelector(".modal-actions")]; + +function endAsking(go) { + $("prefs-unsaved").hidden = true; + for (const node of behindPrompt()) node.inert = false; + const { resolve, from } = asking; + asking = null; + // Keep editing (or a failed Save) goes back into the form; going on hands + // focus back to what asked, so the action it carries on with owns it. + if (!go) hooks.focusOpen(); + else if (from && from.isConnected && !from.closest("[hidden]")) from.focus(); + resolve(go); +} + +// Before anything leaves an agent form with an unsaved edit (Close, Esc, a +// backdrop click, another tab, Back to summary): Save, Discard or Keep +// editing, asked inside the dialog. Resolves true when it may go on. +export function confirmUnsaved() { + if (!hooks.hasUnsaved()) return Promise.resolve(true); + if (asking) return asking.promise; + let resolve; + const promise = new Promise((r) => (resolve = r)); + asking = { resolve, promise, from: document.activeElement }; + $("prefs-unsaved-name").textContent = hooks.unsavedName(); + for (const node of behindPrompt()) node.inert = true; + $("prefs-unsaved").hidden = false; + $("prefs-unsaved-save").disabled = false; + $("prefs-unsaved-save").focus(); + return promise; +} + +// Plain true while nothing is unsaved, so a tab switch or a close happens in +// this same tick. +const guard = () => (hooks.hasUnsaved() || asking ? confirmUnsaved() : true); + +async function closePrefs() { + if (await guard()) $("looks-modal").close(); +} + +function wireUnsaved() { + const box = el("div", "prefs-unsaved"); + box.id = "prefs-unsaved"; + box.hidden = true; + box.setAttribute("role", "alertdialog"); + box.setAttribute("aria-labelledby", "prefs-unsaved-title"); + box.setAttribute("aria-describedby", "prefs-unsaved-text"); + const inner = el("div", "prefs-unsaved-box"); + const title = el("h3", null, "Unsaved changes"); + title.id = "prefs-unsaved-title"; + const text = el("p"); + text.id = "prefs-unsaved-text"; + const name = el("strong"); + name.id = "prefs-unsaved-name"; + text.append("You have unsaved changes to ", name, "."); + const save = el("button", "btn small primary", "Save"); + save.type = "button"; + save.id = "prefs-unsaved-save"; + const discard = el("button", "btn small ghost", "Discard"); + discard.type = "button"; + const keep = el("button", "btn small ghost", "Keep editing"); + keep.type = "button"; + save.addEventListener("click", async () => { + save.disabled = true; + const ok = await hooks.saveOpen(); + save.disabled = false; + if (asking) endAsking(ok); + }); + discard.addEventListener("click", () => { + hooks.discardOpen(); + endAsking(true); + }); + keep.addEventListener("click", () => endAsking(false)); + const actions = el("div", "prefs-unsaved-actions"); + actions.append(save, discard, keep); + inner.append(title, text, actions); + box.append(inner); + $("looks-modal").append(box); +} + +export function wirePrefs() { + const dlg = $("looks-modal"); + wireUnsaved(); + lightDismiss(dlg, guard); + $("looks-done").addEventListener("click", closePrefs); + // Esc: held while a form has an unsaved edit, and Keep editing while the prompt asks. + dlg.addEventListener("keydown", (e) => { + if (e.key !== "Escape") return; + if (asking) { + e.preventDefault(); + endAsking(false); + } else if (hooks.hasUnsaved()) { + e.preventDefault(); + closePrefs(); + } + }); + dlg.addEventListener("cancel", (e) => { + if (!asking && !hooks.hasUnsaved()) return; + e.preventDefault(); + if (!asking) closePrefs(); + }); + hooks.wireAgentsView(); + prefsTabs = wireTabs({ + tabs: PREFS_TABS, + list: $("prefs-tabs"), + panels: $("prefs-panels"), + prefix: "prefs", + tabClass: "prefs-tab", + beforeSelect: () => guard(), + // The hint describes the tab rather than naming it, so a screen reader's + // tab name stays the label, at any width. + renderTab: (t, btn) => { + const hint = el("span", "prefs-tab-hint", t.hint); + hint.id = "prefs-hint-" + t.id; + hint.setAttribute("aria-hidden", "true"); + btn.append(el("span", "prefs-tab-label", t.label), hint); + btn.setAttribute("aria-describedby", hint.id); + }, + onSelect: (id) => { + showResetFor(id); + $("looks-modal").querySelector(".prefs-body").scrollTop = 0; + }, + }); + $("btn-looks").addEventListener("click", () => openPrefs()); + $("looks-reset").addEventListener("click", () => { + const tab = prefsTabs.current(); + const keys = prefsResetScope(tab); + if (!keys) return; + resetLooks(keys); + const saved = saveLooks(); + redraw(); + markSaved($("prefs-panel-" + tab).querySelector("fieldset"), saved); + }); + onSwatchSaved((saved) => markSaved($("looks-swatches").closest("fieldset"), saved)); +} diff --git a/src/web-console/public/screens/starting.js b/src/web-console/public/screens/starting.js index 564d56f..d591fd6 100644 --- a/src/web-console/public/screens/starting.js +++ b/src/web-console/public/screens/starting.js @@ -4,7 +4,7 @@ import { page, redraw } from "../state.js"; import { el, approvalTip } from "../render.js"; import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js"; import { skillByName } from "../skills.js"; -import { agentAdrift, doingNow, docs } from "../selectors.js"; +import { agentAdrift, doingNow, docs, loopDriving } from "../selectors.js"; const $ = (id) => document.getElementById(id); @@ -132,10 +132,12 @@ function renderStarting(main) { const elapsed = startingElapsed(); const pane = posePane(main, "launching starting", page.S.workflow); pane.appendChild(el("p", "card-kicker", "Starting up")); - pane.appendChild(el("h2", "launch-title", `Starting ${workflowTitle(page.S.workflow)}`)); + const looping = loopDriving(); + pane.appendChild(el("h2", "launch-title", looping ? "The loop is starting this phase" : `Starting ${workflowTitle(page.S.workflow)}`)); pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length])); pane.appendChild(el("p", "launch-hint", startingHint(elapsed))); - pane.appendChild(approvalTip()); + // A loop runs with permission checks off, so no approval will come. + if (!looping) pane.appendChild(approvalTip()); startLaunchTicker(); } @@ -180,8 +182,17 @@ function startLaunchTicker() { } } +// A phase that has reported is not starting: the app is checking the report, +// running the quick check and committing, which can take minutes. +function renderLoopChecking(main) { + const pane = posePane(main, "waiting-pane", page.S.workflow); + pane.appendChild(el("h2", null, "The loop is checking this phase")); + pane.appendChild(el("p", null, "The agent has reported. The app is checking that against the spec before it moves on, so you don't need to do anything.")); +} + export function renderWaiting(main) { const doing = doingNow(); + if (!doing && loopDriving() && page.S.loopOutcome) return renderLoopChecking(main); // Nothing asked and nothing said yet: the session is still starting. if (!doing) return renderStarting(main); // The same Planny the session started with, still at it: the spinner that @@ -199,7 +210,9 @@ export function renderWaiting(main) { } pane.appendChild(title); pane.appendChild(el("p", null, doing)); - const ask = "If Plan2Code needs you, the question appears here on its own."; + const ask = loopDriving() + ? "The loop is running this phase by itself, so you don't need to do anything. If it needs you, the question appears here." + : "If Plan2Code needs you, the question appears here on its own."; if (!docs().length) { pane.appendChild(el("p", null, ask)); return; diff --git a/src/web-console/public/screens/workspace.js b/src/web-console/public/screens/workspace.js index b7aadfc..188d655 100644 --- a/src/web-console/public/screens/workspace.js +++ b/src/web-console/public/screens/workspace.js @@ -2,7 +2,7 @@ import { hooks, page } from "../state.js"; import { copyButton, el, lightDismiss, selectContents } from "../render.js"; -import { selSpec, specList, workspaceFolders } from "../selectors.js"; +import { loopDriving, selSpec, specList, workspaceFolders } from "../selectors.js"; import { postJson } from "../net.js"; import { nameProblem } from "../workspace.js"; @@ -114,6 +114,12 @@ export function renderWorkspace() { folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f)); $("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote); $("workspace-scope").textContent = workspaceScopeText(); + // The loop's agents were started with this workspace; changing it now would + // reach nobody (FR-15). Reading and copying paths stays. + const locked = loopDriving(); + for (const id of ["workspace-add", "workspace-browse", "workspace-path"]) $(id).disabled = locked || (id === "workspace-add" && wsBusy); + for (const rm of list.querySelectorAll(".ws-remove")) rm.disabled = locked; + if (locked) setAddMsg("The workspace is fixed while the loop builds."); } function workspaceRow(f) { @@ -281,7 +287,7 @@ function paintWorkspaceRow(li, f) { // sent when the person took a suggested name after a clash. async function addWorkspaceFolder(path, name) { const trimmed = String(path || "").trim(); - if (!trimmed || wsBusy) return; + if (!trimmed || wsBusy || loopDriving()) return; wsBusy = true; $("workspace-add").disabled = true; const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed }); @@ -318,7 +324,7 @@ async function addWorkspaceFolder(path, name) { async function browseWorkspace() { const b = $("workspace-browse"); - if (b.disabled) return; + if (b.disabled || loopDriving()) return; b.disabled = true; setAddMsg("Waiting for the folder picker…"); const { status, body } = await postJson("/workspace/browse", {}); diff --git a/src/web-console/public/selectors.js b/src/web-console/public/selectors.js index dbacd75..3ea5dd6 100644 --- a/src/web-console/public/selectors.js +++ b/src/web-console/public/selectors.js @@ -7,6 +7,7 @@ import { page, redraw } from "./state.js"; import { boardAwaiting } from "./git-board.js"; import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js"; import { activityLabel, workingLine } from "./labels.js"; +import { ASK_BUSY_MS, chatAnswering } from "./chat.js"; export const WORKING_GRACE_MS = 5 * 60 * 1000; @@ -18,6 +19,33 @@ export const WORKING_GRACE_MS = 5 * 60 * 1000; // many missed pokes, not a slow one. const ADRIFT_MS = 3 * 60 * 1000; +// The Implementation Loop is driving this page: the app started the session +// with `open --loop`, and no `loopEnd` has been posted yet. Locks the page +// (FR-15); the stop and finish screens end it. +export const loopDriving = () => Boolean(page.S && page.S.loop && page.S.loop.driving === true && !page.S.loopEnd); + +// Driving, and a required question the loop does not handle itself is open: +// the one case where its card (and Ask) unlock (FR-14). +export const loopWaiting = () => + loopDriving() && + openItems().some((i) => i.required !== false && i.handledBy !== "loop"); + +// The ids of the cards the loop is waiting on the person for, as one string: +// what `local.askLockedAfterSend` remembers, so Ask locks again after a Send +// and stays locked until a different question waits (FR-14). +export const loopWaitingKey = () => + loopWaiting() + ? openItems() + .filter((i) => i.required !== false && i.handledBy !== "loop") + .map((i) => i.id) + .sort() + .join("|") + : ""; + +// Ask is off while the loop drives, except while a question waits and no Send +// has answered that same question yet. +export const loopAskLocked = () => loopDriving() && !(loopWaiting() && page.local.askLockedAfterSend !== loopWaitingKey()); + export const items = () => (page.S && Array.isArray(page.S.items) ? page.S.items : []); export const topics = () => (page.S && Array.isArray(page.S.topics) ? page.S.topics : []); @@ -200,12 +228,19 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page // well clear of its idle deadline, so the server happily outlives the agent // for hours. Until now nothing said so unless the agent had also declared // itself "working", and the normal state while someone answers is "waiting". +// +// An agent answering an Ask message is out of `wait` too, and busy rather than +// gone, so it gets ASK_BUSY_MS before anything calls it adrift. export function agentAdrift() { if (!page.agentLastSeen || page.gone || finish()) return false; const silent = Date.now() - Date.parse(page.agentLastSeen); - return silent > (page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS)); + const limit = page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS); + return silent > (chatAnswering(page.chatFrame) ? Math.max(limit, ASK_BUSY_MS) : limit); } +// Answering an Ask message, and not yet quiet for long enough to doubt it. +export const askBusy = () => chatAnswering(page.chatFrame) && !agentAdrift(); + // With answers sent and nothing collecting them, the agent's quiet allowance // stops counting: those answers are what it is meant to come back for. An // agent that said it is waiting pings from `wait` every five seconds, so a diff --git a/src/web-console/public/send-state.js b/src/web-console/public/send-state.js index 378528b..94f9bcc 100644 --- a/src/web-console/public/send-state.js +++ b/src/web-console/public/send-state.js @@ -11,6 +11,8 @@ import { WORKING_GRACE_MS, openItems, agentAdrift, + loopDriving, + loopWaiting, } from "./selectors.js"; import { finishPaused } from "./answers.js"; import { page } from "./state.js"; @@ -24,6 +26,11 @@ export function sendState() { ? { disabled: true, why: "This session is paused.", short: "Session paused" } : { disabled: true, why: "This session is finished.", short: "Session finished" }; if (page.gone) return { disabled: true, why: "Not connected right now.", short: "Not connected" }; + // The Implementation Loop answers for the agent: nothing to send until it + // stops to ask the person something (FR-15, FR-14). + if (loopDriving() && !loopWaiting()) { + return { disabled: true, why: "The loop is building. Cards unlock when it needs you.", short: "The loop is building" }; + } // A send is still being collected. Blocking here is what keeps someone from // writing over answers nobody has read yet. if (page.pendingResult) { diff --git a/src/web-console/public/skills.js b/src/web-console/public/skills.js index 650d946..ede1ea7 100644 --- a/src/web-console/public/skills.js +++ b/src/web-console/public/skills.js @@ -43,6 +43,11 @@ // `spec: true` when it takes the picked spec), or null; an // optional `help` is Help's line for the card when it differs // from `blurb` +// appOnly the entry is a card the desktop app alone offers (the +// Implementation Loop): no workflow, no installed skill, and no +// list derived from the workflows (WORKFLOWS, the meter, the +// resume command, Help's card list) holds it. `skill` is an id +// only; `workflow` is null. Use FLOW_SKILLS for those lists. // Shared by Implement and Implement + Review. const BUILD_HELPERS = @@ -235,6 +240,32 @@ export const SKILLS = Object.freeze([ // No card of its own: Implement's card launches it when Review is ticked. card: null, }), + // The desktop app's Implementation Loop: a card, not a skill. It has no + // SKILL.md and no console workflow; it drives Implement (or Implement + + // Review) once per phase, each in a fresh agent. Drawn by the dashboard in + // the app only. + skill({ + skill: "plan2code-loop", + workflow: null, + appOnly: true, + label: "Implementation Loop", + name: "Implementation Loop", + pose: null, + builds: false, phased: false, metered: false, templates: false, + weight: null, started: null, ran: null, resume: null, + subagents: null, + states: ["documented", "building"], + greyed: BUILD_GREYED, + card: { + group: "pipeline", + chip: "Step 3", + spec: true, + title: "Implementation Loop", + blurb: "Build every remaining phase unattended, one fresh agent per phase.", + about: + "Builds every remaining phase of the spec without you at the keyboard. Each phase gets a fresh agent that builds it and reviews it. The app checks the result against the spec, runs your quick check, commits, and moves on. It stops at the first phase that goes wrong and tells you why. Desktop app only.", + }, + }), skill({ skill: "plan2code-4-finalize", workflow: "finalize", @@ -413,11 +444,15 @@ export const SKILLS = Object.freeze([ }), ]); -const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s])); -const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s])); +// The entries that are skills with a workflow, in SKILLS order: what every +// list derived from the workflows is built from (an `appOnly` card is not one). +export const FLOW_SKILLS = Object.freeze(SKILLS.filter((s) => !s.appOnly)); + +const BY_WORKFLOW = new Map(FLOW_SKILLS.map((s) => [s.workflow, s])); +const BY_SKILL = new Map(FLOW_SKILLS.map((s) => [s.skill, s])); // Every workflow name the console knows, in SKILLS order. -export const WORKFLOWS = Object.freeze(SKILLS.map((s) => s.workflow)); +export const WORKFLOWS = Object.freeze(FLOW_SKILLS.map((s) => s.workflow)); /** Whether a name is one of WORKFLOWS (`open --workflow`, `handoff new --workflow`). */ export function isWorkflow(name) { diff --git a/src/web-console/public/state.js b/src/web-console/public/state.js index b5b0215..7099553 100644 --- a/src/web-console/public/state.js +++ b/src/web-console/public/state.js @@ -111,6 +111,21 @@ export const page = { // false until the first frame lands, same as every other flag here, and // from an older server that sends none. inApp: false, + // The Implementation Loop, as the desktop app drives it: `loop` is the + // state's `{ driving: true }` or null (it locks the page, selectors.js + // loopDriving); `loopFacts` is what the app answered to `loop-facts` + // (agent, model, effort, permission mode, prompt support); `loopStart` is + // `{ ok, error }` once the app answered a `loop-start`; `loopAction` is the + // same for the stop screen's Resume, Fix and Finalize; `loopNotifyTest` is + // Send a test's `{ waiting }`, then `{ ok, sent, error }` once the app answered. + loop: null, + // The setup screen the dashboard's Implementation Loop card opened, or null + // (screens/loop-setup.js owns the shape). + loopSetup: null, + loopFacts: null, + loopStart: null, + loopNotifyTest: null, + loopAction: null, // The frame's Subagents switch ({ offered, supported, on, instruction, max, // revision }), or null before a server that sends it. subagentsFrame: null, diff --git a/src/web-console/public/styles/dashboard.css b/src/web-console/public/styles/dashboard.css index 4d7de1f..7300211 100644 --- a/src/web-console/public/styles/dashboard.css +++ b/src/web-console/public/styles/dashboard.css @@ -7,7 +7,8 @@ rule, so it needs saying here. */ .footer[hidden] { display: none; } -.dash { max-width: 860px; padding-top: 8px; } +/* The menu follows the Card width setting like the question column does. */ +.dash { max-width: min(var(--card-width), 100%); padding-top: 8px; } .dash-title { margin: 6px 0 8px; font: 600 clamp(26px, 4vw, 36px)/1.1 var(--serif); } .dash-note { margin: 0 0 26px; font-size: 14.5px; color: var(--ink-2); } /* The first-run role nudge: one line above the title, wrapping on a narrow @@ -379,10 +380,10 @@ /* ------------------------------------------------- dashboard confirm */ /* The beat between "I clicked a card" and "it is running": what the pick is, - what it will do, and a START that means it. Narrower than the menu, centered - like the launching pane it precedes. */ + what it will do, and a START that means it. As wide as the menu (the page + width setting), centered like the launching pane it precedes. */ .dash-confirm { - max-width: 560px; + max-width: min(var(--card-width), 100%); margin: 3vh auto 0; display: grid; gap: 10px; @@ -406,6 +407,9 @@ .confirm-head { display: flex; align-items: center; gap: 8px; margin-top: 4px; } .dash-confirm .dash-title { margin: 2px 0 0; } +/* The pane is as wide as the menu, but prose is not: its lines stop at a + readable measure while the controls below keep the full width. */ +.confirm-about, .confirm-detail, .confirm-spec { max-width: 70ch; } .confirm-about { margin: 0; font-size: 14.5px; line-height: 1.55; color: var(--ink-2); } .confirm-detail { margin: 0; font-size: 13px; color: var(--accent); } .confirm-spec { margin: 0; font-size: 13px; color: var(--ink-2); } @@ -428,9 +432,23 @@ /* "Start with a note from your Notebook": the switch, then the tabs beside a preview of the picked one, its pictures each with a tick. */ -.confirm-note-box { display: grid; gap: 8px; } -.confirm-note-switch { display: flex; gap: 8px; align-items: center; color: var(--ink-2); cursor: pointer; } -.confirm-note-switch input { accent-color: var(--accent, currentColor); } +/* Stretched past the confirm's centering, and left aligned: a note reads as + a document, not a caption. */ +/* Its own frame sets it apart from the text above, so no rule: just room. */ +.confirm-note-box { display: grid; gap: 8px; justify-self: stretch; text-align: left; margin-top: 12px; } +.confirm-note-head { + display: grid; + gap: 2px; + padding: 10px 12px; + border: 1px solid var(--accent-line); + border-left: 3px solid var(--accent); + border-radius: 8px; + background: var(--accent-soft); +} +.confirm-note-head.is-on { padding: 8px 12px; } +.confirm-note-switch { display: flex; gap: 10px; align-items: center; color: var(--ink); font-weight: 600; cursor: pointer; } +.confirm-note-switch input { width: 18px; height: 18px; margin: 0; flex: none; accent-color: var(--accent, currentColor); } +.confirm-note-hint { padding-left: 28px; font-size: 12.5px; color: var(--ink-2); } .confirm-note { display: grid; grid-template-columns: minmax(130px, 200px) minmax(0, 1fr); gap: 10px; } .confirm-note > .confirm-note-msg { grid-column: 1 / -1; } .confirm-note-msg { margin: 0; font-size: 13px; color: var(--ink-3); } @@ -480,7 +498,7 @@ /* ------------------------------------------------------- launching pane */ .launching { - max-width: 560px; + max-width: min(var(--card-width), 100%); margin: 4vh auto 0; text-align: center; display: grid; @@ -539,5 +557,54 @@ } .launch-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); max-width: 46ch; } /* A line, never a banner: no border, no background, no icon. */ -.approval-tip { margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); } +.approval-tip { max-width: 70ch; margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); } + +/* --------------------------------------------- the Implementation Loop */ + +/* The card's own link; a span, since a link may not sit inside a button. */ +.dash-card-link { font-size: 12px; color: var(--accent); text-decoration: underline; cursor: pointer; justify-self: start; } + +/* The setup screen: the confirm pane's width, with a left-aligned form. */ +.loop-setup { justify-items: stretch; text-align: left; gap: 14px; } +.loop-setup .card-kicker, .loop-setup .dash-title, .loop-setup .confirm-spec { justify-self: start; } +.loop-lines { display: grid; gap: 4px; } +.loop-line { margin: 0; font-size: 14px; line-height: 1.5; color: var(--ink-2); max-width: 75ch; } +.loop-facts { display: grid; gap: 6px; margin: 0; padding: 12px 14px; background: var(--panel-2); border: 1px solid var(--rule); border-radius: 8px; } +.loop-fact { display: grid; grid-template-columns: minmax(130px, 200px) 1fr; gap: 10px; font-size: 13px; } +.loop-fact dt { color: var(--ink-3); } +.loop-fact dd { margin: 0; color: var(--ink); overflow-wrap: anywhere; white-space: pre-line; } +.loop-form { display: grid; gap: 16px; } +.loop-field { display: grid; gap: 6px; } +.loop-label { margin: 0; font-weight: 600; font-size: 13.5px; } +.loop-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); } +.loop-switch, .loop-radio { display: flex; gap: 8px; align-items: flex-start; cursor: pointer; font-size: 14px; color: var(--ink-2); } +.loop-switch input, .loop-radio input { accent-color: var(--accent, currentColor); margin-top: 3px; } +.loop-radios { display: grid; gap: 6px; } +.loop-radio-body { display: grid; gap: 1px; } +.loop-radio-detail { font-size: 12.5px; color: var(--ink-3); } +.loop-ticks { display: flex; flex-wrap: wrap; gap: 6px 18px; margin-left: 4px; } +.loop-text { font: inherit; font-size: 14px; padding: 6px 10px; color: var(--ink); background: var(--panel-2); border: 1px solid var(--rule); border-radius: 6px; max-width: 520px; width: 100%; } +.loop-text.loop-narrow { width: 90px; } +.loop-text.loop-param { width: 180px; } +.loop-test { display: flex; align-items: center; flex-wrap: wrap; gap: 10px; } +.loop-test p { margin: 0; font-size: 12.5px; } +.loop-number { display: flex; align-items: center; gap: 10px; font-size: 14px; color: var(--ink-2); } +.loop-warn { margin: 0; font-size: 12.5px; color: var(--warn); } +.loop-start { display: grid; gap: 8px; justify-items: start; } +.loop-why { margin: 0; font-size: 13px; color: var(--ink-2); } +.loop-error { margin: 0; font-size: 13px; color: var(--warn); } +.loop-problems { margin: 0; padding-left: 18px; font-size: 13px; color: var(--warn); } +.loop-help { margin-left: auto; } + +/* A card the loop holds: a record with a tag, no inputs. */ +.card.is-loop-handled .loop-tag { margin: 0 0 4px; font-weight: 600; color: var(--accent); } +.card.is-loop-locked .answered { opacity: 0.85; } + +/* The stop and finish screens the loop's end draws. */ +.loop-end { display: grid; gap: 14px; } +.loop-end-phases { width: 100%; border-collapse: collapse; font-size: 13.5px; } +.loop-end-phases th, .loop-end-phases td { text-align: left; padding: 5px 10px 5px 0; border-bottom: 1px solid var(--rule); vertical-align: top; } +.loop-end-phases code { font-family: var(--mono); font-size: 12px; } +.loop-end-files { margin: 0; padding-left: 18px; font-family: var(--mono); font-size: 12px; color: var(--ink-2); } +.loop-end-actions { display: flex; flex-wrap: wrap; gap: 10px; } diff --git a/src/web-console/public/styles/looks.css b/src/web-console/public/styles/looks.css index faf65ec..3d025bd 100644 --- a/src/web-console/public/styles/looks.css +++ b/src/web-console/public/styles/looks.css @@ -6,8 +6,8 @@ appearance: none; flex: none; margin-left: 14px; - width: 30px; - height: 30px; + width: 36px; + height: 36px; padding: 0; display: grid; place-items: center; @@ -17,7 +17,7 @@ cursor: pointer; } .icon-btn:hover { background: var(--panel-2); border-color: var(--rule); } -.icon-btn svg { width: 17px; height: 17px; } +.icon-btn svg { width: 22px; height: 22px; } .icon-btn .ab-ring { fill: none; stroke: var(--ink-3); stroke-width: 1.4; } .icon-btn .ab-mark { fill: none; stroke: var(--ink-2); stroke-width: 1.5; stroke-linecap: round; } .icon-btn .ab-dot { fill: var(--ink-2); } diff --git a/src/web-console/public/styles/notepad.css b/src/web-console/public/styles/notepad.css index a8ab8b4..6fec16e 100644 --- a/src/web-console/public/styles/notepad.css +++ b/src/web-console/public/styles/notepad.css @@ -210,10 +210,12 @@ flex: none; margin: 0 2px 0 2px; padding: 1px 5px; - border: 1px solid var(--rule-2); + border: 1px solid var(--accent-line); border-radius: 999px; - color: var(--ink-3); + background: var(--accent-soft); + color: var(--accent); font-size: 10.5px; + font-weight: 600; line-height: 1.3; white-space: nowrap; } diff --git a/src/web-console/public/styles/pieces.css b/src/web-console/public/styles/pieces.css index 4481457..feccad3 100644 --- a/src/web-console/public/styles/pieces.css +++ b/src/web-console/public/styles/pieces.css @@ -74,6 +74,7 @@ /* ------------------------------------------------------------ options */ .options { list-style: none; margin: 20px 0 0; padding: 0; display: grid; gap: 9px; } +.options-clear { margin-top: 10px; } .option { display: flex; @@ -772,6 +773,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; } .modal.looks { max-width: 720px; } .modal.looks .modal-ranges + .modal-ranges { margin-top: 18px; } .looks-row { grid-template-columns: repeat(3, minmax(0, 1fr)); } +.looks-row.four { grid-template-columns: repeat(4, minmax(0, 1fr)); } .looks-row .help { grid-column: 1 / -1; } /* The Desktop app group exists only inside the app; elsewhere it stays hidden in spite of the grid above. */ @@ -783,7 +785,7 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; } .looks-sound-events.is-off label { cursor: default; } .looks-sound-events.is-off label:hover { border-color: var(--rule-2); } @media (max-width: 720px) { - .looks-row { grid-template-columns: 1fr; } + .looks-row, .looks-row.four { grid-template-columns: 1fr; } } /* User Preferences itself (not the dialogs borrowing .looks): wider, and only the body scrolls, so Back to default and Done never leave the screen. */ diff --git a/src/web-console/public/styles/prefs.css b/src/web-console/public/styles/prefs.css new file mode 100644 index 0000000..aa16b14 --- /dev/null +++ b/src/web-console/public/styles/prefs.css @@ -0,0 +1,188 @@ +/* prefs.css: User Preferences' tabs (the side list, the narrow strip), the Saved + mark, the Agents & models table and form, and the unsaved prompt. */ + +/* --------------------------------------------------------- tabs and panels */ + +.prefs-layout { + display: grid; + grid-template-columns: 200px minmax(0, 1fr); + gap: 20px; + align-items: start; +} +.prefs-tabs { + display: flex; + flex-direction: column; + gap: 2px; + min-width: 0; +} +.prefs-tab { + display: flex; + flex-direction: column; + align-items: flex-start; + gap: 2px; + width: 100%; + padding: 8px 10px; + border: 0; + border-left: 3px solid transparent; + border-radius: 6px; + background: transparent; + color: var(--ink-2); + font: inherit; + font-size: 13.5px; + text-align: left; + cursor: pointer; +} +.prefs-tab:hover { background: var(--panel-2); color: var(--ink); } +.prefs-tab[aria-selected="true"] { background: var(--accent-soft); color: var(--accent); border-left-color: var(--accent); font-weight: 600; } +.prefs-tab:focus-visible { outline: 2px solid var(--focus); outline-offset: 1px; } +.prefs-tab-label { display: block; line-height: 1.3; } +.prefs-tab-hint { display: block; font-size: 12px; line-height: 1.35; color: var(--ink-3); } + +.prefs-panels { min-width: 0; } +.prefs-panel[hidden] { display: none; } + +/* --------------------------------------------------------- Saved mark */ + +/* At the fieldset's top right, level with its legend. Out of the flow: the + fieldsets are grids (the shared range and row classes), where an in-flow mark + would take a cell and push the choices about. It fades out after about + 2 s when the JS adds `is-saved`; an `error` stays put and never fades. */ +.prefs-panel fieldset { position: relative; } +.prefs-saved { + position: absolute; + top: 0; + right: 0; + max-width: 60%; + font-size: 12px; + line-height: 1.3; + text-align: right; + color: var(--ok); + opacity: 0; +} +.prefs-saved.is-saved { opacity: 1; } +.prefs-saved.error { color: var(--danger, #d64545); opacity: 1; } + +@media (prefers-reduced-motion: no-preference) { + @keyframes prefs-saved-fade { + 0%, 70% { opacity: 1; } + 100% { opacity: 0; } + } + .prefs-saved.is-saved { animation: prefs-saved-fade 2s ease-out forwards; } +} +@media (prefers-reduced-motion: reduce) { + .prefs-saved.is-saved { opacity: 1; } +} + +/* --------------------------------------------------------- Agents & models */ + +.prefs-agents { display: grid; gap: 10px; } +.prefs-agents > .help { margin: 0; } +.prefs-agents [hidden] { display: none; } +#agents-status:empty { display: none; } +#agents-status.error { color: var(--danger, #d64545); } +#agents-add { justify-self: start; } + +.prefs-agents-table { width: 100%; border-collapse: collapse; font-size: 13.5px; } +.prefs-agents-table th { + text-align: left; + font-weight: 600; + font-size: 12px; + color: var(--ink-3); + padding: 4px 8px; + border-bottom: 1px solid var(--rule-2); +} +.prefs-agents-table td { padding: 8px; border-bottom: 1px solid var(--rule-2); vertical-align: top; } +.prefs-agents-name span, .prefs-agents-name code { display: block; } +.prefs-agents-name code { font-size: 12px; color: var(--ink-3); } +.prefs-agents-name .help { margin-top: 2px; font-size: 12px; } +.prefs-agents-models { color: var(--ink-2); overflow-wrap: anywhere; } +.prefs-agents-edit { text-align: right; } +.prefs-agents-soon td { color: var(--ink-3); font-style: italic; } + +.prefs-badge, .prefs-unsaved-badge { + display: inline-block; + font-size: 11.5px; + line-height: 1.5; + padding: 0 7px; + border-radius: 10px; + background: var(--panel-2); + color: var(--ink-3); + white-space: nowrap; +} +.prefs-badge.ok { color: var(--ok); } +.prefs-badge.missing { color: var(--warn); } +.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); } + +.prefs-agents-form { display: grid; gap: 10px; } +.prefs-agents-back { justify-self: start; } +.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; } +.prefs-agents-title code { font-size: 12px; color: var(--ink-3); } +.prefs-agents-title:focus { outline: none; } +.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px 14px; } +.prefs-agents-fields > .models-note, +.prefs-agents-fields > [data-field="models"], +.prefs-agents-fields > .prefs-agents-args, +.prefs-agents-fields > .agent-field:has(> .models-list), +.prefs-agents-fields > .agent-field:has(> .prefs-agents-none) { grid-column: 1 / -1; } +.prefs-agents-form input { min-width: 0; } +.prefs-agents-form input.invalid { border-color: var(--danger, #d64545); } +.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } +.prefs-agents-test .help { margin: 0; } +.prefs-agents-none { margin: 0; } +.prefs-agents-args { display: grid; gap: 8px; } +.prefs-agents-args > summary { cursor: pointer; color: var(--accent); font-size: 13px; } +.prefs-agents-args[open] > summary { margin-bottom: 4px; } +.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; } +/* The Saved mark sits in the form's foot, in the flow, after the buttons. */ +.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; } + +/* --------------------------------------------------------- unsaved prompt */ + +/* Over the dialog, inside it: never the browser's confirm(). */ +.prefs-unsaved { + position: absolute; + inset: 0; + z-index: 5; + display: grid; + place-items: center; + padding: 16px; + background: color-mix(in srgb, var(--bg, #000) 55%, transparent); +} +.prefs-unsaved[hidden] { display: none; } +.prefs-unsaved-box { + max-width: 380px; + padding: 16px 18px; + border: 1px solid var(--rule-2); + border-radius: 10px; + background: var(--panel); + box-shadow: 0 8px 30px rgb(0 0 0 / 0.25); +} +.prefs-unsaved-box h3 { margin: 0 0 6px; font-size: 15px; } +.prefs-unsaved-box p { margin: 0 0 12px; } +.prefs-unsaved-actions { display: flex; flex-wrap: wrap; gap: 8px; } + +/* --------------------------------------------------------- narrow screens */ + +@media (max-width: 720px) { + .prefs-layout { grid-template-columns: 1fr; gap: 12px; } + .prefs-tabs { + flex-direction: row; + overflow-x: auto; + overflow-y: hidden; + padding: 0 0 4px; + -webkit-mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent); + mask-image: linear-gradient(to right, #000 calc(100% - 32px), transparent); + } + .prefs-tab { + width: auto; + flex: none; + white-space: nowrap; + border-left: 0; + border-bottom: 3px solid transparent; + border-radius: 6px 6px 0 0; + } + .prefs-tab[aria-selected="true"] { border-bottom-color: var(--accent); } + .prefs-tab-hint { display: none; } + .prefs-agents-models { display: none; } + .prefs-agents-fields { grid-template-columns: 1fr; } +} diff --git a/src/web-console/public/styles/responsive.css b/src/web-console/public/styles/responsive.css index 535eac1..a1f20e5 100644 --- a/src/web-console/public/styles/responsive.css +++ b/src/web-console/public/styles/responsive.css @@ -96,8 +96,6 @@ } /* User Preferences: the launcher's model menu. */ -.models-tabs { display: flex; gap: 6px; } -.models-tabs .btn[aria-pressed="true"] { border-color: var(--accent); color: var(--accent); } .models-note { font-size: 0.9em; opacity: 0.85; } .models-note p, .models-note ul { margin: 0 0 6px; } .models-note ul { padding-left: 18px; } @@ -108,13 +106,6 @@ .models-row input { min-width: 0; } .models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; } .models-actions .help.error { color: var(--danger, #d64545); } -.agents-list { display: grid; gap: 10px; } -.agents-list:empty { display: none; } -.agent-card { display: grid; gap: 8px; padding: 10px; border: 1px solid var(--rule-2); border-radius: 8px; } -.agent-card.invalid { border-color: var(--danger, #d64545); } -.agent-card input { min-width: 0; } -.agent-card input.invalid { border-color: var(--danger, #d64545); } -.agent-top { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 6px; } .agent-field { display: grid; gap: 4px; min-width: 0; } .agent-field > span, .agent-field > label { font-size: 0.85em; opacity: 0.85; } .agent-rows { display: grid; gap: 4px; } @@ -124,7 +115,6 @@ .agent-foot .help { margin: 0; } .agent-foot .agent-test-result { flex: 1 1 auto; } .agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; } -#agents-replace[hidden] { display: none; } /* User Preferences: Cleanup's list of what would go, shown before anything is deleted. */ diff --git a/src/web-console/public/styles/shell.css b/src/web-console/public/styles/shell.css index e30cf28..97c38b6 100644 --- a/src/web-console/public/styles/shell.css +++ b/src/web-console/public/styles/shell.css @@ -178,7 +178,7 @@ h1 { grows to fill the row, so the icon buttons would sit beside the title. The first takes the slack instead; with the block shown its flex already eats the space, so this costs nothing. */ -#btn-about { margin-left: auto; } +#btn-looks { margin-left: auto; } .progress-label { display: flex; @@ -516,6 +516,8 @@ h1 { .footer.is-dash .footer-actions { display: none; } .footer.is-dash .footer-where { grid-column: 2; } .footer.is-dash-done .footer-actions { display: none; } +.footer.is-loop-idle .footer-summary, +.footer.is-loop-idle .footer-actions { visibility: hidden; } .hint { font-size: 12.5px; color: var(--ink-3); display: flex; align-items: center; gap: 7px; } /* A label, not a sentence: the full reason rides in the hint's tooltip, and the dock already carries the ticking clock this would otherwise repeat. */ @@ -544,7 +546,7 @@ kbd { justify-items: center; } .waiting-pane h2 { font: 600 23px/1.3 var(--serif); color: var(--ink); margin: 0; } -.waiting-pane p { margin: 0; } +.waiting-pane p { max-width: 70ch; margin: 0; } /* The words that open the tasks tab: bold in the highlight color, a button that reads as part of the sentence. */ .waiting-jump { diff --git a/src/web-console/public/styles/tokens.css b/src/web-console/public/styles/tokens.css index fe3ec64..a85f91f 100644 --- a/src/web-console/public/styles/tokens.css +++ b/src/web-console/public/styles/tokens.css @@ -46,6 +46,7 @@ which validates the saved choice and paints data-width on first load. */ :root[data-width="narrow"] { --card-width: 720px; } :root[data-width="wide"] { --card-width: 1080px; } +:root[data-width="ultrawide"] { --card-width: 1440px; } /* Dark is written twice on purpose, and the duplication is the whole mechanism. The first copy follows the system unless the person has explicitly asked for diff --git a/src/web-console/public/subagents.js b/src/web-console/public/subagents.js index e4a1b23..fe17f7f 100644 --- a/src/web-console/public/subagents.js +++ b/src/web-console/public/subagents.js @@ -89,7 +89,9 @@ export function cleanSetting(input) { /* ------------------------------------------------------------ the lines */ -// The non-editable part of every "on" block (FR-8). +// The non-editable part an "on" block used to carry (FR-8). The block now says +// state, strength and limit in one line; these sentences move to +// console-subagents.md (Phase 5). Still exported for the suites that read them. export const FRAME_LINES = Object.freeze([ "Hand independent work to helpers if your tools allow it; otherwise carry on alone.", "Report each helper on the page (console-subagents.md); questions for the person stay with you.", @@ -99,7 +101,7 @@ export const FRAME_LINES = Object.freeze([ export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says."; -// The profile line each strength adds to an "on" block. +// The profile sentence each strength used to add to an "on" block; see FRAME_LINES. export const STRENGTH_LINES = Object.freeze({ balanced: "Helper strength: balanced (the table in helper-strength.md as written).", thrifty: "Helper strength: thrifty (one step lighter in strength and effort than the table; reviews never below standard).", @@ -109,20 +111,20 @@ export const STRENGTH_LINES = Object.freeze({ // Only the first line of a block starts at column 0, so no line inside it can // be read as an entry of its own (NFR-5). -export function onLines({ revision, replaces, max, instruction, strength }) { - const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`; +export function onLines({ max, instruction, strength }) { const own = String(instruction || "") .split("\n") .map((line) => line.trimEnd()) .filter((line) => line.trim()); + const word = STRENGTHS.includes(strength) ? strength : DEFAULT_STRENGTH; return [ - `Subagents: on (${label}) — a console setting, not typed by the person.`, - ...[...FRAME_LINES, ...own, STRENGTH_LINES[strength] || STRENGTH_LINES[DEFAULT_STRENGTH], `At most ${max} helpers at once.`].map((line) => " " + line), + `Subagents: on, ${word} strength, at most ${max} helpers at once (a console setting, not typed by the person).`, + ...own.map((line) => " " + line), ]; } -export function offLine(revision) { - return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`; +export function offLine() { + return "Subagents: off. Start no new helpers for the rest of this session."; } /** diff --git a/src/web-console/public/tabs.js b/src/web-console/public/tabs.js new file mode 100644 index 0000000..940df1b --- /dev/null +++ b/src/web-console/public/tabs.js @@ -0,0 +1,103 @@ +// Plan2Code Web Console - tabs shared by Help and User Preferences. +// +// The WAI-ARIA tabs pattern over panels built once in the markup and shown or +// hidden: role="tab" buttons linked to their role="tabpanel", roving +// tabindex, automatic activation, arrow keys plus Home and End. No DOM access +// at module scope: `node --test` imports tabKeyTarget from here. + +// The tab index a key moves to, or -1 when the key is not a tab key. +export function tabKeyTarget(key, index, count) { + switch (key) { + case "ArrowDown": + case "ArrowRight": + return (index + 1) % count; + case "ArrowUp": + case "ArrowLeft": + return (index - 1 + count) % count; + case "Home": + return 0; + case "End": + return count - 1; + default: + return -1; + } +} + +// Below Help's breakpoint the side list becomes a strip across the top. +const NARROW = "(max-width: 720px)"; + +// `tabs` is [{ id, label, hint? }], `list` the role="tablist" element and +// `panels` the element holding one child per tab marked data-tab="". +// `beforeSelect(from, to)` returning false, or a Promise of false, holds the +// switch; `onSelect(id)` runs after one. +export function wireTabs({ tabs, list, panels, prefix, tabClass, renderTab, beforeSelect, onSelect }) { + const tabId = (id) => `${prefix}-tab-${id}`; + const panelId = (id) => `${prefix}-panel-${id}`; + let selected = null; + + for (const t of tabs) { + const btn = document.createElement("button"); + btn.type = "button"; + btn.className = tabClass; + btn.id = tabId(t.id); + btn.setAttribute("role", "tab"); + btn.setAttribute("aria-controls", panelId(t.id)); + btn.setAttribute("aria-selected", "false"); + btn.tabIndex = -1; + if (renderTab) renderTab(t, btn); + else { + const label = document.createElement("span"); + label.textContent = t.label; + btn.appendChild(label); + } + btn.addEventListener("click", () => select(t.id)); + list.appendChild(btn); + const panel = panels.querySelector(`[data-tab="${t.id}"]`); + panel.id = panelId(t.id); + panel.setAttribute("role", "tabpanel"); + panel.setAttribute("aria-labelledby", tabId(t.id)); + panel.tabIndex = 0; + panel.hidden = true; + } + + list.addEventListener("keydown", (e) => { + const current = tabs.findIndex((t) => tabId(t.id) === e.target.id); + if (current < 0) return; + const n = tabKeyTarget(e.key, current, tabs.length); + if (n < 0) return; + e.preventDefault(); + select(tabs[n].id, { focus: true }); + }); + + const narrow = matchMedia(NARROW); + const orient = () => list.setAttribute("aria-orientation", narrow.matches ? "horizontal" : "vertical"); + orient(); + narrow.addEventListener("change", orient); + + async function select(id, { focus = false } = {}) { + if (beforeSelect && selected !== null && selected !== id) { + // Awaited only when it is a Promise, so a plain answer switches in this + // same tick and a caller can focus the new tab straight after. + let go = beforeSelect(selected, id); + if (go && typeof go.then === "function") go = await go; + if (go === false) { + // Held: focus stays on the tab still selected. + if (focus) document.getElementById(tabId(selected)).focus(); + return false; + } + } + for (const t of tabs) { + const on = t.id === id; + const btn = document.getElementById(tabId(t.id)); + btn.setAttribute("aria-selected", String(on)); + btn.tabIndex = on ? 0 : -1; + document.getElementById(panelId(t.id)).hidden = !on; + } + selected = id; + if (onSelect) onSelect(id); + if (focus) document.getElementById(tabId(id)).focus(); + return true; + } + + return { select, current: () => selected }; +} diff --git a/src/web-console/public/tones.js b/src/web-console/public/tones.js index 965d10b..cac35fb 100644 --- a/src/web-console/public/tones.js +++ b/src/web-console/public/tones.js @@ -1,6 +1,18 @@ // Plan2Code Web Console - the tones: short synthesized blips for the activities, silent when Play sounds is off; defines only. import { looks } from "./looks.js"; +import snakeSfx from "./activities/snake-sfx.js"; +import golfSfx from "./activities/golf-sfx.js"; +import trailsSfx from "./activities/trails-sfx.js"; +import bugsSfx from "./activities/bugs-sfx.js"; +import driveSfx from "./activities/drive-sfx.js"; +import stackSfx from "./activities/stack-sfx.js"; +import bumperSfx from "./activities/bumper-sfx.js"; +import rapidsSfx from "./activities/rapids-sfx.js"; +import fuseSfx from "./activities/fuse-sfx.js"; +import hopSfx from "./activities/hop-sfx.js"; +import bounceSfx from "./activities/bounce-sfx.js"; +import ghoulSfx from "./activities/ghoul-sfx.js"; /* ------------------------------------------------------------- tones @@ -14,7 +26,7 @@ import { looks } from "./looks.js"; Every sound here is short (a quarter second at most) and quiet, so a cue never outlasts the moment it belongs to. A tone either sweeps from one pitch to another, or plays `notes` one after another in its time. */ -const TONES = Object.freeze({ +const BLIPS = Object.freeze({ eat: Object.freeze({ type: "triangle", from: 660, to: 880, seconds: 0.12 }), crash: Object.freeze({ type: "sawtooth", from: 220, to: 80, seconds: 0.2 }), // The 3, 2, 1 before a round starts or plays on: a tick per number, then a @@ -52,8 +64,337 @@ const TONES = Object.freeze({ shield: Object.freeze({ type: "sine", from: 1200, to: 500, seconds: 0.14 }), zap: Object.freeze({ type: "sawtooth", from: 1400, to: 200, seconds: 0.15 }), best: Object.freeze({ type: "triangle", notes: Object.freeze([784, 988, 1175, 1568]), seconds: 0.25 }), + // Stack Deploy: a block landing (a low thunk), the overhang sliced off, + // and a perfect drop's chime. The game pitches the thunk and the chime up + // a step of a scale for each perfect in a row. + thunk: Object.freeze({ type: "triangle", from: 240, to: 110, seconds: 0.1 }), + slice: Object.freeze({ type: "square", from: 560, to: 280, seconds: 0.06 }), + perfect: Object.freeze({ type: "triangle", notes: Object.freeze([660, 990]), seconds: 0.14 }), + // Bumper Ring: two cars meeting (a short thud the game pitches up and + // makes louder the harder the hit) and a rival revving up a dash. + ram: Object.freeze({ type: "square", from: 190, to: 70, seconds: 0.09 }), + rev: Object.freeze({ type: "sawtooth", from: 90, to: 260, seconds: 0.18 }), + // Hot Potato: the fuse's tick (the game ticks it quicker and pitches it + // up as the fuse burns down) and the pop of the bomb changing hands. + tick: Object.freeze({ type: "square", from: 1500, to: 1100, seconds: 0.03 }), + pop: Object.freeze({ type: "sine", from: 480, to: 1400, seconds: 0.07 }), + // Crossing Rush: a hop (the game pitches it up a step for each quick hop + // forward in a row), the boing of being sent back, a crossing's bell while + // a train is coming, and the Horn. + hop: Object.freeze({ type: "triangle", from: 520, to: 780, seconds: 0.05 }), + boing: Object.freeze({ type: "sine", from: 260, to: 720, seconds: 0.2 }), + bell: Object.freeze({ type: "triangle", notes: Object.freeze([1320, 990]), seconds: 0.16 }), + horn: Object.freeze({ type: "square", notes: Object.freeze([370, 466]), seconds: 0.22 }), + // Bounce Road: the engine's hum (a soft, low blip the game plays every few + // frames while you pick up speed, pitched up with your speed: a triangle, + // since a sawtooth blipped that often is a buzz), a jump's spring (pitched + // with your speed) and a rival flattened under your wheels (pitched up a + // step for each in a chain); all soft triangles, never a buzz. A low + // thump rumbles while your wheels run on the verge. + beat: Object.freeze({ type: "sine", from: 95, to: 55, seconds: 0.11 }), + engine: Object.freeze({ type: "triangle", from: 82, to: 90, seconds: 0.08 }), + spring: Object.freeze({ type: "triangle", from: 330, to: 990, seconds: 0.14 }), + squash: Object.freeze({ type: "triangle", from: 620, to: 150, seconds: 0.13 }), + // Rapids Run: a shot (a short, soft triangle, since it repeats about seven + // times a second while fire is held, and the game plays it quietly), a + // charge buoy taken (a rising sine), the low battery's two-note beep (the + // game beeps quicker the lower it runs), a dam bursting open (a low + // triangle rumble) and a bank skimmed at speed (a quick sine whoosh the + // game pitches up the more you have skimmed); all soft triangles and + // sines, never a buzz. + pew: Object.freeze({ type: "triangle", from: 1320, to: 880, seconds: 0.04 }), + charge: Object.freeze({ type: "sine", from: 440, to: 1320, seconds: 0.14 }), + lowcell: Object.freeze({ type: "sine", notes: Object.freeze([660, 440]), seconds: 0.16 }), + dambreak: Object.freeze({ type: "triangle", from: 300, to: 60, seconds: 0.25 }), + skim: Object.freeze({ type: "sine", from: 1500, to: 1800, seconds: 0.05 }), + // Ghoul Rush: the flashlight blaster's bolt (a short, soft triangle, since + // it repeats every 100 ms while fire is held; the game nudges its pitch a + // little each time), a ghoul torn apart (pitched up a step for each kill + // in the chain), a stomp's crunch, a ghost's moan, a boss's low roar, a + // soul's thin whisper (pitched up for souls taken in quick succession), a + // zombie groaning behind a wall door, a bat's screech, the key turning + // (a minor rise), the door through to the next room (a falling minor + // run), a board creaking (a crawler coming up, a chandelier or a crumbling + // board about to go), a hellhound's growl, a wraith's shriek, a widow's + // skitter, a bloater's wet spit, and thunder rolling outside. + ghoulBlast: Object.freeze({ type: "triangle", from: 980, to: 620, seconds: 0.05 }), + ghoulStomp: Object.freeze({ type: "sawtooth", from: 220, to: 70, seconds: 0.09 }), + ghoulBoo: Object.freeze({ type: "sine", from: 330, to: 196, seconds: 0.25 }), + ghoulRoar: Object.freeze({ type: "sawtooth", from: 120, to: 48, seconds: 0.25 }), + ghoulCandy: Object.freeze({ type: "sine", from: 1480, to: 1760, seconds: 0.09 }), + zombiePop: Object.freeze({ type: "sawtooth", from: 260, to: 60, seconds: 0.12 }), + zombieGroan: Object.freeze({ type: "sawtooth", from: 110, to: 72, seconds: 0.25 }), + batSwoop: Object.freeze({ type: "square", from: 2200, to: 1400, seconds: 0.08 }), + doorUnlock: Object.freeze({ type: "triangle", notes: Object.freeze([494, 587, 740]), seconds: 0.2 }), + doorThrough: Object.freeze({ type: "triangle", notes: Object.freeze([659, 587, 494, 440]), seconds: 0.25 }), + creakBoard: Object.freeze({ type: "triangle", from: 180, to: 120, seconds: 0.18 }), + ghoulGrowl: Object.freeze({ type: "sawtooth", from: 95, to: 70, seconds: 0.22 }), + ghoulShriek: Object.freeze({ type: "sawtooth", from: 1900, to: 2600, seconds: 0.2 }), + ghoulSkitter: Object.freeze({ type: "square", notes: Object.freeze([2400, 2100, 2500, 2200]), seconds: 0.1 }), + ghoulSpit: Object.freeze({ type: "square", from: 340, to: 110, seconds: 0.1 }), + ghoulThunder: Object.freeze({ type: "sawtooth", from: 70, to: 30, seconds: 0.25 }), }); +/* --------------------------------------------------------- rich tones + + The shared sound kit every game may borrow, richer than a single blip: + a spec here may be `layers`, parts that play together (each its own + `delay` and `gain`), and a part may be noise ("noise" is white, "pink" + and "brown" darker) shaped by a `filter` ({ type, from, to, q }) that + sweeps its cutoff, wobble with `vibrato` ({ rate, depth }, depth a share + of the pitch) or swell in over `attack` seconds. Noise is what makes a + crash, a splash, a skid or an explosion sound like one rather than like + a beep. These run up to a second, still quiet, and a game's own extras + live in its `activities/-sfx.js` (merged in below). */ +const part = (spec) => Object.freeze({ ...spec, ...(spec.notes ? { notes: Object.freeze(spec.notes) } : {}), ...(spec.filter ? { filter: Object.freeze(spec.filter) } : {}), ...(spec.vibrato ? { vibrato: Object.freeze(spec.vibrato) } : {}) }); +const layered = (...parts) => Object.freeze({ layers: Object.freeze(parts.map(part)) }); + +const RICH = Object.freeze({ + // Hits, crashes and explosions. + explode: layered( + { type: "brown", seconds: 0.8, filter: { type: "lowpass", from: 2400, to: 90, q: 0.7 } }, + { type: "sine", from: 140, to: 32, seconds: 0.55, gain: 0.9 }, + { type: "noise", seconds: 0.12, gain: 0.35, filter: { type: "highpass", from: 3000, to: 1500 } }, + ), + blast: layered( + { type: "brown", seconds: 0.38, filter: { type: "lowpass", from: 1800, to: 140 } }, + { type: "sine", from: 110, to: 40, seconds: 0.26, gain: 0.8 }, + ), + smash: layered( + { type: "noise", seconds: 0.36, filter: { type: "bandpass", from: 1800, to: 500, q: 1.1 } }, + { type: "square", from: 180, to: 55, seconds: 0.2, gain: 0.45, filter: { type: "lowpass", from: 1400, to: 300 } }, + { type: "noise", seconds: 0.28, delay: 0.04, gain: 0.25, filter: { type: "highpass", from: 5000, to: 3000 } }, + ), + thud: layered( + { type: "sine", from: 130, to: 48, seconds: 0.14 }, + { type: "brown", seconds: 0.09, gain: 0.6, filter: { type: "lowpass", from: 500, to: 150 } }, + ), + clank: layered( + { type: "square", from: 820, to: 790, seconds: 0.08, gain: 0.45, filter: { type: "lowpass", from: 3000, to: 1500 } }, + { type: "triangle", from: 1230, to: 1210, seconds: 0.22, gain: 0.5 }, + { type: "noise", seconds: 0.04, gain: 0.4, filter: { type: "bandpass", from: 3200, to: 2600, q: 2 } }, + ), + crunch: layered( + { type: "noise", seconds: 0.18, filter: { type: "bandpass", from: 900, to: 280, q: 1.8 } }, + { type: "sawtooth", from: 150, to: 60, seconds: 0.12, gain: 0.4, filter: { type: "lowpass", from: 900, to: 200 } }, + ), + squish: layered( + { type: "noise", seconds: 0.13, filter: { type: "lowpass", from: 1600, to: 200, q: 3 } }, + { type: "sine", from: 420, to: 110, seconds: 0.11, gain: 0.6 }, + ), + splat: layered( + { type: "pink", seconds: 0.16, filter: { type: "bandpass", from: 1300, to: 380, q: 1.4 } }, + { type: "sine", from: 300, to: 85, seconds: 0.12, gain: 0.6 }, + ), + hit: layered( + { type: "square", from: 320, to: 120, seconds: 0.07, gain: 0.6, filter: { type: "lowpass", from: 2400, to: 600 } }, + { type: "noise", seconds: 0.05, gain: 0.5, filter: { type: "bandpass", from: 2200, to: 1400, q: 1.5 } }, + ), + // Movement: air, tires and landings. + whoosh: layered({ type: "pink", seconds: 0.3, attack: 0.08, filter: { type: "bandpass", from: 400, to: 2600, q: 1.4 } }), + swoosh: layered({ type: "pink", seconds: 0.26, attack: 0.04, filter: { type: "bandpass", from: 2600, to: 450, q: 1.4 } }), + skid: layered( + { type: "noise", seconds: 0.38, attack: 0.02, filter: { type: "bandpass", from: 2300, to: 1700, q: 7 } }, + { type: "triangle", from: 1500, to: 1280, seconds: 0.34, gain: 0.25, vibrato: { rate: 31, depth: 0.02 } }, + ), + brake: layered({ type: "noise", seconds: 0.3, attack: 0.03, filter: { type: "bandpass", from: 3100, to: 2500, q: 10 } }), + zoom: layered( + { type: "sawtooth", from: 240, to: 130, seconds: 0.5, attack: 0.2, gain: 0.5, filter: { type: "lowpass", from: 1100, to: 380 } }, + { type: "pink", seconds: 0.5, attack: 0.2, gain: 0.6, filter: { type: "bandpass", from: 900, to: 380, q: 1.2 } }, + ), + jump: layered( + { type: "triangle", from: 300, to: 760, seconds: 0.13 }, + { type: "pink", seconds: 0.12, gain: 0.3, filter: { type: "highpass", from: 1400, to: 2600 } }, + ), + land: layered( + { type: "sine", from: 170, to: 60, seconds: 0.1 }, + { type: "brown", seconds: 0.1, gain: 0.6, filter: { type: "lowpass", from: 700, to: 200 } }, + ), + shift: layered( + { type: "noise", seconds: 0.035, gain: 0.5, filter: { type: "bandpass", from: 2400, to: 2000, q: 3 } }, + { type: "square", from: 160, to: 140, seconds: 0.05, gain: 0.4, filter: { type: "lowpass", from: 900, to: 500 } }, + ), + boost: layered( + { type: "sawtooth", from: 110, to: 460, seconds: 0.48, gain: 0.6, filter: { type: "lowpass", from: 400, to: 3200, q: 4 } }, + { type: "pink", seconds: 0.48, gain: 0.45, filter: { type: "highpass", from: 1200, to: 4200 } }, + ), + riser: layered( + { type: "sawtooth", from: 200, to: 1200, seconds: 0.62, attack: 0.3, gain: 0.5, filter: { type: "lowpass", from: 600, to: 4200 } }, + { type: "noise", seconds: 0.62, attack: 0.3, gain: 0.35, filter: { type: "bandpass", from: 500, to: 4000, q: 1 } }, + ), + honk: layered( + { type: "square", from: 392, to: 388, seconds: 0.24, gain: 0.55, filter: { type: "lowpass", from: 1600, to: 1400 } }, + { type: "square", from: 494, to: 490, seconds: 0.24, gain: 0.55, filter: { type: "lowpass", from: 1600, to: 1400 } }, + ), + trainHorn: layered( + { type: "sawtooth", from: 311, to: 305, seconds: 0.85, attack: 0.05, gain: 0.4, filter: { type: "lowpass", from: 1500, to: 1200 } }, + { type: "sawtooth", from: 370, to: 364, seconds: 0.85, attack: 0.05, gain: 0.4, filter: { type: "lowpass", from: 1500, to: 1200 } }, + { type: "sawtooth", from: 466, to: 458, seconds: 0.85, attack: 0.05, gain: 0.3, filter: { type: "lowpass", from: 1500, to: 1200 } }, + ), + rumble: layered({ type: "brown", seconds: 0.06, filter: { type: "lowpass", from: 320, to: 200 } }), + rumbleLong: layered( + { type: "brown", seconds: 1, attack: 0.2, filter: { type: "lowpass", from: 420, to: 160 } }, + { type: "sine", from: 52, to: 44, seconds: 1, attack: 0.2, gain: 0.6 }, + ), + // Water. + splashBig: layered( + { type: "noise", seconds: 0.42, filter: { type: "bandpass", from: 3200, to: 700, q: 0.7 } }, + { type: "sine", from: 380, to: 95, seconds: 0.16, gain: 0.45 }, + { type: "pink", seconds: 0.3, delay: 0.08, gain: 0.35, filter: { type: "highpass", from: 2500, to: 1500 } }, + ), + bubble: layered({ type: "sine", from: 300, to: 950, seconds: 0.06 }), + slap: layered({ type: "pink", seconds: 0.15, filter: { type: "bandpass", from: 950, to: 480, q: 1.5 } }), + // Rewards and the round. + coinUp: layered( + { type: "square", notes: [988, 1319], seconds: 0.11, gain: 0.55, filter: { type: "lowpass", from: 5000, to: 5000 } }, + { type: "triangle", from: 2637, to: 2637, seconds: 0.26, delay: 0.05, gain: 0.3 }, + ), + sparkle: layered( + { type: "triangle", notes: [1568, 2093, 2637, 3136], seconds: 0.22, gain: 0.5 }, + { type: "noise", seconds: 0.22, gain: 0.15, filter: { type: "highpass", from: 6000, to: 8000 } }, + ), + powerUp: layered( + { type: "square", notes: [523, 659, 784, 1047, 1319], seconds: 0.36, gain: 0.45, filter: { type: "lowpass", from: 3000, to: 3000 } }, + { type: "triangle", notes: [262, 330, 392, 523, 659], seconds: 0.36, gain: 0.6 }, + ), + powerDown: layered( + { type: "square", notes: [784, 659, 523, 392], seconds: 0.36, gain: 0.45, filter: { type: "lowpass", from: 2400, to: 1200 } }, + ), + extraLife: layered( + { type: "triangle", notes: [659, 784, 1319, 1047, 1175, 1568], seconds: 0.48 }, + { type: "square", notes: [330, 392, 659, 523, 587, 784], seconds: 0.48, gain: 0.25, filter: { type: "lowpass", from: 2000, to: 2000 } }, + ), + fanfare: layered( + { type: "square", notes: [523, 523, 523, 659, 784, 784], seconds: 0.6, gain: 0.4, filter: { type: "lowpass", from: 2600, to: 2600 } }, + { type: "triangle", notes: [262, 262, 262, 330, 392, 392], seconds: 0.6, gain: 0.7 }, + ), + victory: layered( + { type: "triangle", notes: [784, 988, 1175, 1568], seconds: 0.44 }, + { type: "square", notes: [392, 494, 587, 784], seconds: 0.44, gain: 0.3, filter: { type: "lowpass", from: 2400, to: 2400 } }, + { type: "noise", seconds: 0.3, delay: 0.3, gain: 0.12, filter: { type: "highpass", from: 7000, to: 9000 } }, + ), + gameOver: layered( + { type: "triangle", notes: [392, 370, 349, 330], seconds: 0.9 }, + { type: "sawtooth", notes: [196, 185, 175, 165], seconds: 0.9, gain: 0.35, filter: { type: "lowpass", from: 900, to: 500 } }, + ), + lifeLost: layered( + { type: "square", from: 520, to: 120, seconds: 0.42, gain: 0.6, vibrato: { rate: 12, depth: 0.04 }, filter: { type: "lowpass", from: 2000, to: 600 } }, + ), + click: layered({ type: "square", from: 1200, to: 1150, seconds: 0.02, gain: 0.4 }), + tickSoft: layered({ type: "noise", seconds: 0.025, filter: { type: "bandpass", from: 4200, to: 3800, q: 4 } }), + warn: layered( + { type: "square", notes: [880, 660, 880, 660], seconds: 0.42, gain: 0.5, filter: { type: "lowpass", from: 2000, to: 2000 } }, + ), + // Sci-fi and combat. + laser: layered( + { type: "square", from: 1800, to: 280, seconds: 0.12, gain: 0.5, filter: { type: "lowpass", from: 4500, to: 1200 } }, + { type: "sawtooth", from: 900, to: 140, seconds: 0.12, gain: 0.3, filter: { type: "lowpass", from: 3000, to: 800 } }, + ), + zapBig: layered( + { type: "sawtooth", from: 2400, to: 80, seconds: 0.26, gain: 0.55, filter: { type: "lowpass", from: 5000, to: 600 } }, + { type: "noise", seconds: 0.2, gain: 0.4, filter: { type: "bandpass", from: 3000, to: 500, q: 1 } }, + ), + shieldUp: layered( + { type: "sine", from: 300, to: 1200, seconds: 0.32, vibrato: { rate: 18, depth: 0.05 } }, + { type: "triangle", from: 600, to: 2400, seconds: 0.32, gain: 0.3 }, + ), + warp: layered( + { type: "sine", from: 400, to: 1600, seconds: 0.34, vibrato: { rate: 24, depth: 0.08 } }, + { type: "pink", seconds: 0.34, gain: 0.3, filter: { type: "bandpass", from: 600, to: 3600, q: 3 } }, + ), + bossIntro: layered( + { type: "sawtooth", from: 55, to: 52, seconds: 1, attack: 0.25, gain: 0.6, filter: { type: "lowpass", from: 300, to: 900, q: 3 } }, + { type: "brown", seconds: 1, attack: 0.25, gain: 0.6, filter: { type: "lowpass", from: 220, to: 160 } }, + { type: "square", notes: [110, 104, 98], seconds: 1, gain: 0.3, filter: { type: "lowpass", from: 600, to: 600 } }, + ), + // Spooky. + doorCreak: layered( + { type: "sawtooth", from: 150, to: 92, seconds: 0.62, attack: 0.05, gain: 0.5, vibrato: { rate: 23, depth: 0.09 }, filter: { type: "bandpass", from: 900, to: 700, q: 3 } }, + ), + gust: layered({ type: "pink", seconds: 0.9, attack: 0.35, filter: { type: "bandpass", from: 300, to: 850, q: 1.2 } }), + heartbeat: layered( + { type: "sine", from: 72, to: 45, seconds: 0.1 }, + { type: "sine", from: 66, to: 42, seconds: 0.11, delay: 0.18, gain: 0.8 }, + ), + wail: layered({ type: "sine", from: 560, to: 880, seconds: 0.65, attack: 0.15, vibrato: { rate: 6, depth: 0.03 } }), + // Crowds and wood. + rattle: layered( + { type: "triangle", notes: [1200, 900, 1100, 820], seconds: 0.16, gain: 0.6 }, + { type: "noise", seconds: 0.12, gain: 0.3, filter: { type: "bandpass", from: 3200, to: 2400, q: 2 } }, + ), + cheer: layered( + { type: "pink", seconds: 1, attack: 0.25, filter: { type: "bandpass", from: 900, to: 1400, q: 0.8 } }, + { type: "noise", seconds: 1, attack: 0.25, gain: 0.2, filter: { type: "highpass", from: 3000, to: 3500 } }, + ), + aww: layered({ type: "pink", seconds: 0.85, attack: 0.1, filter: { type: "bandpass", from: 950, to: 480, q: 1.3 } }), + applause: layered( + ...[0, 0.05, 0.11, 0.14, 0.2, 0.27, 0.31, 0.38, 0.43, 0.5].map((delay, i) => ({ type: "noise", seconds: 0.035, delay, gain: 0.6 + (i % 3) * 0.15, filter: { type: "bandpass", from: 1400 + (i % 4) * 300, to: 1200, q: 1.5 } })), + ), + knock: layered( + { type: "triangle", from: 600, to: 560, seconds: 0.06 }, + { type: "noise", seconds: 0.03, gain: 0.5, filter: { type: "bandpass", from: 1800, to: 1500, q: 2 } }, + ), + crumble: layered( + { type: "brown", seconds: 0.55, filter: { type: "lowpass", from: 900, to: 100 } }, + ...[0, 0.07, 0.15, 0.24].map((delay) => ({ type: "noise", seconds: 0.04, delay, gain: 0.35, filter: { type: "bandpass", from: 1600, to: 900, q: 2 } })), + ), + hiss: layered({ type: "noise", seconds: 0.4, attack: 0.03, gain: 0.6, filter: { type: "highpass", from: 3000, to: 5200 } }), + squeak: layered({ type: "sine", from: 1800, to: 2400, seconds: 0.05 }), +}); + +/* --------------------------------------------------------------- hums + + A hum is a sound that runs for as long as a game keeps asking for it: a + car's engine, a boat's outboard, the river, a light cycle, a fuse's hiss. + A game calls hum(id, name, level, pitch) every frame it wants it, `id` + telling one voice from another (your car and a rival's), and pitch + following its speed. A hum not asked for again within HUM_HOLD_MS fades + out by itself, so a paused, closed or finished game falls quiet without + saying so; hushTones() quiets them all at once. Each hum is oscillators + (`parts`, each its own frequency and gain) and noise (`noise`) through one + filter whose cutoff follows the pitch by `follow` (1 tracks it exactly, 0 + holds still), pulsed by `pulse` ({ rate, depth }, the rate following the + pitch): an engine's firing strokes or a train's clatter. */ +const hums = (table) => Object.freeze(Object.fromEntries(Object.entries(table).map(([k, v]) => [k, Object.freeze(v)]))); + +const HUMS = hums({ + car: { parts: [{ type: "sawtooth", freq: 46 }, { type: "sawtooth", freq: 46.5, gain: 0.7 }, { type: "square", freq: 23, gain: 0.5 }], noise: { color: "brown", gain: 0.2 }, filter: { type: "lowpass", freq: 360, q: 4, follow: 0.9 }, pulse: { rate: 11, depth: 0.45 }, peak: 0.06 }, + toycar: { parts: [{ type: "square", freq: 90 }, { type: "square", freq: 90.8, gain: 0.5 }], filter: { type: "lowpass", freq: 850, q: 2, follow: 1 }, pulse: { rate: 20, depth: 0.5 }, peak: 0.04 }, + electric: { parts: [{ type: "sawtooth", freq: 60 }, { type: "sine", freq: 120, gain: 0.5 }, { type: "sine", freq: 620, gain: 0.12 }], filter: { type: "lowpass", freq: 520, q: 2, follow: 0.8 }, peak: 0.045 }, + outboard: { parts: [{ type: "sawtooth", freq: 38 }, { type: "square", freq: 76, gain: 0.4 }], noise: { color: "brown", gain: 0.35 }, filter: { type: "lowpass", freq: 430, q: 3, follow: 0.9 }, pulse: { rate: 16, depth: 0.6 }, peak: 0.06 }, + river: { noise: { color: "brown", gain: 1 }, filter: { type: "lowpass", freq: 650, q: 0.5, follow: 1 }, pulse: { rate: 0.4, depth: 0.3 }, peak: 0.05 }, + wind: { noise: { color: "pink", gain: 1 }, filter: { type: "bandpass", freq: 600, q: 0.8, follow: 1 }, pulse: { rate: 0.3, depth: 0.4 }, peak: 0.04 }, + cycle: { parts: [{ type: "sawtooth", freq: 98 }, { type: "sawtooth", freq: 98.6 }, { type: "sawtooth", freq: 196.3, gain: 0.3 }], filter: { type: "lowpass", freq: 1100, q: 6, follow: 0.8 }, peak: 0.03 }, + fuse: { noise: { color: "noise", gain: 1 }, filter: { type: "highpass", freq: 3500, q: 0.7, follow: 0.5 }, pulse: { rate: 23, depth: 0.55 }, peak: 0.03 }, + haunt: { parts: [{ type: "sine", freq: 55 }, { type: "sine", freq: 55.8 }, { type: "triangle", freq: 82.4, gain: 0.3 }], filter: { type: "lowpass", freq: 400, q: 1, follow: 0.5 }, pulse: { rate: 0.3, depth: 0.5 }, peak: 0.045 }, + squeal: { parts: [{ type: "triangle", freq: 1450, gain: 0.2 }], noise: { color: "noise", gain: 1 }, filter: { type: "bandpass", freq: 1900, q: 9, follow: 1 }, peak: 0.035 }, + meter: { parts: [{ type: "triangle", freq: 220 }, { type: "square", freq: 220.5, gain: 0.25 }], filter: { type: "lowpass", freq: 1200, q: 1, follow: 1 }, peak: 0.025 }, + swarm: { parts: [{ type: "sawtooth", freq: 180 }, { type: "sawtooth", freq: 183 }, { type: "sawtooth", freq: 177 }], filter: { type: "bandpass", freq: 900, q: 2, follow: 1 }, pulse: { rate: 30, depth: 0.5 }, peak: 0.02 }, + train: { parts: [{ type: "square", freq: 60, gain: 0.4 }], noise: { color: "brown", gain: 1 }, filter: { type: "lowpass", freq: 520, q: 1, follow: 0.7 }, pulse: { rate: 4, depth: 0.7 }, peak: 0.05 }, + crowd: { noise: { color: "pink", gain: 1 }, filter: { type: "bandpass", freq: 1100, q: 0.6, follow: 0.6 }, pulse: { rate: 0.5, depth: 0.4 }, peak: 0.02 }, +}); + +// Every game's own extras, merged after the shared kit; a name may be +// defined only once across them all (the activities suite checks). +const GAME_SFX = Object.freeze([snakeSfx, golfSfx, trailsSfx, bugsSfx, driveSfx, stackSfx, bumperSfx, rapidsSfx, fuseSfx, hopSfx, bounceSfx, ghoulSfx]); + +// A game file holds plain objects; they are frozen here, all the way down. +const deepFreeze = (o) => { + if (o && typeof o === "object") Object.values(o).forEach(deepFreeze); + return Object.freeze(o); +}; + +export const TONE_TABLES = Object.freeze([BLIPS, RICH, ...GAME_SFX.map((s) => deepFreeze(s.tones || {}))]); +export const HUM_TABLES = Object.freeze([HUMS, ...GAME_SFX.map((s) => deepFreeze(s.hums || {}))]); +// And each game's chiptune tracks, which music.js plays. +export const MUSIC_TABLES = Object.freeze(GAME_SFX.map((s) => deepFreeze(s.music || {}))); + +const TONES = Object.freeze(Object.assign({}, ...TONE_TABLES)); +const ALL_HUMS = Object.freeze(Object.assign({}, ...HUM_TABLES)); + +export const toneNames = () => Object.keys(TONES); +export const humNames = () => Object.keys(ALL_HUMS); + // Peak gain, kept modest so a blip sits under the page rather than over it. const PEAK = 0.08; @@ -62,8 +403,18 @@ const PEAK = 0.08; const ATTACK = 0.01; const FLOOR = 0.0001; +// At most this many parts of rich tones sounding at once: a frantic moment +// drops one rather than piling up enough voices to stutter the page. +const MAX_VOICES = 48; + let ctx = null; +let bus = null; + +const noiseBuffers = new Map(); + +let voiceEnds = []; + // Made on first use, not at load, so importing this file in Node is harmless. // A missing AudioContext or a constructor that throws both give null. function audioContext() { @@ -77,6 +428,68 @@ function audioContext() { return ctx; } +// Everything plays through one gentle compressor, so an explosion over an +// engine over a shot never clips; a context without one plays straight out. +function out(c) { + if (bus) return bus; + if (typeof c.createDynamicsCompressor !== "function") return c.destination; + const comp = c.createDynamicsCompressor(); + comp.threshold.value = -20; + comp.knee.value = 12; + comp.ratio.value = 4; + comp.attack.value = 0.003; + comp.release.value = 0.2; + comp.connect(c.destination); + bus = comp; + return bus; +} + +// Two seconds of noise per color, made once and looped from a random point. +function noiseBuffer(c, color) { + if (noiseBuffers.has(color)) return noiseBuffers.get(color); + const length = Math.floor(c.sampleRate * 2); + const buf = c.createBuffer(1, length, c.sampleRate); + const data = buf.getChannelData(0); + let b0 = 0, b1 = 0, b2 = 0, last = 0; + for (let i = 0; i < length; i++) { + const w = Math.random() * 2 - 1; + if (color === "pink") { + b0 = 0.99765 * b0 + w * 0.099046; + b1 = 0.963 * b1 + w * 0.2965164; + b2 = 0.57 * b2 + w * 1.0526913; + data[i] = (b0 + b1 + b2 + w * 0.1848) * 0.2; + } else if (color === "brown") { + last = (last + 0.02 * w) / 1.02; + data[i] = last * 3.5; + } else data[i] = w; + } + noiseBuffers.set(color, buf); + return buf; +} + +const NOISES = new Set(["noise", "pink", "brown"]); + +// Room for `n` more parts that end at `end`, or false while the page is busy. +function room(c, n, end) { + const now = c.currentTime; + voiceEnds = voiceEnds.filter((t) => t > now); + if (voiceEnds.length + n > MAX_VOICES) return false; + for (let i = 0; i < n; i++) voiceEnds.push(end); + return true; +} + +// The running context, its output and its noise, for music.js, which plays +// through the same compressor; null while audio cannot play. +export function audioOut() { + try { + const c = audioContext(); + if (!c || c.state !== "running") return null; + return { c, out: out(c), noise: (color) => noiseBuffer(c, color) }; + } catch { + return null; + } +} + // Called from the click that opens Activities. A browser keeps a new context // suspended until a gesture, and a rejected resume is not an error the page // can act on, so every failure is swallowed. @@ -99,15 +512,70 @@ function blip(c, type, from, to, t0, seconds, peak) { gain.gain.exponentialRampToValueAtTime(peak, t0 + ATTACK); gain.gain.exponentialRampToValueAtTime(FLOOR, end); osc.connect(gain); - gain.connect(c.destination); + gain.connect(out(c)); osc.start(t0); osc.stop(end); } +// One part of a rich tone from t0: an oscillator (sweeping, or stepping +// through `notes`) or a noise, through its filter if it has one, under an +// envelope that swells in over `attack` and dies away by its end. +function voice(c, p, t0, peak, k) { + const end = t0 + p.seconds; + const gain = c.createGain(); + const top = Math.max(FLOOR * 10, peak * (p.gain ?? 1)); + gain.gain.setValueAtTime(FLOOR, t0); + gain.gain.exponentialRampToValueAtTime(top, t0 + Math.min(p.attack ?? ATTACK, p.seconds * 0.8)); + gain.gain.exponentialRampToValueAtTime(FLOOR, end); + let src; + if (NOISES.has(p.type)) { + src = c.createBufferSource(); + src.buffer = noiseBuffer(c, p.type); + src.loop = true; + } else { + src = c.createOscillator(); + src.type = p.type; + if (p.notes) { + const each = p.seconds / p.notes.length; + p.notes.forEach((f, i) => src.frequency.setValueAtTime(f * k, t0 + i * each)); + } else { + src.frequency.setValueAtTime(p.from * k, t0); + src.frequency.exponentialRampToValueAtTime(p.to * k, end); + } + if (p.vibrato) { + const lfo = c.createOscillator(); + const depth = c.createGain(); + lfo.frequency.value = p.vibrato.rate; + depth.gain.value = (p.notes ? p.notes[0] : p.from) * k * p.vibrato.depth; + lfo.connect(depth); + depth.connect(src.frequency); + lfo.start(t0); + lfo.stop(end); + } + } + let head = src; + if (p.filter) { + const f = c.createBiquadFilter(); + f.type = p.filter.type; + f.Q.value = p.filter.q ?? 1; + f.frequency.setValueAtTime(Math.min(20000, p.filter.from * k), t0); + f.frequency.exponentialRampToValueAtTime(Math.min(20000, (p.filter.to ?? p.filter.from) * k), end); + head.connect(f); + head = f; + } + head.connect(gain); + gain.connect(out(c)); + if (NOISES.has(p.type)) src.start(t0, Math.random() * 1.5); + else src.start(t0); + src.stop(end); +} + // Plays one named blip, at `level` (0 to 1) of the usual loudness: a soft -// putt sounds soft. An unknown name, Play sounds off, or a context that is -// missing, suspended or closed all mean silence, not an error. -export function tone(name, level = 1) { +// putt sounds soft. `pitch` scales every frequency (2 is an octave up, kept +// between two octaves down and two up), so a game can climb a scale on one +// blip. An unknown name, Play sounds off, or a context that is missing, +// suspended or closed all mean silence, not an error. +export function tone(name, level = 1, pitch = 1) { try { const spec = Object.hasOwn(TONES, name) ? TONES[name] : null; if (!spec || !looks.sound) return; @@ -115,8 +583,144 @@ export function tone(name, level = 1) { if (!c || c.state !== "running") return; const peak = Math.max(FLOOR * 10, PEAK * Math.min(1, Number(level) || 0)); const t0 = c.currentTime; - if (!spec.notes) return blip(c, spec.type, spec.from, spec.to, t0, spec.seconds, peak); + const k = Math.min(4, Math.max(0.25, Number(pitch) || 1)); + if (spec.layers) { + const last = Math.max(...spec.layers.map((p) => (p.delay || 0) + p.seconds)); + if (!room(c, spec.layers.length, t0 + last)) return; + return spec.layers.forEach((p) => voice(c, p, t0 + (p.delay || 0), peak, k)); + } + if (!spec.notes) return blip(c, spec.type, spec.from * k, spec.to * k, t0, spec.seconds, peak); const each = spec.seconds / spec.notes.length; - spec.notes.forEach((f, i) => blip(c, spec.type, f, f, t0 + i * each, each, peak)); + spec.notes.forEach((f, i) => blip(c, spec.type, f * k, f * k, t0 + i * each, each, peak)); } catch {} } + +/* ------------------------------------------------------ the hum voices */ + +// A hum not asked for again within this long fades out by itself. +const HUM_HOLD_MS = 150; + +// At most this many hums at once; a new one past it is not started. +const MAX_HUMS = 6; + +// How quickly a hum's pitch and loudness follow what the game asks, in +// seconds: quick enough to rev, slow enough never to zipper. +const GLIDE = 0.05; + +const live = new Map(); + +let watchdog = null; + +function startHum(c, spec) { + const amp = c.createGain(); + const level = c.createGain(); + level.gain.value = 0; + amp.connect(level); + level.connect(out(c)); + let head = amp; + let filter = null; + if (spec.filter) { + filter = c.createBiquadFilter(); + filter.type = spec.filter.type; + filter.Q.value = spec.filter.q ?? 1; + filter.frequency.value = spec.filter.freq; + filter.connect(amp); + head = filter; + } + const oscs = (spec.parts || []).map((p) => { + const o = c.createOscillator(); + const g = c.createGain(); + o.type = p.type; + o.frequency.value = p.freq; + g.gain.value = p.gain ?? 1; + o.connect(g); + g.connect(head); + o.start(); + return o; + }); + const sources = [...oscs]; + if (spec.noise) { + const n = c.createBufferSource(); + const g = c.createGain(); + n.buffer = noiseBuffer(c, spec.noise.color); + n.loop = true; + g.gain.value = spec.noise.gain ?? 1; + n.connect(g); + g.connect(head); + n.start(0, Math.random() * 1.5); + sources.push(n); + } + let lfo = null; + if (spec.pulse) { + lfo = c.createOscillator(); + const depth = c.createGain(); + lfo.frequency.value = spec.pulse.rate; + depth.gain.value = spec.pulse.depth / 2; + amp.gain.value = 1 - spec.pulse.depth / 2; + lfo.connect(depth); + depth.connect(amp.gain); + lfo.start(); + sources.push(lfo); + } + return { spec, level, filter, oscs, lfo, sources, seen: 0 }; +} + +function stopHum(c, id, v) { + live.delete(id); + try { + const t = c.currentTime; + v.level.gain.cancelScheduledValues(t); + v.level.gain.setTargetAtTime(0, t, 0.06); + v.sources.forEach((s) => s.stop(t + 0.5)); + } catch {} +} + +function watch() { + if (watchdog) return; + watchdog = setInterval(() => { + const now = performance.now(); + for (const [id, v] of live) if (!looks.sound || now - v.seen > HUM_HOLD_MS) stopHum(ctx, id, v); + if (!live.size) { + clearInterval(watchdog); + watchdog = null; + } + }, 50); +} + +// Keeps the hum `id` sounding as `name` for another moment, at `level` (0 to +// 1) of its loudness and `pitch` (1 is its own, kept between 0.25 and 4). +// Asking under a different name restarts it as that one. Like tone(), it is +// silence, never an error, while Play sounds is off or the audio is not +// running. +export function hum(id, name, level = 1, pitch = 1) { + try { + const spec = Object.hasOwn(ALL_HUMS, name) ? ALL_HUMS[name] : null; + const c = audioContext(); + if (!spec || !looks.sound || !c || c.state !== "running") return; + let v = live.get(id); + if (v && v.spec !== spec) { + stopHum(c, id, v); + v = null; + } + if (!v) { + if (live.size >= MAX_HUMS) return; + v = startHum(c, spec); + live.set(id, v); + watch(); + } + v.seen = performance.now(); + const t = c.currentTime; + const k = Math.min(4, Math.max(0.25, Number(pitch) || 1)); + const loud = spec.peak * Math.min(1, Math.max(0, Number(level) || 0)); + v.level.gain.setTargetAtTime(loud, t, GLIDE); + v.oscs.forEach((o, i) => o.frequency.setTargetAtTime(spec.parts[i].freq * k, t, GLIDE)); + if (v.filter) v.filter.frequency.setTargetAtTime(Math.min(18000, spec.filter.freq * k ** (spec.filter.follow ?? 1)), t, GLIDE); + if (v.lfo) v.lfo.frequency.setTargetAtTime(spec.pulse.rate * k, t, GLIDE); + } catch {} +} + +// Quiets every hum at once: the window stopped ticking a game. +export function hushTones() { + if (!ctx) return; + for (const [id, v] of live) stopHum(ctx, id, v); +} diff --git a/src/web-console/routes.mjs b/src/web-console/routes.mjs index 5510c38..536967c 100644 --- a/src/web-console/routes.mjs +++ b/src/web-console/routes.mjs @@ -31,6 +31,8 @@ import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./s import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs"; import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs"; import { specKey } from "./workspace.mjs"; +import { readLoopSetup, saveLoopSetup } from "./loop-setup.mjs"; +import { phaseChecklist } from "./spec-files.mjs"; import { PR_HOST_KINDS, readSubagentSetting, @@ -115,6 +117,8 @@ const ROUTES = [ { match: (p) => Object.hasOwn(WORKSPACE_EDITS, p), method: "POST", origin: true, run: workspaceEdit }, { path: "/workspace/scope", method: "POST", origin: true, run: workspaceScope }, { path: "/workspace/browse", method: "POST", origin: true, run: workspaceBrowse }, + { path: "/loop-setup", method: "GET", run: loopSetupGet }, + { path: "/loop-setup", method: "POST", origin: true, run: loopSetupPost }, { path: "/cancel", method: "POST", origin: true, run: cancel }, { path: "/ping", method: "POST", run: ping }, { path: "/bye", origin: true, run: bye }, @@ -418,7 +422,7 @@ function draft(req, res, ctx) { * Whittle a POSTed settings object down to what a settings file may hold. * The page only sends { theme, accent } today, but the file is shared and * forward-compatible: any flat string/number/boolean may live in it. Nested - * objects, arrays and a hundred-key dump may not — this is a preference file, + * objects, arrays and a two-hundred-key dump may not: this is a preference file, * not free storage, and it is read back into the page unfiltered. */ function cleanLooks(input) { @@ -428,7 +432,9 @@ function cleanLooks(input) { if (k === "__proto__" || k.length > 64) continue; const t = typeof v; if (t === "number" || t === "boolean" || (t === "string" && v.length <= 256)) out[k] = v; - if (Object.keys(out).length > 40) return null; + // The Activities' best scores alone take a key per game and per golf + // course, so the cap leaves room for them all. + if (Object.keys(out).length > 120) return null; } return Object.keys(out).length ? out : null; } @@ -632,7 +638,7 @@ function agentsTest(req, res) { }); } -// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in +// User Preferences -> System -> Cleanup. `{ scan: true }` lists what is not needed in // ~/.plan2code and the project's old completed specs; `{ delete: [id] }` // removes those of the ids a fresh scan still finds. Never this session, // never a path the page sent. @@ -1310,6 +1316,57 @@ function chatDecision(req, res, ctx) { }); } +/* ---------------------------------------------- the Implementation Loop */ + +// The Implementation Loop's setup for this project (loop-setup.mjs): what was +// saved over the defaults. The quick check is text the console only stores. +const loopProject = (ctx) => (ctx.readState() || {}).project || ctx.project || ctx.worktree() || ""; + +// `?spec=specs/` adds the setup screen's read-only facts (FR-3): the +// phases not yet marked done, the branch and the count of uncommitted files. +// The server reads the project here and never writes it. +function loopSetupGet(req, res, ctx, url) { + const answer = readLoopSetup(loopProject(ctx)); + const spec = url && url.searchParams.get("spec"); + if (spec === null || spec === undefined) return json(res, 200, answer); + if (!/^specs\/[^/\\]+$/.test(spec) || /^specs\/\./.test(spec)) return json(res, 400, { error: "spec must be a folder directly under specs/" }); + const state = ctx.readState() || {}; + let phasesLeft = []; + try { + const overview = fs.readFileSync(path.join(loopProject(ctx), spec, "overview.md"), "utf8"); + phasesLeft = phaseChecklist(overview) + .filter((p) => p.marker !== "x" && p.marker !== "X") + .map((p) => ({ n: p.number, name: p.name })); + } catch { + /* no overview.md: nothing to build */ + } + const pending = state.scan && Number.isInteger(state.scan.pending) ? state.scan.pending : null; + // What to prefill an empty quick check with: the project's own build, then + // lint, script. Text only; nothing here runs it. + let suggestedQuickCheck = ""; + try { + const scripts = JSON.parse(fs.readFileSync(path.join(loopProject(ctx), "package.json"), "utf8")).scripts || {}; + const name = ["build", "lint"].find((n) => typeof scripts[n] === "string"); + if (name) suggestedQuickCheck = "npm run " + name; + } catch { + /* no package.json, or not JSON: no suggestion */ + } + return json(res, 200, { ...answer, phasesLeft, branch: state.branch || "", pending, suggestedQuickCheck }); +} + +function loopSetupPost(req, res, ctx) { + return readBody(req, (err, body) => { + if (err && err.tooBig) return json(res, 413, { error: "too large" }); + if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { ok: false, problems: ["the setup must be a JSON object"] }); + try { + return json(res, 200, { ok: true, setup: saveLoopSetup(loopProject(ctx), body) }); + } catch (e) { + if (Array.isArray(e.problems)) return json(res, 400, { ok: false, problems: e.problems }); + return json(res, 500, { error: String(e.message) }); + } + }); +} + /* --------------------------------------------------------- the workspace */ // The Workspace: the original folder plus any the person adds as context. diff --git a/src/web-console/server.mjs b/src/web-console/server.mjs index 110b631..0451675 100644 --- a/src/web-console/server.mjs +++ b/src/web-console/server.mjs @@ -46,9 +46,8 @@ import { import { serverWorkspace } from "./workspace.mjs"; import { serverSubagents } from "./settings.mjs"; import { inAppSignal } from "./in-app.mjs"; -import { chatOffline } from "./public/chat.js"; +import { chatAnswering, chatOffline } from "./public/chat.js"; import { meterView } from "./public/meter.js"; -import { startsClean } from "./public/hops.js"; import { SERVABLE, asset } from "./static.mjs"; import { handle } from "./routes.mjs"; import { checkForUpdate } from "./update-check.mjs"; @@ -175,12 +174,17 @@ function chatPickedUp() { return cursorSeen.seq; } -function chatOfflineNow(state) { +// The frame's chat block without `offline`. A caller that already built it +// (stateFrame) passes it in rather than building it twice. +const chatNow = (state) => ({ ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp() }); + +function chatOfflineNow(state, chat = chatNow(state)) { return chatOffline({ finish: state && state.finish, agent: state && state.agent, agentLastSeenMs: agentSeenAt, now: Date.now(), + answering: chatAnswering(chat), }); } @@ -214,31 +218,15 @@ const workspace = serverWorkspace({ }); /** - * Open a conversation when there is none, and a new one whenever the page - * passes through the dashboard. The reset line carries the workflow it was - * opened under, so a server that restarts across a hop still sees the switch. - * A resume that keeps its workflow keeps its conversation. + * Open a conversation when there is none. A hop to another skill keeps it: + * the person is still talking to the same agent, and switchWorkflow() carries + * the agent's replies across, so only New conversation starts a new one. */ function ensureConversation(state) { if (!state) return; - const last = currentConversation(readChat(DIR)); - let entry = null; - if (!last.conversation) { - entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" }); - } else if ( - // The same hops `open --resume` treats as a fresh start, by the rule in - // public/hops.js (a blank page, the agent's replies included). Without a - // new conversation, the old questions would show as unanswered again. - startsClean(last.workflow, state.workflow) - ) { - entry = appendChat(DIR, { - kind: "reset", - conversation: last.conversation + 1, - workflow: state.workflow, - reason: "switch", - }); - } - if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason }); + if (currentConversation(readChat(DIR)).conversation) return; + const entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" }); + appendEvent(DIR, { type: "chat-reset", reason: entry.reason }); } /* ------------------------------------------------------------ subagents */ @@ -259,13 +247,14 @@ const IN_APP = Boolean(inAppSignal()); // stream (see /events). function stateFrame(state) { const { pending, stop } = resultFlags(); + const chat = chatNow(state); return { rev, state, agentLastSeen: agentLastSeen(), pendingResult: pending, pendingStop: stop, - chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) }, + chat: { ...chat, offline: chatOfflineNow(state, chat) }, workspace: workspace.workspaceView(), meter: meterView(ledgerEntries()), subagents: subagents.view(state), diff --git a/src/web-console/sessions.mjs b/src/web-console/sessions.mjs index 0b8d242..1c064e3 100644 --- a/src/web-console/sessions.mjs +++ b/src/web-console/sessions.mjs @@ -279,12 +279,15 @@ export async function removeSessions(sessionsDir, sids) { } // The console folder's own files that no sweep may ever remove: the person's -// looks, the folders remembered per project and spec, the Subagents switch +// looks, the folders remembered per project and spec, the Implementation +// Loop's setup per project and its report while a build is under way, the Subagents switch // saved per project and workflow, what each unknown git host is, the pointer // to this console's directory, and the cached release check. export const PROTECTED_CONSOLE_FILES = new Set([ "looks.json", "workspaces.json", + "loop-setup.json", + "loop-reports.json", "subagents.json", "pr-hosts.json", "console-dir", diff --git a/src/web-console/spec-files.mjs b/src/web-console/spec-files.mjs index 3bd9a61..d50aca3 100644 --- a/src/web-console/spec-files.mjs +++ b/src/web-console/spec-files.mjs @@ -38,6 +38,40 @@ export function statusOf(text) { return m ? m[2] : null; } +/** + * The Phase Checklist rows of an overview.md as `[{ number, marker, name }]` + * (the first "Phase N" on each checkbox line names the phase), in file order; + * empty when there is no checklist. Read-only facts for the loop's setup + * screen: the scripts that write the marks stay src/skill-scripts/specs.mjs. + */ +export function phaseChecklist(overview) { + const lines = (overview || "").split(/\r?\n/); + const at = lines.findIndex((l) => /^#{1,6}\s+.*Phase Checklist/i.test(l)); + if (at < 0) return []; + // The section runs to the next heading of the same or a higher level, so a + // sub-heading inside the checklist does not cut it short. + const level = lines[at].match(/^#+/)[0].length; + const rows = []; + for (let i = at + 1; i < lines.length; i++) { + const heading = lines[i].match(/^(#+)\s/); + if (heading && heading[1].length <= level) break; + const box = lines[i].match(CHECKBOX_RE); + if (!box) continue; + const text = lines[i] + .replace(CHECKBOX_RE, "") + .replace(/\[([^\]]*)\]\([^)]*\)/g, "$1") + .replace(/[*_`]/g, "") + .replace(/\s+/g, " ") + .trim(); + const num = text.match(/\bPhase\s+(\d+)\b/i); + if (!num) continue; + const after = text.slice(num.index + num[0].length).replace(/^\s*[:\-–—]\s*/, ""); + const name = after.split(/\s+[-–—]\s+|\s+\(|\s+_\(|:\s|\s+see\s+phase-/i)[0].replace(/\s*phase-\d+\.md\s*$/i, "").trim(); + rows.push({ number: Number(num[1]), marker: box[1], name: name.replace(/\s*\[Milestone[^\]]*\]\s*$/i, "") || `Phase ${num[1]}` }); + } + return rows; +} + /** * A phase file's tasks by where they stand. The task lines when the file has * them, so an Acceptance Criteria checkbox is not counted as a task; every diff --git a/src/web-console/static.mjs b/src/web-console/static.mjs index 71da190..36dec2e 100644 --- a/src/web-console/static.mjs +++ b/src/web-console/static.mjs @@ -40,6 +40,8 @@ export const SERVABLE = new Set([ "boot.js", "chat.js", "help.js", + "tabs.js", + "prefs.js", "starters.js", "workspace.js", "meter.js", @@ -60,12 +62,15 @@ export const SERVABLE = new Set([ "favicon.png", "screens/core.js", "screens/ending.js", + "screens/loop-setup.js", "screens/docs.js", "screens/cards.js", "screens/starting.js", "screens/dashboard.js", "screens/git-host.js", "screens/looks.js", + "screens/agents-view.js", + "screens/prefs-dialog.js", "screens/cleanup.js", "screens/help-dialog.js", "screens/workspace.js", @@ -78,7 +83,119 @@ export const SERVABLE = new Set([ "activities/golf-holes.js", "activities/golf-draw.js", "activities/golf-decor.js", + "activities/golf-kit.js", + "activities/golf-paint.js", + "activities/golf-looks.js", + "activities/golf-course-pirate.js", + "activities/golf-course-cave.js", + "activities/golf-course-dino.js", + "activities/golf-course-candy.js", + "activities/golf-course-space.js", + "activities/golf-course-frost.js", + "activities/golf-look-dino.js", + "activities/golf-look-candy.js", + "activities/golf-look-space.js", + "activities/golf-look-frost.js", + "activities/trails.js", + "activities/bugs.js", + "activities/drive.js", + "activities/stack.js", + "activities/bumper.js", + "activities/bumper-draw.js", + "activities/rapids.js", + "activities/rapids-draw.js", + "activities/fuse.js", + "activities/fuse-draw.js", + "activities/hop.js", + "activities/hop-draw.js", + "activities/bounce.js", + "activities/bounce-draw.js", + "activities/bounce-roads.js", + "activities/bounce-road.js", + "activities/bounce-rivals.js", + "activities/bounce-scenery.js", + "activities/bounce-cars.js", + "activities/ghoul.js", + "activities/ghoul-draw.js", + "activities/ghoul-rooms.js", + "activities/ghoul-bones.js", + "activities/ghoul-bones-draw.js", + "activities/ghoul-graveyard.js", + "activities/ghoul-graveyard-draw.js", + "activities/ghoul-grounds.js", + "activities/ghoul-grounds-draw.js", + "activities/ghoul-chapel.js", + "activities/ghoul-chapel-draw.js", + "activities/ghoul-sanatorium.js", + "activities/ghoul-sanatorium-draw.js", + "activities/ghoul-village.js", + "activities/ghoul-village-draw.js", + "activities/ghoul-village-world.js", + "activities/ghoul-village-wolf.js", + "activities/ghoul-mine.js", + "activities/ghoul-mine-draw.js", + "activities/ghoul-mine-world.js", + "activities/ghoul-mine-tommy.js", + "activities/ghoul-cart.js", + "activities/ghoul-cart-draw.js", + "activities/ghoul-sled.js", + "activities/ghoul-sled-draw.js", + "activities/ghoul-carnival.js", + "activities/ghoul-carnival-draw.js", + "activities/ghoul-carnival-world.js", + "activities/ghoul-frozen.js", + "activities/ghoul-frozen-draw.js", + "activities/ghoul-frozen-world.js", + "activities/ghoul-flare.js", + "activities/ghoul-picker-draw.js", + "activities/ghoul-powers.js", + "activities/ghoul-arms.js", + "activities/ghoul-arms-draw.js", + "activities/ghoul-rockets.js", + "activities/ghoul-rockets-draw.js", + "activities/ghoul-pans.js", + "activities/ghoul-run.js", + "activities/ghoul-dice.js", + "activities/ghoul-dice-draw.js", + "activities/ghoul-gameover-draw.js", + "activities/ghoul-bonus.js", + "activities/ghoul-bonus-draw.js", + "activities/ghoul-monsters-draw.js", + "activities/pills.js", + "activities/snake-sfx.js", + "activities/golf-sfx.js", + "activities/trails-sfx.js", + "activities/bugs-sfx.js", + "activities/drive-sfx.js", + "activities/stack-sfx.js", + "activities/bumper-sfx.js", + "activities/rapids-sfx.js", + "activities/fuse-sfx.js", + "activities/hop-sfx.js", + "activities/bounce-sfx.js", + "activities/ghoul-sfx.js", + "activities/ghoul-sfx-graveyard.js", + "activities/ghoul-sfx-grounds.js", + "activities/ghoul-sfx-chapel.js", + "activities/ghoul-sfx-sanatorium.js", + "activities/ghoul-sfx-village.js", + "activities/ghoul-sfx-mine.js", + "activities/ghoul-sfx-carnival.js", + "activities/ghoul-sfx-frozen.js", + "activities/ghoul-sfx-sled.js", + "activities/ghoul-ride-core.js", + "activities/ghoul-ride-scenes.js", + "activities/ghoul-ride.js", + "activities/ghoul-ride-gfx.js", + "activities/ghoul-ride-draw-kinds.js", + "activities/ghoul-ride-draw-sets.js", + "activities/ghoul-ride-draw-hud.js", + "activities/ghoul-ride-draw.js", + "activities/ghoul-ride-voices.js", + "activities/ghoul-sfx-ride.js", + "activities/ghoul-sfx-arms.js", "tones.js", + "music.js", "notepad-tabs.js", "net.js", "notepad.js", @@ -95,7 +212,7 @@ export const SERVABLE = new Set([ // Layers first, then one file per screen, then responsive and print last so // its overrides still come after everything they override. The files are not // on SERVABLE: they reach the page only through /app.css. -export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "activities.css", "git.css", "responsive.css"]; +export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "prefs.css", "notepad.css", "activities.css", "git.css", "responsive.css"]; // The files joined with one newline between them (each file's own last newline // is that one), as the server serves them before the accent rules. The test @@ -117,10 +234,13 @@ export function joinedStyles() { // other means (preload hints, the inline boot state) rather than by caching. const assets = new Map(); +// `npm run play` sets this so an edit to a page file shows on the next reload. +const FRESH = process.env.PLAN2CODE_CONSOLE_DEV === "1"; + export const etagOf = (body) => `"${crypto.createHash("sha1").update(body).digest("base64url").slice(0, 20)}"`; export function asset(rel) { - let a = assets.get(rel); + let a = FRESH ? undefined : assets.get(rel); if (!a) { let body = rel === "app.css" ? joinedStyles() : fs.readFileSync(path.join(PUBLIC_DIR, rel)); if (rel === "app.css") body = Buffer.concat([body, Buffer.from(accentCss())]);