Compare commits

..
31 Commits
Author SHA1 Message Date
jparkerweb cedc3300ed Merge pull request #16 from jparkerweb/v3-orchestrator
Plan2Code v3.0.0: desktop app, Implementation Loop, strength-matched helpers, custom agents, PR Prep and Write missing tests
2026-11-05 21:58:11 -08:00
jparkerweb 8bace16e06 Pace the keys in the in-app full-screen test so the browser's late answers cannot undo the next one
AI Assisted
2026-11-05 20:47:41 -08:00
jparkerweb e87148ad10 Pin Math.random in the Activities logic tests so a rare roll cannot fail one at random
AI Assisted
2026-11-05 20:26:49 -08:00
jparkerweb 23ac3a9c19 Fix two Ubuntu flakes: try more road for a Bounce Road rival, and wait for the board's focus before the last F press
AI Assisted
2026-11-05 20:05:02 -08:00
jparkerweb a0ac6eb655 Hand every page test a page that has gone quiet, and retry the @ list until it names the project
AI Assisted
2026-11-05 19:44:35 -08:00
jparkerweb 958c0f4ccc Let the page go quiet before typing in the Markdown answer box test
AI Assisted
2026-11-05 19:25:50 -08:00
jparkerweb 959554d127 Make the Ask send self-healing and let the page go quiet before scrolling in tests, so late redraws stop failing them
AI Assisted
2026-11-05 19:05:59 -08:00
jparkerweb fc2921c848 Retype the @ in the session modules test if a redraw swallowed it
AI Assisted
2026-11-05 18:51:33 -08:00
jparkerweb e0b64e5895 Let the note tray go quiet before the Ask picview test opens a picture
AI Assisted
2026-11-05 18:34:52 -08:00
jparkerweb 7139d0340c Cache the apt packages and the npm downloads in CI
AI Assisted
2026-11-05 18:21:09 -08:00
jparkerweb e23ef8b3ec Fix two Windows flakes: wait for a disabled Markdown field to open before filling it, and give the installer tests 60s for a slow runner
AI Assisted
2026-11-05 17:55:13 -08:00
jparkerweb 7336b7fcc5 Wait for both full-screen messages in the in-app Activities test: the list already ended in false
AI Assisted
2026-11-05 17:49:03 -08:00
jparkerweb 4265eda68b Drop the npm cache from the npm test job: the repo does not track a root lockfile
AI Assisted
2026-11-05 17:18:38 -08:00
jparkerweb 15019dbc88 Speed up CI: cancel superseded PR runs, Ubuntu only on pull requests, and a fast prose job for docs-only changes. Put Before you start above the install command again
AI Assisted
2026-11-05 17:12:49 -08:00
jparkerweb 2e2edd538a Condense the v3.0.0 changelog to its main features, set the release date, and rebuild the landing page around the desktop app
AI Assisted
2026-11-05 17:08:41 -08:00
jparkerweb 807b6b038c Wait for the events stream to connect before posting the submit it must report
AI Assisted
2026-11-05 15:17:00 -08:00
jparkerweb 8922d2e391 Wait for the Welcome to appear before dismissing it in the session page tests
AI Assisted
2026-11-05 14:55:14 -08:00
jparkerweb 4352f3027d Fix two macOS-only test races: wait for F to fill the screen, and pick a mention from the page instead of clicking a list that repaints
AI Assisted
2026-11-05 14:35:56 -08:00
jparkerweb da6b738fc8 Fix two flaky page tests: wait for the editor before scrolling a card, and poll for the saved Welcome instead of a waitForFunction that returned at once
AI Assisted
2026-11-05 14:16:34 -08:00
jparkerweb 8ddf37911e Fix CI: tests follow Activities starting off, findAgent fixture uses a portable path, Ghoul Rush eye test waits for the eye
AI Assisted
2026-11-05 13:50:17 -08:00
jparkerweb 17f98e62b5 Let coverage read take a runner folder so relative lcov paths resolve, and fix Handoff's script path
AI Assisted
2026-11-05 11:39:04 -08:00
jparkerweb 2cb174ecf0 Make the console survive locked files and private handles, and start with Activities off
AI Assisted
2026-11-05 11:38:59 -08:00
jparkerweb c52244bee1 Keep metrics and bot out of plan2code update unless run from a git checkout, and end shims cleanly
AI Assisted
2026-11-05 11:38:59 -08:00
jparkerweb 0b6a376915 Refuse run ids that could leave the runs folder and stop replacements being read as patterns
AI Assisted
2026-11-05 11:38:58 -08:00
jparkerweb b17213322c Harden the app's loop commit gate, agent launch and file writes, and tighten workflow permissions
AI Assisted
2026-11-05 11:38:57 -08:00
jparkerweb 30fd1134ea Add a Reconnect to agent button where the agent has gone quiet
AI Assisted
2026-11-05 10:03:09 -08:00
jparkerweb 6376a68f85 Add Flock Dash, the thirteenth Activities game, with sounds and music
AI Assisted
2026-11-05 07:57:21 -08:00
jparkerweb e924cf5cde Fix Light Trails so a turn on a Wide Trail does not crash into your own side cells
AI Assisted
2026-11-05 07:57:13 -08:00
jparkerweb be31f6af89 Merge pull request #15 from jparkerweb/notepad
Add Notebook tabs and a CodeMirror editor, rename Notepad to Notebook…
2026-10-20 12:03:06 -07:00
jparkerweb 50acdc8216 Merge pull request #14 from jparkerweb/notepad
Notepad
2026-10-19 20:03:17 -07:00
jparkerweb a19dc6c5df Merge pull request #13 from jparkerweb/feature/utility-updates
Feature/utility updates
2026-10-18 17:24:09 -07:00
120 changed files with 6003 additions and 483 deletions

No files matched your search

+8 -5
View File
@@ -246,7 +246,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title, picker card line `blurb` and module path) an optional `courses` list (Mini golf's six course ids, which open a course dashboard), `bestKey(id, course?)`, the flat looks.json key for its best score (`activityBestSnake`, one per golf course `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, `bestKeys(entry)`, every best key a game keeps, and documents the game contract including the course parts (`courses` and `preview()` on the export, `setCourse()` and `course` on the game), the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title, picker card line `blurb` and module path) an optional `courses` list (Mini golf's six course ids, which open a course dashboard), `bestKey(id, course?)`, the flat looks.json key for its best score (`activityBestSnake`, one per golf course `activityBestGolfPirate` to `activityBestGolfFrost`, `activityBestTrails`, `activityBestBugs`, `activityBestDrive`, `activityBestStack`, `activityBestBumper`, `activityBestRapids`, `activityBestFuse`, `activityBestHop`, `activityBestBounce`, `activityBestGhoul`, `activityBestFlock`); lists Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, `bestKeys(entry)`, every best key a game keeps, and documents the game contract including the course parts (`courses` and `preview()` on the export, `setCourse()` and `course` on the game), the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
| `public/activities/snake.js` | Snake: its rules as plain exported functions and the game contract (`create({ canvas, tone, onScore })` returning `start`, `pause`, `resume`, `key`, `tick`, `resize`, `score`, `state`); it never runs a timer or listens for keys, so the Activities window drives it; it also holds the music's rules: `MUSIC_TRACKS`, `dealMusic(random, last)` (a round's shuffle of the ten tracks, never opening on the last round's opener), `trackFor(deck, level)` and `heat(round)` (the snake's speed as 0.3 to 1, so the lead and drums are in from the first step) |
| `public/activities/trails.js` | Light Trails: its rules as plain exported functions (`newRound`, `newHeat`, `turn`, `boost`, `advance` in 8 ms slices (where your crash is held for `GRACE_MS`, a turn in that time riding out of it; rivals get no grace), `choose` and `room` for the rivals' flood-fill steering, `applyPower` (a Mystery becoming another pad), `pickPower` (by each pad's `from` arena, a Heart only under `MAX_LIVES`), `fireLaser`, `hyperjump`, `awardLives` (a life every `LIFE_SCORE` points, the mark moving on at the cap), `spawnItem`, `closeRing`), the `ARENAS` (rivals, sharpness and what each adds), the `POWERS` pads (Boost, Phase, Eraser, Slow-mo, Coin, Heart, Shield held across heats until a crash in your grace pops it, Laser with `LASER_SHOTS`, Score x2 through one `gain()` every score goes through, Wide Trail with its side cells in `rider.wide`, Coin Rain whose `rain` coins never hold back a pad, Hyperjump, Mystery) and the game contract; `START_LIVES` is 5; memo is the furthest arena reached; a read-only `round` getter for the tests only; it also holds the music's rules: `MUSIC_TRACKS` (its five songs) and `dealMusic(random, last)` (a shuffle of them, never opening on `last`); a run plays the deal one song after another, each in full from the top (asking with `{ restart: true }` until the music takes it), moves on when `music()` answers `"ended"`, deals again after the last, and a new run deals afresh, never opening on the song the last run was playing; its tones and hums play `SFX_LOUDER` times as loud through tones.js's `louder`, all but the engine drones (`DRONES`), kept low under the songs |
| `public/activities/bugs.js` | Bug Hunt: its rules as plain exported functions (`newRound`, `spawnWave`, `slotPos`, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `hurtBug`, `hurtBoss`, `hitShip`, `applyPower`, `ghostly`, `tentacleTip`, `bossRadius`), the `BUGS` by first wave, the `BOSSES` every `BOSS_EVERY` waves, the `POWERS`, the `SECTORS` scenery and the game contract with `release()`; memo is the tally of `DISCOVERIES` as bits; a read-only `round` getter for the tests only |
@@ -256,8 +256,8 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/activities/bumper-draw.js` | Bumper Ring's drawing: `drawScene(ctx, view)` from a plain view `bumper.js` builds (the round, the board geometry, the effects, the pill numbers), each arena's ring in its fixed palette (`themeFor`), the floor (ice, oil, holes, bumpers, the magnet, the warning bands), the cars (Planny upright at the wheel of a car in `--accent`, star eye and stick arms; rivals with a face each), the pills (laid out by `hudLayout`, which starts a row below rather than run into the ring's countdown or off the board), banners and the start and end strip, and `readColors(canvas)`; decides nothing |
| `public/activities/rapids.js` | Rapids Run: its rules as plain exported functions over a round on a river scrolling down a 64 unit wide field, 84 units of it on the board (`newRound(seed)`, `newRiver(seed)`, `buildStretch(river, n, random)` (a stretch's rows from its own seed, each row a center, width and island width: a calm opening, then drifts, narrows and islands, every bank slanting at most `SLOPE` a unit, every channel at least `MIN_CHANNEL` wide, then a `BASIN_W` basin on a boss stretch and the narrowing to the `DAM_W` dam; and its plan of foes, buoys and crates, none in the first `SAFE_START` (where you start again) or by the dam), `ensureRiver`, `riverAt` (a row's banks and island eased from the row before's, so they slant as drawn), `channelsAt`, `channelAt`, `isWater`, `onLand` (the hull sampled at seven points), `placeAt` (the start of a stretch, its dam whole and its plan loaded afresh), `advance` in 4 ms slices over `round.input`, which `key()` and `release()` set: steering eased in, the whirlpools' tug, the speed held (up, down or neither, times the stretch's `pace`), the battery drained (`DRAIN` a second cruising, more at speed), distance points, the guns (`FIRE_MS`, Spread's fan), shots against foes, the boss, the dam and buoys, the foes (skiffs and darters drift and turn at the banks, a darter swerves into your lane, gulls take off as you near and swoop across, sentries fire at you), the boss (`spawnBoss` holds the river and the battery; its volleys by kind), bolts, pickups (a buoy `BUOY_CHARGE`, the magnet's pull, crates), crashes (`lose`: a shield takes any crash but a flat battery and slides you off a bank; blinking for `GRACE_MS` after a restart), skims (`SKIM_POINTS` each `SKIM_MS` closer than `SKIM_GAP` at speed), the dam (`hitDam`, then past it the next stretch, with `FLAWLESS_POINTS` times it for no life lost), `hurtFoe` (the combo, up to `MAX_COMBO`), `hurtBoss` (a life back and a crate), `applyPower`, `stretchFor` (built once a stretch; past the eighth, Night Water 2, 3 and on), `underBanner`, `screenY`, `seeded`), the `FOES`, `BOSSES`, `POWERS` and `STRETCHES`, and the game contract with `release()` (held arrows steer, speed and slow, held space fires; a pause lets go of every key); memo is the furthest dam blasted, which can pass 8; a read-only `round` getter for the tests only. Tuned by a scratch sim: a careful bot clears a stretch in 20 to 35 seconds, and the battery runs flat for one that grabs too few buoys |
| `public/activities/rapids-draw.js` | Rapids Run's drawing: `drawScene(ctx, view)` from one view object `rapids.js` refills each frame, in field units: the strip above the field in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run off the board and centers its rows in the strip), the river a look at a time (`LOOKS`: meadow, autumn, canyon, marsh, dusk and night, each in fixed colors, the look changing at each dam): banded banks, the water between them with shore lines and flow streaks carried downstream by the view's clock, pointed islands, trees or rocks; the dam ahead (hazard stripes, a crack for every share knocked out, a trickle once it is close to going) and the broken one behind; charge buoys, crates with their glyphs, whirlpools, skiffs, darters, mines, bank sentries aiming at you and gull drones with their shadows; the mini-boss and its health bar; Planny's jet-skimmer in your highlight with a white trim (so a blue highlight still shows on blue water), his wake, jets, arms to the bars (up when a dam or a boss goes), his box and his star eye in your highlight, bobbing with the star spinning after a crash; shots, bolts, sparks, rings, floating words (kept on the field by `labelSpot`), the combo's big number, the battery gauge beside the field (green, amber, then red and blinking under the low mark), banners, and the start and end strip with the big final score and a dot per named stretch whose dam you have blasted; `readColors(canvas)`, `lookColor`, `inkOn`, `contrast`; decides nothing |
| `public/activities/flock.js` | Flock Dash: its rules as plain exported functions over a round (`newRound(seed)`, `steer`, `recordPath`, `placeFlock`, `screenX`, `collect`, `spawnStrays`, `advance`) and the game contract. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it. |
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky, the strays, the flock, Planny as the lead bird with a star for an eye, and the pills. |
| `public/activities/flock.js` | Flock Dash: its rules as plain exported functions over a round scrolling right to left over a 96 by 54 unit field (`newRound(seed)`, `steer` (the leader eased up and down inside the `BAND_MIN` to `BAND_MAX` band at the left), `recordPath`, `placeFlock`, `screenX`, `collect` and `spawnStrays` (a stray joins the flock, the combo up to `MAX_COMBO` within `COMBO_MS`), `buildStage(seed, n)` (a stage's hazards by distance from its own seed, a clear `SAFE_START` and `SAFE_END`, and `clearGap` keeping a way through), `moveHazards`, `hazardHits`, `snapAt` (a snap drops the birds behind the one hit, `scattered` for `SCATTER_MS` so they can be picked up again), `hitLeader` (a life, or a shield; `GRACE_MS` after), `reachPortal` (the jet stream portal, the V of `V_POINTS` a bird when the flock has `min`, `FLAWLESS_POINTS` for no snap or life lost, and the final portal that sways), `applyPower` (crates: tailwind, shield up to `MAX_SHIELDS`, magnet), `banner`, `bannerRow`, `underBanner`, `advance` in `SLICE_MS` slices, `teaser`, `seeded`, `dealMusic`), the `STAGES` table (eight stages, each with its speed, length, stray gap, portal `min`, hazard weights and gap; the place to tune the difficulty), the `HAZARDS` (balloon, gust, stream, cluster, storm, kite, each from its own stage) and `POWERS`, and the game contract with `release()` (held arrows steer, a pause lets go of every key); the round also carries `events` (what the draw and the sounds react to) and `warned` (one gust or storm warning each); memo is the furthest stage reached. The flock is a recorded path with running arc length: follower k sits `k * SPACING` behind the leader along it, so it copies every turn at any speed. `MUSIC_TRACKS` names the five songs, dealt afresh each round |
| `public/activities/flock-draw.js` | Flock Dash's drawing: `drawScene(ctx, view)` and `hudLayout` from one view object `flock.js` refills each frame, in field units: the sunset sky (`SKIES`, one palette per stage: the sun sinking, clouds, a rim light from stage 6 and stars on the last), the hazards (balloons and bunches, the head-wind's warning band and gust, slipstreams, thunderheads with their flash and bolt, kites on their strings), the strays and scattered birds, the flock, Planny as the lead bird with a star for an eye, crates and the magnet ring, the tailwind streaks, the portal and the V, the pills (laid out by `hudLayout`, which shrinks them to fit the board), banners, and the end strip with the final score, the best and the teaser; `readColors(canvas)`; decides nothing |
| `public/activities/fuse.js` | Hot Potato: its rules as plain exported functions over a round on a 104 by 70 arena (`newRound`, `newMatch(round, venue)`, which lights each bomb on a rival, never you, in a match's first fuse, `advance` in 8 ms slices over `round.input`, which `key()` and `release()` set, `move` (speed eased toward the held direction at `GRIP`, a dash holding its line, belts and ice from the floor), `dash` (a holder's dash is a numbered lunge), `tag` (a holder touching a runner with no bomb passes it, never inside `NO_TAGBACK_MS` of the bomb changing hands, nor back to the one who just passed it within `TAGBACK_MS` while three or more are left, `tagBack`, with `tagSafe` saying who is safe that way for the drawing; a fuse under `PASS_FLOOR_MS`, `NO_TAGBACK_MS` plus `PASS_REACT_MS`, is raised to it on any pass, once a fuse for each runner (`bomb.lifted`); your pass scores, a hot one under `HOT_MS` as passed steps the streak), `burn` (Freeze takes its share first), `blast` (the holder out, everyone near knocked back, the match over when that was you or one is left), `nextFuse` (a survivor with no bomb, the next shorter fuse from `fuseFor`, never more bombs than one for every two left), `think` (a holder chases by its own flood-fill path, weighted toward a boxed-in or dashless target; a runner without a bomb scores candidate spots by the holders' path distance against its own and flees to the best; personalities bend both), `applyPower`, `spawnPickup`, `speedOf`, `clearLine`, `rivalPower` and `venueFor` (each built once per venue), `rivalColors(you)`), the `VENUES`, `LAYOUTS`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` never dashes on a repeat); a rival holder winds up (`WINDUP_MS`, shorter when sharp) or, a Trickster, feints (`FAKE_MS`) before a lunge, and a runner a lunge comes at dodges once a lunge at its venue's odds after its reaction time; the fuse ticks quicker and higher as it burns down, on one clock however many bombs burn (yours, else the shortest); a bomb whose fuse has run out passes to nobody; memo is the furthest venue reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/hot-potato.md`) |
| `public/activities/fuse-draw.js` | Hot Potato's drawing: `drawScene(ctx, view)` from one view object `fuse.js` refills each frame, in arena units: the strip above the arena in the page's colors with the pills (laid out by `hudLayout`, which starts a second row rather than run into the fuse and centers its rows in the strip), each venue's floor in its fixed palette (`themeFor`, `venueColor`), ice, running belts, the Rooftop's open edge, the things to run round, pickups, the runners (Planny on his feet with his star eye and stick arms, flailing while he holds a bomb, and still Planny when charred; arms and feet on the floor in `limbInk(level)`, the ink that stands out from that venue's tiles; rivals with a mark per personality; a white ring with a dark edge at the feet of a runner safe from a tag-back; the charred waddle to the nearest wall and the fall from the roof), the bomb over its holder (a red ball with a `<<<` band, growing and glowing as it burns, flashing white while it cannot be passed, its fuse a shortening curl with a spark, the last seconds in big numbers (under the holder's feet when there is no room above, `countY`), a hop across on a pass), blast clouds, the Blackout's dark worked out once a frame in cells, the red edge pulse in a fuse's last second, banners and the start and end strip with the big final score, and `readColors(canvas)`; decides nothing |
| `public/activities/hop.js` | Crossing Rush: its rules as plain exported functions over a round on a strip `COLS` (11) cells wide of 30 to 40 lanes, `VIEW_ROWS` (14) on the board at once (`newRound`, `newHeat(round, zone)`, which builds the heat's lanes from the round's seed, kept when a heat runs again, `buildLanes(zone, seed)` (groups of road, highway, ice, river, turtle, rapids or rail lanes with a grass row between each two, the zone's new thing first; the same seed builds the same lanes), `advance` in 8 ms slices (lanes flow, riders drift with their log, rivals choose, everyone is checked where they stand before any hop moves on, then hops and flights; hoppers home in the same slice finish by the moment each landed, a dead heat to you), `hop(round, hopper, dir)` (one cell, two with a Spring; a hopper counts in the cell it leaves for the first half and the one it lands on for the second; an icy lane slides it a cell more), `laneAt`, `occupied(round, row, col, atMs)` (a car or a train on it, or in a river no float or the edge, `atMs` ahead through `shiftAt`, which follows a lane's flips, surges and a Horn exactly), `sendBack` (to the last grass row, `safeBelow`, crediting a shove within `SHOVE_CREDIT_MS`), `shove(round, from, to)` (a cell the way `from` faces, only on a hopper `inReach` and never on one past the half of its hop home, once every `SHOVE_MS`), `plan(round, hopper, random, power)` (a look ahead of `LOOKAHEAD` to `LOOKAHEAD_SHARP` hops over the lanes as they will move, each hop followed by the hopper's wait where it lands; never a hop where it would be hit or fall in at full sharpness; a sloppy rival now and then hops on regardless), `applyPower`, `zoneFor` and `rivalPower` (each built once per zone), `rivalColors(you)`, `standings`), the `ZONES`, `RIVALS` and `POWERS`, and the game contract with `release()` (`key(name, repeat)` hops once a press: never on a repeat, never again until the arrow is let go, never with the press that plays on, and with one hop queued behind the one in the air; a pause drops what is held and the queue); rivals wait `REACT_MS` down to a sharp rival's after each landing, a Bruiser shoves anyone beside it into a lane, a Tagalong follows a row behind you and shoves near the top, and a rival that lets a shove go weighs the next one only after `SHOVE_LOOK_MS`; memo is the furthest zone reached, which can pass 9; a read-only `round` getter for the tests only. Tuned by a scratch sim (see "As built" in `game-ideas/crossing-rush.md`) |
@@ -450,9 +450,10 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
| `public/tones.js` | the activities' sound engine, all synthesized in the browser. Three parts: a shared kit of rich one-shot sounds (`RICH`: `layers` of parts played together, each a wave or a noise (`noise`, `pink`, `brown`) with its own `delay`, `gain`, `attack`, a sweeping `filter` and `vibrato`: `explode`, `smash`, `skid`, `whoosh`, `splashBig`, `fanfare`, `gameOver` and some fifty more, up to 1.2 s, at most `MAX_VOICES` parts sounding at once), held **hums** (`hum(id, name, level, pitch)`, called every frame a game wants it: oscillators and noise through one filter that follows the pitch, pulsed for an engine's strokes; a hum not asked for within `HUM_HOLD_MS` fades by itself, so a paused or closed game goes quiet without saying so, `hushTones()` quiets every one and the Activities window calls it whenever it stops ticking; at most `MAX_HUMS`; shared ones `car`, `toycar`, `electric`, `outboard`, `river`, `wind`, `cycle`, `fuse`, `haunt`, `squeal`, `meter`, `swarm`, `train`, `crowd`), and each game's own extras in `public/activities/<id>-sfx.js` (`{ tones, hums }`, plain objects, names prefixed with the game id, merged and frozen here; a name may be defined once across all of them, which `scripts/test-web-console-tones.mjs` checks along with every spec's shape and every name a game's source asks for). Everything plays through one compressor. The older single blips (`BLIPS`): `tone(name, level, pitch)` with an optional loudness from 0 to 1 and an optional pitch that scales every frequency, kept between 0.25 and 4, and an optional fourth `louder` (a game lifting its sounds as a whole, up to `LOUDER_MAX`, also the fifth argument of `hum()`), `unlockTones()`; Snake's blips plus golf's `putt`, `wall`, `bump`, `cup`, `ace` (a three-note rise), `splash`, `power` (a power-up, three notes), `tunnel`, `boom` (a cannon putt), `sizzle` (lava) and `fall` (the pit), the countdown's `count` and `go`, Stack Deploy's `thunk`, `slice` and `perfect`, which it pitches up a scale step for each perfect in a row, and Bumper Ring's `ram`, pitched and leveled by how hard the hit, and `rev`, a rival winding up a dash, and Hot Potato's `tick`, the fuse, which it ticks quicker and pitches higher as the fuse burns down, and `pop`, a pass, and Crossing Rush's `hop`, which it pitches up a step for each quick hop forward in a row, `boing`, a send-back, `bell`, a train coming, and `horn`, and Bounce Road's `engine`, a soft low triangle hum it plays every few frames while you pick up speed (quiet once you cruise or coast), pitched up with your speed, `spring`, a jump, pitched with your speed, and `squash`, a rival flattened, pitched up a step for each in a chain, and `beat`, a low thump while your wheels run on the verge (it borrows the other games' blips for its hazards and rivals), and Rapids Run's `pew` (a shot, a short soft triangle played quietly about seven times a second while fire is held), `charge` (a buoy taken), `lowcell` (the low battery's two-note beep, quicker the lower it runs), `dambreak` (a dam bursting) and `skim` (a bank skimmed at speed, pitched up the more you have skimmed), and Ghoul Rush's `ghoulBlast` (the blaster's bolt, a short soft triangle repeated while fire is held), `zombiePop` (a kill, pitched up a step for each in the chain), `ghoulStomp`, `ghoulBoo`, `ghoulRoar` and `zombieGroan` (now kept for the other games and the tests: Ghoul Rush's monsters speak with their own voices from `ghoul-sfx.js`), `ghoulCandy` (pitched up for candy in quick succession), `batSwoop` (a bat's kill), `doorUnlock` (the key), `doorThrough` (the door to the next room) and `creakBoard` (a crawler coming up, a chandelier or a crumbling board about to go), all soft triangles and sines), silent while Play sounds is off; separate from `sound.js`'s cue queue |
| `public/music.js` | the games' chiptune music: a small sequencer over `tones.js`'s context and compressor (`audioOut()`). A game calls `music(name, intensity)` from its `tick`; the track fades out within `MUSIC_HOLD_MS` once it stops being asked for, picks up again on the bar it left, asking for a different track crossfades the two over `CROSSFADE_S` (the old one keeps playing as it fades, so a new level is not a cut), and `hushMusic()` stops it at once. Tracks are note data under `music` in each game's `activities/<id>-sfx.js` (`{ bpm, rush, bar, voices, patterns, order }`, `bar` the steps in a bar when it is not 16, so the track resumes on a bar start and each pattern is whole bars: pulse, triangle and noise-drum voices, each joining once the intensity reaches its `from`; a step a token, `A4`, `-` to hold, `.` a rest, `A3^037` an arpeggio, drums `k s h o`), read by `compileTrack()` and booked `LOOKAHEAD_S` ahead on the audio clock. It also plays recorded **songs**: mp3s a game names under `songs` in its sfx file (a name to a served path, merged by `tones.js` as `SONG_TABLES`, listed by `songNames()`), asked for the same way, one `<audio>` element each made on first use, at `SONG_PEAK` times the volume, faded over `SONG_FADE_MS`; a song plays once, never looped, `music()` returning `"playing"` or `"ended"` (which the window's wrapper passes back to the game), `{ restart: true }` taking it back to the top with `load()` (no seeking, since the server sends no byte ranges), and a song no longer asked for fades and pauses where it was. The window plays it only while Play sounds, Play game sounds and Play game music (`looks.gameMusic`, off by default) are all on |
| `public/activities/snake-sfx.js` · `public/activities/flock-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-rush/sfx/ghoul-sfx.js` | each game's own sound effects as data, `{ tones, hums }` in the shapes `tones.js` documents, every name prefixed with the game id (`driveEngine`, `ghoulMoan`), merged and frozen by `tones.js`; no imports, but for `ghoul-sfx.js`, which merges each Ghoul Rush stage's own `ghoul-sfx-<stage>.js` into its `tones`, `hums` and `music`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` has `songs` instead of `music` |
| `public/activities/snake-sfx.js` · `public/activities/flock-sfx.js` · `public/activities/golf-sfx.js` · `public/activities/trails-sfx.js` · `public/activities/bugs-sfx.js` · `public/activities/drive-sfx.js` · `public/activities/stack-sfx.js` · `public/activities/bumper-sfx.js` · `public/activities/rapids-sfx.js` · `public/activities/fuse-sfx.js` · `public/activities/hop-sfx.js` · `public/activities/bounce-sfx.js` · `public/activities/ghoul-rush/sfx/ghoul-sfx.js` | each game's own sound effects as data, `{ tones, hums }` in the shapes `tones.js` documents, every name prefixed with the game id (`driveEngine`, `ghoulMoan`), merged and frozen by `tones.js`; no imports, but for `ghoul-sfx.js`, which merges each Ghoul Rush stage's own `ghoul-sfx-<stage>.js` into its `tones`, `hums` and `music`, and `snake-sfx.js`, which merges `snake-music.js` as its `music`; `trails-sfx.js` and `flock-sfx.js` have `songs` instead of `music` |
| `public/activities/snake-music.js` | Snake's ten music tracks as data (no imports): `SNAKE_MUSIC`, `{ bpm, rush, voices, patterns, order }` each, named `snake<Place>` and listed in `MUSIC_TRACKS` in `snake.js`. A round deals them in a fresh order, one to each level, so a run hears a different track at every level and none twice. They were picked on the pages in `prototypes/music/snake` (rhythm-first folk and world tunes led by something plucked or reedy, mostly dark or modal), and their bars are not all sixteen steps: 6/8 is 12, 7/8 is 14, ten beats is 20, twelve beats is 24, each pattern a whole number of its bars; merged by `snake-sfx.js` |
| `public/activities/light-trails/1.mp3` to `5.mp3` | Light Trails' five background songs, named `trailsSong1` to `trailsSong5` under `songs` in `trails-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 7.6 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm |
| `public/activities/flock-dash/1.mp3` to `5.mp3` | Flock Dash's five background songs, named `flockSong1` to `flockSong5` under `songs` in `flock-sfx.js` and listed in `SERVABLE`; re-encoded for size with ffmpeg the way Light Trails' were (80 kbps stereo MP3 at 44.1 kHz, loudness-normalized to -16 LUFS with `loudnorm`, metadata stripped), about 6.4 MB together, and copied into every skill with the rest of the console. The server leaves them out of its start-up cache warm; `flock.js` deals all five in a fresh order each round with `dealMusic()`, plays each in full one after another and deals again after the last, never opening on the song that just ended |
| `public/activities/ghoul-rush/stages/graveyard/ghoul-sfx-graveyard.js` | The Graveyard's own sounds as data (no imports): `GRAVEYARD_SFX`, its `tones` (the picked `ghoul<Kind><Act>` sounds of the grasping hands, mourners, grave robbers, rotters and their legs, carrion crows and Mother Mourning) and `music` (`ghoulLychgate`, `ghoulGraves`, `ghoulMausoleums`, `ghoulAngel`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own. Every new stage gets its own `ghoul-sfx-<stage>.js`, listed in `STAGE_SFX` there |
| `public/activities/ghoul-rush/stages/grounds/ghoul-sfx-grounds.js` | The Grounds' own sounds as data (no imports): `GROUNDS_SFX`, its `tones` (the 32 picked `ghoul<Kind><Act>` sounds of the topiary beasts, rootlings, lantern moths, mulch crawlers, the Groundskeeper and the Hedge shears' snip) and `music` (`ghoulMaze`, `ghoulTopiary`, `ghoulGazebo`, `ghoulYard`, named in `ROOM_MUSIC`), merged by `ghoul-sfx.js` after the house's own via `STAGE_SFX` |
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry, and the page's shared full-screen picture preview (`openPicview`, the `#picview` dialog every thumbnail opens) |
@@ -507,6 +508,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (`done`, `happy`); a finished screen gets no special case, so one still offering a press points and lights `ready` (the desktop app's taskbar dot follows), a stranded press is `attention`, and only all done or paused is `plain`; `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
| `public/continue-button.js` | The one control that wakes a quiet agent. `continueButton(label, cls)` is a button asking the app for `agent-continue` (held off 4 s after a press); `reconnectOffer(cls)` is that button labeled **Reconnect to agent** under the app and, in a browser, a line telling the person to type `continue` in their terminal. Used by the status line (`screens/core.js`: the dashboard's quiet, launch-saved and way-home-saved lines), the Ask tab (`screens/ask.js`, left of Send while the red no-agent line shows) and the saved-and-waiting launch screen (`screens/starting.js`, app only; a browser reads the hint). |
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered), `terminal-open` (the in-app **terminal** button, shown in place of the word in every What to check line while the app's terminal panel is collapsed: the app presses the panel's own Collapse/View button, and only when collapsed; the app tells the page the panel's state with `terminal-state` `{ collapsed }` on the page's `console-ready` and on every change, heard through `onAppMessage` into `page.terminalCollapsed`), `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all) and `activities-full` (`{ on }`, an Activities game going in or out of full screen: the app lays the console's frame over its bar and terminal and puts the window in full screen, and out of it only if it put it there; `taskbarSwitch()` checks the boolean, and the window permissions are in `capabilities/default.json`). Nothing outside a frame |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table, one entry per non-null `subagents` field in `skills.js`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
@@ -603,6 +605,7 @@ Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-
- **Banners never get in the way.** A banner over the board (`"Hit!"`, a new level, a power-up) is placed on the frame it first shows, on the part of the board away from the player, and fades to `BANNER_SEE_THROUGH` (0.12) over `BANNER_FADE_MS` while the player, or anything the player must react to (a diving bug, a bomb, a rival, a hazard, the road over a hill), is in its strip; Snake's `bannerRow()` and `underBanner()` are the model. Give the banner object a `see` field, multiply the draw's alpha by it, and export the strip check (`underBanner`) for the unit suite.
- **The window owns pausing.** A game never resumes itself; `screens/activities.js` decides when a key or click plays on, including the hold on a question or finish (see the row above), so a game needs nothing of its own for it. Full screen is the window's too (`setFull()`: the button, `F`, and a turn or finish putting it back; `fitFull()` sizes the game to the whole screen (black bars where its shape leaves room) and docks the overlaid panel in a bar that holds it, `data-dock="side"` or `"below"`, or floats it, `"float"`, shrunk to the score while a round plays and the pointer is still; and tells the desktop app `activities-full`); a game only sees a bigger `resize()`, so a new game needs nothing for it, as long as its `resize()` sets the canvas's CSS size.
- **Every moment has a sound, and moving things hum.** A game plays a one-shot through the `tone` it is handed for each event worth hearing (a hit, a pickup, a level, a new best, game over) and keeps continuous things (an engine, a motor, wind, water, a fuse, a monster close by) going with `hum(id, name, level, pitch)` from its `tick`, pitch following speed. Never a one-shot every frame: a repeating cue is throttled by a timer in the round. Its own sounds live in `activities/<id>-sfx.js`, named with the game id; the shared kit is in `tones.js`. `create()` defaults `tone` and `hum` to no-ops, since the suites make games with neither, and a sound never changes the game's state.
- **Its logic tests pin the dice.** A game rolls `Math.random` for roads, spawns and layouts, and an unlucky roll once failed a test on CI at random (Ghoul Rush's Eye, Bounce Road twice). Import `./seed-random.mjs` FIRST in every `scripts/test-web-console-activities*.mjs` file: it seeds `Math.random` (set `PLAN2CODE_TEST_SEED` to try another roll), so a test sees the same world on every run.
## Status Line
@@ -661,4 +664,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls exactly those, with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls those (metrics and bot only when run from a git checkout), with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
+1 -1
View File
@@ -28,7 +28,7 @@
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console` (`-<uid>` on Linux and macOS, a 0700 folder with 0600 handles), or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
+1 -1
View File
@@ -126,7 +126,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|------|--------|
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
## How the Installer Works
+104 -3
View File
@@ -4,15 +4,80 @@ on:
push:
branches: [main]
pull_request:
types: [opened, synchronize, reopened, labeled]
# Run the full three-system matrix by hand on any branch.
workflow_dispatch:
permissions:
contents: read
# A newer push to a pull request replaces its still-running checks. A push to main always
# finishes, so a merged change is never left half checked.
concurrency:
group: app-${{ github.event.pull_request.number || github.ref }}
cancel-in-progress: ${{ github.event_name == 'pull_request' }}
# Speed: a pull request runs on Ubuntu only (the cheapest runner) unless it carries the
# `full-matrix` label; pushes to main and manual runs use all three systems. A change that
# touches only the website, the README, the changelog or similar skips the heavy jobs and runs
# the fast `prose` job instead, which keeps the checks that read those files.
jobs:
changes:
name: changes
runs-on: ubuntu-latest
outputs:
code: ${{ steps.diff.outputs.code }}
steps:
- uses: actions/checkout@v4.2.2
with:
fetch-depth: 0
- id: diff
shell: bash
run: |
set -euo pipefail
case "${{ github.event_name }}" in
pull_request) base="${{ github.event.pull_request.base.sha }}" ;;
push) base="${{ github.event.before }}" ;;
*) base="" ;;
esac
# A manual run, a new branch or a base git cannot find: run everything.
if [ -z "$base" ] || [ "$base" = "0000000000000000000000000000000000000000" ] || ! git cat-file -e "$base^{commit}" 2>/dev/null; then
echo "code=true" >> "$GITHUB_OUTPUT"
exit 0
fi
files="$(git diff --name-only "$base" HEAD)"
echo "Changed files:"; echo "$files"
# .readme/, AGENTS.md and .agents-docs/ are read by tests, so they count as code.
if [ -n "$files" ] && ! echo "$files" | grep -qvE '^(docs/|prototypes/|README\.md$|CHANGELOG\.md$|QUICK-REFERENCE\.md$|LICENSE$)'; then
echo "code=false" >> "$GITHUB_OUTPUT"
else
echo "code=true" >> "$GITHUB_OUTPUT"
fi
prose:
name: prose checks
needs: changes
if: needs.changes.outputs.code == 'false'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
with:
node-version: 20
- name: Versions agree
run: node scripts/check-versions.mjs
- name: Spelling, install command in the docs, line endings
run: node --test scripts/test-us-english.mjs scripts/test-getting-started.mjs scripts/test-line-endings.mjs scripts/test-check-versions.mjs
app:
name: app (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest, ubuntu-latest]
os: ${{ fromJSON(github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix') && '["ubuntu-latest"]' || '["windows-latest","macos-latest","ubuntu-latest"]') }}
defaults:
run:
working-directory: plan2code-app
@@ -40,11 +105,29 @@ jobs:
key: cargo-${{ runner.os }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
restore-keys: |
cargo-${{ runner.os }}-
- name: Name this week for the apt cache
if: runner.os == 'Linux'
id: week
run: echo "week=$(date +%G-%V)" >> "$GITHUB_OUTPUT"
- name: Cache the Linux system packages
# The WebKit packages are hundreds of MB, and the runner's Ubuntu mirror is sometimes
# slow (one download took 7 minutes), so keep the downloaded .deb files. The key rolls
# over weekly so versions do not go stale; an older week still restores what it can.
if: runner.os == 'Linux'
uses: actions/cache@v6.1.0
with:
path: ~/apt-archives
key: apt-tauri-${{ runner.os }}-${{ steps.week.outputs.week }}
restore-keys: |
apt-tauri-${{ runner.os }}-
- name: Install Linux system packages
if: runner.os == 'Linux'
run: |
mkdir -p "$HOME/apt-archives/partial"
sudo apt-get update
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb
sudo apt-get -o Dir::Cache::archives="$HOME/apt-archives" install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb
# apt ran as root: hand the folder back so the cache step can read and save it.
sudo chown -R "$(id -u):$(id -g)" "$HOME/apt-archives"
- name: Install the app's packages
run: npm ci
- name: Vendor the xterm files cargo needs
@@ -87,15 +170,33 @@ jobs:
node-tests:
name: npm test (${{ matrix.os }})
needs: changes
if: needs.changes.outputs.code == 'true'
runs-on: ${{ matrix.os }}
strategy:
fail-fast: false
matrix:
os: [windows-latest, macos-latest, ubuntu-latest]
os: ${{ fromJSON(github.event_name == 'pull_request' && !contains(github.event.pull_request.labels.*.name, 'full-matrix') && '["ubuntu-latest"]' || '["windows-latest","macos-latest","ubuntu-latest"]') }}
steps:
- uses: actions/checkout@v4.2.2
- uses: actions/setup-node@v4.4.0
with:
node-version: 20
- name: Cache the npm downloads
# setup-node's own cache needs a tracked lockfile and the root has none, so cache npm's
# download folder directly (both places it lives: Linux and macOS, then Windows).
uses: actions/cache@v6.1.0
with:
path: |
~/.npm
~/AppData/Local/npm-cache
key: npm-${{ runner.os }}-${{ hashFiles('package.json', 'plan2code-metrics/package.json') }}
restore-keys: |
npm-${{ runner.os }}-
- run: npm install
- run: npm test
- name: Metrics tests
working-directory: plan2code-metrics
run: |
npm install
npm test
+13 -1
View File
@@ -14,8 +14,16 @@ on:
push:
tags: ['v*']
# Read-only by default: the build jobs run dependency install scripts and build scripts, so
# only the publish job holds a write token.
permissions:
contents: write
contents: read
# A release published after its tag push starts a second run for the same tag: queue it behind
# the first so two builds never upload over each other.
concurrency:
group: release-app-${{ github.event.release.tag_name || github.ref_name }}
cancel-in-progress: false
jobs:
build:
@@ -34,6 +42,8 @@ jobs:
shell: bash
steps:
- uses: actions/checkout@v4.2.2
with:
persist-credentials: false
- uses: actions/setup-node@v4.4.0
with:
node-version: 22
@@ -83,6 +93,8 @@ jobs:
name: attach to the release
needs: build
runs-on: ubuntu-latest
permissions:
contents: write
env:
GH_TOKEN: ${{ github.token }}
TAG: ${{ github.event.release.tag_name || github.ref_name }}
+31 -14
View File
@@ -528,8 +528,8 @@ working in.
### 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. 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
games to play while you wait, say through a long build. Thirteen ship today,
**Snake**, **Mini golf**, **Light Trails**, **Bug Hunt**, **Sunset Drive**, **Stack Deploy**, **Bumper Ring**, **Rapids Run**, **Hot Potato**, **Crossing Rush**, **Bounce Road**, **Ghoul Rush** and **Flock Dash**. 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
@@ -548,15 +548,15 @@ 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, Snake a different one at every level, dealt from ten at
the start of a round so none repeats, and Ghoul Rush a track for each room, played at
one steady level and fuller in a boss fight), and Light Trails plays five
recorded songs as background music, each in full, one after another in an
order shuffled for every run: turn on **Play game music** in **User
Preferences → Sounds & activities** (it starts off). **Play game sounds** there turns the games'
one steady level and fuller in a boss fight), and Light Trails and Flock Dash play five
recorded songs each as background music, each in full, one after another in an
order shuffled for every run: turn on **Play activity music** in **User
Preferences → Sounds & activities** (it starts off). **Play activity 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 (Snake, Light Trails and Sunset Drive start at 70,
game's music volume and is remembered per game (Snake, Light Trails, Sunset Drive and Flock Dash start at 70,
Ghoul Rush at 65).
- **Snake** speeds up as it grows: 120 ms a step at its starting three cells,
@@ -1431,6 +1431,22 @@ Ghoul Rush at 65).
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).
- **Flock Dash** is a side-scrolling flight through a sunset sky, with Planny
as the lead bird. Hold up or down to climb and dive within a band in the
left part of the sky, and left or right to ease forward or back. Strays
drift in from the right; fly into one and it joins the flock, which
follows the exact path you flew, each bird a set distance behind the one
before. Balloons, gusts, slipstreams, storm clouds and kites are in the
way: a hit on the leader costs one of three lives, and a hit on the line
snaps it there, scattering the birds behind (fly back through them within
3 seconds or they are gone). Eight stages, each faster than the last,
each end at a jet stream portal: with enough birds the flock forms a V
and pays a bonus, and the final portal moves. Tailwind, shield and magnet
crates help, pickups in quick succession build a combo of up to x5, and a
stage with no snap and no bird lost pays a flawless bonus. Five recorded
songs play as background music in a shuffled order. The end screen's nudge
to play again names the next hazard or stage you have yet to reach, and the
furthest stage you reached is kept privately.
- **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, and **Unpause game**. While that banner is up, only
@@ -1459,10 +1475,10 @@ Ghoul Rush at 65).
P or Esc during the count pauses again.
- **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
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, fires while held in Ghoul Rush, where held arrows run, up jumps once a press and down drops through a shelf, and climbs and dives in Flock Dash, where held up and down fly the leader and held left and right ease forward and back), 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, 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
Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash 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
@@ -1472,7 +1488,7 @@ Ghoul Rush at 65).
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, 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
- **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, Flock Dash's furthest stage, 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.
@@ -1695,7 +1711,8 @@ When a newer Plan2Code release is out, the dashboard shows an **UPDATE
AVAILABLE** banner at the top. Click it for the details: the version you
have, the new one (linked to its Releases page) and the command that updates
you, `plan2code update`, with a Copy button. It updates everything that was
installed (the skills, the `plan2code` command and any extras you added), with
installed (the skills, the `plan2code` command, the app and the status line; the
metrics and bot extras only from a git checkout), with
no menu, and never uninstalls anything. If the `plan2code` command is not
installed, the dialog also shows the install command,
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
@@ -1737,7 +1754,7 @@ The gear button in the top bar opens **User Preferences**, always on its first t
| **System** | Cleanup, and Desktop app (only inside the desktop app) |
| **Sounds & activities** | Sounds and Activities |
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.
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 activity sounds); Activities best scores stay. It is not shown on Agents & models or System, which have nothing to reset.
### Agents & models
@@ -1773,7 +1790,7 @@ Most people never need this tab: Plan2Code finds the agents installed on the mac
| You closed the tab | Open the link again. Everything is where you left it. After about two minutes with no tab open the link stops working: ask the agent to resume the session for a new one. |
| The link stopped working | Tell the agent. It restarts the session and gives you a new link. |
| Your agent session died while you were mid-answer | Press Send anyway. Your answers are written to disk and are never discarded, including when the session is restarted. The next session picks them up. |
| The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up. Answering here still works, and what you send is held for it. |
| The page says Plan2Code is not running | It has not checked in for a few minutes. Look at the terminal: it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type `continue` in the terminal and it picks your answers up (in the desktop app, the **continue** or **Reconnect to agent** button in the sidebar, beside Send on the Ask tab, and on a saved launch types it for you). Answering here still works, and what you send is held for it. |
| You are not sure anything is connected | The **?** at the top right opens Help. Its *What this page is* tab says what keeps the page alive and whether both halves are talking at that moment, and *When something looks stuck* covers what to check. |
| You would rather use the terminal after all | Say so. Nothing is lost. |
@@ -1848,7 +1865,7 @@ exception being the note attachments the agent keeps for a spec, above):
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
| `~/.plan2code/handoffs/<id>.md`, `<id>.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/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/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 and Play game sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` 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<Id>`: 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/looks.json` | your role, theme, colors, sounds and card width, the Show Activities and Play activity sounds switches (`hideActivities`, `activitySounds`), the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` 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<Id>`: 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/<id>/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 & models), read by the `plan2code` command and the desktop app | always |
+1 -1
View File
@@ -36,7 +36,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
## Web Console
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (twelve small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (sLine truncated
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (thirteen small games, Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, listed in `public/activities.js` with one module per game under `public/activities/` (Ghoul Rush is its own folder of modules, `public/activities/ghoul-rush/`) and a card line (`blurb`) each, a picker page of game cards once two are listed that plays one game at a time (another pick drops the last game's round), driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person (while that pause's banner is up, only by its **Unpause game** button), best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`; Mini golf opens on a dashboard of its six 18-hole courses, one file each under `public/activities/golf-course-<id>.js`, and keeps a best per course, `activityBestGolf<Course>`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found, Light Trails' furthest arena, Bug Hunt's tally of finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's most stages cleared in a run, Flock Dash's furthest stage), never shown to the agent), a built-in 21-topic Help, the app-only **Implementation Loop** (a dashboard card and a setup screen drawn by the page, `public/screens/loop-setup.js`; the last setup remembered per project in `~/.plan2code/console/loop-setup.json`, owned by `loop-setup.mjs`; a page that locks while `state.loop.driving` is set, until the app posts `loopEnd`; a skill run with `--loop` reports a `loopOutcome` instead of asking for sign-off, per `notes/loop.md`), a first-run Welcome, User Preferences (gear: four tabs, Appearance, Agents & models, System and Sounds & activities, on the `public/tabs.js` helper Help also uses, with `public/prefs.js`, `screens/prefs-dialog.js` and `screens/agents-view.js`), an agent-less **setup** page (the `setup` workflow `plan2code` or the desktop app opens when no agent can run: each built-in's found / outside-PATH / missing state from `agent-lookup.mjs`, install lines, Check again, Use it from here, starter templates and Start, which hands the tab to the new agent through a token-guarded `POST /handover` and a `move` event; the app shows it in its window from a Set up an agent button instead) and a bug/idea link to GitHub issues. On opted-in skills (every workflow but the dashboard, Finalize, Changelog, Git and Handoff) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the twelve helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; taskLine truncated
One agent list and one lookup rule serve the launcher, the console and the app: `src/launcher/agents.json` (the built-ins and starter templates with per-OS install data) and `src/web-console/agent-lookup.mjs` (`loadAgentList()` and `findAgent()`, both copied by `install.js` into `~/.plan2code/bin/`); the app carries a Rust twin held to the same cases by `scripts/fixtures/agent-lookup-cases.json`.
Building or changing an Activities game: follow the game rules in [Architecture](./.agents-docs/AGENTS-architecture.md) ("Building an Activities game": lives in the solid lives pill, the endless-lives code (`cheat(on)`) in every game with lives, banners placed away from the player and see-through over what matters, pausing left to the window).
+19 -98
View File
@@ -6,113 +6,34 @@ All notable changes to Plan2Code will be documented in this file.
### ✨ Added
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **New Session** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Reconnect the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
- **desktop app**: the window's own title (and so its taskbar entry) now reads **Plan2Code - &lt;folder name&gt;** once a project is open, instead of a plain **Plan2Code** every window shares; two or more windows on different projects read apart without opening each one to check.
- **helpers**: a helper (subagent) no longer has to run on the session's own model and effort. A new shared reference, `helper-strength.md`, shipped in Pathfinder, Quick Task, Implement, Implement + Review and Review, matches each helper job to a strength (`light`, `standard`, `strongest` or `inherit`) and an effort (`low`, `medium` or `high`) from signals that can be checked, with floors, one-step escalation and a fallback order for tools that cannot set either, and never names a model or vendor. Review, Implement + Review and Pathfinder name the strength for the helpers they start, and the rules apply in terminal sessions too.
- **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review.
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort".
- **web console**: picking a spec on the dashboard that is not documented yet now shows its main files as read-only tabs in the top bar, like the **Overview** tab of a documented spec: **Map** for a Pathfinder map (`pathfinder/map.md`) and **Plan draft** for Plan's live `PLAN-DRAFT-*.md`, each when it exists. Once the spec has an `overview.md`, Overview replaces them.
- **web console**: start Pathfinder, Plan or Quick Task (on **Start fresh**) or Revise plan (on a picked spec with no plan change waiting) from a Notebook tab. A lit card's confirm pane offers **Start with a note from your Notebook**, with the tab list, a preview of the whole tab and up to five ticked pictures (the first five start ticked; a tab over 50 KB says so). The skill's first box arrives filled with the tab's text and pictures, editable, and the agent reads it only once you send it; nothing about the tab rides the launch itself. The tab then shows a **sent** badge and a "Sent to <Skill> · <Date>" line in the Notebook, and the Notebook's privacy line now reads: the agent never reads your Notebook, and a tab reaches it only when you start a workflow with it.
- **web console**: **Ask for suggestions**, a chip in the **Notes on this** panel of an open choice, multi or confirm card, asks Plan2Code what it would pick and why, on its own: it sends one request for that card (with anything typed in the note box), and every pick already staged, on that card or another, stays staged. The request shows in the thread tagged **Asked for suggestions** until the agent replies there, with the chip held off meanwhile; `console.md` tells the agent to answer a `Suggestions wanted on <title>:` line in the item's thread with each suggestion and why, re-posting the question only when that helps. A re-post that drops an option clears only the pick staged on it, and a banner names the question.
- **web console**: **Activities**, a die in the top bar right of the megaphone, opens a window of small games to play while you wait, say through a long build. The first is **Snake**, built in-house from local files (arrows or WASD, space or Enter to start, P or Enter to pause and play on, Esc to close). It speeds up as it grows and gets wilder each level: every new level opens in Slow-mo (which eases back to full speed as it runs out, never with a jolt), and every 5 foods brings something new (rocks that flash before they land, mystery boxes, portals, tail-cutting comets, chaos, then ice, where a turn slides two steps before it takes), five power-ups turn up on their own (Shield, Slow-mo, Magnet, Ghost, Scissors), a mystery box holds one of nine surprises (Jackpot, Gold rush, Lights out, Disco fever and more), each level serves its own fruit (an apple, then cherries, an orange, grapes, a banana, a strawberry, watermelon, a peach and a golden apple) on its own scenery (meadow, desert, lagoon, starry night, carnival, ice, volcano, gold), the last food of every odd level from 3 on is a crowned four-cell boss fruit that takes three bites, a runaway fruit on little feet hops away until you corner it or tire it out, quick eating builds a combo up to x5, and passing your best plays a fanfare. A level, power-up or surprise banner opens on the half of the board away from the snake and fades almost clear while the snake is under it or heading into it, so it never hides a crash. The start and end screens count the surprises you have found so far and hint at what waits next. The second is **Mini golf**: goofy holes seen from above on themed courses (see the course dashboard further down), among them Pirate Cove (a shark sea, cannonballs, a kraken, a ghost ship, a skull to putt through) and the Caves of Doom (dark but for the ball's light, with lava, a bottomless pit, mine carts, stone crushers and a sleeping dragon), played arcade style: the aim follows the mouse (or held arrows, turning faster the longer they are held) and points back at the cup after every stop, holding there until the mouse really moves so a click never swings it, one click or space starts a power meter beside the ball and a second sets the power (slow near the bottom for soft putts, fast near the top, with a gold MAX band for a 1.15x putt and a red overswing band past it that shanks the ball), a 6 second shot clock starts the meter for you, a meter left running dribbles the ball, and holding space or the mouse fast-forwards the roll, with par per hole, at most 8 strokes a hole, and its best kept as the lowest full round. Glowing power-up pads help the next putt: a free putt, a cannon shot, a ghost ball that floats over water, a cup magnet, a rubber duck that keeps its speed off walls, a huge cup, and a spyglass that shows where the putt will roll. With two games, a picker chooses between them. A new question, a sign-off or a finish pauses the game at once and shows a banner with **Go to it**, so a game never hides your turn; hiding the page or clicking away pauses it too. While that banner is up, nothing resumes until you click its **Unpause game** button, so a key or click already on its way cannot wave the banner away unread; after **Go to it**, or once you close and reopen the window, a game key or a click on the board plays on. Resuming puts the your-turn banner away until the next question. Every round start and every play-on after a pause counts down 3, 2, 1 first, so a game never moves before you are ready. The window's header shows the current game's best. Best scores (shown beside the score and after each round, cleared by **Reset best scores**; the score line is a pair of colored chips with a meter filling toward the best, which glows when you reach it, turns into a rainbow with a burst of sparks when you pass it, and ends the round with **New best!**) and the last pick are saved privately in `~/.plan2code/console/looks.json` and never reach the agent. **User Preferences → Sounds & activities → Show Activities** hides the die everywhere, and Help has a new Activities topic.
- **web console**: Activities has a third game, **Light Trails**: every rider leaves a glowing wall behind it, and the last one still moving wins the heat. Arrows steer and space spends a boost charge (two a heat, up to three). Riding into something holds you in place for a split second first, so a turn pressed then still gets you out (rivals get no such grace). A round runs through nine arenas, from Neon Grid to the Golden Arena, each on its own scenery: a win moves you on, and a crash costs one of five lives and runs the heat again, and every 750 points gives a life back (up to nine). Each arena brings a rival more (Zip, Bolt, then Echo, who ride sharper the further you go) or something new: power-up pads at 2 (Boost, Phase through trails, an Eraser that wipes the trails around you, Slow-mo for the rivals, coins, a beating Heart for a life, and a Shield, held from heat to heat until it takes a crash for you), crystals at 3 with a Laser that zaps rival heads in your line through their trails and Score x2, portals at 4 with a Wide Trail three cells across (you can turn onto the side cells just laid, so a corner never crashes you) and Coin Rain, walls that close in a ring at a time, flashing first, at 5 with a Hyperjump out to open space, and at 6 a rainbow Mystery pad that could be any of them; the first pad of each kind in a run says it is new. A rival out while you still ride scores points, and more when your trail or your laser got it. You ride with Planny's star eye, and the start and end screens show the furthest arena you have reached and what waits next.
- **web console**: Activities has a fourth game, **Bug Hunt**, an arcade shooter. Planny's ship slides along the bottom (the arrows move it, held space fires) and squashes waves of bugs that swoop in from the sides into a swaying formation, then break off and dive at you. The first waves each bring a new bug: the everyday **Bug**, a **Beetle** that splits in two, a zigzagging **Race condition**, an **Exception** that throws things, a **Null pointer** that shots pass through while it fades, and a **Firewall** that soaks up shots. Every fifth wave is a boss: the **Memory Leak**, which grows while you wait, the **Spaghetti Monster**, whose tentacles have to go first, and the **Heisenbug**, which is only there when you look, then round again, tougher. Squashed bugs drop coins and now and then a power-up (Spread shot, Rapid fire, Shield, Slow-mo, Magnet, Refactor, which cleans up the screen, and a 1UP), quick kills build a combo up to x5, and a wave cleared without a hit scores extra. The board is Snake's checkerboard scrolling past with bits of code drifting by, with new scenery every five waves (the Codebase, Legacy Code, Production, the Cloud), and the start and end screens count the 16 bugs, bosses and power-ups found so far.
- **web console**: Activities has a fifth game, **Sunset Drive**, a road racer against the clock. Planny drives a convertible down an endless road seen from behind, with bends, hills, traffic and scenery scrolling past: hold up to drive, down to brake, the arrows to steer, and space burns a nitro can for a burst of speed. The clock sits big in the top middle, blinking red and swelling on every tick in its last ten seconds. Each stage ends at a checkpoint that adds time, and just before it the road splits around a median: the side you keep to picks the next of six roads (Sunset Coast, Canyon Road, Maple Valley, Snowcap Pass, Neon City and Starlight Highway), each with its own sky, props, traffic and points bonus, the harder ones worth more. Coins, clocks and nitro cans line the road, a car passed close at speed scores a close call, and catching up with a car or hitting a palm, cactus or rock on the shoulder costs you speed. As the fork is called, a postcard of each road (its sky, hills, road and scenery, with its name and points bonus) shows in the top corner on its side, the side you are on lit. Spinning **?** boxes on the road hold power-ups, queued up to three: 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 adds its time). **Rocket Hop** leaps over the traffic and the shoulder, **Ghost Car** drives right through cars and props, **Coin Magnet** pulls in every coin across the road, **Monster Truck** flings the cars it hits into the sky for points and flattens props, and **Coin Storm** turns the traffic ahead into coins. The round ends when the clock runs out, and the start and end screens count the roads found so far.
- **web console**: Activities has a sixth game, **Stack Deploy**, a one-button tower stacker. A block slides back and forth above the tower and space, up or a click drops it: the overhang is sliced off and tumbles away, so the next block is narrower, and a block that misses the tower ends the round with the camera pulling back over the whole tower. A drop dead on is a **Perfect**: nothing is sliced, the thunk climbs a scale with each one in a row, the bonus multiplies up to x5, and every third in a row grows the block back. Gold blocks from floor 15 are worth more and grow it twice as much. The slide speeds up from floor 10, and the floors bring twists: blocks from either side that may turn back (20), lag spikes that freeze a block for a beat (30) and wind (40), then a rush through the middle (70) and everything faster (90). The tower goes from server racks to office floors, glass towers and rockets under a sky that turns from day to space, Planny rides the top block (and wobbles after a sloppy drop), and a dashed line marks the highest floor ever reached, which the start screen names with the next style to reach.
- **web console**: Activities has a seventh game, **Bumper Ring**, sumo in bumper cars on a platform over the void. Held arrows push your car that way and momentum carries it; cars bounce off each other and the one closing faster rams and wins the exchange, while two cars leaning in are a pushing match. Space dashes (two charges a heat, one back every six seconds, up to three). A car whose center goes past the edge falls, and the last car on the ring wins the heat: a win moves on, a fall costs one of three lives and runs the heat again. Rivals rev before they dash, so a quick sidestep can send one flying off on its own. Nine arenas, from the **Training Mat** to the **Grand Final** and then endless, sharper Finals, bring five rivals with their own ways (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 in the floor, a magnet and a ring that turns square. After a while the ring shrinks a flashing band at a time, then goes to sudden death, so every heat ends. Knockouts go to the last car to touch the one that fell, quick ones build a combo up to x5 and two at once count double, and the start and end screens show the furthest arena you have reached.
- **web console**: Activities has an eighth game, **Rapids Run**, 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 for double points per distance, held down slows, and held space fires. The battery drains all the while (faster at speed), so run over charge buoys to top it up, or shoot them for 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 starts the stretch again from the last dam (from the basin's mouth once a mini-boss is reached). Each stretch ends at a dam you must blast open to pass, for a stretch bonus and a new stretch name: eight stretches from **Willow Run** to **Old Lock**, then endless, quicker Night Water. The river's foes arrive a kind at a time (patrol skiffs, bob mines, gull drones, bank sentries that shoot back, whirlpools that tug and darters that swerve into your lane), every fourth dam is guarded by a mini-boss (the Dredger, Ironclad and Old Leviathan), and crates hold Spread shot, a Shield, a Magnet and a Surge. Quick sinks build a combo up to x5, skimming a bank at speed scores, the score shows big at the end, and the start and end screens show the furthest dam blasted.
- **web console**: Activities has a ninth game, **Hot Potato**, arena tag with a fizzing bomb: a merge conflict with its `<<<<<<<` markers showing. Held arrows run, whoever holds the bomb runs a little faster and passes it by touching someone, and whoever holds it when the fuse runs out is blown out of the match in a cartoon cloud, then waddles off charred. The fuse ticks quicker as it burns, the bomb grows and glows redder, and the edges pulse in the last second; each fuse in a match is shorter than the one before. Someone just handed the bomb cannot pass it on for a moment, and nobody can hand it straight back while three or more are left (a white ring at their feet shows who is safe); handed it at the last moment, you still get time to pass it, since a pass tops the fuse up to 1.4 seconds, once a fuse for each runner. Space dashes: a lunge for a tag while you hold it, a dodge while you do not, and rivals crouch before they lunge, so a quick sidestep gets you clear. The last one standing wins the match and moves on through nine venues, from the **Break Room** to the **Finale** and then endless, sharper Finales, bringing five rivals with their own ways (the Sprinter, the Hider, the Trickster, who feints, the Pal and the Clingy), pickups (Freeze, Sneakers, Extra Fuse and Swap), long rows of server racks, a roof with no wall on one side, ice, conveyor belts, a blackout and two bombs at once; being blown up costs one of three lives and runs the match again. Hot passes with under a second left chain a streak up to x5, and the start and end screens show the furthest venue reached.
- **web console**: Activities has a tenth game, **Crossing Rush**, a lane-crossing race. Planny and two rival hoppers hop up a strip of lanes a cell at a time, one hop a press: roads of cars and trucks, rivers where you ride the logs and turtles, train tracks that flash red and ring a bell before the train, and grass with bushes and rocks in the way. A car, a train or the water sends a hopper spinning back to the last grass row rather than out, so every heat ends with someone at the top, and the view follows you with a race bar beside it showing everyone's height; a hopper sent back stands dazed for 2 seconds before it may hop again. Pickups stack as you land on them and space uses the oldest first: **Spring** leaps two cells the way you face, **Shield** lets cars and trains through for 3 seconds and **Horn** stops the nearest road, while a **Coin** scores at once; the stack empties every heat. First to the top wins the heat and moves on through nine zones, from **Side Street** to **Rush Hour** and then endless, quicker Rush Hours, bringing logs, trains, diving turtles, trucks and lanes that speed up, a dusk lit by headlights, rivers that turn round and icy lanes that slide you on, and four rivals with their own ways (the careful Hopper, the Daredevil, the pushy Bruiser and the Tagalong, who follows you up). Second or third costs one of three lives and runs the heat again, though the first two zones let second place through. Quick forward hops climb in pitch, clean wins in a row multiply the win up to x3, a car through the cell you just left is a close call, and the start and end screens show the furthest zone reached.
- **web console**: Activities has an eleventh game, **Bounce Road**, a fast scrolling road seen from above. Planny races a springy toy car up a road laid across a giant's house and yard: hold up to drive, the arrows to steer and press space to jump, a faster jump going further. Bump a rival toy car sideways off the road, or land on one 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 (crushes, bump-offs, jumps over holes, trains, balls and barriers, a ramp's big air, close shaves, boost strips) steps a combo that multiplies the points up to x4. Ten stages, each bringing something new, from **Chalk Lane** on the patio through **Kitchen Floor**, **Toy Room**, **Garden Pond**, **Rooftop Gutter** and **Night Lights** (in the dark) to **Monster Mash**, where the Monster truck must be stomped five times, then round again, quicker and meaner. The road has cracks, broken bridges, drawbridges, swaying bridges, road that crumbles behind you, ramps, boost strips, oil slicks, cone and toy-block chicanes, a toy train crossing, rolling balls, sprinklers, gusts of wind and things that fall where you are heading, every hole jumpable at 80% of the top speed after a warning sign and a run-up. Ten rivals, all keener the further you go (they block your line, swerve from under your landings, hop the gaps and keep the pack close): the Zigzag, the Brick (who brake-checks you), the Frog, the Nudge, the Hauler, the Sneak (who drops cones), the Bruiser, the Racer to catch, the Cop (who chases and pushes you toward the edge) and the Monster truck. There are four power-ups (Spring, Bubble, Nitro and Mega wheels), and every car is drawn in full toy-car detail. A stage line pays a bonus for beating its par time, a stage crossed with no life lost gives a life back, and the start and end screens show the furthest stage reached.
- **web console**: Activities has a twelfth game, **Ghoul Rush**, 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, lit only by his glow, his flashlight's cone, candles, moonlight and the odd flash of lightning, with eyes burning in the dark around him: hold left or right to run, up jumps (let go early for a short hop), down drops through a shelf, and held space fires his flashlight blaster ten times a second the way he faces. Grab each room's key, then reach its door, while a horde pours in from the edges of the view. **Zombies** sprint once you are close, **crawlers** drag themselves up through loose boards, **bats** swoop at your chest, **ghosts** can only be hit (or hurt you) while solid, **skeletons** throw bones you can shoot down, **hellhounds** crouch growling and lunge, **widows** drop from the ceiling as you pass under, **wraiths** shriek and dive at where you were, and **bloaters** lob acid that leaves burning puddles and burst when they die; a shot to the head or a stomp from above doubles a kill, and quick kills build a chain up to x10 that runs out in 1.2 seconds. Pits, one-way shelves, crumbling boards and falling chandeliers (which crush whatever is under them) fill eight rooms, from the **Foyer** to the **Crypt**, with a boss every fourth: the **Rotting Gourd**, a giant rotten pumpkin that hops to where you stood and shakes loose gourdlings, and **Old Rattlebones**, who throws volleys of bones and slams shockwaves you jump. Power-ups (Spread shot, Rapid fire, a Garlic shield and a 1UP), souls, a time bonus per room that sends zombies in from the edges once it runs out, a flawless bonus and a life back for each boss add up, a hit or a fall costs one of three lives and restarts the room, and the start and end screens show the most stages cleared in a run.
- **web console**: **Mini golf** now has six themed courses of eighteen holes each, picked from a **course dashboard** that opens from its card: a card per course with a picture of one of its holes, its line, its par and your best round on it, walked by the arrows like the game picker, with **All courses** to get back; once a round is over, space or a click goes back to the dashboard rather than replaying the same course. **Pirate Cove** and the **Caves of Doom** each grow from nine holes to a full eighteen, and four new courses join them: **Dino Valley** (a prehistoric jungle and volcano), **Candy Carnival** (a sweets land), **Cosmic Glow** (black-light glow golf in outer space, where black holes bend your putt) and **Frosty Peaks** (a winter wonderland where the ball glides on ice). Two new hazards came with them: ice, where the ball barely slows, and gravity wells that pull a putt in or push it away. Each course keeps its own best round (`activityBestGolfPirate` to `activityBestGolfFrost` in `looks.json`), and the Mini golf card on the picker counts the courses you have a best on.
- **web console**: the Activities window now opens on a **picker**, a card for each game with a little cover scene, a line about it, its best score and a **Last played** tag, in place of the old row of buttons above the board. A card opens its game, the arrows walk the cards, and **All games** goes back. One game plays at a time: leaving for the picker keeps the round paused on its card (and reopening the window goes straight back into it), and picking a different game ends it.
- **web console**: **User Preferences → Sounds & activities** has a **Play game sounds** switch under Activities, so the games can play silently while the page's own cues (a new question, a reply) still sound. It covers every game's sounds and the window's own (the 3, 2, 1 and the new-best burst), turning it off silences a game playing now, it is grayed out while **Play sounds** is off (and keeps its tick for when sound comes back), and **Back to default** turns it back on. Saved as `activitySounds` in `looks.json`.
- **web console**: Ghoul Rush's flashlight blaster now heats up, so holding (or hammering) space is no longer the whole game: about three seconds of fire go at the full ten bolts a second, then each bolt waits longer, down to one a second, with a **LIGHT** gauge always at the right of the HUD: a bar that 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 (reading **HOT** and throbbing) past it, and in Rapid fire's pink while that runs. Let go of fire and it starts cooling after a fifth of a second, the hottest blaster in about two seconds, so firing in bursts keeps it quick. Rapid fire's bolts add no heat and ignore it.
- **web console**: Ghoul Rush has four more power-ups that are not about the blaster: a **Lantern** pulls the dark far back for 15 seconds, **Bat wings** give one flap in the air per jump for 12 seconds (a press just before landing still jumps on landing), a **Church bell** holds every monster but a boss still for 4 seconds and lets none in until it stops or you reach the door, and an **Hourglass** puts 20 seconds back on the clock. They lie in the Gallery, Library, Kitchen, Conservatory and Attic and drop from kills, and power-ups now drop twice as often, so the blaster ones turn up as often as before.
- **web console**: every Ghoul Rush room but a boss's now has a **TIME** clock in the HUD (70 to 80 seconds by the room's length), red with a tick a second in its last ten; at none it costs a life and the room starts over with a full clock.
- **web console**: Ghoul Rush has music: a track for each room (a haunted music box in the Foyer, a 9/8 synth in the Portrait Gallery, creeping pizzicato in the Library, a gothic organ for the Rotting Gourd, a cauldron swing in the Kitchen, a 5/4 synth in the Conservatory, a phonograph foxtrot in the Attic and a dark-synth fight with Bones in the Crypt). Each plays only its drone and bass in a quiet stretch and grows fuller as monsters close in and in the clock's last ten seconds, with all of it in a boss fight. It plays under **Play game music**, like Sunset Drive's songs.
- **web console**: Light Trails has background music: five recorded songs that play one after another, each in full, for as long as a run lasts. Every new run shuffles them into a fresh order and starts the first from the top, never the song the last run was playing, and once all five have played they are shuffled again. A pause picks the song up where it stopped. It plays under **Play game music**, at the game's own **Music** slider. The light cycles' engine drones (yours and the nearest rival's) are much quieter now, so the songs carry the run, and the game's other sounds are a little louder (1.4 times), so they still cut through.
- **web console**: a game with music has its own **Music** volume slider in the Activities window, beside **Full screen**, remembered per game. Sunset Drive starts at 70 and Ghoul Rush at 50, so its music sits under the house's sounds. The slider is dimmed, and says why, while **Play game music** is off.
- **web console**: Ghoul Rush hides treasure up high, over each room's key shelf (but a boss's): **crystals** worth 250 points each, and in three rooms **Silver bolts**, a power-up found nowhere else whose bolts go on through every monster they hit for 10 seconds. None of it is reachable with one jump; a jump and a **Bat wings** flap from the key shelf takes it, and each of those rooms now has Bat wings on the way.
- **web console**: in Ghoul Rush, a zombie, crawler, spitter or gourdling that reaches the edge of a pit or a drop now stops for a moment, a "?" over its head as it thinks about it, then leaps: across a pit up to 10 units wide to floor at its own height, further down to a lower floor (the Kitchen's 12-unit pit from the counter to the floor), and straight down off a ledge. Wider pits and floor higher than a step still stop it.
- **web console**: Ghoul Rush's house drone is softer, and softer still in the Portrait Gallery and the Attic, where it is pitched higher and carried most.
- **web console**: **R** starts an Activities game's round over, from the 3, 2, 1, whether it is running, paused or finished. In full screen, the panel beside the board now holds the game's **Music** slider too.
- **web console**: in Ghoul Rush, two or more zombies, runners, crawlers or gourdlings bunched under you while you wait on a shelf now climb over each other at once, arms up, to reach you, so camping over a crowd for a run of stomps no longer works; the pile comes back down once you move off. A climber's raised arms hurt you if you land on them; only a landing on its head, between them, is a stomp.
- **web console**: Ghoul Rush no longer rewards camping near the door to farm the endless stream of monsters: each kill of the room's horde (and of the dead that come once the bonus runs out) is worth 80% of the last one in that room, down to a tenth of its points, and never drops a soul or a power-up. The room's own monsters score and drop as before.
- **web console**: Ghoul Rush has three new monsters that sometimes come in place of the usual ones: the **Runner**, a skinny zombie that sprints and falls to one bolt, and gives a high shriek and a red "!" at the screen's edge as it comes into view, so one coming up behind you is heard first; the **Glutton**, a fat, slow zombie that takes five times a zombie's bolts (15), is only bruised by a stomp, and never leaps or climbs; and the rare **Huntsman**, a big spider on the floor that crouches, then springs at you as high as you are (up onto a shelf) and takes twice a widow's bolts.
- **web console**: Ghoul Rush's zombies, runners and crawlers now climb walls up to 8 high after the same moment's thought they give a pit, and walkers cross a crumbling board laid level with the floor over a pit while it is there (falling in if it gives way under them) instead of stopping at its edge.
- **web console**: the Rotting Gourd fight in Ghoul Rush is harder: the Gourd picks one of three moves at random, never one three times running: its hop onto where you stood, a spit of two acid globs (after a half-second shake) that leave burning puddles, or a quake that leaps straight up and sends a shockwave along the floor both ways when it lands (a glowing orange crest trailing green embers, lit in the dark, so it is easy to see coming). To keep that fair, the Ballroom's arena is now stacked with balconies in three tiers to move around on: up on one over the Gourd's head it only spits at you, never hops; each corner keeps a pocket its hop cannot land on; it shakes a little longer (0.85 s) before each move and has less health (65, down from 80); and its gourdlings jump up onto the balconies after you and run off their ends to follow you down.
- **web console**: every Ghoul Rush monster now has its own voice, a sound for each thing it does: coming in, climbing or hopping, growling, lunging, shrieking, diving, spitting, throwing, taking a hit and dying. That covers the zombie, runner, glutton, crawler, bat, ghost, wraith, skeleton, gourdling, hellhound, widow, huntsman and bloater, and both bosses, who also have their own wake-up, hop, slam, wind-up and death. A zombie's gurgle, a skeleton's hollow cackle and a hellhound's growl now tell you what is coming before you see it. Rapid fire on one monster plays its cry at most about seven times a second, and a Rattlebones volley plays once for its three bones.
- **web console**: Ghoul Rush is now played in **stages**, picked as you go, so no two runs go the same way. Every run starts in **the Long Hall**, a long, easy walk with only zombies. Out of it, and out of every boss's room, you choose the next stage from two you have not played that run (one, once a single stage is left). Each card shows the stage with its boss standing in it, its name and its boss; left and right pick one out, space or up goes in. A stage is three rooms and then a boss: **the Manor** (Foyer, Portrait Gallery, Library, then the Rotting Gourd in the Ballroom) and **the East Wing** (Kitchen, Conservatory, Attic, then Old Rattlebones in the Crypt). Clear every stage and you **escape**, a win with its own fanfare, instead of the rooms coming around again. Each stage cleared makes the next one's monsters quicker, tougher and let out sooner, and its boss stronger and worth more. A boss now always gives a life back, and you can hold up to **nine** lives (up from five); the 1UP also drops a little more often. The start and end screens show the most stages you have cleared in a run, with a dot per stage.
- **web console**: an Activities game can go **Full screen**: a button under the board (or `F`) gives the game the whole screen, with the browser's own full screen where it allows one. The board grows as big as its shape allows, and the room its shape leaves holds a panel with the game's name, the score line (score, the meter toward the best, the best) and **Exit full screen**: beside the board on a wide screen, along the bottom on a tall one, and where the shape leaves no room (Sunset Drive on a 16:9 screen) the board gives up a little width for it, so nothing is ever laid over the play. The pointer hides after two still seconds. `F`, `Esc` or **Exit full screen** puts it back. In the desktop app the window goes full screen too, with the console laid over the bar and the terminal. When Plan2Code needs you (a question, a sign-off or a finish) and pauses the game, the window goes back to its own size so the banner and the page show.
- **web console**: every Activities game now has a full soundscape, still made in the browser with no audio files. The sound engine gained noise, sweeping filters, layered sounds and held **hums** that follow the action, so engines rev and fall away with your speed (Sunset Drive's V8 shifts through five gears, with tire squeal, wind and traffic that passes with a Doppler drop), Rapids Run's outboard purrs over the river, Bounce Road's toy car buzzes ahead of a Monster truck's rumble, Bumper Ring's electric cars whine over a crowd, light cycles drone, fuses hiss louder as they burn down, and every Mini golf course and Ghoul Rush room has its own ambience. Crashes, splashes, explosions, landings, pickups, combos, bosses, new bests and game over each get a sound of their own in every game. A hum fades by itself the moment a game pauses or closes, and **Play sounds** still silences everything.
- **web console**: Activities games can play chiptune music, written as note data and played by a small sequencer in the page (pulse-wave leads and arpeggios, a triangle bass and a noise drum kit). A track builds with the action. Sunset Drive gives each road its own song (surf rock on Sunset Coast, flamenco on Canyon Road, a 70s funk chase through Maple Valley, uplifting trance on Snowcap Pass, darksynth in Neon City and retro sci-fi on Starlight Highway), each starting as a lone bass line at a standstill, bringing in drums, chords and the lead as you pick up speed, and playing quicker on nitro; reaching a new road crossfades into its song. It is off until you turn on **Play game music** in **User Preferences → Sounds & activities**, and it fades the moment a game pauses or closes.
- **web console**: every Activities game with lives shows them as a solid pink pill with a heart per life, readable at a glance, and the banners in Bug Hunt, Sunset Drive, Stack Deploy and Bounce Road now fade almost clear while you, or whatever is coming at you, are under them, as the other games' banners already did.
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
- **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents & models** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli <id>` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed.
- **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app.
- **desktop app**: the taskbar entry now shows when Plan2Code needs you, mirroring the console's tab icon. Windows: a green dot on your move (a finished screen too, while it still offers a button to press, such as back to the dashboard or a review), a red dot on needs attention (or a finished screen whose press was never collected), none while busy or once nothing is left to press, and one short burst of flashes when the window is not focused (the button stays lit until focused). macOS: a red `!` dock badge on needs attention and one bounce (the system badge cannot be green). Linux: a count badge where the desktop supports it, plus the urgency hint. The dot clears when the agent ends, the page reloads or the page stops answering. **User Preferences → System → Desktop app** (inside the app only) has the switch **Show on the taskbar when Plan2Code needs me**, on by default and saved in the app's own `app.json`.
- **pr-prep**: a new dashboard utility, **Get a PR ready** (`/plan2code-pr-prep`), for the moment before you open a pull request. It reads what changed on the branch, asks first whether to include uncommitted work, and picks the checks that cover the changes from the project's test map (or, with no map, from commands it finds in the project's config files and confirms with you), each with a reason, plus the full suite when shared ground was touched. You untick what to skip; it runs the rest with a timeout per check and says **Ready**, **Ready with notes** (something trimmed, timed out, could not start, or a changed file no test covers) or **Not ready**. It writes a PR description to copy, following the repo's pull-request template when there is one, with the create-a-PR link (no `gh` needed), and offers to save the report as `PR-READINESS-<date>.md` in the branch's spec folder. It never commits, pushes or opens the PR.
- **test**: a new dashboard utility, **Write missing tests** (`/plan2code-test`). It asks where to look (the branch's changes, a folder or the whole project), finds the source files no test covers by matching them to tests by name, folder and imports, and offers a real coverage run on top when the project already has a coverage tool (Node's test runner, Jest, Go, or Vitest, pytest-cov and Coverlet when installed), never running it silently. The plan opens with **How this project writes tests** for each runner (folder, file naming, command, helpers, assertion style), so the new tests match the old ones; on your approval it writes and runs unit and integration tests. It never changes source code: a test that exposes a real bug is kept, on a yes, as the reproduction for `/plan2code-diagnose`. A project with no runner is offered its language's built-in one (`node --test`, `unittest`, `go test`, `cargo test`), and a job past 8 source files, 8 new test files or 2 runners can **Continue** with the top 8 gaps or **Escalate** to a PLAN-DRAFT that `/plan2code-1-plan` resumes at Phase 2.
- **test map**: projects can describe their tests in one Markdown table under `## Test map` in `AGENTS.md` (or behind one link to `.agents-docs/AGENTS-test-map.md`), with the columns `Area`, `Paths` (globs), `Run` (the command for that area) and `Shared` (`yes` when a change there reaches everything). PR Prep and Test read it to pick checks and runners, and offer to write or update it at the end of a run. **Init** proposes one when it finds test commands, and **Init Update** checks an existing map's paths and commands still match the project and offers one when tests exist but no map does; nothing is written without a yes.
- **git**: after a push or publish, or when the branch is pushed with nothing left to commit, the git skill now names `/plan2code-pr-prep` as the likely next step: run the checks and write the PR description.
- **web console**: a one-answer question (a pick-one list, or a menu) now has a **Clear** button under its options that takes the card back to how it arrived: no pick, and nothing in **Something else**. A radio pick cannot be unticked by clicking it again, so before this a stray pick could only be swapped for another. The button shows only while the answer has not been sent.
- **contributors**: `npm run play` opens the web console straight from `src/` with the server reading each page file fresh, so a change to an Activities game shows on the next page reload, without `npm run build:skills` or a reinstall.
- **first run**: when no agent CLI can be used (a fresh install, an agent installed but off PATH, the only agent gone after an uninstall, or `--cli` naming a missing agent), the `plan2code` command and the desktop app show one **setup page**: the web console running an agent-less `setup` workflow. It lists each built-in agent (Claude Code, Devin, Codex) as **found**, **found outside PATH** or **not found**, with install commands for your OS, an install page link and **Check again**, plus four starter templates (Pi, Gemini CLI, OpenCode, GitHub Copilot CLI). **Use it from here** makes an off-PATH agent usable without a restart; once an agent is found the run carries straight on, the same browser tab (or the app's launch card) picking up where it left off. With no window or no person, the command prints the install steps and exits 127. One shared agent list (`src/launcher/agents.json`, installed to `~/.plan2code/bin/`) and one lookup rule (`agent-lookup.mjs`, with a Rust twin in the app held to the same fixture cases) serve the launcher, the console and the app; the maintainer skill `plan2code-model-update` is now `plan2code-launcher-update` and re-checks the list's install data too.
- **desktop app**: the Implementation Loop setup has **Set strength per phase**: pick Thrifty, Balanced, Best or Match my session for each phase of the spec, and each phase's agent starts on the model and effort that strength maps to for the loop's agent. A phase left alone runs on the launch choice, so a loop with the toggle off behaves as before. The phase's helpers follow its strength, the one retry steps up a strength, and the loop strip and the loop report show what each phase ran on. Claude Code and Devin ship with a mapping; for any other agent **Strengths in the loop** in User Preferences, Agents & models, maps each strength to one of its models.
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface and runs Claude Code, Devin, Codex or your own agent in a terminal panel it owns, with every console page (Ask, Workspace, Help, Preferences, Git, Notebook) inside the window. **New Session** replaces the agent with a fresh one on a brief the app builds from its own record of the session, so in-progress work carries over. **Update skills** brings the installed skills level with the app, and the taskbar shows when Plan2Code needs you. `plan2code` opens the app when a desktop is available; `plan2code --classic` keeps the terminal-only flow.
- **implementation loop**: the app builds a spec phase by phase, each phase in a fresh agent, and writes a report. **Set strength per phase** runs each phase on the model and effort of a chosen strength (Thrifty, Balanced, Best or Match my session), the loop strip and report show what each phase ran on, and the end screen offers **Back to the dashboard** and a way to ask a stopped loop a question. It replaces the `plan2code-loop` CLI (see Breaking).
- **helpers**: helpers (subagents) now run at a strength and effort matched to their job (`light`, `standard`, `strongest` or `inherit`), never tied to one model or vendor, and Plan and Revise Plan offer them too. In the web console, the **Subagents** dialog turns helpers on or off per project and skill and has a **Helper strength** choice (Balanced, Thrifty, Best or Match my session), and the Subagents tab shows what each helper ran with.
- **custom agents**: add your own agent CLIs under **User Preferences → Agents & models** (saved in `~/.plan2code/agents.json`) and start them from `plan2code --cli <id>` or the app. When no agent can be used, a first-run **setup page** lists each built-in agent as found, found outside PATH or not found, with install commands for your OS, starter templates and **Check again**, then carries on once an agent is found.
- **pr-prep**: a new utility, **Get a PR ready** (`/plan2code-pr-prep`), picks the checks that cover your branch's changes, runs them, says Ready, Ready with notes or Not ready, and writes a PR description to copy. It never commits, pushes or opens the PR.
- **test**: a new utility, **Write missing tests** (`/plan2code-test`), finds source files no test covers and, once you approve its plan, writes tests in the project's own style. It never changes source code. Both utilities read an optional **test map** (a `## Test map` table in `AGENTS.md`), which Init can propose.
- **activities**: a die in the console's top bar opens a window of thirteen small games to play while you wait: Snake, Mini golf (six 18-hole courses), Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash. A game pauses the moment Plan2Code needs you, has sounds and optional music, can go full screen, and keeps its best score privately. Off until you turn on **Show Activities** in **User Preferences → Sounds & activities**.
- **web console**: start Pathfinder, Plan, Quick Task or Revise plan from a **Notebook** tab: the skill's first box arrives filled with the tab's text and pictures, and the agent reads it only once you send it.
- **web console**: answer boxes render Markdown live, **Ask for suggestions** asks Plan2Code what it would pick and why on an open question, a **Clear** button takes a one-answer question back to unanswered, a plan's Build order card has **Combine phases**, and a spec that is not documented yet shows its Pathfinder map and plan draft as read-only tabs.
- **workflows**: Finalize offers a final review and asks once before its rating questions, Diagnose lets you skip two of its opening questions, and Git names `/plan2code-pr-prep` as the likely next step after a push.
- **contributors**: `npm run play` opens the web console straight from `src/`, so a change shows on the next page reload without rebuilding or reinstalling.
### 💥 Breaking
- **the `plan2code-loop` CLI is no longer an install target, and the package is removed.** The `plan2code-loop/` directory is deleted, and with it the installer's `O. LOOP CLI` advanced option and the loop's install, update and uninstall wiring. Its docs (`.readme/autonomous-loop.md`, `.agents-docs/AGENTS-plan2code-loop.md`) are gone too, and every remaining mention across the docs, templates, metadata and comments is removed or reworded. The desktop app's **Implementation Loop**, which superseded the CLI, is a separate feature built into the app and is unchanged.
**Stale installs are still cleaned up.** `install.js` keeps a small `removeLegacyLoopShims()` step that removes the old global artifacts (`plan2code-loop`, `plan2code-loop.cmd`, `plan2code-loop.ps1` and `node_modules/plan2code-loop` under the npm prefix) when they are present. `update()` runs it once before reinstalling and quietly skips a stale `"loop"` entry in `~/.plan2code/install.json`; uninstall runs it too.
- **the `plan2code-loop` CLI is no longer an install target, and the package is removed.** The `plan2code-loop/` directory and the installer's `O. LOOP CLI` option are gone; the desktop app's **Implementation Loop** supersedes it. Stale installs are still cleaned up: update and uninstall remove the old global `plan2code-loop` command and npm package when they are present.
### 🔧 Changed
- **web console**: **User Preferences** is now four tabs in a side list (a sideways strip on narrow screens) instead of one long column: **Appearance**, **Agents & models**, **System** and **Sounds & activities**. Look and sound settings still save as they change and now show a **Saved** mark; **Back to default** resets only its own tab (and is hidden on the two tabs it has nothing to reset), and **Done** reads **Close**. **Agents & models** is a summary table of Claude Code, Devin, Codex and your own agents, with each one's models and a **Found** / **Not found** on PATH badge, and **Edit** opens a full form per agent with **Save** and **Discard**, an **Unsaved** badge and a Save / Discard / Keep editing prompt before an unsaved edit is lost. The separate Models section is gone: each built-in agent's form lists the models that come with Plan2Code beside your own. Help shares the same tab handling, and its User Preferences topic now covers every tab.
- **docs**: all prose, help text, skill prompts and comments now use US English spelling (color, gray, behavior, canceled, -ize), and `npm test` checks it (`scripts/test-us-english.mjs`).
- **web console**: **User Preferences → Appearance → Highlight color** now offers 38 colors in two rows of nineteen, covering the range of a Paint-style picker: new **Maroon**, **Peach**, **Brown**, **Cream**, **Lemon**, **Forest**, **Mint**, **Aqua**, **Lavender**, **Pink** and **Mono** (near-black in light mode, near-white in dark). Five near twins were merged (Copper into Rust, Marigold into Gold, Mustard into Lemon, Jade into Emerald, Lilac into Violet); a saved choice of one of those keeps its twin instead of falling back to Ocean.
- **web console**: the **Subagents** dialog is wider and shorter, like the Notebook: Helpers and At most share a row, and the four Helper strength choices sit side by side, each wearing the Subagents tab's colored level badge (Thrifty light, Balanced standard, Best strongest, Match my session plain), now ordered from lightest to strongest.
- **launcher**: after you pick the agent, `plan2code` now asks whether to turn its permission prompts off (Yes by default, so pressing Enter starts it as before), and only for an agent that has a flag for it: every built-in does, a custom agent only when it has bypass arguments. `plan2code --keep-permissions` keeps the prompts without asking; with no terminal to ask on, prompts are off as before. The installer no longer prints its warning about the command starting agents with prompts off.
- **launcher**: when no agent CLI is installed, `plan2code` now prints each supported agent's install command and official page, and points at User Preferences → Agents & models for another CLI, before it exits.
- **desktop app**: a clean start is now one press. Pathfinder's **Start fresh** menu option reads **Start New Session** under the app, and sending it asks the app for its New Session (the resume command is copied first; declining the app's confirm leaves the usual finish). A finished step that names a skill to run next shows a **Start a New Session** button beside its command, also copying the command first. The plain web console keeps its wording and does neither. The app's console frame also now allows clipboard writes, so the copied command and every **Copy** button can reach the clipboard there.
- **desktop app**: the launch card's agent choice is built from the agents that are installed, so a machine with only Devin or Codex starts on it with Start enabled, instead of assuming Claude Code.
- **desktop app**: the window now opens maximized, filling the screen with the title bar and taskbar still showing; restoring it from maximized gives the old 1280x800 size.
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching the terminal's own default; untick it for an agent that keeps its normal approval prompts.
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight color. Its confirmation no longer claims "What it was doing is not saved" (not always true).
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
- **desktop app**: the collapsed terminal panel's **Expand** button now reads **View Agent Terminal**, and docked right it reads top to bottom instead of running off the edge of the narrow strip.
- **desktop app**: the agent no longer prints the console's web address in the terminal panel, since the page is already in the window beside it: `terminalLine` under the app points at the dashboard instead, and the agent contract says to give no link there.
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter (and, under Claude Code, its send-now chord) into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
- **desktop app**: **New Session** now starts the fresh agent on a new console session, so the session meter starts over at green. Before, the fresh agent joined the window's old session, and the meter stayed red after the very press it asks for. The brief of where you were is still written from the old session first, and the old console shuts itself down once the window moves on.
- **web console**: the **Wrapping up** dialog after **Stop session** no longer closes itself when the stop lands: it turns into **Done**, with every step ticked, and stays up until you close it, so someone who stepped away comes back to an answer. Its "you can close the window/tab if you need to" line is gone.
- **web console**: a plan's **Build order** card has a **Combine phases** button beside **No changes**. One click fills the box with a request to merge phases where possible while keeping each to a clear concern. It shows only in Plan and Revise plan, where the breakdown is phases.
- **web console**: Help now reads right in the desktop app throughout, not just in the topics fixed before: what this page is and how long it runs, the troubleshooting table and its diagram, scroll memory, drafts, the session meter's red advice, Ask's "no agent" line and Privacy's link and address notes all name the app's window, its terminal panel, **New Session** and **Reconnect the console** instead of a browser tab, a link or a new conversation. The status line's approval hint says "the terminal panel" there too. In a browser, Help is unchanged.
- **desktop app**: the top bar's buttons now look like the console's own: rounded, quiet until hovered, then in your highlight color from User Preferences (the app keeps it for the next launch), with **New Session** outlined in it as the likely next step.
- **desktop app**: the New Session confirmation shows Planny, drawn like the console's own (outlined shell, star eye, smile), holding a steaming cup of coffee, and its buttons use the console's style: **New Session** in your highlight color, **Cancel** a plain button. The same highlight applies to the panel's other one-button prompts, such as **Retry** and **Reconnect the console**.
- **desktop app**: the top bar is rebuilt around two menus and one next step. The project shows as its folder name, with the full path and **Change project** in its menu; **New Session** always sits just left of the agent's menu, which carries a state dot, an amber **checks off** badge in place of the "Permission checks are off for ..." sentence, and **Change agent** once the agent has ended. The console's and the skills' messages share one slot at the right end that shows the most pressing step with its button (**Reconnect the console**, **Update skills**) and "+N more" for the rest, so the bar no longer overflows when several things go wrong at once. The repeated "Plan2Code" label, the full path, the "agent:" prefix and the long "Nothing starts until you press New Session" line are gone.
- **web console**: **User Preferences → Agents & models** is rebuilt as a master-detail split: the agent list stays pinned on the left and picking a row opens that agent's form in the pane beside it, so moving between agents no longer goes through a summary-to-form round trip. The same split carries the agent-less setup page (pick list left, state and way forward right). Behind it `agents-view.js` is split into a `screens/agents/` component set (data, list editor, summary, form) behind the unchanged `mountAgentsView` API, and the agent styles live in their own `styles/agents.css`. The setup page's starter templates are offered on the tab too, under **Or start from a template**: **Use this template** opens the new-agent form prefilled. Every capability is kept: per-form Save and Discard, the Unsaved prompt, Test, Delete, the 409 Save anyway path, and the setup states and templates. The Preferences dialog itself now follows the Card width pick, never wider than the wide preset (1080px), instead of a fixed 880px.
- **web console**: **User Preferences** is now four tabs (Appearance, Agents & models, System, Sounds & activities), **Agents & models** is a list beside a form for the picked agent, and **Highlight color** offers 38 colors.
- **web console**: reads right inside the desktop app. Advice that assumed a terminal (the session meter, the update banner, the finished-step guide, Help) points at the app's **New Session**, **Update skills** and **Reconnect the console** instead.
- **launcher**: `plan2code` asks whether to turn the agent's permission prompts off (Yes by default; `--keep-permissions` keeps them), and with no agent installed it prints each agent's install command and page before it exits.
- **docs**: all prose, help text, skill prompts and comments use US English spelling, and `npm test` checks it.
### 🐛 Fixed
- **custom agents**: on Windows, a custom agent whose installer added its folder to the user PATH is now offered by `plan2code` and the desktop app every time, not only from a terminal opened after the install. Both read the saved PATH as well as the one they inherited, and the agent starts with it too.
- **web console**: on the dashboard, canceling one spec's Delete and quickly opening another's no longer leaves **Delete it** doing nothing; the first dialog's late close cleared the second dialog's spec.
- **web console**: a handoff's **Copy** button keeps showing **Copied** (or **Copy was refused**) when the dashboard redraws while the clipboard answers, instead of the word landing on a button that was already replaced.
- **web console**: a finished screen's press (**Commit it now**, **Update CHANGELOG first**, **Back to the dashboard**, **Continue here**, a review) that nothing picks up, because the agent's turn ended while the screen waited, no longer says "Opening Changelog…" forever. After a minute of silence the line beside Planny says Plan2Code is not running and the choice is saved, with **continue** to type in the terminal (a button that types it there, under the app).
- **desktop app**: under Claude Code, the console's **continue** button also sends Claude Code's send-now chord (ctrl+x ctrl+s), so a `continue` it held as a queued message behind a stuck turn is delivered in one press instead of waiting in the terminal.
- **desktop app**: links that leave the console (**Open pull request**, links in documents, the feedback button) open in the default browser instead of doing nothing; when no browser can be started, the page shows the link with a **Copy** button to paste into one.
- **web console**: answers sent and not picked up bring up the "not running, type **continue**" help after a minute of the agent's silence (three when it said it was working), instead of after its quiet allowance, which a build can set to half an hour.
- **web console**: a failed Send says why: the lost-contact state and its reconnect help at once when the console is gone, the console's reason when it refuses the send, or that the console is still up and Send can be pressed again.
- **desktop app**: a test console started inside the app (for example by `cargo test` during a build) can no longer take over the window. Before, the window followed it, then fell back to an empty dashboard once the test shut it down, and the build's question sat on a page no one could see. The app now ignores any page whose session is not in its own console store.
- **desktop app**: a console too busy to answer a health check in time (a machine running a test suite) is given a second, longer look and then resumed on the same session. It is no longer swapped for a fresh, empty dashboard mid-build.
- **desktop app**: the Implementation Loop's end screen offers **Back to the dashboard** next to its other actions, on a finished loop and a stopped one, and it works with no agent running (it opens a fresh dashboard console session in the frame). The screen's status line also tells the truth now: it reads "Loop finished. Pick what happens next." (or "The loop stopped.") as your move instead of spinning "Starting Building + review…", so the taskbar dot goes green there instead of staying dark while the loop's finished page waits.
- **custom agents**: on Windows, an agent whose installer added its folder to the user PATH is offered right away, not only from a terminal opened after the install.
- **web console**: a finished screen's press that nothing picks up now says Plan2Code is not running and how to continue, a failed Send says why, and links that leave the console open in the default browser from the desktop app.
- **desktop app**: a test console started during a build can no longer take over the window, and a console too busy to answer a health check is no longer swapped for an empty dashboard mid-build.
## v2.11.1
+1 -1
View File
@@ -16,7 +16,7 @@ The web console is the main way in: a local page where questions, documents, bui
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) |
| Update | `plan2code update` | Updates everything that was installed, with no menu; never uninstalls anything |
| Update | `plan2code update` | Updates the skills, command, app and status line, with no menu (metrics and the bot only from a git checkout: `node install.js`); never uninstalls anything |
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
+706 -125
View File
File diff suppressed because it is too large. Load diff
+13 -4
View File
@@ -2305,10 +2305,12 @@ function getLauncherShims(binDir, nodePath = process.execPath) {
'@echo off',
`rem ${LAUNCHER_MARKER}`,
`if not exist "${cmdNode}" goto p2c_path_node`,
`"${cmdNode}" "${cmdDest}" %*`,
'exit /b %ERRORLEVEL%',
// Each command ends its own line with `& exit /b`: cmd.exe reads a running .cmd by byte
// offset, and `plan2code update` rewrites this file while it runs, so nothing may be read
// after the command returns. A bare `exit /b` keeps the command's exit code.
`"${cmdNode}" "${cmdDest}" %* & exit /b`,
':p2c_path_node',
`node "${cmdDest}" %*`,
`node "${cmdDest}" %* & exit /b`,
'',
].join('\r\n'),
},
@@ -2597,7 +2599,7 @@ function uninstallLauncher() {
const shortcut = getShortcutFile();
if (isOurShortcut(shortcut)) remove(shortcut);
forgetInstalled('launcher');
for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD]) {
for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD, AGENTS_DEST, AGENT_LOOKUP_DEST]) {
if (fs.existsSync(file)) remove(file);
}
try {
@@ -2855,6 +2857,13 @@ async function update({ steps = UPDATE_STEPS, cleanShims = removeLegacyLoopShims
const results = {};
for (const piece of INSTALL_PIECES) {
if (!pieces.includes(piece) || piece in results) continue;
// The metrics and bot commands run from this folder: from npx's cache (which the launcher
// note above calls free to delete) they would break once it is cleared, so only a checkout updates them.
if ((piece === 'metrics' || piece === 'bot') && !fs.existsSync(path.join(__dirname, '.git'))) {
results[piece] = 'kept (update it from a git checkout: node install.js)';
console.log('');
continue;
}
const outcome = {};
try {
const code = await steps[piece]({ quiet: true, unattended: true, outcome });
+1
View File
@@ -10,6 +10,7 @@
//! REPORT <json> write <json> as `loopOutcome` into the session's state.json
//! (PLAN2CODE_CONSOLE_HOME and PLAN2CODE_CONSOLE_SID name it), say
//! `REPORT written` (`REPORT unavailable` when either is missing)
//! ENV <name> print the variable as `ENV <name>=<value>`
//! HANG say `HANGING`, then go silent for good (no more lines read)
//! <other> echoed back as `echo: <line>`
//!
+24 -2
View File
@@ -631,8 +631,30 @@ pub fn launch_spec(
spec.args,
&std::env::var("PATH").unwrap_or_default(),
);
spec.program = program;
spec.args = args;
if program == "cmd" && args.first().map(String::as_str) == Some("/c") {
// A shim wrapped for cmd: quote the line, hand it over in a variable
// and keep cmd from trying the project folder before PATH, exactly as
// a custom .cmd agent does (a same-named file in a cloned repo must not
// run in the agent's place). Accepted trade-off: the variable reaches
// everything the agent starts, so a `cmd` it runs as a tool no longer
// finds `gradlew` or `setup.bat` in the project without `.\`; custom
// .cmd agents already behave this way.
let line: Vec<String> = args[1..].iter().map(|arg| quote_for_cmd(arg)).collect();
spec.env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
spec.env.push((
"NoDefaultCurrentDirectoryInExePath".to_string(),
"1".to_string(),
));
spec.args = vec![
"/d".to_string(),
"/c".to_string(),
format!("%{CMD_LINE_ENV}%"),
];
spec.program = program;
} else {
spec.program = program;
spec.args = args;
}
}
spec
}
+7 -2
View File
@@ -366,8 +366,9 @@ pub fn commit(
/// Take what a failed commit left staged out of the index, so a commit the
/// person makes by hand does not carry a mark the loop took back.
pub fn unstage(project: &Path) {
let _ = loop_tools::git_unstage_all(project);
pub fn unstage(project: &Path) -> Option<String> {
let unstaged = loop_tools::git_unstage_all(project);
(!unstaged.ok).then(|| first_line(&unstaged.output))
}
/// The phases the spec shows done (`done`) that the commit log does not hold:
@@ -793,6 +794,10 @@ mod tests {
#[test]
fn commit_stages_the_marked_files_but_leaves_an_ignored_spec_folder_alone() {
if !git_ready() || !node_ready() {
assert!(
std::env::var_os("CI").is_none(),
"git or node is not on PATH"
);
return;
}
let repo = init_repo("commit-ignored");
+30 -9
View File
@@ -2107,10 +2107,19 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
Ok(()) => {}
Err(loop_commit::StageError::Add(failure)) => {
keep_output(ctx, &failure.output);
loop_commit::unstage(&snap.project);
let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit;
let detail = format!("git add failed: {}", failure.first_line);
let line = stop_line(&cause, n, &detail, false);
let detail = if failure.first_line == loop_tools::STAGED_TOO_LONG {
failure.first_line.clone()
} else {
format!("git add failed: {}", failure.first_line)
};
let mut line = stop_line(&cause, n, &detail, false);
if let Some(why) = left_staged {
line = format!(
"{line}. The files are still staged ({why}): run git reset before committing by hand"
);
}
return stop(cause, line);
}
Err(loop_commit::StageError::Problem(problem)) => {
@@ -2145,11 +2154,18 @@ fn handle_outcome(ctx: &Ctx, snap: &Snapshot, raw: &Value) -> bool {
}
Err(failure) => {
keep_output(ctx, &failure.message);
if snap.setup.commit {
loop_commit::unstage(&snap.project);
}
let left_staged = if snap.setup.commit {
loop_commit::unstage(&snap.project)
} else {
None
};
let staged_note = left_staged
.map(|why| {
format!("; the files are still staged ({why}): run git reset before committing by hand")
})
.unwrap_or_default();
return refused(format!(
"the phase could not be marked done ({})",
"the phase could not be marked done ({}){staged_note}",
one_line(&failure.message)
));
}
@@ -2270,13 +2286,18 @@ fn commit_failed(
keep_output(ctx, &failure.output);
let (cause, line) = match loop_commit::undo(prepared, marked) {
Ok(()) => {
loop_commit::unstage(&snap.project);
let left_staged = loop_commit::unstage(&snap.project);
let cause = StopCause::Commit;
let detail = match failure.stage {
loop_commit::Stage::Add => format!("git add failed: {}", failure.first_line),
loop_commit::Stage::Commit => failure.first_line.clone(),
};
let line = stop_line(&cause, n, &detail, false);
let mut line = stop_line(&cause, n, &detail, false);
if let Some(why) = left_staged {
line = format!(
"{line}. The files are still staged ({why}): run git reset before committing by hand"
);
}
(cause, line)
}
Err(why) => {
+149 -20
View File
@@ -6,6 +6,7 @@
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use std::process::{Command, Stdio};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::{Duration, Instant};
@@ -23,6 +24,13 @@ pub struct ToolRun {
/// Output kept per call: the tail, which is where a failure says why.
const OUTPUT_LIMIT: usize = 200 * 1024;
/// What a stop says when too many files are staged to check.
pub const STAGED_TOO_LONG: &str =
"too many changed files to check: add generated folders to .gitignore, then Resume";
/// Output kept for the staged-file list the commit gate checks (far above any real list).
const STAGED_LIST_LIMIT: usize = 64 * 1024 * 1024;
/// The limit for node and git calls.
pub const QUICK_LIMIT: Duration = Duration::from_secs(60);
/// The limit for the person's quick check.
@@ -42,6 +50,8 @@ fn append_tail(buf: &mut Vec<u8>, bytes: &[u8], limit: usize) {
fn pump<R: Read + Send + 'static>(
mut source: R,
sink: Arc<Mutex<Vec<u8>>>,
keep: Keep,
cut: Arc<AtomicBool>,
) -> thread::JoinHandle<()> {
thread::spawn(move || {
let mut chunk = [0u8; 8192];
@@ -50,7 +60,16 @@ fn pump<R: Read + Send + 'static>(
Ok(0) | Err(_) => break,
Ok(n) => {
if let Ok(mut buf) = sink.lock() {
append_tail(&mut buf, &chunk[..n], OUTPUT_LIMIT);
match keep {
Keep::Tail(cap) => append_tail(&mut buf, &chunk[..n], cap),
Keep::Head(cap) => {
let room = cap.saturating_sub(buf.len()).min(n);
buf.extend_from_slice(&chunk[..room]);
if room < n {
cut.store(true, Ordering::Relaxed);
}
}
}
}
}
}
@@ -67,17 +86,45 @@ fn run_limited(cmd: Command, stdin: Option<&str>, limit: Duration) -> ToolRun {
/// `run_limited`, with stderr dropped when `keep_stderr` is false: a list read
/// from stdout must not be mixed with a warning git printed beside it.
fn run_limited_with(
mut cmd: Command,
cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
) -> ToolRun {
run_capped(cmd, stdin, limit, keep_stderr, Keep::Tail(OUTPUT_LIMIT)).0
}
/// Which part of a long output a call keeps.
#[derive(Clone, Copy)]
enum Keep {
/// The last `n` bytes, where a failure says why.
Tail(usize),
/// The first `n` bytes; anything after is read and dropped, and the call
/// reports it was cut. For a list a safety check must read whole.
Head(usize),
}
/// `run_limited_with` with the part kept chosen, and whether output was dropped.
fn run_capped(
mut cmd: Command,
stdin: Option<&str>,
limit: Duration,
keep_stderr: bool,
keep: Keep,
) -> (ToolRun, bool) {
let cut = Arc::new(AtomicBool::new(false));
cmd.env("PATH", crate::node_check::resolved_path());
#[cfg(windows)]
{
use std::os::windows::process::CommandExt;
cmd.creation_flags(0x08000000); // CREATE_NO_WINDOW
}
#[cfg(unix)]
{
// Its own process group, so a timeout can end every descendant at once.
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
cmd.stdin(if stdin.is_some() {
Stdio::piped()
} else {
@@ -92,17 +139,26 @@ fn run_limited_with(
let mut child = match cmd.spawn() {
Ok(child) => child,
Err(e) => {
return ToolRun {
ok: false,
code: None,
output: format!("could not start: {e}"),
}
return (
ToolRun {
ok: false,
code: None,
output: format!("could not start: {e}"),
},
false,
);
}
};
let sink = Arc::new(Mutex::new(Vec::new()));
let readers = [
child.stdout.take().map(|s| pump(s, Arc::clone(&sink))),
child.stderr.take().map(|s| pump(s, Arc::clone(&sink))),
child
.stdout
.take()
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
child
.stderr
.take()
.map(|s| pump(s, Arc::clone(&sink), keep, Arc::clone(&cut))),
];
if let (Some(text), Some(mut pipe)) = (stdin, child.stdin.take()) {
// A child that exits before reading closes the pipe: not an error here.
@@ -148,11 +204,14 @@ fn run_limited_with(
}
output.push_str(&format!("(stopped after {})", describe_limit(limit)));
}
ToolRun {
ok: status.is_some_and(|s| s.success()),
code: status.and_then(|s| s.code()),
output,
}
(
ToolRun {
ok: status.is_some_and(|s| s.success()),
code: status.and_then(|s| s.code()),
output,
},
cut.load(Ordering::Relaxed),
)
}
/// "1 minute", "15 minutes", "2 seconds".
@@ -180,11 +239,14 @@ fn kill_tree(pid: u32) {
}
#[cfg(not(windows))]
{
let _ = Command::new("pkill")
.args(["-KILL", "-P", &pid.to_string()])
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
// The child leads its own process group (see run_limited): a negative
// pid ends the whole group, grandchildren included.
if let Ok(pgid) = i32::try_from(pid) {
// SAFETY: kill(2) takes plain integers and touches no memory.
unsafe {
libc::kill(-pgid, libc::SIGKILL);
}
}
}
}
@@ -347,15 +409,26 @@ pub fn git_add_paths(project: &Path, paths: &[&Path]) -> ToolRun {
/// The names of the staged files, as `git diff --cached --name-only -z` prints
/// them: NUL-separated, so no path is quoted.
pub fn git_staged(project: &Path) -> Result<Vec<String>, String> {
let run = run_limited_with(
git_staged_capped(project, STAGED_LIST_LIMIT)
}
/// `git_staged` with the size the list may reach. The secret and size gate
/// reads every staged name, so a list over the cap fails closed rather than
/// being checked in part.
fn git_staged_capped(project: &Path, cap: usize) -> Result<Vec<String>, String> {
let (run, cut) = run_capped(
git(project, &["diff", "--cached", "--name-only", "-z"]),
None,
QUICK_LIMIT,
false,
Keep::Head(cap),
);
if !run.ok {
return Err(run.output.trim().to_string());
}
if cut {
return Err(STAGED_TOO_LONG.to_string());
}
Ok(split_nul(&run.output))
}
@@ -558,6 +631,62 @@ fn parse_json_object(run: &ToolRun) -> Result<serde_json::Value, String> {
mod tests {
use super::*;
#[test]
fn a_capped_run_keeps_the_part_asked_for_and_says_when_output_was_cut() {
if Command::new("node").arg("--version").output().is_err() {
assert!(std::env::var_os("CI").is_none(), "node is not on PATH");
return;
}
fn run(keep: Keep, text: &str) -> (ToolRun, bool) {
let mut cmd = Command::new("node");
cmd.args(["-e", &format!("process.stdout.write('{text}')")]);
run_capped(cmd, None, QUICK_LIMIT, false, keep)
}
let (tail, tail_cut) = run(Keep::Tail(4), "aaaabbbb");
assert!(tail.ok);
assert_eq!(tail.output, "bbbb");
assert!(!tail_cut, "a tail keeper never reports a cut");
let (head, head_cut) = run(Keep::Head(4), "aaaabbbb");
assert_eq!(head.output, "aaaa");
assert!(head_cut);
let (whole, whole_cut) = run(Keep::Head(8), "aaaabbbb");
assert_eq!(whole.output, "aaaabbbb");
assert!(!whole_cut);
}
#[test]
fn a_staged_list_over_the_cap_is_refused_not_checked_in_part() {
if Command::new("git").arg("--version").output().is_err() {
assert!(std::env::var_os("CI").is_none(), "git is not on PATH");
return;
}
let repo =
std::env::temp_dir().join(format!("plan2code-staged-cap-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&repo);
std::fs::create_dir_all(&repo).unwrap();
let git_in = |args: &[&str]| {
let status = Command::new("git")
.args(args)
.current_dir(&repo)
.status()
.unwrap();
assert!(status.success(), "git {args:?}");
};
git_in(&["init", "-q"]);
for name in [".env", "a.txt", "b.txt"] {
std::fs::write(repo.join(name), "x").unwrap();
}
git_in(&["add", "-A"]);
// A cap below the list's size: refused, never a list missing its first names.
assert_eq!(
git_staged_capped(&repo, 8),
Err(STAGED_TOO_LONG.to_string())
);
let all = git_staged_capped(&repo, 1024).unwrap();
assert_eq!(all, [".env", "a.txt", "b.txt"]);
let _ = std::fs::remove_dir_all(&repo);
}
#[test]
fn the_commit_message_is_read_from_the_scripts_output_without_a_shell() {
let ok = r#"{"ok":true,"subject":"Add it","message":"Add it\n\nAI Assisted"}"#;
+6 -6
View File
@@ -798,7 +798,7 @@ async fn update_skills(
/// The OS folder picker, shown when no folder is known; a choice becomes the
/// launcher's remembered folder.
#[tauri::command]
#[tauri::command(async)]
fn pick_project_folder(
app: tauri::AppHandle,
state: State<'_, AppState>,
@@ -847,7 +847,7 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
/// fresh for it rather than reusing anything from the one just left. Picking
/// nothing (canceled) leaves the current project untouched. One project per
/// window stays; this replaces it, it does not add a second.
#[tauri::command]
#[tauri::command(async)]
fn change_project(
app: tauri::AppHandle,
state: State<'_, AppState>,
@@ -876,7 +876,7 @@ fn change_project(
/// is `console_setup_start` below: the agent-less `setup` page, which is no
/// dashboard and has no agent to announce it, so the app opens it itself.
/// Nothing to show yet is an error the page words for the person.
#[tauri::command]
#[tauri::command(async)]
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
console_start_impl(&state)
}
@@ -894,7 +894,7 @@ fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
/// The bar's poll: none (never started or stopped on purpose), running, or
/// dead (started but not answering).
#[tauri::command]
#[tauri::command(async)]
fn console_status(state: State<'_, AppState>) -> serde_json::Value {
let Ok(guard) = state.console.lock() else {
return serde_json::json!({ "state": "none", "url": null });
@@ -927,7 +927,7 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
/// on its own), and the URL comes back for the page to frame. When
/// `console.mjs` cannot be found the error names it, and the page shows its
/// plain "skills are missing" checklist row.
#[tauri::command]
#[tauri::command(async)]
fn console_setup_start(
app: tauri::AppHandle,
state: State<'_, AppState>,
@@ -1254,7 +1254,7 @@ fn loop_finalize(state: State<'_, AppState>) -> Result<(), String> {
/// fresh dashboard console in its place. Needs no agent: a dashboard session
/// is only `console.mjs open --workflow dashboard`, which the supervisor runs
/// itself.
#[tauri::command]
#[tauri::command(async)]
fn loop_dashboard(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
let app = state.app.get().cloned().ok_or("no window yet")?;
let origin = window_origin(&app);
+1 -1
View File
@@ -155,7 +155,7 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
std::fs::create_dir_all(parent).map_err(err)?;
}
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
std::fs::write(file, json).map_err(err)?;
crate::loop_driver::write_atomic(&file, &json)?;
Ok(ProjectDir {
dir: dir.to_path_buf(),
source: ProjectSource::Picked,
+1 -1
View File
@@ -153,7 +153,7 @@ fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> R
}
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings))
.map_err(|e| e.to_string())?;
std::fs::write(file, json).map_err(|e| e.to_string())
crate::loop_driver::write_atomic(file, &json)
}
#[cfg(test)]
+4 -4
View File
@@ -257,7 +257,7 @@ mod tests {
let lines = std::sync::Mutex::new(Vec::<String>::new());
let result =
with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || {
run_update_within("9.9.9", Duration::from_secs(10), |line| {
run_update_within("9.9.9", Duration::from_secs(60), |line| {
lines.lock().unwrap().push(line.to_string())
})
});
@@ -273,7 +273,7 @@ mod tests {
let result = with_fake_launcher(
"tag",
"console.log(process.argv.slice(2).join(' '));",
|| run_update_within("9.9.9", Duration::from_secs(10), |_| {}),
|| run_update_within("9.9.9", Duration::from_secs(60), |_| {}),
);
assert_eq!(result, Ok("update --tag v9.9.9".to_string()));
}
@@ -281,7 +281,7 @@ mod tests {
#[test]
fn run_update_fails_with_the_installer_s_own_last_line() {
let result = with_fake_launcher("fail", "console.log('oops'); process.exit(1);", || {
run_update_within("9.9.9", Duration::from_secs(10), |_| {})
run_update_within("9.9.9", Duration::from_secs(60), |_| {})
});
assert_eq!(result, Err("the update did not finish: oops".to_string()));
}
@@ -298,7 +298,7 @@ mod tests {
fn a_missing_launcher_is_an_error_not_a_panic() {
let result = with_fake_launcher("missing", "", || {
std::fs::remove_file(launcher_dir().unwrap().join("plan2code.js")).unwrap();
run_update_within("9.9.9", Duration::from_secs(10), |_| {})
run_update_within("9.9.9", Duration::from_secs(60), |_| {})
});
assert!(result.unwrap_err().contains("is missing"));
}
+14 -1
View File
@@ -2,7 +2,7 @@ import fs from 'fs';
import os from 'os';
import path from 'path';
import { describe, it, expect, afterEach } from 'vitest';
import { avg, rate, buildCohortKey, backfillPromptVersions, cohortKeyForRun, aggregate } from './aggregator.js';
import { avg, rate, buildCohortKey, backfillPromptVersions, cohortKeyForRun, aggregate, writeRunFile } from './aggregator.js';
import type { PromptVersions, RunMetrics } from './types.js';
// ── avg() ─────────────────────────────────────────────────────────────────────
@@ -251,3 +251,16 @@ describe('aggregate', () => {
expect(result.current_cohort_key).toBe(buildCohortKey(local.prompt_versions));
});
});
describe('writeRunFile', () => {
it('refuses a run_id that is not a run-<id> name, so it cannot leave the runs folder', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'p2c-runs-'));
try {
const run = { ...makeRun({}), run_id: '../../escape' };
expect(() => writeRunFile(run, path.join(dir, 'runs'))).toThrow(/run-<id>/);
expect(fs.existsSync(path.join(dir, 'escape.json'))).toBe(false);
} finally {
fs.rmSync(dir, { recursive: true, force: true });
}
});
});
+4
View File
@@ -230,6 +230,10 @@ export function loadAggregated(outputPath: string): AggregatedMetrics | null {
* Returns true if written, false if a file for that run_id already existed.
*/
export function writeRunFile(run: RunMetrics, runsDir: string): boolean {
// The id becomes a file name: only the collector's own shape may reach a path.
if (!/^run-[A-Za-z0-9-]{1,64}$/.test(run.run_id)) {
throw new Error(`Refusing run_id "${String(run.run_id).slice(0, 80)}": it is not a run-<id> name.`);
}
const destPath = path.join(runsDir, `${run.run_id}.json`);
if (fs.existsSync(destPath)) {
+3 -3
View File
@@ -5,11 +5,11 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import type { AggregatedMetrics } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js';
const ANALYZE_PROMPT_PATH = new URL('../src/prompts/analyze.md', import.meta.url).pathname
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
const ANALYZE_PROMPT_PATH = fileURLToPath(new URL('../src/prompts/analyze.md', import.meta.url));
// ── Helpers ───────────────────────────────────────────────────────────────────
@@ -40,7 +40,7 @@ function readPromptFiles(plan2codeRoot: string): Record<string, string> {
function interpolate(template: string, vars: Record<string, string>): string {
let result = template;
for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(`{{${key}}}`, value);
result = result.replaceAll(`{{${key}}}`, () => value);
}
return result;
}
+2 -2
View File
@@ -67,7 +67,7 @@ function applyEdit(edit: PromptEdit, plan2codeRoot: string): boolean {
console.error(chalk.red(`✗ Cannot apply: old_text not found in ${edit.file} (may have been modified by a previous edit)`));
return false;
}
content = content.replace(edit.old_text, edit.new_text);
content = content.replace(edit.old_text, () => edit.new_text);
// Post-apply char count check
if (content.length > CHAR_LIMIT) {
@@ -173,7 +173,7 @@ export async function reviewAndApply(opts: ApplierOptions): Promise<ApplierResul
if (success) {
applied++;
// Update in-memory content to reflect the edit
promptContents[edit.file] = promptContents[edit.file].replace(edit.old_text, edit.new_text);
promptContents[edit.file] = promptContents[edit.file].replace(edit.old_text, () => edit.new_text);
} else {
failed++;
}
+6
View File
@@ -87,6 +87,12 @@ describe('parseSubmissionPayload', () => {
expect(result).toBeNull();
});
it('returns null when run_id is not a run-<id> name (it becomes a file name)', () => {
for (const run_id of ['../../x', 'run-../x', 'x', 'run-' + 'a'.repeat(65), 'run-a/b']) {
expect(parseSubmissionPayload(issueBody({ ...VALID_PAYLOAD, run_id }))).toBeNull();
}
});
it('returns null when user_feedback.overall_rating is a string instead of a number', () => {
const badPayload = {
...VALID_PAYLOAD,
+2 -1
View File
@@ -242,7 +242,8 @@ export function parseSubmissionPayload(body: string): RunMetrics | null {
if (!parsed) return null;
if (parsed['schema_version'] !== '1.0') return null;
if (!isString(parsed['run_id'])) return null;
// The id becomes a file name in the runs folder: only the collector's own shape.
if (!isString(parsed['run_id']) || !/^run-[A-Za-z0-9-]{1,64}$/.test(parsed['run_id'])) return null;
if (!isString(parsed['plan2code_version'])) return null;
const feedbackRaw = parsed['user_feedback'];
+1 -1
View File
@@ -128,7 +128,7 @@ describe('parseProposalFromResponse', () => {
});
it('returns null for malformed JSON', () => {
const result = parseProposalFromResponse('```json\n{broken json]\n```');
const result = parseProposalFromResponse('```json\n[{"old_text": broken]\n```');
expect(result).toBeNull();
});
+5 -5
View File
@@ -6,19 +6,19 @@
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import type { PromptEdit, PromptProposal } from './types.js';
import { invokeLLM, type AgentType } from './invoke-llm.js';
const CHAR_LIMIT = 20_000;
const IMPROVE_PROMPT_PATH = new URL('../src/prompts/improve.md', import.meta.url).pathname
.replace(/^\/([A-Za-z]:)/, '$1'); // Fix Windows path
const IMPROVE_PROMPT_PATH = fileURLToPath(new URL('../src/prompts/improve.md', import.meta.url));
// ── Helpers ───────────────────────────────────────────────────────────────────
function interpolate(template: string, vars: Record<string, string>): string {
let result = template;
for (const [key, value] of Object.entries(vars)) {
result = result.replaceAll(`{{${key}}}`, value);
result = result.replaceAll(`{{${key}}}`, () => value);
}
return result;
}
@@ -93,7 +93,7 @@ export function validateEdit(
}
// Check char count after edit
const afterContent = fileContent.replace(edit.old_text, edit.new_text);
const afterContent = fileContent.replace(edit.old_text, () => edit.new_text);
if (afterContent.length > CHAR_LIMIT) {
errors.push(`Edit would cause "${edit.file}" to exceed ${CHAR_LIMIT} char limit (would be ${afterContent.length} chars).`);
}
@@ -232,7 +232,7 @@ export async function generateImprovement(opts: ImproverOptions): Promise<Improv
if (result.valid) {
// Compute accurate char counts
const fileContent = promptContents[edit.file] ?? '';
const afterContent = fileContent.replace(edit.old_text, edit.new_text);
const afterContent = fileContent.replace(edit.old_text, () => edit.new_text);
edit.char_count_before = fileContent.length;
edit.char_count_after = afterContent.length;
edit.char_count_delta = afterContent.length - fileContent.length;
+1 -1
View File
@@ -81,7 +81,7 @@
{
"name": "an install folder with %NAME% expands against vars",
"platform": "win",
"entry": { "command": "goose", "installDirs": { "win": ["%TOOLS%\\bin"] } },
"entry": { "command": "goose", "installDirs": { "win": ["%TOOLS%/bin"] } },
"dirs": { "tools": ["bin/goose.exe"] },
"env": { "path": "", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD", "vars": { "TOOLS": "{tools}" } },
"state": "outside",
+79
View File
@@ -116,9 +116,38 @@ export async function openSession(browser, { t, workflow, payload: first, projec
s.page.on("pageerror", (e) => s.errors.push(e.message));
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
await drawn(s.page);
// Redraws that follow the first one (the workspace frame, a scan, the update check) land a
// moment later, and on a busy runner a test that has already scrolled, typed or opened
// something loses it to them. Hand the test a page that has gone quiet. A fake clock freezes
// the page's own timers, so those sessions are left as they are.
if (!clock) await quiet(s.page);
return s;
}
// Waits until the document has not changed for `quietMs`, or `maxMs` at most (a page that never
// goes quiet must not block a test). Counts mutations in the page and polls the count from
// here, so it needs no timer in the page.
export async function quiet(page, { quietMs = 300, maxMs = 4000 } = {}) {
await page
.evaluate(() => {
if (window.__quiet) return;
window.__quiet = { n: 0 };
new MutationObserver(() => window.__quiet.n++).observe(document.body, { subtree: true, childList: true, attributes: true, characterData: true });
})
.catch(() => {});
const end = Date.now() + maxMs;
let last = -1;
let since = Date.now();
while (Date.now() < end) {
const n = await page.evaluate(() => (window.__quiet ? window.__quiet.n : -1)).catch(() => -1);
if (n !== last) {
last = n;
since = Date.now();
} else if (Date.now() - since >= quietMs) return;
await new Promise((r) => setTimeout(r, 50));
}
}
// The page has adopted a state frame: app.js has replaced the boot pane the
// markup ships with.
export async function drawn(page) {
@@ -186,12 +215,62 @@ export async function fillBox(locator, text) {
const box = locator.first();
const isField = await box.evaluate((n) => Boolean(n.field)).catch(() => false);
if (!isField) return box.fill(text);
// A field is drawn disabled until the page knows the agent's state (the Ask box, for one),
// and a disabled field drops what is typed into it, leaving Send off for good: give it a
// moment to open, on whichever element the box is by then.
for (let i = 0; i < 200; i++) {
const open = await box.evaluate((n) => n.isConnected && !n.classList.contains("is-disabled")).catch(() => false);
if (open) break;
await new Promise((r) => setTimeout(r, 50));
}
await box.evaluate((n, t) => {
n.field.value = t;
n.field.emitInput();
}, text);
}
// Waits until nothing inside the element has changed for `quietMs`. A late redraw (state that
// rides an event, a scan that lands after the page is drawn) replaces what a test has just
// scrolled or opened, and the test then fails on a slow runner: let the page go quiet first.
export async function settled(page, selector, quietMs = 500) {
await page.locator(selector).first().evaluate(
(n, ms) =>
new Promise((resolve) => {
let timer;
const done = () => {
observer.disconnect();
resolve();
};
const observer = new MutationObserver(() => {
clearTimeout(timer);
timer = setTimeout(done, ms);
});
observer.observe(n, { subtree: true, childList: true, attributes: true, characterData: true });
timer = setTimeout(done, ms);
}),
quietMs
);
}
// Types a message in the Ask box and presses Send. The composer is rebuilt whenever the page's
// view of the agent changes, and a box filled just before a rebuild can come back empty with Send
// off: fill again until Send is on, and when it never is, fail with the composer's own reason
// (its disabled note) instead of a minute-long click timeout.
export async function sendAsk(page, text) {
const send = page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true });
let on = false;
for (let attempt = 0; attempt < 6 && !on; attempt++) {
await fillBox(page.locator("#ask-input"), text);
on = await send.isEnabled().catch(() => false);
if (!on) await page.waitForTimeout(500);
}
if (!on) {
const note = await page.locator(".ask-composer .ask-disabled-note").innerText().catch(() => "no disabled note");
throw new Error(`Send in the Ask box stayed off after typing ${text.length} characters: ${note}`);
}
await send.click();
}
// The text a box holds: a Markdown field through its facade, a real input
// through its value.
export const boxValue = (locator) => locator.first().evaluate((n) => (n.field ? n.field.value : n.value));
+17
View File
@@ -0,0 +1,17 @@
// Pins Math.random to a seeded generator for a test file that drives an Activities game, so the
// game's own dice (a road with a crack where a test wanted plain road, a spawn that lands out of
// reach) give the same layout on every run and a rare roll can never fail a test at random.
// Import it FIRST in the file: a game module may roll at load time.
//
// A seed that fails a test is a real finding, not a flake: set PLAN2CODE_TEST_SEED to reproduce
// another roll, for example to hunt a bug the fixed seed hides.
let state = Number(process.env.PLAN2CODE_TEST_SEED || 20261105) >>> 0;
// mulberry32: small, fast and good enough for game dice.
Math.random = () => {
state = (state + 0x6d2b79f5) | 0;
let t = Math.imul(state ^ (state >>> 15), 1 | state);
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
};
+11
View File
@@ -168,3 +168,14 @@ test("coverage read: exactly one format flag is required", () => {
assert.equal(C(dir, "read", "--lcov", "a", "--go-func", "b").code, 2);
assert.equal(C(dir).code, 2);
});
test("coverage read --lcov --cwd: a runner's relative paths get its folder in front", () => {
const dir = tmp("cov-cwd");
write(dir, "lcov.info", "SF:src/x.ts\nDA:1,1\nLF:1\nLH:1\nend_of_record\nSF:D:/elsewhere/y.ts\nDA:1,0\nLF:1\nLH:0\nend_of_record\n");
const r = C(dir, "read", "--lcov", "lcov.info", "--cwd", "./packages/api/");
assert.equal(r.code, 0, r.stderr);
assert.deepEqual(
r.json.files.map((f) => f.file),
["D:/elsewhere/y.ts", "packages/api/src/x.ts"]
);
});
@@ -5,6 +5,7 @@
// and records every point it draws through, as in
// scripts/test-web-console-activities-rapids.mjs.
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import { CAR_STYLES, MARGINS, STYLE_NAMES, carLength, carReach, drawCarBody, drawCarShadow, rgbOf, shade, styleOf } from "../src/web-console/public/activities/bounce-cars.js";
@@ -6,6 +6,7 @@
// handed, so a stub canvas stands in for the page, as in
// scripts/test-web-console-activities.mjs, whose helpers this file copies.
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import * as bounce from "../src/web-console/public/activities/bounce.js";
@@ -193,7 +194,10 @@ const eventsOf = (round, type) => round.events.filter((e) => e.type === type);
// A rival of `kind` put at (x, d), still and on the ground, going nowhere on
// its own.
function bounceRival(round, kind, x, d, over = {}) {
const car = bounce.spawnRival(round, kind, steady, round.cars[0].d + 300);
// A rival only spawns on plain road, and the road is generated at random: a crack or a bridge can
// sit at the first spot tried, so try further along until one takes. The rival is moved anyway.
let car = null;
for (let at = round.cars[0].d + 300; !car && at < round.cars[0].d + 3000; at += 40) car = bounce.spawnRival(round, kind, steady, at);
assert.ok(car, `a ${kind} spawns`);
Object.assign(car, { x, d, v: 0, tv: 0, vx: 0, kx: 0, air: 0, tx: x, lane: x, hopIn: 1e9, dropIn: 1e9, mode: "calm", ...over });
return car;
@@ -5,6 +5,7 @@
// handed, so a stub canvas stands in for the page, as in
// scripts/test-web-console-activities.mjs, whose helpers this file copies.
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import * as bounce from "../src/web-console/public/activities/bounce.js";
File diff suppressed because it is too large. Load diff
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's secondary weapons: the double tap that uses one (hammering spends one at most, a hold carries on as bolts), the bag and its HUD pill, what each weapon does, what they may do to a boss, where they are placed and how they drop, and that all of it draws and sounds.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Grand Banister (the Manor's bonus round, between the Library and the Ballroom): its shape (every break clears with a jump and swallows a rider that does not jump, the brass under-rails, every low can be ducked, spacing, checkpoints, the clock), the ride's speed on slopes and its lean and brake, its jump, ducking and diving, a vase, a candlestick, a hanging frame, a chandelier on its pendulum, a ghostly butler, the cobwebs, a fall off the rail, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9), endless lives for every new cause, a voice for every event, the drawing, and bots that ride the whole stair (one that rides well, one that never dodges).
// Run with: node --test scripts/test-web-console-activities-ghoul-banister.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -4,6 +4,7 @@
// mud spans that slow and sink you, the Bog Runner's stub and the Drowning
// Pool's boss spec. The monsters' rules, the fight and the ride land in
// later phases.
import "./seed-random.mjs";
import { test } from "node:test";
import { readFileSync } from "node:fs";
import assert from "node:assert/strict";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Old Rattlebones: his volley and slam, the skull he throws like a boomerang (and is headless without), the bone rain and the skeletons he raises once his rage begins, the double slam, and what each move looks and sounds like.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Bone Stair (the finale's second ride, between Kill II and the Pit): its shape (the spiral's flights and seams, every gap of missing treads clears with a jump and swallows YOU without one, every ribcage can be ducked, spacing, checkpoints, the last step over the Pit's floor), the run's speed (DOWN and LEFT slow YOU), every obstacle's cost and cause (missing treads, treads giving way, ribcages, skeletons, hands, masonry, the rubble), the telegraphs (shadows, creaks and cracks, fingers over the edge, skeletons rising), shooting skeletons down, the pursuit meter (the gap that clean running opens and hits, ducks and holds close), the catch, three hearts of its own, the grade and the dice, endless lives, the finish, no random numbers, its sounds and its drawing on a fake canvas, and bots that play it well and badly.
// Run with: node --test scripts/test-web-console-activities-ghoul-bonestair.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's boss intro cards: every boss room has an entry (the boss's exact name, an epithet, no em dash, never the hero's name), the card shows when a boss room is entered (after the bonus ride too) and in no other room, not again on a retry, any fresh move key, fire or click moves it on after the lockout (repeats and early presses never do), it never moves on by itself, a pause holds it, and it draws for every boss on a fake canvas (through the boss's own art, with a fallback when the art throws or is missing).
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Midnight Carnival stage: its four rooms (the Midway, the Hall of Mirrors, the Funhouse with its conveyor floors, the Big Top), grinners that honk out acid balloons, marionettes that drop on their strings, Mirror You that copies your moves and shots half a second late, strongmen that lob barbells, circus hounds that leap through hoops of fire, Cotton Candy and the Custard Pie (found only here), and the Ringmaster, whose puppet hangs on three strings: cut them all and he is open for four seconds.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Runaway Cart (the Deep Seam Mine's ride room): its shape (between the Collapse and the Seam, every gap clears at the cart's speed with a jump, every beam can be ducked, checkpoints spaced, the clock covers the ride), the cart's speed on slopes, leaning and braking, its jump and its steering in the air, a ramp's launch, landing on the upper or the lower line of a split, a fall into the chasm and the respawn at the last checkpoint, ducking under a beam, rubble, crates (two shots break one), the boulder behind, the buffer stop and the door, the ledge imp, a canary's slide of rubble, endless lives for every new cause, a voice for every event, the drawing, and a bot that rides the whole room.
// Run with: node --test scripts/test-web-console-activities-ghoul-cart.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Chapel stage: its four rooms, gargoyles that are stone on their perch and dive when you pass under, choir ghosts whose song quickens the monsters near them, censer monks and their smoke, bats in the bells, the bell toll that freezes everything for a second, Holy Water (found only here), and the Choirmaster, whose organ pipes guard him and whose columns of notes have one gap each.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Lucky die: it comes only from a kill, stacks to nine and lasts the run; when a life would be lost one rolls: a 4 to 6 brings Planny back (the monsters in view blown apart in an ordinary room, a boss's room untouched; a 5 adds a heart, a 6 a heart and a Garlic shield), a 3 or 2 costs the life and leaves a gift for the respawn, a 1 only laughs.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's ending: four pages that obey the story's rules (2 to 4 short lines, no digits, no em dash, YOU on each, the gag's FINAL NOTICE); the House's last room opens it instead of the win; a press turns pages only after the lockout and finishes the typing first; holding fire skips it, a tap never does; the last page wins the run once, with n = round.winN; the window's keys, a click, a pause, its track and its sounds; every scene draws on a fake canvas at many moments; every event it raises has a react; every tone it names exists.
// Run with: node --test scripts/test-web-console-activities-ghoul-ending.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -8,6 +8,7 @@
// shoot apart), the kill and its retreat in order with the door kept until it has gone, a bot's
// fight length, the voices, words and drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-eye.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -652,7 +653,8 @@ test("Ghoul Rush's dollhouse draws: the landing, the fight with the Eye in every
standAt(r, 10);
frame("the landing");
standAt(r, r.spec.arena + 14);
for (let ms = 0; ms < 1600; ms += 16) g.tick(16);
// The House's intro runs a seed-dependent while: tick until its Eye exists, not a fixed time.
for (let ms = 0; ms < 1600 || (!r.boss.eye && ms < 20000); ms += 16) g.tick(16);
for (const [state, decoy] of [["flare", -1], ["flare", 6], ["open", -1], ["closing", -1], ["shut", -1]]) {
Object.assign(r.boss.eye, { state, ms: 300, full: 1000, room: 4, decoy });
frame(`the Eye ${state}`);
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Frozen Lake stage: its rooms (Ice Fishing Huts, Snowbound Lodge, The Black Ice, the Widow's Web), slippery ice and thin ice that cracks and breaks, under-ice hands, snow shades you only see by their footprints, frozen ghouls that slide and shatter, ice wraiths whose dive leaves you frozen, Hot Cocoa and the Road Flare (found only here), and the Frost Widow, whose veil melts only to a burning barrel or a flare.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's game over: a lost end plays the mechanical laugh track (and a win does not), and the "G A M E - O V E R" banner drops in letter by letter and draws on a fake canvas.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Graveyard stage: its four rooms, grasping hands, mourners and their wail, grave robbers, rotters and the legs they leave, carrion crows, the graves rotters climb out of, and Mother Mourning, who can only be hurt while she watches and drops a stone fist on whatever moves.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Grounds stage: its four rooms, topiary beasts that creep only when your back is turned, rootlings under the lawn, lantern moths, mulch crawlers, the Hedge shears (found only here), and the Groundskeeper, whose lantern takes triple damage, whose scythe is jumped, whose fire burns the floor and who mounts a mower at half his hp.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Code Blue (Blackmoor Sanatorium's bonus round, between the Surgical Theater and the Night Ward): its shape (every elevator shaft clears with a jump and swallows a gurney that does not jump, every low can be ducked, spacing, the surge lamps and the blackout waves, checkpoints, the clock), the gurney's speed on slopes, its jump, ducking, a wheelchair that rolls, an IV stand, a lamp or a door overhead, an orderly in a doorway, the surge lamp shot from the air, the lights-out rhythm (the countdown, the dark, the lights back), the heartbeat monitor, a fall down a shaft, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9) and the clean-dark-stretches die, endless lives for every cause, a voice for every event, the drawing, and bots that ride the whole way (one that dodges well, one that never does).
// Run with: node --test scripts/test-web-console-activities-ghoul-gurney.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Midnight Hearse (the Graveyard's bonus round, between the Mausoleum Row and Angel's Rest): its shape (two lanes, the gates, every thing spaced for a player, the closed stretches with a gate before each), the hearse's motion (a steady speed, a jump, a duck, a hop between lanes only at a gate), each obstacle and its cost (grave, headstone, cross, branch, hand, crow, wreck), the lamp and its lanterns, the coffins thrown out and the ghouls that sit up in them, the hearts and the grade and the dice, endless lives, the drawing and the sounds, and bots that play it.
// Run with: node --test scripts/test-web-console-activities-ghoul-hearse.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -6,6 +6,7 @@
// the weak beats that only knock it back, the white, the last thump, the fall, the daylight and its
// door), a life lost keeping it all, a bot's fight length at full depth, the voices, words and drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-heart.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's stage intro cards: every stage has one (3 or 4 lines, short, no em dash, never the hero's name), the card shows when a stage is entered and not before the pick, any move key or fire moves it on after the minimum (repeats and early presses never do) and it never moves on by itself, and it draws on a fake canvas.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Drowned Lantern (Gallows Bog's bonus round, between the Stilt House and the Drowning Pool, a top-down game on one screen and not a ride): the island, the walk and the slide, the flare and the oil, the shrines and the run to the boat, each hunter's one rule (the Lurker hears steps on wood and dashes down a lane through where it heard you, the wisps guard the shrines and burst in a flare, the leeches never enter the light, the bog bodies take only someone standing still, Old Mother Bog's hand), the hearts and the grade, the clock, determinism, the balance (a bot that ignores the hunters loses, one that plays them wins), the voices, the hums and the drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-lantern.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -5,6 +5,7 @@
// weighted pick, the wall in front of the house, the retreat in order and its standing door, a
// bot's fight length, the voices, words and drawing.
// Run with: node --test scripts/test-web-console-activities-ghoul-marrow.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Down the Hatch (the finale's first ride, after the Front Lawn): its shape (eleven swallows, every fork's hole swallows a rider who does not jump and its gristle ledge catches one who does, every uvula can be ducked, spacing, checkpoints every 8 to 10 seconds, the lip), the ride's speed on slopes and bile, its jump and duck, a rib, a uvula-lamp, a squeeze's throb, close and ease (peristalsis), the swallowed furniture, a plunge, the checkpoints, the lip and the door, the bonus round's three hearts and dice (3 to 8), endless lives for every cause, a voice for every event, the drawing, the telegraphs, and bots that ride the whole throat (one that rides well finishes, one that never dodges loses all three hearts without a game over).
// Run with: node --test scripts/test-web-console-activities-ghoul-mat.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Deep Seam Mine stage: its four rooms (always dark, the cage lifts, the water, the rockfall), rocks that fall after a dust warning and crush monsters and cost a life, the knocker imp that steals your light but never a life, the canary ghost whose scream brings three rocks down, the dead miner that digs out of the wall, the blind crawler that hunts by sound, the cage you can ride, the Hard Hat and Dynamite (found only here), and the Tommyknocker, who knocks, sweeps his hammer, puts the lights out, sinks into the seam and bursts out dazed, and rages at half his hp.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Gardener's Revenge (the Grounds' bonus round, between the Gazebo and the Groundskeeper's Yard): its shape (every pond and ditch clears with a jump and swallows a mower that does not jump, every low can be ducked), the mower's motion, each obstacle's cost and cause, the blades (cutting, the heat, the jam, the lawn cut), the topiary beasts, the hearts, the checkpoints, the finish and the dice, endless lives, the art on a fake canvas, and the two bots (one that plays well finishes in time, one that never dodges loses).
// Run with: node --test scripts/test-web-console-activities-ghoul-mower.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Holy Roller (the Chapel's bonus round, between the Organ Loft and the Choir): an endless-runner seen from behind, in three lanes. Its room and its seeded course (every thing in the way has a safe answer, a safe path exists at every moment), the speed ramp, the lanes and the wall bump, the jump and the slide, each kind of obstacle's cost and cause, the gargoyles and the bell ropes, the wax souls, the combo and the halo's magnet, the grade, the last heart ending the round with the run going on, endless lives, the Garlic shield, the sounds and words, the drawing on a fake canvas, and bots that play it well and badly.
// Run with: node --test scripts/test-web-console-activities-ghoul-pew.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,6 +1,7 @@
// Web console tests, Ghoul Rush's retry mercy: after a loss in a room, each restart of it sets one power-up a few steps ahead of Planny (never the first attempt, never in a ride or bonus room), the kind from its own hash so no shared roll shifts, on a firm surface, replacing the last one uncollected, reset when the room is cleared.
// Run with: node --test scripts/test-web-console-activities-ghoul-retry.mjs
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's dark ride (the Midnight Carnival's bonus round): its place (between the funhouse and the Big Top), the bonus round's five hearts and the flow on to the boss, the dice rule, the controls (arrows, Space, the mouse, the duck zone), aim assist, the mini-bosses, the Exit's twist, a bot that rides it all and one that does nothing, the endless-lives code, and every event voiced.
// Run with: node --test scripts/test-web-console-activities-ghoul-ride.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Blackmoor Sanatorium stage: its four rooms, orderlies that grab and throw you (and cost no life), gurneys that park, rattle and roll, flickers you can only hit and be hurt by when the lamps go out, specimen bloaters and their formaldehyde, the lamps' flicker, Smelling Salts and the Bone Saw (found only here), and the Night Matron, whose lantern cone builds heat, is stopped by the medicine cabinets and cannot reach the boards, with her syringes, arms and rage.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Coffin Sled (the Frozen Lake's bonus round, between the Black Ice and the Widow's Web): its shape (every crack clears with a jump and swallows a sled that does not jump, every low can be ducked, spacing, checkpoints, the clock), the sled's speed on slopes, its jump, ducking, a headstone, a drift, a branch, a hand in the snow, the ghoul that pops up and the icicles (bolts that follow the hill), a fall into a crack, the checkpoint, the jump off the end and the door, the bonus round's hearts and dice (3 to 9), endless lives for every new cause, a voice for every event, the drawing, and bots that ride the whole hill (one that dodges well, one that never does).
// Run with: node --test scripts/test-web-console-activities-ghoul-sled.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's intro story: 6 to 8 pages that fit the field, never name the hero, stay generic about stages (no names, no counts) and speak to YOU; a run opens on it and ends in The Long Hall; the lockout, the typing that finishes first, every key and a click, the skip by holding fire, a pause that holds it; never in the practice stage select, on a respawn or in a new room; every page draws on a fake canvas at many moments; every sound it asks for exists.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Servants' Back Stairs (the East Wing's bonus round, between the Attic and the Crypt): its shape (every gap between flights clears with a jump and swallows a tray that does not jump, every low can be ducked, spacing, checkpoints, greased stretches, the clock), the tray's speed on slopes and grease, its jump and duck, a pot, cutlery, a ham, pans, the cook's dish, the domes and plates (the courses), the cherries, a fall down the stairs, the checkpoint, the jump off the last shelf and the door, the bonus round's hearts and dice (3 to 9), endless lives for every new cause, a voice for every event, the drawing, and bots that ride the whole route (one that dodges well, one that never does).
// Run with: node --test scripts/test-web-console-activities-ghoul-tray.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,4 +1,5 @@
// Web console tests, Ghoul Rush's Hollow End Village stage: its four rooms, the moonrise (a moon that climbs over each room and, at full, turns the villagers into wolf-men and makes the moonhounds grow), torch mob villagers that lob fire, hanged men that drop on their ropes, shutter ghouls that can be hit only while out, moonhounds, Wolfsbane (found only here), and the Beast of Hollow End, which clings to the wall for double damage, pounces under a shadow, swipes, howls for hounds and rages at half its hp.
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -1,5 +1,6 @@
// Web console tests, Ghoul Rush's Torch Mob (Hollow End Village's bonus round, between the Square and the Green): its shape (every ditch and the bridge clear with a jump and swallow a wagon that does not jump, every low can be ducked, spacing, checkpoints), the wagon's speed (the brake that is also a duck), every obstacle's cost and cause (barrels, crates, washing lines, inn signs, pitchforks, torches, horses, ditches, the river, the mob), the throwers' wind-up and aim, shooting torches and forks out of the air, the horses, the pursuit meter (the gap that clean riding opens and braking, hits and fire close), the hay fire, the catch, hearts of its own, the grade and the dice, endless lives, the checkpoints, the finish, no random numbers, its sounds and its drawing on a fake canvas, and bots that play it well and badly.
// Run with: node --test scripts/test-web-console-activities-ghoul-wagon.mjs
import "./seed-random.mjs";
import { test } from "node:test";
import assert from "node:assert/strict";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
@@ -5,6 +5,7 @@
// handed, so stub canvases that count or record calls stand in for the page.
// The rules are plain functions over a round, driven here slice by slice.
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
@@ -5,6 +5,7 @@
// handed, so a stub canvas stands in for the page, as in
// scripts/test-web-console-activities.mjs, whose helpers this file copies.
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import * as rapids from "../src/web-console/public/activities/rapids.js";
+32 -5
View File
@@ -1,4 +1,4 @@
// Web console tests, the activities: the shared game contract every listed game answers, Snake's rules, mini golf's rules, course and controls, Light Trails' rules and rivals, Bug Hunt's waves, bugs and bosses, Sunset Drive's road, traffic and forks, Stack Deploy's drops, perfects and twists, Bumper Ring's physics, rivals and arenas, the lives pill and tones of Rapids Run, Ghoul Rush and Bounce Road (their rules live in their own suites), Hot Potato's bomb, fuse, rivals and venues, and Crossing Rush's lanes, hops, shoves, planner and zones.
// Web console tests, the activities: the shared game contract every listed game answers, Snake's rules, mini golf's rules, course and controls, Light Trails' rules and rivals, Bug Hunt's waves, bugs and bosses, Sunset Drive's road, traffic and forks, Stack Deploy's drops, perfects and twists, Bumper Ring's physics, rivals and arenas, the lives pill and tones of Rapids Run, Ghoul Rush, Bounce Road and Flock Dash (their rules live in their own suites), Hot Potato's bomb, fuse, rivals and venues, and Crossing Rush's lanes, hops, shoves, planner and zones.
// Run with: node --test scripts/test-web-console-activities.mjs
//
// No browser and no server: a game draws only through the canvas it is handed,
@@ -6,6 +6,7 @@
// walks every entry in ACTIVITIES plus a stub second game defined here, which
// is what proves a new game needs no change to the window.
import "./seed-random.mjs";
import test from "node:test";
import assert from "node:assert/strict";
import path from "node:path";
@@ -29,6 +30,7 @@ import { hudLayout as hopHudLayout, labelSpot as hopLabelSpot, LANES as HOP_LANE
import * as bounce from "../src/web-console/public/activities/bounce.js";
import * as rapids from "../src/web-console/public/activities/rapids.js";
import * as ghoul from "../src/web-console/public/activities/ghoul-rush/ghoul.js";
import * as flock from "../src/web-console/public/activities/flock.js";
import { ACCENTS } from "../src/web-console/public/palette.js";
import { LIVES, LIVES_BACK, LIVES_INK, livesText, pillContrast } from "../src/web-console/public/activities/pills.js";
@@ -262,8 +264,8 @@ const listedGames = async () => {
/* --------------------------------------------------------------- list */
test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush, and each entry's module is a file under public/activities/", () => {
assert.deepEqual(ACTIVITIES.map((a) => a.id), ["snake", "golf", "trails", "bugs", "drive", "stack", "bumper", "rapids", "fuse", "hop", "bounce", "ghoul"]);
test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash, and each entry's module is a file under public/activities/", () => {
assert.deepEqual(ACTIVITIES.map((a) => a.id), ["snake", "golf", "trails", "bugs", "drive", "stack", "bumper", "rapids", "fuse", "hop", "bounce", "ghoul", "flock"]);
assert.equal(ACTIVITIES[1].title, "Mini golf");
assert.equal(ACTIVITIES[2].title, "Light Trails");
assert.equal(ACTIVITIES[3].title, "Bug Hunt");
@@ -275,6 +277,7 @@ test("the list names Snake, Mini golf, Light Trails, Bug Hunt, Sunset Drive, Sta
assert.equal(ACTIVITIES[9].title, "Crossing Rush");
assert.equal(ACTIVITIES[10].title, "Bounce Road");
assert.equal(ACTIVITIES[11].title, "Ghoul Rush");
assert.equal(ACTIVITIES[12].title, "Flock Dash");
for (const a of ACTIVITIES) {
assert.ok(Object.isFrozen(a), `${a.id} is frozen`);
assert.equal(a.module, a.id === "ghoul" ? "/activities/ghoul-rush/ghoul.js" : `/activities/${a.id}.js`);
@@ -308,7 +311,7 @@ test("memoKey builds a flat looks.json key from a list id", () => {
test("musicKey builds a flat looks.json key, and a game with music has a default volume a saved one replaces", () => {
assert.equal(musicKey("ghoul"), "activityMusicGhoul");
assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["snake", 70], ["trails", 70], ["drive", 70], ["ghoul", 65]], "the games with music, at about the level they were picked at on the prototype pages");
assert.deepEqual(ACTIVITIES.filter((a) => a.music !== undefined).map((a) => [a.id, a.music]), [["snake", 70], ["trails", 70], ["drive", 70], ["ghoul", 65], ["flock", 70]], "the games with music, at about the level they were picked at on the prototype pages");
const ghoulEntry = ACTIVITIES.find((a) => a.id === "ghoul");
assert.equal(musicLevel(ghoulEntry, undefined), 0.65, "nothing saved: the default");
assert.equal(musicLevel(ghoulEntry, "loud"), 0.65, "not a number: the default");
@@ -2450,6 +2453,30 @@ test("Light Trails: a Wide Trail lays your wall three cells wide, and the cells
assert.equal(you.wide.length, 0, "wiped cells leave the list");
});
test("Light Trails: on a Wide Trail you turn onto the side cells just laid, but the older ones are still wall", () => {
const round = racing(trails.newRound(still));
const you = round.riders[0];
park(round, you, 10, 15, "right");
trails.applyPower(round, "wide");
trails.advance(round, trails.STEP_MS, still);
assert.deepEqual({ x: you.x, y: you.y }, { x: 11, y: 15 });
assert.equal(trails.turn(round, "up"), true);
trails.advance(round, trails.STEP_MS, still);
assert.equal(you.alive, true, "the corner turn rides onto the fresh side cell");
assert.deepEqual({ x: you.x, y: you.y }, { x: 11, y: 14 });
assert.ok(!you.wide.some((c) => c.x === 11 && c.y === 14), "that cell is the line now, not a side cell");
// Only the pair beside your head is fresh: one step on, the last pair is wall.
trails.advance(round, trails.STEP_MS, still);
assert.deepEqual({ x: you.x, y: you.y }, { x: 11, y: 13 });
assert.deepEqual(you.fresh.map((c) => `${c.x},${c.y}`).sort(), ["10,13", "12,13"]);
// Riding back down into a side cell laid two steps ago is a crash as ever.
park(round, you, 12, 15, "up");
round.grid[14 * trails.COLS + 12] = 1;
you.fresh = [];
trails.advance(round, trails.STEP_MS + trails.GRACE_MS + 8, still);
assert.equal(you.alive, false, "an older side cell is your wall");
});
test("Light Trails: Hyperjump moves you to an open cell clear of everyone, facing open space", () => {
const round = racing(trails.newRound(still));
const you = round.riders[0];
@@ -6232,7 +6259,7 @@ test("lives read at a glance: a heart per life up to five, a count past that, an
});
test("every game with lives draws them in the lives pill, solid, with a heart per life", () => {
for (const [name, game] of [["trails", trails], ["bugs", bugs], ["bumper", bumper], ["fuse", fuse], ["hop", hop], ["bounce", bounce], ["rapids", rapids], ["ghoul", ghoul]]) {
for (const [name, game] of [["trails", trails], ["bugs", bugs], ["bumper", bumper], ["fuse", fuse], ["hop", hop], ["bounce", bounce], ["rapids", rapids], ["ghoul", ghoul], ["flock", flock]]) {
const { canvas, pills, reset } = pillCanvas("#ffffff");
const g = game.default.create({ canvas });
g.resize(900, 900);
+19 -6
View File
@@ -355,20 +355,33 @@ test("the Desktop app group shows only in the app's frame, reflects the app's sa
});
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) => {
// Activities start off for a new person: save them on for this test.
const looksFile = path.join(HOME, "looks.json");
fs.writeFileSync(looksFile, JSON.stringify({ looks: { hideActivities: false } }));
t.after(() => fs.rmSync(looksFile, { force: true }));
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");
// Each key asks the browser for its own full screen too, and the browser answers a moment
// later: keys fired faster than a person could press them let a late answer to one undo the
// next (seen on slow runners). Pace them: wait for the message to the app, then let the
// browser settle.
const pace = async (key, count) => {
await s.page.keyboard.press(key);
await until(async () => (await told()).length >= count, 5000);
await s.page.waitForTimeout(250);
};
await pace("f", 1);
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");
await pace("f", 2);
await pace("f", 3);
await pace("Escape", 4);
assert.deepEqual(await told(), [true, false, true, false], "F and Esc each give it back");
await s.page.keyboard.press("f");
await pace("f", 5);
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);
await until(async () => (await told()).length >= 6, 5000);
assert.deepEqual(await told(), [true, false, true, false, true, false], "and so does a new question");
});
+136 -25
View File
@@ -1,6 +1,6 @@
// Page tests for Activities: the die in the top bar on every screen, the
// window opening on the picker (a card per game, walked by the arrows, one
// game at a time, All games back to it), Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush in play, the keys
// game at a time, All games back to it), Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash in play, the keys
// staying inside the window, Esc and P, and every pause rule (a new question,
// a finish, a hidden page, a window blur), none of which ever resumes play by
// itself. Mini golf in the real window: aim by mouse, two clicks to putt,
@@ -20,7 +20,7 @@
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import test, { beforeEach, after } from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, drawn, itemCard, boxValue, fillBox } from "./page-test-helpers.mjs";
import { until, HOME } from "./web-console-test-helpers.mjs";
@@ -30,11 +30,17 @@ const suite = pageSuite(test);
// The person's saved looks, shared by every session in this console home.
const LOOKS_FILE = path.join(HOME, "looks.json");
// Starts a test from the given saved looks (none when left out) and leaves
// none behind, so a best score or a hidden die never leaks into the next test.
// Activities start off for a new person, so a test that saves no looks of its
// own still starts with the die showing. savedLooks() replaces this file.
beforeEach(() => fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { hideActivities: false } })));
after(() => fs.rmSync(LOOKS_FILE, { force: true }));
// Starts a test from the given saved looks and leaves none behind, so a best
// score or a hidden die never leaks into the next test. Activities start off
// for a new person, so every test starts with them on (hideActivities false)
// unless it saves its own switch.
function savedLooks(t, looks) {
if (looks) fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks }));
else fs.rmSync(LOOKS_FILE, { force: true });
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { hideActivities: false, ...looks } }));
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
}
@@ -166,7 +172,7 @@ test("the die sits right of the megaphone and opens on the picker, a card per ga
const next = await s.page.evaluate(() => document.getElementById("btn-feedback").nextElementSibling?.id);
assert.equal(next, "btn-activities");
await openPicker(s);
assert.deepEqual(await cardTitles(s), ["Snake", "Mini golf", "Light Trails", "Bug Hunt", "Sunset Drive", "Stack Deploy", "Bumper Ring", "Rapids Run", "Hot Potato", "Crossing Rush", "Bounce Road", "Ghoul Rush"]);
assert.deepEqual(await cardTitles(s), ["Snake", "Mini golf", "Light Trails", "Bug Hunt", "Sunset Drive", "Stack Deploy", "Bumper Ring", "Rapids Run", "Hot Potato", "Crossing Rush", "Bounce Road", "Ghoul Rush", "Flock Dash"]);
assert.ok(await s.page.locator("#activities-board").isHidden(), "no board behind the picker");
assert.ok(await s.page.locator("#activities-back").isHidden(), "nothing to go back to");
assert.equal(await s.page.locator("#activities-title").innerText(), "Activities", "the header names no game");
@@ -188,9 +194,9 @@ test("the arrows walk the picker's cards, and space or Enter opens the one in fo
assert.equal(await focusedCard(s), "snake");
await s.page.keyboard.press("ArrowRight");
assert.equal(await focusedCard(s), "golf");
for (let i = 0; i < 11; i++) await s.page.keyboard.press("ArrowRight");
assert.equal(await focusedCard(s), "ghoul", "the last card stays put");
for (let i = 0; i < 10; i++) await s.page.keyboard.press("ArrowLeft");
for (let i = 0; i < 12; i++) await s.page.keyboard.press("ArrowRight");
assert.equal(await focusedCard(s), "flock", "the last card stays put");
for (let i = 0; i < 11; i++) await s.page.keyboard.press("ArrowLeft");
assert.equal(await focusedCard(s), "golf");
await s.page.keyboard.press("Enter");
// Mini golf opens on its course dashboard, walked the same way.
@@ -277,7 +283,7 @@ test("a new session's picker marks the last played and puts focus on it, and a l
assert.match(await card(s, "golf").innerText(), /Last played/);
assert.doesNotMatch(await card(s, "snake").innerText(), /Last played/);
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, lastActivity: "chess" } }));
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, hideActivities: false, lastActivity: "chess" } }));
const again = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
await openPicker(again);
assert.equal(await focusedCard(again), "snake", "an unknown pick puts focus on the first card");
@@ -1121,6 +1127,7 @@ test("Full screen gives the board the whole screen with a panel holding the scor
const back = await fullParts(s);
assert.ok(!back.full && !back.rail && !back.scoreInRail, "F puts it back, the score under the board again");
await s.page.keyboard.press("f");
await until(async () => (await fullParts(s)).full, 5000);
assert.ok((await fullParts(s)).full, "and F fills it again");
await s.page.click("#activities-rail-exit");
assert.ok(!(await fullParts(s)).full, "the panel's Exit full screen puts it back");
@@ -1217,7 +1224,7 @@ const COUNT_SOUNDS = () => {
};
};
test("Play game sounds in User Preferences silences the games and the countdown, Play sounds off grays it out, and Back to default turns it back on", async (t) => {
test("Play activity sounds in User Preferences silences the games and the countdown, Play sounds off grays it out, and Back to default turns it back on", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING, init: COUNT_SOUNDS });
const played = () => s.page.evaluate(() => window.__oscillators);
// Starts a fresh round with the 3, 2, 1, which plays a blip, and closes it.
@@ -1261,7 +1268,7 @@ test("Play game sounds in User Preferences silences the games and the countdown,
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).activitySounds === true);
});
test("a game with music has its own Music slider, at its default until moved, kept once moved, and dimmed while Play game music is off", async (t) => {
test("a game with music has its own Music slider, at its default until moved, kept once moved, and dimmed while Play activity music is off", async (t) => {
savedLooks(t, { gameMusic: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
const slider = s.page.locator("#activities-music-level");
@@ -1285,8 +1292,8 @@ test("a game with music has its own Music slider, at its default until moved, ke
});
await openActivities(s, "ghoul");
assert.equal(await boxValue(slider), "80", "kept");
assert.equal(await slider.isDisabled(), true, "Play game music off: dimmed");
assert.match(await s.page.locator("#activities-music").getAttribute("title"), /Play game music/, "and says why");
assert.equal(await slider.isDisabled(), true, "Play activity music off: dimmed");
assert.match(await s.page.locator("#activities-music").getAttribute("title"), /Play activity music/, "and says why");
});
test("the board is laid out again when the banner appears, so the canvas is never clipped", async (t) => {
@@ -2085,26 +2092,26 @@ test("saved Activities values that do not hold up fall back to their defaults",
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
const looks = await pageLooks(s);
assert.equal(looks.activityBestSnake, 0, "a negative best is none");
assert.equal(looks.hideActivities, false, "a switch that is not a boolean is on");
assert.equal(looks.hideActivities, true, "a switch that is not a boolean is off, the default");
assert.equal(looks.lastActivity, "", "a last pick that is not a string is none");
await iconUsable(s, "a skill screen");
assert.ok(await s.page.locator("#btn-activities").isHidden(), "and the die stays hidden");
fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks: { welcomeSeen: true, activityBestSnake: 3.7 } }));
const again = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
assert.equal((await pageLooks(again)).activityBestSnake, 3, "a best is a whole number");
});
test("Back to default turns Show Activities back on and keeps the best scores", async (t) => {
savedLooks(t, { welcomeSeen: true, activityBestSnake: 12, lastActivity: "snake", hideActivities: true });
test("Back to default turns Show Activities back off and keeps the best scores", async (t) => {
savedLooks(t, { welcomeSeen: true, activityBestSnake: 12, lastActivity: "snake", hideActivities: false });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
assert.ok(await s.page.locator("#btn-activities").isHidden(), "the saved switch hides the die");
await iconUsable(s, "a skill screen with the switch saved on");
await s.page.click("#btn-looks");
await s.page.click("#prefs-tab-sounds");
await s.page.locator("#looks-modal[open]").waitFor();
await s.page.click("#looks-reset");
await s.page.click("#looks-done");
await iconUsable(s, "a skill screen after Back to default");
await until(async () => (await serverLooks(s)).hideActivities === false, 5000);
assert.ok(await s.page.locator("#btn-activities").isHidden(), "the default hides the die again");
await until(async () => (await serverLooks(s)).hideActivities === true, 5000);
const saved = await serverLooks(s);
assert.equal(saved.activityBestSnake, 12, "the best score stays");
assert.equal(saved.lastActivity, "snake", "the last pick stays");
@@ -2139,7 +2146,7 @@ test("Show Activities in User Preferences hides the die on the dashboard and on
await dash.page.click("#prefs-tab-sounds");
await dash.page.locator("#looks-modal[open]").waitFor();
const box = dash.page.locator("#looks-activities");
assert.ok(await box.isChecked(), "on by default");
assert.ok(await box.isChecked(), "on as saved");
await box.uncheck();
await dash.page.click("#looks-done");
assert.ok(await dash.page.locator("#btn-activities").isHidden(), "the die is gone from the dashboard");
@@ -2513,10 +2520,114 @@ test("Ghoul Rush plays in the real window: its board's shape and Planny big enou
}, 5000);
});
test("the server serves the activities' scripts, golf's seventeen, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring's two, Rapids Run's two, Hot Potato's two, Crossing Rush's two, Bounce Road's seven, Ghoul Rush's ninety-five, every game's sound effects and the shared pills included", () => {
test("Flock Dash plays in the real window: its board's shape, Enter starts a round, a held up arrow raises the leader until let go, a stray in front of the leader joins the flock, F goes full screen and back, and the last life lost saves the best and the furthest stage", async (t) => {
savedLooks(t, { welcomeSeen: true });
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_WORKING });
await handTicks(s);
// The hazards and crates are cleared before every tick and the leader kept
// in grace, so only the keys and the strays placed here move the round.
await s.page.evaluate(async () => {
const m = await import("/screens/activities.js");
const { ACTIVITIES } = await import("/activities.js");
const flock = (await import("/activities/flock.js")).default;
window.__calm = true;
const watched = {
...flock,
create: (opts) => {
const g = flock.create(opts);
const tick = g.tick;
g.tick = (ms) => {
const r = g.round;
if (window.__calm && r) {
r.hazards.length = r.crates.length = 0;
r.leader.grace = 1e9;
}
tick(ms);
};
return (window.__flock = g);
},
};
m.setActivityList(ACTIVITIES.map((e) => (e.id === "flock" ? { ...e, game: watched } : e)));
});
await openActivities(s, "flock");
assert.equal(await overlay(s), "Press space to start");
const { W, H } = await s.page.evaluate(async () => {
const { W, H } = await import("/activities/flock.js");
return { W, H };
});
const box = await s.page.locator("#activities-canvas").boundingBox();
assert.ok(Math.abs(box.width / box.height - W / H) < 0.02, `a ${W} by ${H} board, not ${box.width} by ${box.height}`);
const you = () =>
s.page.evaluate(() => {
const r = window.__flock.round;
return { ...r.input, y: r.leader.y, flock: r.flock.length, strays: r.strays.length, over: r.over };
});
// Enter starts a round and has no release: nothing may be left held.
await s.page.keyboard.press("Enter");
assert.equal(await overlay(s), "", "Enter starts a round");
await step(s, 20, 16);
let me = await you();
assert.deepEqual([me.up, me.down, me.left, me.right], [false, false, false, false], "the start leaves no key held");
// A held up arrow raises the leader until let go.
const y0 = me.y;
await s.page.keyboard.down("ArrowUp");
await step(s, 12, 16);
me = await you();
assert.ok(me.up && me.y < y0 - 1, `held up climbs (${y0} to ${me.y})`);
await s.page.keyboard.up("ArrowUp");
assert.equal((await you()).up, false, "let go, it stops climbing");
await step(s, 40, 16);
const rest = (await you()).y;
await step(s, 10, 16);
assert.ok(Math.abs((await you()).y - rest) < 0.01, "and the leader holds its height");
// A stray placed just ahead of the leader joins the flock.
const before = (await you()).flock;
await s.page.evaluate(() => {
const r = window.__flock.round;
r.strays.length = 0;
window.__strayId = r.nextId++;
r.strays.push({ id: window.__strayId, x: r.leader.x + 1.5, y: r.leader.y, bob: 0 });
});
await until(async () => (await you()).flock > before || (await step(s, 2, 16), false), 5000);
assert.ok((await you()).flock >= before + 1, "the stray joined the flock");
assert.ok(
await s.page.evaluate(() => !window.__flock.round.strays.some((b) => b.id === window.__strayId)),
"and it is the placed stray that is gone from the sky"
);
// F fills the screen and F puts it back, the round still running.
await s.page.keyboard.press("f");
await until(async () => (await fullParts(s)).full, 5000);
await s.page.keyboard.press("f");
await until(async () => !(await fullParts(s)).full, 5000);
assert.equal(await overlay(s), "", "a running game");
// Lose the last life: the round ends and saves its best and furthest stage.
await s.page.evaluate(async () => {
const { hitLeader } = await import("/activities/flock.js");
window.__calm = false;
const r = window.__flock.round;
r.score = Math.max(r.score, 120);
r.lives = 1;
r.active.shields = 0;
r.leader.grace = 0;
hitLeader(r);
});
await step(s, 10, 16);
await until(async () => (await overlay(s)).startsWith("Score:"), 5000);
const score = await s.page.evaluate(() => window.__flock.score);
assert.ok(score >= 120);
await until(async () => {
const looks = await serverLooks(s);
return looks.activityBestFlock === score && looks.activityMemoFlock === 1;
}, 5000);
});
test("the server serves the activities' scripts, golf's seventeen, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring's two, Rapids Run's two, Hot Potato's two, Crossing Rush's two, Bounce Road's seven, Ghoul Rush's ninety-five, Flock Dash's three, every game's sound effects and the shared pills included", () => {
const server = fs.readFileSync(new URL("../src/web-console/static.mjs", import.meta.url), "utf8");
const servable = server.slice(server.indexOf("const SERVABLE = new Set(["), server.indexOf("]);", server.indexOf("const SERVABLE = new Set([")));
for (const file of ["activities.js", "tones.js", "music.js", "activities/snake.js", "activities/snake-music.js", "screens/activities.js", "activities/golf.js", "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-rush/ghoul.js", "activities/ghoul-rush/draw/ghoul-draw.js", "activities/ghoul-rush/core/ghoul-rooms.js", "activities/ghoul-rush/stages/wing/ghoul-bones.js", "activities/ghoul-rush/stages/wing/ghoul-bones-draw.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js", "activities/ghoul-rush/stages/village/ghoul-village.js", "activities/ghoul-rush/stages/village/ghoul-village-draw.js", "activities/ghoul-rush/stages/village/ghoul-village-world.js", "activities/ghoul-rush/stages/village/ghoul-village-wolf.js", "activities/ghoul-rush/stages/mine/ghoul-mine.js", "activities/ghoul-rush/stages/mine/ghoul-mine-draw.js", "activities/ghoul-rush/stages/mine/ghoul-mine-world.js", "activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js", "activities/ghoul-rush/rides/cart/ghoul-cart.js", "activities/ghoul-rush/rides/cart/ghoul-cart-draw.js", "activities/ghoul-rush/rides/sled/ghoul-sled.js", "activities/ghoul-rush/rides/sled/ghoul-sled-draw.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js", "activities/ghoul-rush/rides/banister/ghoul-banister.js", "activities/ghoul-rush/rides/banister/ghoul-banister-draw.js", "activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew.js", "activities/ghoul-rush/rides/pew/ghoul-pew-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew-course.js", "activities/ghoul-rush/rides/pew/ghoul-pew-world.js", "activities/ghoul-rush/rides/mower/ghoul-mower.js", "activities/ghoul-rush/rides/mower/ghoul-mower-draw.js", "activities/ghoul-rush/rides/tray/ghoul-tray.js", "activities/ghoul-rush/rides/tray/ghoul-tray-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js", "activities/ghoul-rush/arms/ghoul-flare.js", "activities/ghoul-rush/stages/bog/ghoul-bog.js", "activities/ghoul-rush/stages/bog/ghoul-bog-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js", "activities/ghoul-rush/rides/mat/ghoul-mat-room.js", "activities/ghoul-rush/rides/mat/ghoul-mat.js", "activities/ghoul-rush/rides/mat/ghoul-mat-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-pit-room.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js", "activities/ghoul-rush/story/ghoul-ending.js", "activities/ghoul-rush/story/ghoul-ending-draw.js", "activities/ghoul-rush/draw/ghoul-picker-draw.js", "aLine truncated
for (const file of ["activities/flock.js", "activities/flock-draw.js", "activities/flock-sfx.js", "activities.js", "tones.js", "music.js", "activities/snake.js", "activities/snake-music.js", "screens/activities.js", "activities/golf.js", "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-rush/ghoul.js", "activities/ghoul-rush/draw/ghoul-draw.js", "activities/ghoul-rush/core/ghoul-rooms.js", "activities/ghoul-rush/stages/wing/ghoul-bones.js", "activities/ghoul-rush/stages/wing/ghoul-bones-draw.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard.js", "activities/ghoul-rush/stages/graveyard/ghoul-graveyard-draw.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds.js", "activities/ghoul-rush/stages/grounds/ghoul-grounds-draw.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel.js", "activities/ghoul-rush/stages/chapel/ghoul-chapel-draw.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium.js", "activities/ghoul-rush/stages/sanatorium/ghoul-sanatorium-draw.js", "activities/ghoul-rush/stages/village/ghoul-village.js", "activities/ghoul-rush/stages/village/ghoul-village-draw.js", "activities/ghoul-rush/stages/village/ghoul-village-world.js", "activities/ghoul-rush/stages/village/ghoul-village-wolf.js", "activities/ghoul-rush/stages/mine/ghoul-mine.js", "activities/ghoul-rush/stages/mine/ghoul-mine-draw.js", "activities/ghoul-rush/stages/mine/ghoul-mine-world.js", "activities/ghoul-rush/stages/mine/ghoul-mine-tommy.js", "activities/ghoul-rush/rides/cart/ghoul-cart.js", "activities/ghoul-rush/rides/cart/ghoul-cart-draw.js", "activities/ghoul-rush/rides/sled/ghoul-sled.js", "activities/ghoul-rush/rides/sled/ghoul-sled-draw.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney.js", "activities/ghoul-rush/rides/gurney/ghoul-gurney-draw.js", "activities/ghoul-rush/rides/banister/ghoul-banister.js", "activities/ghoul-rush/rides/banister/ghoul-banister-draw.js", "activities/ghoul-rush/rides/banister/ghoul-sfx-banister.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse.js", "activities/ghoul-rush/rides/hearse/ghoul-hearse-draw.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon.js", "activities/ghoul-rush/rides/wagon/ghoul-wagon-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew.js", "activities/ghoul-rush/rides/pew/ghoul-pew-draw.js", "activities/ghoul-rush/rides/pew/ghoul-pew-course.js", "activities/ghoul-rush/rides/pew/ghoul-pew-world.js", "activities/ghoul-rush/rides/mower/ghoul-mower.js", "activities/ghoul-rush/rides/mower/ghoul-mower-draw.js", "activities/ghoul-rush/rides/tray/ghoul-tray.js", "activities/ghoul-rush/rides/tray/ghoul-tray-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-draw.js", "activities/ghoul-rush/stages/carnival/ghoul-carnival-world.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-draw.js", "activities/ghoul-rush/stages/frozen/ghoul-frozen-world.js", "activities/ghoul-rush/arms/ghoul-flare.js", "activities/ghoul-rush/stages/bog/ghoul-bog.js", "activities/ghoul-rush/stages/bog/ghoul-bog-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-draw.js", "activities/ghoul-rush/rides/mat/ghoul-mat-room.js", "activities/ghoul-rush/rides/mat/ghoul-mat.js", "activities/ghoul-rush/rides/mat/ghoul-mat-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-dollhouse-room.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-eye.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-eye-draw.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair-room.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair.js", "activities/ghoul-rush/rides/bonestair/ghoul-bonestair-draw.js", "activities/ghoul-rush/stages/marrow/ghoul-pit-room.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-heart.js", "activities/ghoul-rush/stages/marrow/ghoul-marrow-heart-draw.js", "activities/ghoul-rush/story/ghoul-ending.js", "activities/ghoul-rush/storLine truncated
assert.ok(servable.includes(`"${file}"`), `SERVABLE includes ${file}`);
}
for (let n = 1; n <= 5; n++) {
assert.ok(servable.includes(`"activities/flock-dash/${n}.mp3"`), `SERVABLE includes activities/flock-dash/${n}.mp3`);
}
});
+6 -6
View File
@@ -9,7 +9,7 @@
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, itemCard, textOf , fillBox, boxValue} from "./page-test-helpers.mjs";
import { pageSuite, openSession, itemCard, textOf , fillBox, boxValue, sendAsk, settled } from "./page-test-helpers.mjs";
import { reportedHelper } from "./web-console-test-helpers.mjs";
import { readChat } from "../src/web-console/inbox.mjs";
@@ -56,9 +56,7 @@ async function openAsk(s) {
// Types a question and presses Send in the Ask pane.
async function askQuestion(s, text) {
const box = s.page.locator("#ask-input");
await fillBox(box, text);
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
await sendAsk(s.page, text);
}
// What a person sees break: a question typed in Ask that never reaches the
@@ -197,6 +195,9 @@ test("a picture thumbnail opens the picview from the note tray and a sent Ask me
const aside = s.page.locator("#aside");
await aside.locator('input[type="file"]').setInputFiles({ name: "shot.png", mimeType: "image/png", buffer: PNG });
await aside.locator(".attach-thumb.is-ready").waitFor();
// The tray can redraw a moment after an upload lands (the state it rides on arrives by event),
// and a redraw after Esc would take the restored focus with the old button: let it go quiet first.
await settled(s.page, "#aside");
await aside.locator(".attach-open").click();
await s.page.locator("#picview[open]").waitFor();
@@ -216,8 +217,7 @@ test("a picture thumbnail opens the picview from the note tray and a sent Ask me
const comp = s.page.locator(".ask-composer");
await comp.locator('input[type="file"]').setInputFiles({ name: "shot2.png", mimeType: "image/png", buffer: PNG });
await comp.locator(".attach-thumb.is-ready").waitFor();
await fillBox(box, "See the screenshot.");
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
await sendAsk(s.page, "See the screenshot.");
const sent = s.page.locator(".ask-row.person .attach-thumb").last();
await sent.waitFor();
await sent.locator(".attach-open").click();
+11 -1
View File
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { gitInit } from "./skill-script-helpers.mjs";
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf, scrollCard, stylesOf, styleOf , fillBox, boxValue} from "./page-test-helpers.mjs";
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf, scrollCard, stylesOf, styleOf , fillBox, boxValue, settled } from "./page-test-helpers.mjs";
const suite = pageSuite(test);
@@ -49,6 +49,9 @@ test("the answer box renders Markdown live, like the Notebook", async (t) => {
const content = card.locator(".md-host .cm-content");
await content.waitFor({ timeout: 15000 });
assert.equal(await card.locator("textarea").count(), 0, "the answer box is the Markdown editor, not a textarea");
// A redraw that lands while the box is typed in sends the caret back to the start (seen on
// slow runners as "plain**bold**"): let the page go quiet before typing.
await settled(s.page, "#main");
await content.click();
await content.pressSequentially("**bold**\nplain");
await card.locator(".cm-strong", { hasText: "bold" }).waitFor();
@@ -225,6 +228,11 @@ test("a redraw keeps your place: the scroll and the focused field survive an age
},
});
// The answer box's editor mounts after the first draw and may redraw the
// card: wait for it before scrolling, so no redraw can replace the card
// between the scroll and the agent's post.
await itemCard(s.page, "q1").locator(".md-host .cm-content").first().waitFor();
// Reading a question part-way down: the card scrolls itself.
const card = itemCard(s.page, "q1");
assert.equal(await scrollCard(card, 400), 400, "the question card scrolls");
@@ -314,6 +322,7 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
await settled(s.page, "#main > .dash");
await scrollCard(s.page.locator("#main > .dash"), 150);
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard scrolls");
await unrelatedPost(s, "Dashboard, take two");
@@ -329,6 +338,7 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
await s.page.setViewportSize({ width: 1280, height: 300 });
const pane = "#main > .waiting-pane";
await s.page.locator(pane).waitFor();
await settled(s.page, pane);
await scrollCard(s.page.locator(pane), 60);
const waitingAt = await scrollTopOf(s.page, pane);
assert.ok(waitingAt > 0, "the waiting screen scrolls");
+2 -1
View File
@@ -179,7 +179,8 @@ test("the Welcome shows on a first dashboard, saves that it was seen, and Help's
await s.page.getByRole("button", { name: "Start building" }).click();
await welcome.waitFor({ state: "hidden" });
// Saved with the other looks, so it holds for the next page too.
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).welcomeSeen === true);
// Polled from here: waitForFunction does not wait on an async predicate, so it passed before the POST landed.
assert.ok(await until(() => s.page.evaluate(async () => ((await (await fetch("/looks")).json()).looks || {}).welcomeSeen === true)), "the Welcome being seen was saved");
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
+4 -4
View File
@@ -767,7 +767,7 @@ test("Back to default resets only the tab on screen, and is hidden on Agents & m
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.locator("#looks-activities").check();
await s.page.click("#prefs-tab-agents");
assert.equal(await s.page.locator("#looks-reset").isHidden(), true, "hidden on Agents & models");
@@ -780,18 +780,18 @@ test("Back to default resets only the tab on screen, and is hidden on Agents & m
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);
assert.equal(await s.page.locator("#looks-activities").isChecked(), true, "and Activities on");
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 s.page.locator("#looks-activities").isChecked(), false, "the sounds reset puts Activities back off");
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";
return saved.sound === true && saved.hideActivities === true && saved.theme === "dark";
});
});
+149 -15
View File
@@ -11,7 +11,7 @@ import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject , fillBox, boxValue} from "./page-test-helpers.mjs";
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject , fillBox, boxValue, sendAsk } 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";
@@ -173,6 +173,120 @@ test("a finished screen's press that nothing collects says Plan2Code is not runn
await until(async () => (await toApp(s, "agent-continue")).length === 1, 5000);
});
// A dashboard whose agent stopped answering (its terminal died or sat idle for
// a long while): the sidebar offers to wake it. Under the app that is the
// continue button; in a browser it is the instruction to type it.
const DASH_MENU = { menu: { note: "Pick one." }, agent: { status: "waiting" } };
test("a quiet dashboard agent shows a continue button under the app, which asks the app to type it", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "dashboard",
clock: true,
payload: DASH_MENU,
env: { PLAN2CODE_IN_APP: "1" },
init: FAKE_APP_FRAME,
});
// The dashboard's wake-up intro covers the page until it is skipped.
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await skip.waitFor({ state: "hidden" });
await dismissWelcome(s);
await s.page.clock.fastForward(200_000);
await lineSays(s, /^Plan2Code has gone quiet\./);
assert.match(await s.page.locator("#planny").getAttribute("class"), /\bis-adrift\b/);
assert.equal(await whatToCheck(s).count(), 1, "the quiet line carries What to check");
const press = s.page.locator("#agent-text .agent-key-btn");
assert.equal(await press.textContent(), "continue");
await press.click();
await until(async () => (await toApp(s, "agent-continue")).length === 1, 5000);
});
test("a quiet dashboard agent in a browser says to type continue in the terminal, with no button", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", clock: true, payload: DASH_MENU });
await s.page.clock.fastForward(200_000);
await lineSays(s, /^Plan2Code has gone quiet\./);
assert.match(await textOf(statusLine(s)), /type continue there/);
assert.equal(await s.page.locator("#agent-text .agent-key-btn").count(), 0, "a browser cannot type into a terminal");
assert.equal(await s.page.locator("#agent-text .agent-key").count(), 1, "continue shows as a key to type");
});
// A pick nobody collected: the saved-and-waiting screen. Under the app it holds
// a Reconnect to agent button; in a browser its hint says to type continue.
async function pickFromMenu(s) {
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await skip.waitFor({ state: "hidden" });
await dismissWelcome(s);
const main = s.page.locator("#main");
await main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) }).click();
await main.getByRole("button", { name: "Start Plan" }).click();
await main.getByRole("heading", { name: /^Waking up / }).waitFor();
await s.page.clock.fastForward(200_000);
await main.getByRole("heading", { name: /is saved and waiting$/ }).waitFor();
return main;
}
test("a saved pick nobody collected offers Reconnect to agent under the app, which asks the app to type continue", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "dashboard",
clock: true,
payload: DASH_MENU,
env: { PLAN2CODE_IN_APP: "1" },
init: FAKE_APP_FRAME,
});
const main = await pickFromMenu(s);
assert.match(await textOf(main), /Press Reconnect to agent below\./);
await main.getByRole("button", { name: "Reconnect to agent", exact: true }).click();
await until(async () => (await toApp(s, "agent-continue")).length === 1, 5000);
});
test("a saved pick nobody collected says to type continue in a browser, with no button", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", clock: true, payload: DASH_MENU });
const main = await pickFromMenu(s);
assert.match(await textOf(main), /Return to the terminal and type continue\./);
assert.equal(await main.getByRole("button", { name: "Reconnect to agent" }).count(), 0);
});
// The Ask tab's red "No agent available" line leads nowhere on its own. Under
// the app a Reconnect to agent button sits left of Send and asks the app to type
// continue; in a browser the line tells the person to.
async function askOffline(s) {
await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click();
await s.page.locator("#ask-input").waitFor();
await s.page.clock.fastForward(200_000);
await s.page.waitForFunction((t) => document.body.innerText.includes(t), CHAT_OFFLINE_TEXT, { timeout: 10000 });
}
test("the Ask tab offers Reconnect to agent left of Send when no agent is there, under the app", async (t) => {
const s = await openSession(await suite.browser(), {
t,
workflow: "plan",
clock: true,
payload: PLAN_QUESTION,
env: { PLAN2CODE_IN_APP: "1" },
init: FAKE_APP_FRAME,
});
await askOffline(s);
const row = s.page.locator(".ask-composer");
const reconnect = row.getByRole("button", { name: "Reconnect to agent", exact: true });
assert.equal(await reconnect.count(), 1);
const [r, send] = await Promise.all([reconnect.boundingBox(), row.getByRole("button", { name: "Send", exact: true }).boundingBox()]);
assert.ok(r.x + r.width <= send.x + 1, "Reconnect to agent sits left of Send");
assert.equal(await row.getByRole("button", { name: "Send", exact: true }).isDisabled(), true, "Send stays off");
await reconnect.click();
await until(async () => (await toApp(s, "agent-continue")).length === 1, 5000);
});
test("the Ask tab in a browser says to type continue in the terminal, with no reconnect button", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", clock: true, payload: PLAN_QUESTION });
await askOffline(s);
const row = s.page.locator(".ask-composer");
assert.equal(await row.getByRole("button", { name: "Reconnect to agent" }).count(), 0);
assert.match(await textOf(row), /type continue in your terminal/i);
});
test("Continue here is hidden once the session meter is red, and the command and fresh-session advice stay", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
// Ten points: a thirty-task phase scores ten, the red level.
@@ -643,8 +757,7 @@ test("answers a working agent has not collected bring up the saved-and-waiting l
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 fillBox(s.page.locator("#ask-input"), "What does the export include?");
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
await sendAsk(s.page, "What does the export include?");
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();
@@ -755,9 +868,7 @@ test("the footer keeps its workspace label on the dashboard, and the label opens
// Past Planny's wake-up and, on this console home's first run, the Welcome.
await s.page.getByRole("button", { name: "Skip the intro" }).click();
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 dismissWelcome(s);
const foot = s.page.locator("footer.footer");
const where = s.page.locator("#footer-where");
await where.waitFor();
@@ -793,24 +904,47 @@ test("a workflow page uses its modules: the full footer, the session meter, @ su
// The @ list is the workspace frame, which can land after the page draws;
// the footer has one label per width tier once it has.
await s.page.waitForFunction(() => (document.getElementById("footer-where").dataset.key || "").includes("\n"));
const box = itemCard(s.page, "q1").locator(".md-host");
const ed = box.locator(".cm-content");
await ed.click();
await ed.pressSequentially("See @");
await s.page.locator("#mention-pop").waitFor();
assert.match(await textOf(s.page.locator("#mention-pop")), new RegExp(name));
// A redraw can replace the box while it is typed in: the typing is lost, or the list closes
// with the box it belonged to (both seen on slow runners). Clear the box and type again until
// the list is up and names the project, up to four times, then assert it for real.
const pop = s.page.locator("#mention-pop");
const listed = async () => {
try {
await pop.waitFor({ timeout: 3000 });
return new RegExp(name).test(await pop.innerText({ timeout: 1500 }));
} catch {
return false;
}
};
for (let attempt = 0; attempt < 4; attempt++) {
const ed = itemCard(s.page, "q1").locator(".md-host .cm-content").first();
await ed.click();
await ed.pressSequentially("See @");
if (await listed()) break;
await fillBox(itemCard(s.page, "q1").locator(".md-host"), "");
}
await pop.waitFor();
assert.match(await textOf(pop), new RegExp(name));
// favicon.js: the person's move puts a bar on the tab icon.
await s.page.waitForFunction(() => document.querySelector('link[rel="icon"][type="image/svg+xml"]').href.startsWith("data:image/svg+xml"));
});
// The Welcome opens a moment after the page is drawn, so a one-shot
// isVisible() can miss it and leave it covering the page. Give it a short
// wait to appear; a console home that has seen it never shows it.
async function dismissWelcome(s) {
const done = s.page.getByRole("button", { name: "Start building" });
const shown = await done.waitFor({ timeout: 2500 }).then(() => true, () => false);
if (shown) await done.click();
await done.waitFor({ state: "hidden" });
}
// The dashboard, past Planny's wake-up and the first-run Welcome.
async function pastTheIntro(s) {
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
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 dismissWelcome(s);
}
// What a person sees break: a handoff offered where there is nothing to hand off.
+4 -1
View File
@@ -86,7 +86,10 @@ test("an @ in a note offers the workspace's folders, and picking one writes its
await pop.waitFor();
const options = pop.locator(".mention-opt");
assert.deepEqual(await options.allTextContents(), ["@datasets"], "only the folder that matches what was typed");
await options.first().click();
// The list repaints on every key release, so Playwright's click can lose
// its option to a repaint on a slow machine and retry for a minute: click
// the option in one step from the page instead.
await s.page.evaluate(() => document.querySelector("#mention-pop .mention-opt").click());
await pop.waitFor({ state: "detached" });
assert.equal(await boxValue(note), "Look in @datasets ");
+16 -4
View File
@@ -326,8 +326,14 @@ test("a stale dashboard launch says the pick is saved and how to wake the agent"
kicker: "Saved",
title: "Pathfinder is saved and waiting",
quip: "Plan2Code is not running right now.",
hint: "Return to the terminal and send any message. Plan2Code will collect this launch and continue here.",
hint: "Return to the terminal and type continue. Plan2Code will collect this launch and continue here.",
});
// Under the desktop app the Reconnect to agent button is on the screen, so
// the hint points at it instead of the terminal.
assert.equal(
staleLaunchFeedback("Pathfinder", true, true).hint,
"Press Reconnect to agent below. Plan2Code will collect this launch and continue here."
);
assert.equal(staleLaunchFeedback("Pathfinder", false), null);
});
@@ -337,10 +343,15 @@ test("a stale dashboard launch says the pick is saved and how to wake the agent"
// never sent.
test("the submitted event names the items that went", async () => {
const port = Number(new URL(baseUrl).port);
// Resolved once the stream is connected: a submit posted before then is
// never delivered to it, which timed out on a slow runner.
let connected;
const open = new Promise((resolve) => (connected = resolve));
const frame = new Promise((resolve, reject) => {
const req = http.request(
{ host: "127.0.0.1", port, path: "/events", method: "GET", headers: { cookie: cookieFor(baseUrl, token) } },
(res) => {
connected();
let buf = "";
res.setEncoding("utf8");
res.on("data", (chunk) => {
@@ -366,6 +377,7 @@ test("the submitted event names the items that went", async () => {
req.end();
});
await open;
await post("/submit", {
actions: [{ i: "__brief", type: "brief", range: "today" }],
reply: "Write a brief for today.",
@@ -838,18 +850,18 @@ test("prefs: Back to default resets Appearance or Sounds & activities only, and
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" });
Object.assign(looks, { theme: "dark", width: "wide", accent: "violet", role: "pm", sound: false, soundQuestion: false, hideActivities: false, 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);
assert.equal(looks.hideActivities, false);
resetLooks(prefsResetScope("sounds"));
assert.equal(looks.sound, true);
assert.equal(looks.soundQuestion, true);
assert.equal(looks.hideActivities, false);
assert.equal(looks.hideActivities, DEFAULT_LOOKS.hideActivities);
assert.equal(looks.activityBestSnake, 7, "best scores stay");
assert.equal(looks.lastActivity, "snake", "the last pick stays");
} finally {
+16
View File
@@ -18,6 +18,8 @@ import { MUSIC_TRACKS } from "../src/web-console/public/activities/snake.js";
import snakeSfx from "../src/web-console/public/activities/snake-sfx.js";
import { MUSIC_TRACKS as TRAILS_TRACKS } from "../src/web-console/public/activities/trails.js";
import trailsSfx from "../src/web-console/public/activities/trails-sfx.js";
import { MUSIC_TRACKS as FLOCK_TRACKS } from "../src/web-console/public/activities/flock.js";
import flockSfx from "../src/web-console/public/activities/flock-sfx.js";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const GAMES = path.join(ROOT, "src/web-console/public/activities");
@@ -402,6 +404,20 @@ test("music: Light Trails lists exactly the songs it has, each an mp3 on disk th
}
});
test("music: Flock Dash lists exactly the songs it has, each an mp3 on disk the server serves, and no chiptune tracks", () => {
const songs = new Set(songNames());
assert.equal(flockSfx.music, undefined, "its music is the songs, not note data");
assert.deepEqual([...FLOCK_TRACKS].sort(), Object.keys(flockSfx.songs).sort(), "the game lists the songs its sound file has");
for (const name of FLOCK_TRACKS) {
assert.ok(songs.has(name), `song "${name}" exists`);
assert.equal(SONG_TABLES.filter((t) => Object.hasOwn(t, name)).length, 1, `${name} is defined once`);
assert.ok(!musicNames().includes(name), `${name} is not also a chiptune track`);
const file = flockSfx.songs[name];
assert.ok(SERVABLE.has(file), `${file} is servable`);
assert.ok(fs.statSync(path.join(ROOT, "src/web-console/public", file)).size > 0, `${file} is on disk`);
}
});
// A stand-in <audio>: records what music.js asks of it.
class FakeAudio {
static made = [];
+1 -1
View File
@@ -52,7 +52,7 @@ The dashboard lists the handoff for this checkout until it is picked up, and old
`specs/` is gitignored — Glob/Grep and file search silently skip it. If the
conversation worked inside `specs/<feature>/`, confirm the exact state before
writing with `node "<S>/specs.mjs" status specs/<feature>`, which reads the disk:
writing with `node "<S>/specs.mjs" status specs/<feature>` (`<S>` is `scripts/` beside this SKILL.md: `~/.agents/skills/plan2code-handoff/scripts/` globally), which reads the disk:
- Which `phase-X.md` is in progress, and which of its tasks are still open
(each phase's `tasks` and `openTasks`: checkboxes are ground truth, not the
+10 -3
View File
@@ -14,7 +14,7 @@ import { EXIT, fail, out, parseArgs, run } from "./common.mjs";
const USAGE = `
coverage.mjs: per-file coverage from a coverage tool's output. JSON on stdout.
node coverage.mjs read --lcov <file> [--root <dir>]
node coverage.mjs read --lcov <file> [--root <dir>] [--cwd <dir>]
node coverage.mjs read --go-func <file> [--root <dir>]
Prints { ok, format, files: [{ file, lines, hit, pct }], total },
files sorted by path, pct with one decimal.
@@ -22,7 +22,9 @@ coverage.mjs: per-file coverage from a coverage tool's output. JSON on stdout.
lines is LF (or the DA count when LF is missing), hit is LH
(or the DA lines with hits above 0). Paths are made relative
to --root (default: the current folder) with forward slashes;
an absolute path outside the root is kept as given. total
an absolute path outside the root is kept as given. A relative
SF: path is relative to the runner's folder: pass it as --cwd
(relative to the root) to get project-relative paths. total
sums every file.
go-func "<import path>/<file>.go:<line>: <func> <pct>%" lines,
grouped by file: pct is the mean of the file's functions,
@@ -149,7 +151,7 @@ function readGoFunc(text, root) {
/* ------------------------------------------------------------------ main */
async function main(argv) {
const args = parseArgs(argv, { values: ["lcov", "go-func", "root"] });
const args = parseArgs(argv, { values: ["lcov", "go-func", "root", "cwd"] });
const [cmd, ...extra] = args._;
if (!cmd) fail(EXIT.USAGE, "missing-command", "A subcommand is required: read.", "Run with --help for usage.");
if (cmd !== "read") fail(EXIT.USAGE, "unknown-command", `Unknown subcommand "${cmd}".`, "Use: read.");
@@ -166,6 +168,11 @@ async function main(argv) {
fail(EXIT.NOT_FOUND, "no-file", `Cannot read ${file}.`, "Run the coverage command first, then pass the file it wrote.");
}
const read = format === "lcov" ? readLcov(text, root) : readGoFunc(text, root);
const prefix = path.posix.normalize(slash(args.cwd || ".")).replace(/\/+$/, "").replace(/^\.$/, "");
if (read && format === "lcov" && prefix) {
for (const f of read.files) if (!isAbs(f.file)) f.file = path.posix.join(prefix, f.file);
read.files.sort(byPath);
}
if (!read) {
fail(
EXIT.INVALID,
+1 -1
View File
@@ -73,7 +73,7 @@ Run `test-match.mjs gaps --scope <branch|path|all>` (with `--path <p>` for a nam
**Coverage, only when the project already has it.** When `discover` lists a `coverage` entry for a runner in scope, offer it on one card naming the command and what it covers. Never run it without a yes.
- **Yes:** when `cmd` has an `<out>` placeholder (already quoted), replace just `<out>` with a file in the session folder (`open` printed it; in the terminal, the OS temp folder). Run it with `run-check.mjs` in its `cwd`, with a `--log` file. Then read the output with `coverage.mjs read`, per `reads`: `--lcov <out>` when the command wrote to `<out>`, else `--lcov <cwd>/coverage/lcov.info` (Jest's and Vitest's default); `--go-func <log>` for Go, whose `go tool cover -func` table is printed into the run's log. Files at 0% or under 50% that matching called covered become extra gaps, method `coverage`. A coverage run that fails or times out, or a `coverage.mjs read` that fails (exit 3 or 4, as for .NET's Cobertura output): say so in one line, and matching alone continues.
- **Yes:** when `cmd` has an `<out>` placeholder (already quoted), replace just `<out>` with a file in the session folder (`open` printed it; in the terminal, the OS temp folder). Run it with `run-check.mjs` in its `cwd`, with a `--log` file. Then read the output with `coverage.mjs read`, per `reads`: `--lcov <out>` when the command wrote to `<out>`, else `--lcov <cwd>/coverage/lcov.info` (Jest's and Vitest's default), always with `--cwd <the entry's cwd>` so its relative paths line up with the project's; `--go-func <log>` for Go, whose `go tool cover -func` table is printed into the run's log. Files at 0% or under 50% that matching called covered become extra gaps, method `coverage`. A coverage run that fails or times out, or a `coverage.mjs read` that fails (exit 3 or 4, as for .NET's Cobertura output): say so in one line, and matching alone continues.
- **No:** matching alone continues, and the plan says coverage was skipped.
Every gap carries the method that found it (`matching` or `coverage`), ranked as `gaps` ranks them; coverage gaps follow the matching ones, lowest percent first. No gaps at all → say every source file in scope has a test, offer the test map (Step 8) when the run had none, and end.
+1 -1
View File
@@ -40,7 +40,7 @@ The absolute token count before the context bar (`84k ⋅`) only appears on Pro/
```bash
node install.js
# Select A (Install All + dev tools) or C (Custom) → S (Status Line)
# Select A (Advanced) → S (Status Line), or A → E (Everything)
```
This automatically:
+25 -11
View File
@@ -360,7 +360,11 @@ export async function cmdOpen() {
// line, not from the state, and picks the state up on its first request or
// poll tick. No page can reach it before it is listening, and the state is
// on disk long before a browser gets there.
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
// Looked up under the project the session itself names (as `post` and `wait`
// do), so an agent whose shell moved to another repo finds its server instead
// of starting a second one for the same session.
const sessionProj = state && typeof state.project === "string" && state.project ? state.project : project;
const existing = sid && (args.resume || args.session) ? listHandles(sessionProj).find((h) => h.sid === sid) : null;
// A live pid gets a second, longer look before it is given up on, as `stop`
// gives one: a server busy right after a post can miss the first, and a
// second server for the same session strands the page on the first.
@@ -369,7 +373,7 @@ export async function cmdOpen() {
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
: Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
if (!existing) boot = await startServer(sessionProj, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -504,14 +508,14 @@ export async function cmdOpen() {
// A handle whose pid is alive but is not ours (the pid was reused) leaves
// this for last: nothing could be started until that was known.
let started = boot || (await startServer(project, worktree, sid, dir));
let started = boot || (await startServer(sessionProj, worktree, sid, dir));
let handle = await awaitHandle(started);
if (!handle && started.handoff) {
// The handover went wrong somewhere (a platform that will not pass the
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
started = await startServer(sessionProj, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -679,7 +683,7 @@ function isFolder(p) {
async function startServer(project, worktree, sid, dir, { handoff = true, noBrowser = false } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
ensureDir(path.dirname(handlePath), 0o700);
fs.rmSync(handlePath, { force: true });
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
@@ -778,6 +782,16 @@ function tail(file, lines) {
}
}
// A missing browser command raises ENOENT as an event, after the try/catch has
// returned: without a listener it would end `open` before it printed the link.
function quietSpawn(command, args, options) {
// The shell form passes its options in the second place.
const child = Array.isArray(args) ? spawn(command, args, options) : spawn(command, [], args);
child.on("error", () => {});
child.unref();
return child;
}
/**
* Best-effort, never fatal. If we cannot open a browser we still printed the URL,
* and the URL is the primary channel.
@@ -793,7 +807,7 @@ function openBrowser(url) {
// carries nothing a shell would read.
const custom = process.env.PLAN2CODE_BROWSER;
if (custom) {
spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref();
quietSpawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true });
return;
}
@@ -801,16 +815,16 @@ function openBrowser(url) {
if (plat === "win32") {
// The empty "" is the mandatory window-title argument: omit it and
// `start` treats a quoted URL as the title and opens nothing.
spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
quietSpawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
windowsVerbatimArguments: true,
detached: true,
stdio: "ignore",
windowsHide: true,
}).unref();
});
return;
}
if (plat === "darwin") {
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
quietSpawn("open", [url], { detached: true, stdio: "ignore" });
return;
}
// Linux and friends. WSL first: xdg-open there either is absent or opens a
@@ -818,11 +832,11 @@ function openBrowser(url) {
if (isWsl()) {
const exe = findAgent({ command: "wslview" }).state === "found" ? "wslview" : "powershell.exe";
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
quietSpawn(exe, argsFor, { detached: true, stdio: "ignore" });
return;
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless
spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
quietSpawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" });
} catch {
/* never fatal */
}
+8 -8
View File
@@ -2,7 +2,7 @@
//
// Two directories with deliberately different durability:
//
// runtime handle os.tmpdir()/plan2code-console/<cwd-hash>/<sid>.json
// runtime handle os.tmpdir()/plan2code-console[-<uid>]/<cwd-hash>/<sid>.json (0700 folder, 0600 file: it holds the session token)
// port, pid, token, url. Losing it on reboot is correct,
// because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.)
//
@@ -59,7 +59,7 @@ export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
// session someone is actually using.
export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME
? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime")
: path.join(os.tmpdir(), "plan2code-console");
: path.join(os.tmpdir(), "plan2code-console" + (typeof process.getuid === "function" ? "-" + process.getuid() : ""));
export const SCHEMA = 1;
@@ -81,8 +81,8 @@ export function parseArgs(argv) {
/* ------------------------------------------------------------------- fs */
export function ensureDir(dir) {
fs.mkdirSync(dir, { recursive: true });
export function ensureDir(dir, mode) {
fs.mkdirSync(dir, mode === undefined ? { recursive: true } : { recursive: true, mode });
return dir;
}
@@ -91,21 +91,21 @@ export function ensureDir(dir) {
// The retry loop is not paranoia: on Windows, antivirus and the search indexer
// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent,
// unreproducible on demand, and looks exactly like a logic bug. Retry from day one.
export function writeJsonAtomic(file, data) {
export function writeJsonAtomic(file, data, mode) {
const body = JSON.stringify(data, null, 2);
writeTextAtomic(file, body);
writeTextAtomic(file, body, mode);
return body;
}
// The same write for plain text, as UTF-8 (a Buffer is written as is): a temp
// file beside the target, fsync, then a rename, retried while Windows still
// holds the old file.
export function writeTextAtomic(file, text) {
export function writeTextAtomic(file, text, mode) {
const tmp = file + "." + process.pid + ".tmp";
let lastErr;
for (let attempt = 0; attempt < 4; attempt++) {
try {
const fd = fs.openSync(tmp, "w");
const fd = mode === undefined ? fs.openSync(tmp, "w") : fs.openSync(tmp, "w", mode);
try {
fs.writeFileSync(fd, text, "utf8");
fs.fsyncSync(fd);
+16 -1
View File
@@ -130,7 +130,22 @@ export function markHandoffUsed(id, now = clock()) {
const file = path.join(handoffsDir(), id + ".json");
const tmp = `${file}.${process.pid}.tmp`;
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + "\n");
fs.renameSync(tmp, file);
// Windows scanners hold transient locks: retry the rename, and never leave the temp file.
for (let attempt = 0; ; attempt++) {
try {
fs.renameSync(tmp, file);
break;
} catch (err) {
const transient = err.code === "EPERM" || err.code === "EBUSY" || err.code === "EACCES";
if (!transient || attempt >= 3) {
try {
fs.rmSync(tmp, { force: true });
} catch {}
throw err;
}
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 40 * (attempt + 1));
}
}
return next;
}
+18
View File
@@ -262,6 +262,24 @@ function recoverIndex(dir) {
function prepare(dir, folder) {
migrate(dir, folder);
let index = readIndex(dir);
if (!index && fs.existsSync(path.join(dir, INDEX_FILE))) {
// A scanner's brief lock reads as "damaged" through readJson: wait it out, and
// refuse the write (rather than rebuild every tab) while the file stays locked.
let lastErr = null;
for (let attempt = 0; attempt < 4 && !index; attempt++) {
try {
fs.readFileSync(path.join(dir, INDEX_FILE));
lastErr = null;
index = readIndex(dir);
break;
} catch (err) {
lastErr = err;
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
sleepSync(40 * (attempt + 1));
}
}
if (!index && lastErr && (lastErr.code === "EPERM" || lastErr.code === "EBUSY" || lastErr.code === "EACCES")) throw lastErr;
}
if (!index) {
index = fs.existsSync(path.join(dir, INDEX_FILE)) ? recoverIndex(dir) : { order: [], last: null, tabs: {} };
writeIndex(dir, index);
+1
View File
@@ -44,6 +44,7 @@ export const ACTIVITIES = Object.freeze([
entry("hop", "Crossing Rush", "Hop through traffic and rivers. Race your rivals to the top."),
entry("bounce", "Bounce Road", "Ten wild stages of toy-car mayhem. Jump, stomp and outrun the Monster truck."),
entry("ghoul", "Ghoul Rush", "Run and gun through a pitch-dark haunted house. Keep moving.", { music: 65, module: "/activities/ghoul-rush/ghoul.js" }),
entry("flock", "Flock Dash", "Lead your flock through the sunset sky. Dodge everything, keep the line.", { music: 70 }),
]);
const cap = (word) => word[0].toUpperCase() + word.slice(1);
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,765 @@
// Plan2Code Web Console - Flock Dash's drawing: the sunset sky, the hazards and the portal, the strays and the flock, Planny as the lead bird with a star for an eye, the pills and the banners, from a view flock.js refills.
//
// Drawing only: no rules and no state of its own. flock.js hands drawScene()
// one view object of the moment (the round, the board's geometry, the colors
// readColors() took from the page), so the rules never touch a canvas and this
// file never decides anything. Everything is drawn in field units under one
// scale. Anything that moves on its own (wings, a stray's bob) follows the
// view's clock, never Math.random(), so a paused game's frame stays still.
//
// The sky (one palette per stage), the hazards and the birds keep their own fixed
// colors, the same in light and dark. The pills are opaque dark with text that reads on them at 4.5:1
// (pills.js). The strip the pills sit on and Planny (in your highlight) follow
// the page.
import { drawPill, LIVES, livesText } from "./pills.js";
const FALLBACK_COLORS = Object.freeze({ board: "#ffffff", line: "#e4ddd1", you: "#206cc3", ink: "#1d1a17" });
// The page's tokens, read again at each round and each resize, so the board
// follows a theme or highlight change made while the game sat paused. A stub
// canvas in Node has no computed style, so every color falls back.
export function readColors(canvas) {
let style = null;
try {
style = typeof getComputedStyle === "function" ? getComputedStyle(canvas) : null;
} catch {}
const pick = (name, fallback) => (style && style.getPropertyValue(name).trim()) || fallback;
return {
board: pick("--panel", FALLBACK_COLORS.board),
line: pick("--rule", FALLBACK_COLORS.line),
you: pick("--accent", FALLBACK_COLORS.you),
ink: pick("--ink", FALLBACK_COLORS.ink),
};
}
export const GOLD = "#f5b301";
export const STAGE_COLOR = "#ff9a4d";
export const DANGER = "#ff5a5a";
export const FLOCK_COLOR = "#2b2140";
export const STRAY_COLOR = "#fff3dc";
export const HAZARD_COLORS = Object.freeze({ balloon: "#e8413c", gust: "#d9f2ff", stream: "#7fe3f0", cluster: "#b44fd6", storm: "#3a3550", kite: "#2fbf71" });
export const POWER_COLORS = Object.freeze({ tailwind: "#5fd7a8", shield: "#4fc3f7", magnet: "#c58bff" });
export const SUCCESS = "#5fd77a";
const STRAY_RIM = "#2b2140";
// One palette per stage, golden afternoon deepening through sunset to violet
// dusk: the sky's three colors, the clouds' tint, the sun's color and how far
// down the field it sits (past 1 it has set), and the pale rim followers need
// once the sky is as dark as they are. The first stars come out at stage 8.
export const SKIES = Object.freeze({
1: Object.freeze({ top: "#5b8fc7", mid: "#e9a95c", horizon: "#ffcb6b", cloud: "#fff4dc", sun: "#fff3b0", sunY: 0.55, rim: null, stars: 0 }),
2: Object.freeze({ top: "#4f76b8", mid: "#ea9a58", horizon: "#ffc062", cloud: "#ffe9cc", sun: "#ffeaa0", sunY: 0.62, rim: null, stars: 0 }),
3: Object.freeze({ top: "#4a5fa6", mid: "#e8834f", horizon: "#ffb05a", cloud: "#ffdcc0", sun: "#ffe08a", sunY: 0.68, rim: null, stars: 0 }),
4: Object.freeze({ top: "#4a4d96", mid: "#e26c5a", horizon: "#ff9a52", cloud: "#ffcdb8", sun: "#ffd070", sunY: 0.74, rim: null, stars: 0 }),
5: Object.freeze({ top: "#453f88", mid: "#cf5a72", horizon: "#f98a55", cloud: "#f4b8b8", sun: "#ffb860", sunY: 0.8, rim: null, stars: 0 }),
6: Object.freeze({ top: "#3d3378", mid: "#b44d86", horizon: "#ef7a5c", cloud: "#dfa0c0", sun: "#ff9f58", sunY: 0.86, rim: "#ffd9a8", stars: 0 }),
7: Object.freeze({ top: "#2f2866", mid: "#8a4392", horizon: "#d9656c", cloud: "#b784c4", sun: "#ff8a5c", sunY: 0.93, rim: "#ffd9a8", stars: 0 }),
8: Object.freeze({ top: "#1c1a4a", mid: "#4f2f80", horizon: "#a8487c", cloud: "#7c63a8", sun: "#ff7a6a", sunY: 1.02, rim: "#ffd9a8", stars: 26 }),
});
const skyFor = (stage) => SKIES[stage] || SKIES[1];
const SUN_X = 0.72;
const SUN_R = 6.5;
const RIM = 0.32;
// The two cloud layers: how fast each scrolls against the sky, how many clouds,
// their size and strength, and the band of height they keep to.
const CLOUD_LAYERS = Object.freeze([
Object.freeze({ rate: 0.3, count: 5, size: 0.8, alpha: 0.35, top: 0.04, band: 0.4 }),
Object.freeze({ rate: 0.6, count: 4, size: 1.3, alpha: 0.5, top: 0.22, band: 0.55 }),
]);
// Past each edge a cloud wraps out of sight: half this is more than the widest reaches.
const CLOUD_RUN = 40;
const BLINK_MS = 110;
const LEADER_TILT = 0.5;
const LEADER_W = 5;
const LEADER_H = 4;
const LEADER_INK = "#1d1a17";
const BALLOON_CREAM = "#fff3dc";
const BASKET = "#7a4d2b";
const PARTY = Object.freeze([HAZARD_COLORS.cluster, "#ff5fa2", "#38b6ff", "#ffd23f", "#2fbf71"]);
const GLOW_STEPS = 3;
const GLOW = 2.2;
const GLOW_FINAL = 4;
const RING_RX = 3.4;
const RING_RX_FINAL = 2.6;
const V_FADE_MS = 400;
const JAG_STEPS = 7;
const BOB = 0.6;
const BOB_RATE = 0.003;
const FLAP_RATE = 0.014;
const TAU = Math.PI * 2;
const STREAK_GAP = 11;
const STREAK_LEN = 5;
const LOOSE_ALPHA_MIN = 0.25;
const BANNER_SHADE = "rgba(0, 0, 0, 0.3)";
const END_SHADE = "rgba(0, 0, 0, 0.55)";
const END_H = 18;
const CRATE_BOX = 2.6;
const CRATE_GLOW = 3.4;
const WIND_STREAKS = 5;
const WIND_RUN = 18;
const WIND_LEN = 4;
const WIND_RATE = 40;
const pillWidth = (h, text) => h * 0.7 + text.length * h * 0.42;
function pill(ctx, x, y, h, text, color, fill = 1) {
ctx.font = `800 ${h * 0.62}px system-ui, -apple-system, "Segoe UI", sans-serif`;
drawPill(ctx, x, y, pillWidth(h, text), h, text, color, fill, y + h * 0.54);
}
const HUD_SHRINK = 0.92;
const HUD_SHRINK_MIN = 0.6;
function layPills(h, W, lives, hud, stripH) {
const gap = h * 0.3;
const edge = h * 0.4;
const y0 = h * 0.35;
const out = [];
let x = edge;
let y = y0;
const put = (text, color, fill = 1) => {
const w = pillWidth(h, text);
if (x > edge && x + w > W - edge) {
x = edge;
y += h + gap;
}
out.push({ x, y, w, text, color, fill });
x += w + gap;
};
put(hud.stage, STAGE_COLOR);
put(livesText(lives), LIVES);
put(`Score ${hud.score}`, GOLD);
put(`Flock ${hud.flock} / ${hud.min}`, hud.flock >= hud.min ? SUCCESS : STRAY_COLOR);
if (hud.combo > 1) put(`x${hud.combo}`, GOLD);
for (const p of hud.powers || []) put(p.text, p.color, p.fill);
const drop = Math.max(0, (stripH - (y + h) - y0) / 2);
for (const p of out) {
p.y += drop;
p.h = h;
}
return { out, over: stripH ? y + h > stripH : false };
}
// Where the pills go, `h` units tall in a strip `stripH` tall on a board `W`
// wide: the stage, lives, the score and the flock against the portal's minimum
// (in the success color once met) from the left, then the combo
// while it is above 1 and the power-ups running. A row that
// would leave the strip shrinks every pill a step at a time until it fits; only
// past HUD_SHRINK_MIN does a row spill below the strip, over the field, where
// drawScene paints the pills last.
export function hudLayout(h, W, lives, hud, stripH = 0) {
let k = 1;
let laid = layPills(h, W, lives, hud, stripH);
while (laid.over && k > HUD_SHRINK_MIN) {
k = Math.max(HUD_SHRINK_MIN, k * HUD_SHRINK);
laid = layPills(h * k, W, lives, hud, stripH);
}
return laid.out;
}
function drawHud(ctx, v) {
const { g, colors } = v;
ctx.fillStyle = colors.board;
ctx.fillRect(0, 0, g.W, g.HUD_H);
ctx.fillStyle = colors.line;
ctx.fillRect(0, g.HUD_H - 0.25, g.W, 0.25);
}
function drawPills(ctx, v) {
const { g } = v;
if (v.state !== "running" && v.state !== "paused") return;
for (const p of hudLayout(v.pillH, g.W, v.round.infinite ? Infinity : v.round.lives, v.hud, g.HUD_H)) pill(ctx, p.x, p.y, p.h, p.text, p.color, p.fill);
}
// A number from 0 to 1 for a seed and an index, so the clouds and stars of a
// round always sit in the same places.
function scatter(seed, k) {
let t = Math.imul((seed >>> 0) ^ Math.imul(k + 1, 0x9e3779b1), 0x5bd1e995);
t ^= t >>> 15;
t = Math.imul(t, t | 61);
t ^= t >>> 13;
return (t >>> 0) / 4294967296;
}
function disc(ctx, x, y, r, color) {
ctx.fillStyle = color;
ctx.beginPath();
ctx.arc(x, y, r, 0, TAU);
ctx.fill();
}
function drawStars(ctx, v, sky) {
const { g, round } = v;
ctx.fillStyle = "#ffffff";
for (let k = 0; k < sky.stars; k++) {
ctx.globalAlpha = 0.45 + 0.45 * Math.abs(Math.sin(v.clock * 0.0012 + k));
ctx.fillRect(scatter(round.seed, 1000 + k) * g.FIELD_W, scatter(round.seed, 2000 + k) * g.FIELD_H * 0.6, 0.3, 0.3);
}
ctx.globalAlpha = 1;
}
function drawSun(ctx, g, sky) {
const x = g.FIELD_W * SUN_X;
const y = g.FIELD_H * sky.sunY;
ctx.globalAlpha = 0.16;
disc(ctx, x, y, SUN_R * 1.9, sky.sun);
ctx.globalAlpha = 0.28;
disc(ctx, x, y, SUN_R * 1.4, sky.sun);
ctx.globalAlpha = 1;
disc(ctx, x, y, SUN_R, sky.sun);
}
// Two layers of clouds drifting behind everything, slower than the sky, wrapping
// around from their places in the round's seed.
function drawClouds(ctx, v, sky) {
const { g, round } = v;
const run = g.FIELD_W + CLOUD_RUN;
ctx.fillStyle = sky.cloud;
CLOUD_LAYERS.forEach((layer, l) => {
ctx.globalAlpha = layer.alpha;
for (let k = 0; k < layer.count; k++) {
const key = (l + 1) * 100 + k * 3;
const home = scatter(round.seed, key) * run - round.scroll * layer.rate;
const x = ((home % run) + run) % run - CLOUD_RUN / 2;
const y = (layer.top + scatter(round.seed, key + 1) * layer.band) * g.FIELD_H;
const w = (6 + scatter(round.seed, key + 2) * 8) * layer.size;
ctx.beginPath();
ctx.ellipse(x, y, w, w * 0.28, 0, 0, TAU);
ctx.ellipse(x - w * 0.35, y - w * 0.14, w * 0.42, w * 0.26, 0, 0, TAU);
ctx.ellipse(x + w * 0.25, y - w * 0.2, w * 0.5, w * 0.32, 0, 0, TAU);
ctx.fill();
}
});
ctx.globalAlpha = 1;
}
function drawSky(ctx, v) {
const { g, round } = v;
const palette = skyFor(round.stage);
const sky = typeof ctx.createLinearGradient === "function" ? ctx.createLinearGradient(0, 0, 0, g.FIELD_H) : null;
if (sky) {
sky.addColorStop(0, palette.top);
sky.addColorStop(0.58, palette.mid);
sky.addColorStop(1, palette.horizon);
}
ctx.fillStyle = sky || palette.mid;
ctx.fillRect(0, 0, g.FIELD_W, g.FIELD_H);
drawStars(ctx, v, palette);
drawSun(ctx, g, palette);
drawClouds(ctx, v, palette);
}
// How a wing sits at this moment of its beat, from -1 (down) to 1 (up).
const flapAt = (clock, phase) => Math.sin(clock * FLAP_RATE + phase);
function birdBody(ctx, x, y, r) {
ctx.moveTo(x + r, y);
ctx.ellipse(x, y, r, r * 0.5, 0, 0, TAU);
ctx.moveTo(x + r * 0.85, y - r * 0.2);
ctx.lineTo(x + r * 1.5, y);
ctx.lineTo(x + r * 0.85, y + r * 0.2);
ctx.closePath();
}
// A wing from the shoulder at x, its tip `lift` above the body and swept back.
function birdWing(ctx, x, y, r, lift) {
ctx.moveTo(x + r * 0.4, y);
ctx.quadraticCurveTo(x, y - lift * 0.7, x - r * 0.75, y - lift);
ctx.quadraticCurveTo(x - r * 0.3, y - lift * 0.25, x - r * 0.45, y);
ctx.closePath();
}
// A small bird flying right, `r` units long: a body and two wings on their beat,
// each filled on its own, with a rim under them when the sky needs one.
function drawBird(ctx, x, y, r, color, beat, rim) {
const near = r * 1.5 * beat;
const far = r * 1.05 * beat;
const back = x - r * 0.4;
if (rim) {
ctx.strokeStyle = rim;
ctx.lineWidth = RIM;
ctx.beginPath();
birdBody(ctx, x, y, r);
birdWing(ctx, x, y, r, near);
birdWing(ctx, back, y, r, far);
ctx.stroke();
}
ctx.fillStyle = color;
ctx.beginPath();
birdBody(ctx, x, y, r);
ctx.fill();
ctx.beginPath();
birdWing(ctx, back, y, r, far);
ctx.fill();
ctx.beginPath();
birdWing(ctx, x, y, r, near);
ctx.fill();
}
function drawStar(ctx, x, y, r, color) {
ctx.fillStyle = color;
ctx.strokeStyle = LEADER_INK;
ctx.lineWidth = 0.14;
ctx.beginPath();
for (let k = 0; k < 10; k++) {
const a = -Math.PI / 2 + (k * Math.PI) / 5;
const d = k % 2 ? r * 0.42 : r;
if (k) ctx.lineTo(x + Math.cos(a) * d, y + Math.sin(a) * d);
else ctx.moveTo(x + Math.cos(a) * d, y + Math.sin(a) * d);
}
ctx.closePath();
ctx.stroke();
ctx.fill();
}
function roundedBox(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.lineTo(x + w - r, y);
ctx.quadraticCurveTo(x + w, y, x + w, y + r);
ctx.lineTo(x + w, y + h - r);
ctx.quadraticCurveTo(x + w, y + h, x + w - r, y + h);
ctx.lineTo(x + r, y + h);
ctx.quadraticCurveTo(x, y + h, x, y + h - r);
ctx.lineTo(x, y + r);
ctx.quadraticCurveTo(x, y, x + r, y);
ctx.closePath();
}
// Planny leads, in bird form: his box in your highlight, the star for an eye, two
// wings on the beat and his feet tucked up, tilted with his climb. He blinks
// while nothing can hit him.
function drawLeader(ctx, v) {
const { leader } = v.round;
const you = v.colors.you;
const beat = flapAt(v.clock, 0);
if (leader.grace > 0 && Math.floor(v.clock / BLINK_MS) % 2) ctx.globalAlpha = 0.35;
ctx.save();
ctx.translate(leader.sx, leader.y);
ctx.rotate(Math.max(-1, Math.min(1, leader.vy / v.g.CLIMB)) * LEADER_TILT);
const wing = (x, lift) => {
ctx.beginPath();
birdWing(ctx, x, 0, 2.2, lift);
ctx.fillStyle = you;
ctx.fill();
ctx.strokeStyle = LEADER_INK;
ctx.lineWidth = 0.22;
ctx.stroke();
};
wing(-1.2, 2.7 * beat);
ctx.strokeStyle = LEADER_INK;
ctx.lineWidth = 0.32;
ctx.beginPath();
ctx.moveTo(-0.9, LEADER_H / 2);
ctx.lineTo(-1.9, LEADER_H / 2 + 0.55);
ctx.moveTo(0.5, LEADER_H / 2);
ctx.lineTo(-0.5, LEADER_H / 2 + 0.55);
ctx.stroke();
ctx.fillStyle = GOLD;
ctx.beginPath();
ctx.moveTo(LEADER_W / 2 - 0.1, -0.6);
ctx.lineTo(LEADER_W / 2 + 1.1, 0.1);
ctx.lineTo(LEADER_W / 2 - 0.1, 0.8);
ctx.closePath();
ctx.fill();
roundedBox(ctx, -LEADER_W / 2, -LEADER_H / 2, LEADER_W, LEADER_H, 1.1);
ctx.fillStyle = you;
ctx.fill();
ctx.strokeStyle = LEADER_INK;
ctx.lineWidth = 0.25;
ctx.stroke();
drawStar(ctx, 0.75, -0.45, 1.1, GOLD);
wing(-0.5, 3.1 * beat);
ctx.restore();
ctx.globalAlpha = 1;
}
// A hot-air balloon: the striped envelope (its hit circle), ropes and a basket.
function drawHotAir(ctx, x, y, r) {
disc(ctx, x, y, r, HAZARD_COLORS.balloon);
ctx.fillStyle = BALLOON_CREAM;
ctx.beginPath();
ctx.ellipse(x, y, r * 0.62, r * 0.98, 0, 0, TAU);
ctx.fill();
ctx.fillStyle = HAZARD_COLORS.balloon;
ctx.beginPath();
ctx.ellipse(x, y, r * 0.26, r * 0.98, 0, 0, TAU);
ctx.fill();
ctx.strokeStyle = BASKET;
ctx.lineWidth = 0.18;
ctx.beginPath();
ctx.moveTo(x - r * 0.5, y + r * 0.85);
ctx.lineTo(x - 0.6, y + r + 0.9);
ctx.moveTo(x + r * 0.5, y + r * 0.85);
ctx.lineTo(x + 0.6, y + r + 0.9);
ctx.stroke();
ctx.fillStyle = BASKET;
ctx.fillRect(x - 0.7, y + r + 0.9, 1.4, 1);
}
// A bunch of party balloons, their strings meeting at a knot under them.
function drawBunch(ctx, x, y, h) {
const knotY = y + h.h / 2 + 1;
ctx.strokeStyle = STRAY_RIM;
ctx.lineWidth = 0.14;
ctx.beginPath();
for (const p of h.parts) {
ctx.moveTo(x + p.dx, y + p.dy + p.r);
ctx.lineTo(x, knotY);
}
ctx.stroke();
h.parts.forEach((p, i) => {
disc(ctx, x + p.dx, y + p.dy, p.r, PARTY[i % PARTY.length]);
ctx.globalAlpha = 0.45;
disc(ctx, x + p.dx - p.r * 0.35, y + p.dy - p.r * 0.35, p.r * 0.25, "#ffffff");
ctx.globalAlpha = 1;
});
}
function drawBand(ctx, x, y, w, h, color, alpha) {
ctx.globalAlpha = alpha;
ctx.fillStyle = color;
ctx.fillRect(x, y - h / 2, w, h);
ctx.globalAlpha = 1;
}
// A gust's warning: arrows at its height along the right edge, pulsing.
function drawGustWarning(ctx, v, h) {
const { g } = v;
ctx.globalAlpha = 0.55 + 0.45 * Math.sin(v.clock * 0.014);
ctx.strokeStyle = HAZARD_COLORS.gust;
ctx.lineWidth = 0.5;
for (let k = 0; k < 3; k++) {
const x = g.FIELD_W - 2 - k * 2.4;
ctx.beginPath();
ctx.moveTo(x, h.y - h.h / 2);
ctx.lineTo(x - 1.6, h.y);
ctx.lineTo(x, h.y + h.h / 2);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
// A live gust: a white band, streaked along its way.
function drawGust(ctx, v, h, sx) {
drawBand(ctx, sx, h.y, h.w, h.h, HAZARD_COLORS.gust, 0.28);
ctx.globalAlpha = 0.75;
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 0.28;
for (let k = 0; k < 7; k++) {
const at = (k * 5.3 + v.clock * 0.03) % h.w;
const y = h.y + ((k % 3) - 1) * (h.h / 3.2);
ctx.beginPath();
ctx.moveTo(sx + h.w - at, y);
ctx.lineTo(sx + h.w - at + 4, y);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
// Streaks flowing toward the player at twice the stage's speed.
function drawStream(ctx, v, h, sx) {
drawBand(ctx, sx, h.y, h.w, h.h, HAZARD_COLORS.stream, 0.22);
ctx.strokeStyle = HAZARD_COLORS.stream;
ctx.lineWidth = 0.25;
for (const y of [h.y - h.h / 2, h.y + h.h / 2]) {
ctx.beginPath();
ctx.moveTo(sx, y);
ctx.lineTo(sx + h.w, y);
ctx.stroke();
}
const flow = (v.clock / 1000) * v.round.speed * 2;
for (let row = 0; row < 3; row++) {
const y = h.y + (row - 1) * (h.h / 3);
for (let at = (row * 7 - flow) % STREAK_GAP; at < h.w; at += STREAK_GAP) {
if (at < 0) continue;
ctx.beginPath();
ctx.moveTo(sx + at, y);
ctx.lineTo(sx + Math.min(h.w, at + STREAK_LEN), y);
ctx.stroke();
}
}
}
// A kite on its string, the line that snaps a bird: a diamond with its spars and
// a tail of bows that swings with the kite, hanging away from its string.
function drawKite(ctx, v, h, sx, tipX) {
const { g } = v;
const R = g.KITE_R;
ctx.strokeStyle = STRAY_RIM;
ctx.lineWidth = 0.3;
ctx.beginPath();
ctx.moveTo(sx, h.top ? 0 : g.FIELD_H);
ctx.lineTo(tipX, h.y);
ctx.stroke();
ctx.fillStyle = HAZARD_COLORS.kite;
ctx.beginPath();
ctx.moveTo(tipX, h.y - R);
ctx.lineTo(tipX + R, h.y);
ctx.lineTo(tipX, h.y + R);
ctx.lineTo(tipX - R, h.y);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = BALLOON_CREAM;
ctx.lineWidth = 0.18;
ctx.beginPath();
ctx.moveTo(tipX, h.y - R);
ctx.lineTo(tipX, h.y + R);
ctx.moveTo(tipX - R, h.y);
ctx.lineTo(tipX + R, h.y);
ctx.stroke();
const swing = Math.sin(v.clock * 0.004 + h.phase) * 0.7;
const away = h.top ? 1 : -1;
ctx.fillStyle = "#ffd23f";
for (let k = 1; k <= 3; k++) {
const x = tipX + swing * k * 0.6 - k * 0.5;
const y = h.y + away * (R + k * 1.1);
ctx.beginPath();
ctx.moveTo(x - 0.5, y - 0.3);
ctx.lineTo(x + 0.5, y + 0.3);
ctx.lineTo(x + 0.5, y - 0.3);
ctx.lineTo(x - 0.5, y + 0.3);
ctx.closePath();
ctx.fill();
}
}
// A dark cloud; while it beats, a warning column that pulses, then the strike
// down it as a jagged bolt inside the column it can hit.
function drawStorm(ctx, v, h, sx) {
const { g, round } = v;
disc(ctx, sx - h.w * 0.25, h.y, h.h * 0.8, HAZARD_COLORS.storm);
disc(ctx, sx + h.w * 0.25, h.y, h.h * 0.8, HAZARD_COLORS.storm);
disc(ctx, sx, h.y - h.h * 0.2, h.h, HAZARD_COLORS.storm);
ctx.globalAlpha = 0.5;
ctx.fillStyle = "#5a5474";
ctx.beginPath();
ctx.ellipse(sx, h.y - h.h * 0.45, h.w * 0.32, h.h * 0.4, 0, 0, TAU);
ctx.fill();
ctx.globalAlpha = 1;
if (h.phase === "idle") return;
const [lo, hi] = h.top ? [h.y, h.y + g.STORM_REACH] : [h.y - g.STORM_REACH, h.y];
const mid = h.col - round.scroll;
const col = mid - g.STORM_COL / 2;
if (h.phase === "warn") {
drawBand(ctx, col, (lo + hi) / 2, g.STORM_COL, hi - lo, DANGER, 0.2 + 0.2 * Math.abs(Math.sin(v.clock * 0.02)));
return;
}
drawBand(ctx, col, (lo + hi) / 2, g.STORM_COL, hi - lo, "#fff7b0", 0.5);
ctx.strokeStyle = "#ffffff";
ctx.lineWidth = 0.55;
ctx.beginPath();
for (let k = 0; k <= JAG_STEPS; k++) {
const t = k / JAG_STEPS;
const x = mid + (k === 0 ? 0 : (scatter(round.seed, Math.floor(h.beat) + k) - 0.5) * g.STORM_COL * 0.9);
const y = h.top ? lo + (hi - lo) * t : hi - (hi - lo) * t;
if (k) ctx.lineTo(x, y);
else ctx.moveTo(x, y);
}
ctx.stroke();
}
function drawHazards(ctx, v) {
const { g, round } = v;
for (const h of round.hazards) {
const sx = h.x - round.scroll;
if (h.kind === "gust") {
if (h.warnAt === undefined) continue;
if (h.live) drawGust(ctx, v, h, sx);
else drawGustWarning(ctx, v, h);
continue;
}
if (sx - h.w > g.FIELD_W || sx + h.w < 0) continue;
if (h.kind === "balloon") drawHotAir(ctx, sx, h.y, h.r);
else if (h.kind === "cluster") drawBunch(ctx, sx, h.y, h);
else if (h.kind === "kite") drawKite(ctx, v, h, sx, h.tipX - round.scroll);
else if (h.kind === "stream") drawStream(ctx, v, h, sx);
else if (h.kind === "storm") drawStorm(ctx, v, h, sx);
}
}
// The jet stream's glowing swirl ring, seen a little from the side. The last one
// has the smaller ring and the larger glow.
function drawPortal(ctx, v) {
const { portal, scroll, stage } = v.round;
const final = stage === v.g.MAX_STAGE;
const glow = final ? GLOW_FINAL : GLOW;
const rx = final ? RING_RX_FINAL : RING_RX;
const ry = portal.h / 2;
const sx = portal.x - scroll;
if (sx < -rx - glow * GLOW_STEPS || sx > v.g.FIELD_W + rx + glow * GLOW_STEPS) return;
ctx.strokeStyle = GOLD;
ctx.globalAlpha = 0.14;
for (let k = GLOW_STEPS; k >= 1; k--) {
ctx.lineWidth = 0.8 + k * glow;
ctx.beginPath();
ctx.ellipse(sx, portal.y, rx, ry, 0, 0, TAU);
ctx.stroke();
}
ctx.globalAlpha = 1;
ctx.lineWidth = 0.8;
ctx.beginPath();
ctx.ellipse(sx, portal.y, rx, ry, 0, 0, TAU);
ctx.stroke();
ctx.strokeStyle = "#fff7d6";
ctx.lineWidth = 0.35;
for (let k = 0; k < 4; k++) {
const from = v.clock * 0.005 + (k * TAU) / 4;
ctx.beginPath();
ctx.ellipse(sx, portal.y, rx * 0.68, ry * 0.92, 0, from, from + 1.1);
ctx.stroke();
}
}
// While the V forms: a faint gold line along each arm as the flock glides in.
function drawV(ctx, v) {
const { portal, flock, leader, scroll } = v.round;
if (!portal.v || !flock.length) return;
const ends = [flock[flock.length - 1], flock[Math.max(0, flock.length - 2)]];
if (typeof ends[0].x !== "number" || typeof ends[1].x !== "number") return;
ctx.globalAlpha = 0.5 * Math.max(0, Math.min(1, Math.min(portal.v.t, v.g.V_MS - portal.v.t) / V_FADE_MS));
ctx.strokeStyle = GOLD;
ctx.lineWidth = 0.4;
ctx.beginPath();
ctx.moveTo(ends[0].x - scroll, ends[0].y);
ctx.lineTo(leader.sx, leader.y);
ctx.lineTo(ends[1].x - scroll, ends[1].y);
ctx.stroke();
ctx.globalAlpha = 1;
}
// Loose birds fade through their last second, but stay faintly in sight as they
// fly off.
function drawScattered(ctx, v) {
const { round } = v;
for (const b of round.scattered) {
ctx.globalAlpha = Math.max(LOOSE_ALPHA_MIN, Math.min(1, (b.until - round.now) / 1000));
drawBird(ctx, b.x - round.scroll, b.y, 1.3, STRAY_COLOR, flapAt(v.clock, b.id * 1.7), STRAY_RIM);
}
ctx.globalAlpha = 1;
}
// A crate: a small box in its power's color with a soft glow.
function drawCrates(ctx, v) {
const { g, round } = v;
for (const c of round.crates) {
const sx = c.x - round.scroll;
if (sx < -CRATE_GLOW || sx > g.FIELD_W + CRATE_GLOW) continue;
const color = POWER_COLORS[c.kind];
ctx.globalAlpha = 0.3;
disc(ctx, sx, c.y, CRATE_GLOW, color);
ctx.globalAlpha = 1;
ctx.fillStyle = color;
ctx.fillRect(sx - CRATE_BOX / 2, c.y - CRATE_BOX / 2, CRATE_BOX, CRATE_BOX);
ctx.strokeStyle = FLOCK_COLOR;
ctx.lineWidth = 0.25;
ctx.strokeRect(sx - CRATE_BOX / 2, c.y - CRATE_BOX / 2, CRATE_BOX, CRATE_BOX);
}
}
// How far the magnet reaches, as a faint ring around the leader.
function drawMagnetRing(ctx, v) {
const { g, round } = v;
if (round.active.magnet <= 0 || !round.leader.alive) return;
ctx.globalAlpha = 0.35;
ctx.strokeStyle = POWER_COLORS.magnet;
ctx.lineWidth = 0.3;
ctx.beginPath();
ctx.arc(round.leader.sx, round.leader.y, g.MAGNET_REACH, 0, TAU);
ctx.stroke();
ctx.globalAlpha = 1;
}
// Speed streaks rushing away behind the last bird of the line.
function drawTailwind(ctx, v) {
const { round } = v;
if (round.active.tailwind <= 0 || !round.leader.alive) return;
const last = round.flock[round.flock.length - 1];
const tail = last && typeof last.x === "number" ? last : { x: round.leader.x, y: round.leader.y };
const x = tail.x - round.scroll - 2;
ctx.globalAlpha = 0.6;
ctx.strokeStyle = POWER_COLORS.tailwind;
ctx.lineWidth = 0.3;
for (let k = 0; k < WIND_STREAKS; k++) {
const back = (k * 5 + (v.clock / 1000) * WIND_RATE) % WIND_RUN;
const y = tail.y + (k - (WIND_STREAKS - 1) / 2) * 1.4;
ctx.beginPath();
ctx.moveTo(x - back, y);
ctx.lineTo(x - back - WIND_LEN, y);
ctx.stroke();
}
ctx.globalAlpha = 1;
}
function label(ctx, text, x, y, size, color, maxWidth) {
ctx.font = `800 ${size}px system-ui, -apple-system, "Segoe UI", sans-serif`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.fillText(text, x, y, maxWidth);
}
// A strip across the field, its place chosen away from the leader, fading out
// at the end of its time and to see-through while anything is under it.
function drawBanner(ctx, v, b) {
const { g, round } = v;
const p = 1 - Math.max(0, b.until - round.now) / b.ms;
ctx.globalAlpha = (p > 0.82 ? Math.max(0, (1 - p) / 0.18) : 1) * b.see;
ctx.fillStyle = BANNER_SHADE;
ctx.fillRect(0, b.row - g.BANNER_HALF, g.FIELD_W, g.BANNER_HALF * 2);
label(ctx, b.text, g.FIELD_W / 2, b.row - 1, 4.2, b.color, g.FIELD_W - 4);
if (b.sub) label(ctx, b.sub, g.FIELD_W / 2, b.row + 3.2, 2.2, "#ffffff", g.FIELD_W - 4);
ctx.globalAlpha = 1;
}
// The end of a run, along the bottom of the field (the window's own message sits
// in the middle): how it went, the score, the best, and the nudge to go again.
function drawEnd(ctx, v, end) {
const { g } = v;
const top = g.FIELD_H - END_H;
const mid = g.FIELD_W / 2;
ctx.fillStyle = END_SHADE;
ctx.fillRect(0, top, g.FIELD_W, END_H);
const title = end.won ? (end.flawless ? `You made it! Flawless +${end.flawless}` : "You made it!") : "Out of lives";
label(ctx, title, mid, top + 2.8, 2.8, end.won ? GOLD : "#ffffff", g.FIELD_W - 4);
label(ctx, String(end.score), mid, top + 7.8, 6, GOLD, g.FIELD_W - 4);
label(ctx, end.fresh ? `A new best! ${end.best}` : `Best ${end.best}`, mid, top + 12.2, 2.2, "#ffffff", g.FIELD_W - 4);
label(ctx, end.teaser, mid, top + 15.6, 2.2, "#ffffff", g.FIELD_W - 4);
}
export function drawScene(ctx, v) {
const { g, round } = v;
ctx.save();
ctx.scale(v.u, v.u);
ctx.fillStyle = v.colors.board;
ctx.fillRect(0, 0, g.W, g.H);
drawHud(ctx, v);
ctx.translate(g.PAD, g.HUD_H);
ctx.save();
ctx.beginPath();
ctx.rect(0, 0, g.FIELD_W, g.FIELD_H);
if (typeof ctx.clip === "function") ctx.clip();
drawSky(ctx, v);
drawHazards(ctx, v);
drawPortal(ctx, v);
drawCrates(ctx, v);
drawMagnetRing(ctx, v);
drawTailwind(ctx, v);
drawV(ctx, v);
for (const s of round.strays) {
drawBird(ctx, s.x - round.scroll, s.y + Math.sin(v.clock * BOB_RATE + s.bob) * BOB, 1.3, STRAY_COLOR, flapAt(v.clock, s.bob), STRAY_RIM);
}
const { rim } = skyFor(round.stage);
for (const b of round.flock) {
if (typeof b.x === "number") drawBird(ctx, b.x - round.scroll, b.y, 1.4, FLOCK_COLOR, flapAt(v.clock, b.id * 1.7), rim);
}
drawScattered(ctx, v);
if (round.leader.alive || v.state === "over") drawLeader(ctx, v);
if (v.end) drawEnd(ctx, v, v.end);
else if (round.banner && round.banner.row !== null) drawBanner(ctx, v, round.banner);
ctx.restore();
ctx.translate(-g.PAD, -g.HUD_H);
drawPills(ctx, v);
ctx.restore();
}
@@ -0,0 +1,147 @@
// Plan2Code Web Console - flock: its own sound effects, merged into tones.js beside the shared kit; defines only.
//
// `tones` are one-shot sounds played with tone(name, level, pitch); `hums` are
// held sounds kept going with hum(id, name, level, pitch). Both take the shapes
// tones.js documents, as plain objects (tones.js freezes them). A name may be
// defined only once across tones.js and every game's file. No imports.
export default {
// The music: recorded songs, each a name to an mp3 the server serves (listed in
// SERVABLE), played by music.js one after another in the order flock.js deals them.
songs: {
flockSong1: "activities/flock-dash/1.mp3",
flockSong2: "activities/flock-dash/2.mp3",
flockSong3: "activities/flock-dash/3.mp3",
flockSong4: "activities/flock-dash/4.mp3",
flockSong5: "activities/flock-dash/5.mp3",
},
tones: {
// A stray picked up: a short, bright bird chirp (the game raises its pitch
// with the combo, so it stays soft and under a tenth of a second).
flockChirp: {
layers: [
{ type: "triangle", from: 1800, to: 2600, seconds: 0.07, gain: 0.25 },
{ type: "sine", from: 2400, to: 3200, seconds: 0.05, gain: 0.12 },
],
},
// A scattered bird picked back up: a softer, lower two-note chirp.
flockRejoin: {
layers: [{ type: "triangle", notes: [1047, 1319], seconds: 0.1, gain: 0.22 }],
},
// The line snapping: a plucked tone falling away, and a flutter of bandpassed noise.
flockSnap: {
layers: [
{ type: "triangle", from: 660, to: 220, seconds: 0.25, gain: 0.45, filter: { type: "lowpass", from: 2400, to: 500 } },
{ type: "noise", seconds: 0.03, gain: 0.3, filter: { type: "bandpass", from: 2500, to: 1800, q: 3 } },
{ type: "noise", seconds: 0.03, delay: 0.05, gain: 0.25, filter: { type: "bandpass", from: 2500, to: 1800, q: 3 } },
{ type: "noise", seconds: 0.03, delay: 0.1, gain: 0.2, filter: { type: "bandpass", from: 2500, to: 1800, q: 3 } },
],
},
// The leader hit: a thump and a squawk.
flockHit: {
layers: [
{ type: "sine", from: 150, to: 50, seconds: 0.15, gain: 0.8 },
{ type: "square", from: 500, to: 220, seconds: 0.15, gain: 0.3, filter: { type: "lowpass", from: 2000, to: 800 } },
],
},
// A shield soaking a hit: a bright metallic ping over a soft whoosh.
flockShield: {
layers: [
{ type: "sine", from: 2400, to: 2400, seconds: 0.35, gain: 0.3 },
{ type: "triangle", from: 3136, to: 3136, seconds: 0.25, delay: 0.02, gain: 0.15 },
{ type: "pink", seconds: 0.3, attack: 0.1, gain: 0.2, filter: { type: "bandpass", from: 700, to: 2600, q: 1.4 } },
],
},
// A crate opened: a sparkling rise.
flockPower: {
layers: [
{ type: "triangle", notes: [1047, 1319, 1568, 2093, 2637], seconds: 0.4, gain: 0.4 },
{ type: "sine", from: 2000, to: 4000, seconds: 0.4, gain: 0.15 },
],
},
// The gust warning: a rising whoosh of pink noise.
flockGust: {
layers: [{ type: "pink", seconds: 0.6, attack: 0.3, gain: 0.5, filter: { type: "bandpass", from: 200, to: 1400, q: 1.2 } }],
},
// The storm warning: a low crackle of noise.
flockThunder: {
layers: [
{ type: "brown", seconds: 0.5, gain: 0.6, filter: { type: "lowpass", from: 260, to: 140 } },
{ type: "noise", seconds: 0.04, delay: 0.1, gain: 0.3, filter: { type: "bandpass", from: 1200, to: 900, q: 2 } },
{ type: "noise", seconds: 0.04, delay: 0.22, gain: 0.25, filter: { type: "bandpass", from: 1200, to: 900, q: 2 } },
{ type: "noise", seconds: 0.04, delay: 0.32, gain: 0.3, filter: { type: "bandpass", from: 1200, to: 900, q: 2 } },
],
},
// Lightning striking: a sharp white crack with a low boom under it.
flockStrike: {
layers: [
{ type: "noise", seconds: 0.12, gain: 0.6, filter: { type: "highpass", from: 4000, to: 1500 } },
{ type: "sine", from: 90, to: 35, seconds: 0.5, gain: 0.8 },
{ type: "brown", seconds: 0.4, gain: 0.4, filter: { type: "lowpass", from: 300, to: 80 } },
],
},
// A portal passed: a whooshing shimmer.
flockPortal: {
layers: [
{ type: "sine", from: 500, to: 1500, seconds: 0.7, attack: 0.2, gain: 0.3, vibrato: { rate: 14, depth: 0.04 } },
{ type: "pink", seconds: 0.7, attack: 0.2, gain: 0.3, filter: { type: "bandpass", from: 400, to: 3000, q: 2 } },
],
},
// The V formed: a rising arpeggio of triangle notes.
flockV: {
layers: [{ type: "triangle", notes: [523, 659, 784, 1047], seconds: 0.4, gain: 0.5 }],
},
// A flawless stage: a bright little fanfare.
flockFlawless: {
layers: [
{ type: "triangle", notes: [784, 784, 988, 1319], seconds: 0.44, gain: 0.5 },
{ type: "square", notes: [392, 392, 494, 659], seconds: 0.44, gain: 0.25, filter: { type: "lowpass", from: 2400, to: 2400 } },
],
},
// A new stage: a clean four-note climb.
flockStage: {
layers: [
{ type: "triangle", notes: [523, 659, 784, 1047], seconds: 0.3, gain: 0.45 },
{ type: "square", notes: [262, 330, 392, 523], seconds: 0.3, gain: 0.15, filter: { type: "lowpass", from: 1600, to: 1600 } },
],
},
// A new best: a short sparkling run.
flockBest: {
layers: [
{ type: "triangle", notes: [1568, 2093, 2637, 3136, 2637, 3136], seconds: 0.3, gain: 0.4 },
{ type: "noise", seconds: 0.2, gain: 0.1, filter: { type: "highpass", from: 6000, to: 8000 } },
],
},
// Game over: a falling run.
flockOver: {
layers: [
{ type: "triangle", notes: [523, 466, 392, 330, 262], seconds: 0.6, gain: 0.5 },
{ type: "sawtooth", notes: [262, 233, 196, 165], seconds: 0.6, gain: 0.2, filter: { type: "lowpass", from: 900, to: 500 } },
],
},
// The run won: a longer, happy fanfare.
flockWin: {
layers: [
{ type: "triangle", notes: [523, 659, 784, 659, 784, 1047], seconds: 0.9, gain: 0.5 },
{ type: "square", notes: [262, 330, 392, 330, 392, 523], seconds: 0.9, gain: 0.25, filter: { type: "lowpass", from: 2400, to: 2400 } },
],
},
},
hums: {
// The wind past the flock: soft filtered pink noise; pitch follows flight speed.
// Kept under the music, so it stays quiet.
flockWind: {
noise: { color: "pink", gain: 1 },
filter: { type: "bandpass", freq: 500, q: 0.8, follow: 1 },
pulse: { rate: 0.3, depth: 0.3 },
peak: 0.015,
},
// Riding a slipstream: a faster, brighter rush with a light pulse.
flockStream: {
noise: { color: "pink", gain: 1 },
filter: { type: "bandpass", freq: 1400, q: 1.2, follow: 1 },
pulse: { rate: 6, depth: 0.4 },
peak: 0.02,
},
},
};
File diff suppressed because it is too large. Load diff
Loaded 100 of 120 files, more files were not shown because too many files have changed in this diff. Show more