Compare commits

...
8 Commits
68 changed files with 4929 additions and 198 deletions

No files matched your search

+7 -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 |
@@ -661,4 +663,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
+8
View File
@@ -5,6 +5,9 @@ on:
branches: [main]
pull_request:
permissions:
contents: read
jobs:
app:
name: app (${{ matrix.os }})
@@ -99,3 +102,8 @@ jobs:
node-version: 20
- 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).
+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).
+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)]
+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;
+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"]
);
});
File diff suppressed because it is too large. Load diff
+31 -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,
@@ -29,6 +29,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 +263,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 +276,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 +310,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 +2452,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 +6258,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);
+115 -11
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,
@@ -166,7 +166,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 +188,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.
@@ -1217,7 +1217,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 +1261,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 +1285,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) => {
@@ -2513,10 +2513,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`);
}
});
+122
View File
@@ -173,6 +173,128 @@ 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" });
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) {
await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
}
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" });
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) {
await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
}
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.
+7 -1
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);
});
+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
+12 -5
View File
@@ -55,7 +55,7 @@ export const FADE_MS = 700;
// When your next step would crash, you hold in place for GRACE_MS first: a
// turn pressed in that time rides out of it, and only then is it a crash.
// Rivals get no grace.
export const GRACE_MS = 150;
export const GRACE_MS = 190;
// Space spends a charge on BOOST_MS of speed. Every heat starts with
// START_CHARGES, and a Boost pad adds one, up to MAX_CHARGES.
@@ -257,7 +257,7 @@ export function pace(round, rider) {
}
function makeRider(id, spawn) {
return { id, x: spawn.x, y: spawn.y, dir: spawn.dir, queue: [], alive: true, acc: 0, stall: null, prev: { x: spawn.x, y: spawn.y }, path: [{ x: spawn.x, y: spawn.y }], wide: [], fade: 0, by: null };
return { id, x: spawn.x, y: spawn.y, dir: spawn.dir, queue: [], alive: true, acc: 0, stall: null, prev: { x: spawn.x, y: spawn.y }, path: [{ x: spawn.x, y: spawn.y }], wide: [], fresh: [], fade: 0, by: null };
}
const portalAt = (round, x, y) => round.portals.find((p) => p.x === x && p.y === y) || null;
@@ -586,7 +586,7 @@ export function hyperjump(round, random = Math.random) {
if (space > most) [most, dir] = [space, name];
}
const from = { x: you.x, y: you.y };
Object.assign(you, { x: best.x, y: best.y, prev: { x: best.x, y: best.y }, dir, queue: [], stall: null, acc: 0 });
Object.assign(you, { x: best.x, y: best.y, prev: { x: best.x, y: best.y }, dir, queue: [], stall: null, acc: 0, fresh: [] });
if (!active(round, "phase")) {
round.grid[at(best.x, best.y)] = 1;
you.path.push({ x: best.x, y: best.y });
@@ -596,7 +596,9 @@ export function hyperjump(round, random = Math.random) {
}
// Wide Trail: the cells either side of your head turn to your trail too,
// where they are open.
// where they are open. The pair just laid stays `fresh` until your next step,
// and you may ride onto it, so a turn at a corner never crashes into your own
// side cells.
function widen(round, r) {
const d = DIRS[r.dir];
for (const side of [-1, 1]) {
@@ -607,6 +609,7 @@ function widen(round, r) {
if (round.riders.some((o) => o.alive && o.x === x && o.y === y)) continue;
round.grid[at(x, y)] = r.id + 1;
r.wide.push({ x, y });
r.fresh.push({ x, y });
}
}
@@ -621,7 +624,8 @@ function landing(round, r, dir) {
if (portal) ({ x, y } = portal.to);
const cell = round.grid[at(x, y)];
const phased = r.id === 0 && active(round, "phase");
if (cell !== 0 && !(phased && cell > 0)) return { x, y, portal, by: cell > 0 ? cell - 1 : cell === BLOCK ? "block" : "wall" };
const fresh = r.fresh.some((c) => c.x === x && c.y === y);
if (cell !== 0 && !(phased && cell > 0) && !fresh) return { x, y, portal, by: cell > 0 ? cell - 1 : cell === BLOCK ? "block" : "wall" };
// Only a phased rider or a portal can bring one head onto another.
const other = round.riders.find((o) => o !== r && o.alive && o.x === x && o.y === y);
return { x, y, portal, by: other ? other.id : null };
@@ -694,6 +698,9 @@ function move(round, r, to, random = Math.random) {
const i = at(x, y);
r.x = x;
r.y = y;
// Onto a side cell just laid: it is your head's now, part of the line.
if (r.fresh.length) r.wide = r.wide.filter((c) => c.x !== x || c.y !== y);
r.fresh = [];
if (!(r.id === 0 && active(round, "phase"))) {
round.grid[i] = r.id + 1;
r.path.push({ x, y });
+6 -2
View File
@@ -861,13 +861,17 @@ export function deleteSummary(spec) {
};
}
export function staleLaunchFeedback(title, adrift) {
// `inApp`: the desktop app puts a Reconnect to agent button on the screen
// (starting.js), so the hint points at it; a browser has only the terminal.
export function staleLaunchFeedback(title, adrift, inApp = false) {
if (!adrift) return null;
return {
kicker: "Saved",
title: `${title || "Your workflow"} 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: inApp
? "Press Reconnect to agent below. Plan2Code will collect this launch and continue here."
: "Return to the terminal and type continue. Plan2Code will collect this launch and continue here.",
};
}
+49
View File
@@ -0,0 +1,49 @@
// Plan2Code Web Console - the one button that wakes a quiet agent.
//
// Under the desktop app the agent's terminal is in the same window, so a press
// asks the app to type "continue" there (the app types that word and nothing
// else). A browser cannot reach a terminal, so those spots say what to type.
import { page } from "./state.js";
import { tellApp } from "./app-bridge.js";
import { el } from "./render.js";
// Held off for a few seconds after a press, so a double press does not send it twice.
const CONTINUE_HOLD_MS = 4000;
// Kept here, not on the button: a screen that redraws builds a fresh button,
// which must still be held off for the rest of the four seconds.
let heldUntil = 0;
/**
* A button asking the app to type continue into the agent's terminal. `label`
* is the button's words; the status line keeps its own small key look, the Ask
* tab and the waiting screens say "Reconnect to agent".
*/
export function continueButton(label = "continue", cls = "agent-key agent-key-btn") {
const btn = el("button", cls, label);
btn.type = "button";
btn.disabled = Date.now() < heldUntil;
btn.title = "Type continue in the agent's terminal";
btn.addEventListener("click", () => {
btn.disabled = true;
heldUntil = Date.now() + CONTINUE_HOLD_MS;
tellApp("agent-continue");
setTimeout(() => (btn.disabled = false), CONTINUE_HOLD_MS);
});
return btn;
}
/**
* What a spot with no agent to talk to offers: the button under the app, and
* under a browser a line telling the person to type continue in their terminal.
* Null when there is nothing to offer.
*/
export function reconnectOffer(cls = "reconnect-offer") {
if (page.inApp) return continueButton("Reconnect to agent", "btn small " + cls);
const note = el("p", cls + " help");
note.appendChild(document.createTextNode("To wake the agent, type "));
note.appendChild(el("strong", "agent-key", "continue"));
note.appendChild(document.createTextNode(" in your terminal."));
return note;
}
+33 -16
View File
@@ -2650,13 +2650,13 @@
<p class="help-lead">
The <strong>die</strong> in the top bar opens
<strong>Activities</strong>: small games to play while you wait, say
through a long build. Twelve games ship: <strong>Snake</strong>,
through a long build. Thirteen games ship: <strong>Snake</strong>,
<strong>Mini golf</strong>, <strong>Light Trails</strong>,
<strong>Bug Hunt</strong>, <strong>Sunset Drive</strong>,
<strong>Stack Deploy</strong>, <strong>Bumper Ring</strong>,
<strong>Rapids Run</strong>, <strong>Hot Potato</strong>,
<strong>Crossing Rush</strong>, <strong>Bounce Road</strong> and
<strong>Ghoul Rush</strong>. The window opens on a card for each game, with its best score; click one
<strong>Crossing Rush</strong>, <strong>Bounce Road</strong>,
<strong>Ghoul Rush</strong> and <strong>Flock Dash</strong>. The window opens on a card for each game, with its best score; click one
(or walk them with the arrows and press <kbd>Space</kbd>) to play it,
and <strong>All games</strong> takes you back. One game plays at a
time: a round left for the cards waits, paused, on its card, and
@@ -2959,6 +2959,18 @@
lost; and 2000 for the Gourd and 2500 for Rattlebones, times the
lap, with a life back.
</li>
<li>
<strong>Flock Dash</strong>: lead Planny's flock through a sunset
sky. Strays drift in from the right; fly into one and it joins the
flock, following the exact path you flew. 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 (pick them back up within 3
seconds or they are gone). Eight stages, each ending at a jet
stream portal that forms a V for a bonus when enough birds reach
it; the final portal moves. Tailwind, shield and magnet crates help,
and quick pickups build a combo of up to x5.
</li>
</ul>
<h4>It never hides your turn</h4>
<ul>
@@ -3052,6 +3064,11 @@
<kbd>Space</kbd> to fire (in bursts: the blaster slows as it heats
and cools once you let go).
</li>
<li>
Flock Dash: up and down (or <kbd>W</kbd> and <kbd>S</kbd>) climb and
dive, left and right (or <kbd>A</kbd> and <kbd>D</kbd>) ease forward
and back.
</li>
<li><kbd>Space</kbd> starts a round, and plays again after a pause.</li>
<li><kbd>P</kbd> pauses and plays.</li>
<li><kbd>R</kbd> starts the round over, from the countdown.</li>
@@ -3076,22 +3093,22 @@
<p>
The window's title shows the best for the game on screen, and the
line under the board shows it beside your score, and each card shows
its game's. For Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road and Ghoul Rush the best is
its game's. For Snake, Light Trails, Bug Hunt, Sunset Drive, Stack Deploy, Bumper Ring, Rapids Run, Hot Potato, Crossing Rush, Bounce Road, Ghoul Rush and Flock Dash the best is
your highest score; for Mini golf it is your lowest full round of eighteen holes,
kept for each course on its own, and a round left halfway never counts. <strong>Reset best
scores</strong>, at the bottom of the window, clears them all after a
second click to confirm.
</p>
<h4>Hiding it</h4>
<h4>Showing and hiding it</h4>
<p>
Don't want the die? Untick <strong>Show Activities</strong> in User
Preferences (the gear) and it is gone from every screen. To play
without sound, untick <strong>Play game sounds</strong> beside it.
A game with music (turn on <strong>Play game music</strong> there) has
The die is off until you tick <strong>Show Activities</strong> in User
Preferences (the gear); untick it again and it is gone from every screen. To play
without sound, untick <strong>Play activity sounds</strong> beside it.
A game with music (turn on <strong>Play activity music</strong> there) has
its own <strong>Music</strong> slider under the board for how loud it plays.
</p>
<p>
Best scores, Snake's surprises found, Light Trails' furthest arena, Bug Hunt's finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's furthest room, each game's music volume, your last pick and that switch are saved privately on
Best scores, Snake's surprises found, Light Trails' furthest arena, Bug Hunt's finds, Sunset Drive's roads found, Stack Deploy's highest floor, Bumper Ring's furthest arena, Rapids Run's furthest dam, Hot Potato's furthest venue, Crossing Rush's furthest zone, Bounce Road's furthest stage, Ghoul Rush's furthest room, Flock Dash's furthest stage, each game's music volume, your last pick and that switch are saved privately on
this machine, with your other preferences, and never sent anywhere.
</p>
</section>
@@ -3392,8 +3409,8 @@
<li>
<strong>Activities</strong>: <strong>Show Activities</strong> puts
the die in the top bar, which opens small games to play while you
wait. Untick it to hide the die on every screen.
<strong>Play game sounds</strong> turns the games' sounds on or
wait. It starts unticked; untick it again to hide the die on every screen.
<strong>Play activity sounds</strong> turns the games' sounds on or
off, leaving every other sound as it is; with Play sounds off, the
games are silent too.
</li>
@@ -3662,10 +3679,10 @@
</fieldset>
<fieldset data-section="activities" class="modal-ranges looks-activities">
<legend>Activities</legend>
<label><input type="checkbox" id="looks-activities" checked /> <span>Show Activities</span></label>
<label><input type="checkbox" id="looks-activity-sounds" checked /> <span>Play game sounds</span></label>
<label><input type="checkbox" id="looks-game-music" /> <span>Play game music</span></label>
<p class="help">The die in the top bar opens small games to play while you wait. Play game sounds turns the games' sounds on or off, and Play game music their music; Play sounds, above, silences them too.</p>
<label><input type="checkbox" id="looks-activities" /> <span>Show Activities</span></label>
<label><input type="checkbox" id="looks-activity-sounds" checked /> <span>Play activity sounds</span></label>
<label><input type="checkbox" id="looks-game-music" /> <span>Play activity music</span></label>
<p class="help">The die in the top bar opens small games to play while you wait. Play activity sounds turns the games' sounds on or off, and Play activity music their music; Play sounds, above, silences them too.</p>
</fieldset>
</section>
</div>
+2 -2
View File
@@ -31,11 +31,11 @@ export const DEFAULT_LOOKS = {
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
hideUnavailable: true,
// Activities: the top bar's die, whether its games play sounds (under Play
// Activities: the top bar's die (hidden until someone turns on Show Activities), whether its games play sounds (under Play
// sounds, which silences them too), the game last picked, and one best score
// per listed game (activityBestSnake) or, for a game with courses, per
// course (activityBestGolfPirate), each a flat key for cleanLooks().
hideActivities: false,
hideActivities: true,
activitySounds: true,
// Whether a game plays its music too (chiptune or recorded songs): off until asked for.
gameMusic: false,
+19 -3
View File
@@ -22,7 +22,7 @@ import { hushMusic, music as playMusic } from "../music.js";
const $ = (id) => document.getElementById(id);
// Every sound the window and its games make goes through these two, so
// Preferences' Play game sounds silences them all (and Play sounds, which
// Preferences' Play activity sounds silences them all (and Play sounds, which
// tones.js checks, does too).
const tone = (...args) => {
if (looks.activitySounds) playTone(...args);
@@ -30,7 +30,7 @@ const tone = (...args) => {
const hum = (...args) => {
if (looks.activitySounds) playHum(...args);
};
// And the music, which also needs Play game music, at the game's own
// And the music, which also needs Play activity music, at the game's own
// music volume (the window's Music slider). A song's "playing" or "ended"
// goes back to the game, which moves on to its next song on "ended".
const musicFor = (entry) => (name, intensity, options) => {
@@ -38,7 +38,7 @@ const musicFor = (entry) => (name, intensity, options) => {
return undefined;
};
const MUSIC_TITLE = "This game's music volume";
const MUSIC_OFF_TITLE = "Turn on Play game music in User Preferences to hear it";
const MUSIC_OFF_TITLE = "Turn on Play activity music in User Preferences to hear it";
// Quiets every held sound and the music: the window stopped ticking a game.
function hushTones() {
@@ -907,6 +907,22 @@ const COVERS = Object.freeze({
["rect", { x: 59, y: 49.4, width: 6, height: 6, rx: 1.5, fill: "none", "stroke-width": 0.8, class: "cv-ink3-line" }],
["path", { d: "M62.0 50.0 L62.6 51.5 L64.2 51.6 L63.0 52.6 L63.4 54.2 L62.0 53.3 L60.6 54.2 L61.0 52.6 L59.8 51.6 L61.4 51.5 Z", class: "cv-accent" }],
],
flock: [
...[0, 1, 2, 3, 4, 5].map((k) => ["rect", { y: k * 10, width: 120, height: 10, fill: ["#4b2a7a", "#6a3b8f", "#944a9c", "#c75b93", "#ec6f7a", "#f5965c"][k] }]),
["circle", { cx: 90, cy: 58, r: 8, fill: "#fff3b0" }],
["rect", { y: 60, width: 120, height: 12, fill: "#f7c35e" }],
...[[8, 22], [18, 28], [28, 24], [38, 30], [48, 34]].map(([x, y]) => ["path", { d: "M-5 0 Q-2.5 -4 0 -0.5 Q2.5 -4 5 0 Q2.5 -1.5 0 1.5 Q-2.5 -1.5 -5 0 Z", transform: `translate(${x} ${y})`, fill: "#2b2140" }]),
["path", { d: "M96 6 Q106 6 106 18 Q106 30 98 36 H94 Q86 30 86 18 Q86 6 96 6 Z", fill: "#e2553f", stroke: "#2b2140", "stroke-width": 1 }],
["rect", { x: 91, y: 9, width: 3, height: 23, fill: "#f4f1ea" }],
["rect", { x: 98, y: 9, width: 3, height: 23, fill: "#f4f1ea" }],
["path", { d: "M94 36 L93 39 M98 36 L99 39", stroke: "#2b2140", "stroke-width": 0.8 }],
["rect", { x: 92.5, y: 39, width: 7, height: 4.5, rx: 1, fill: "#8a5a30" }],
["rect", { transform: "translate(36 6)", x: 20, y: 28, width: 28, height: 22, rx: 9, class: "cv-accent" }],
["path", { transform: "translate(36 6)", d: "M47 34 L53 37 L47 40 Z", fill: "#ff8a1f" }],
["path", { transform: "translate(36 6)", d: "M24 40 Q32 47 42 40 Q36 46 24 44 Z", fill: "#000000", "fill-opacity": 0.22 }],
["path", { transform: "translate(36 6)", d: "M34 31.4 L34.9 33.8 L37.4 33.9 L35.4 35.5 L36.1 37.9 L34 36.5 L31.9 37.9 L32.6 35.5 L30.6 33.9 L33.1 33.8 Z", fill: "#f5b301" }],
["path", { transform: "translate(36 6)", d: "M28 50 V53 H31 M37 50 V53 H40", fill: "none", "stroke-width": 1.6, "stroke-linecap": "round", "stroke-linejoin": "round", class: "cv-accent-line" }],
],
fuse: [
["rect", { width: 120, height: 72, fill: "#dcc9a6" }],
...[0, 1, 2, 3, 4, 5].flatMap((r) => [0, 1, 2, 3, 4, 5, 6, 7].filter((c) => (c + r) % 2).map((c) => ["rect", { x: c * 16, y: r * 12, width: 16, height: 12, fill: "#d1bc95" }])),
+5
View File
@@ -11,6 +11,7 @@ import { attachMentions } from "../mention-box.js";
import { makeMdField } from "../md-field.js";
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
import { postJson } from "../net.js";
import { reconnectOffer } from "../continue-button.js";
import { suggestState } from "../send-state.js";
import { CHECKIN_LINE, helperRows, showSwitch, switchLabel, defaultInstruction, PATHFINDER_RESEARCH_LINE, STRENGTHS, DEFAULT_STRENGTH, STRENGTH_HELP } from "../subagents.js";
@@ -337,6 +338,10 @@ function askComposer(ss) {
row.appendChild(hint);
}
// No agent there: under the app a button that types continue in its terminal,
// left of Send; in a browser, the line telling the person to.
if (ss.state === "offline" && !finish()) row.appendChild(reconnectOffer("ask-reconnect"));
const go = el("button", "btn small primary", "Send");
go.type = "button";
row.appendChild(go);
+6 -1
View File
@@ -391,7 +391,12 @@ export function renderCard(item) {
const skip = el("button", "btn tiny", skipped ? "Do not skip" : "Skip this one");
skip.type = "button";
skip.style.marginTop = "16px";
skip.addEventListener("click", () => (skipped ? stage(item.id, null) : skipAndMoveOn(item.id)));
skip.addEventListener("click", () => {
if (!skipped) return skipAndMoveOn(item.id);
// Keep a note typed with the skip: the box still shows it, so the send must carry it.
const kept = page.local.staged[item.id];
stage(item.id, kept && kept.text ? { type: "answer", kind: item.kind, text: kept.text } : null);
});
card.appendChild(skip);
if (page.local.skipFlash === item.id) {
card.classList.add("is-skip-flash");
+10 -20
View File
@@ -72,6 +72,7 @@ import { board, renderGitBoard, resetBoard } from "./git-host.js";
import { renderWorkspace, tellFolderIssues } from "./workspace.js";
import { openHelpOn } from "./help-dialog.js";
import { linkLeavesPage, onAppMessage, startNewSession, tellApp } from "../app-bridge.js";
import { continueButton } from "../continue-button.js";
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
import { renderHandoff, renderLoopEnd, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
import { renderNotepadButton } from "./notepad.js";
@@ -1167,6 +1168,12 @@ let moodVar = 0;
const STRANDED_LINE =
"Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval.";
// The dashboard's quiet lines: the pick or the way home is saved, and typing
// **continue** in the terminal (a button under the app) wakes the agent.
const WAKE_TAIL = "If the terminal is idle, type **continue** there to wake it.";
const DASH_QUIET_LINE = `Plan2Code has gone quiet. A pick still waits here for it. ${WAKE_TAIL}`;
const HOMEWARD_QUIET_LINE = `Your way back to the dashboard is saved and waiting for Plan2Code. ${WAKE_TAIL}`;
// The agent is out of `wait` answering an Ask message (askBusy()), so a send
// waits for it to finish that first.
const ASK_BUSY_LINE = "Plan2Code is answering your Ask message. Your answers are saved, and it picks them up after that.";
@@ -1175,23 +1182,6 @@ const ASK_BUSY_LINE = "Plan2Code is answering your Ask message. Your answers are
const PRESS_STRANDED_LINE =
"Plan2Code is not running. Your choice is saved and waiting for it. If the terminal is idle, type **continue** there and it will pick it up; it may also be waiting for your permission approval.";
// The status line's **continue**, under the app: a press asks the app to type
// it into the agent's terminal. Held off for a few seconds after, so a double
// press does not send it twice.
const CONTINUE_HOLD_MS = 4000;
function continueButton() {
const btn = el("button", "agent-key agent-key-btn", "continue");
btn.type = "button";
btn.title = "Type continue in the agent's terminal";
btn.addEventListener("click", () => {
btn.disabled = true;
tellApp("agent-continue");
setTimeout(() => (btn.disabled = false), CONTINUE_HOLD_MS);
});
return btn;
}
// Under the app with its terminal panel collapsed (the app's `terminal-state`),
// "terminal" in a What to check line is a button asking the app to expand it.
function terminalButton(word) {
@@ -1325,7 +1315,7 @@ export function renderStatus() {
// until the agent resumes the session as the dashboard.
if (page.local.homeward && !isDashboard()) {
return agentAdrift()
? say("adrift", "Your way back to the dashboard is saved and waiting for Plan2Code.")
? say("adrift", HOMEWARD_QUIET_LINE, "", false, true)
: say("work", "Saving your place and opening the dashboard…", "", true);
}
// The dashboard's three states, ahead of the question logic it never
@@ -1335,13 +1325,13 @@ export function renderStatus() {
if (page.local.launching) {
const stale = staleLaunchFeedback(page.local.launching.title, agentAdrift());
return stale
? say("adrift", `${page.local.launching.title} is saved and waiting for Plan2Code.`)
? say("adrift", `${page.local.launching.title} is saved and waiting for Plan2Code. ${WAKE_TAIL}`, "", false, true)
: say("work", `Waking up ${page.local.launching.title}…`, "", true);
}
if (page.dashPick) return say("point", `Start ${page.dashPick.title} when you're ready.`);
// The cards work before the agent's menu lands, so a pick is always
// theirs; the line still says what the agent is up to, or that it went quiet.
if (agentAdrift()) return say("adrift", "Plan2Code has gone quiet. A pick still waits here for it.");
if (agentAdrift()) return say("adrift", DASH_QUIET_LINE, "", false, true);
const doing = page.S.agent && typeof page.S.agent.activity === "string" ? page.S.agent.activity.trim() : "";
if (agentWorking() && !page.S.menu) return say("point", `Pick what we are doing today. ${doing || "Plan2Code is looking over the project."}`);
return say("point", "Your move: pick what we are doing today.");
+3 -3
View File
@@ -625,7 +625,7 @@ async function copyHandoffText(text, id, label) {
// CLI reads the stored skill and spec, marks the handoff used and falls back
// to Quick Task if either is gone.
async function pickUpHandoff(h) {
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
if (page.gone || page.pendingResult || page.local.launching || page.launchScoping || finish()) return;
page.launchScoping = true;
await hooks.syncWorkspaceScope(h.spec || "");
try {
@@ -1091,7 +1091,7 @@ export function renderConfirm(main, entry) {
// marks the action as being about the session, and it reaches the agent
// through the same wait loop. The dashboard reads `skill` off it.
export async function launchSkill(entry) {
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
if (page.gone || page.pendingResult || page.local.launching || page.launchScoping || finish()) return;
const target = launchTarget(entry, selSpec());
// The card was clickable, so this should never fire — but a spec picked in
// one tab could have shifted the ground under a stale render in another.
@@ -1351,7 +1351,7 @@ export function wireDashboard() {
$("delete-name").addEventListener("keydown", (e) => {
if (e.key === "Enter") {
e.preventDefault();
deleteStep();
if (!$("delete-go").disabled) deleteStep();
}
});
// `close` is queued, so it can land after the dialog was opened again for
+1 -1
View File
@@ -899,7 +899,7 @@ export function renderStopping() {
extra.replaceChildren();
if (stuck) {
extra.appendChild(
el(
textWithCode(
"p",
"stop-note",
page.inApp
+15 -3
View File
@@ -3,6 +3,7 @@
import { page, redraw } from "../state.js";
import { el, approvalTip } from "../render.js";
import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js";
import { continueButton } from "../continue-button.js";
import { skillByName } from "../skills.js";
import { agentAdrift, doingNow, docs, loopDriving } from "../selectors.js";
@@ -100,7 +101,8 @@ function posePane(main, cls, workflow) {
const pane = el("div", cls);
pane.dataset.pose = pose;
pane.appendChild(startStage(workflow));
if (held) main.insertBefore(pane, held);
// The old pane (another pose) is replaced, not left beside the new one.
if (held && held.parentNode === main) held.replaceWith(pane);
else main.appendChild(pane);
return pane;
}
@@ -119,7 +121,7 @@ export function renderLaunching(main) {
const l = page.local.launching || {};
const pane = posePane(main, "launching", l.skill && skillByName(l.skill)?.workflow);
const stale = staleLaunchFeedback(l.title, agentAdrift());
const stale = staleLaunchFeedback(l.title, agentAdrift(), page.inApp);
pane.appendChild(el("p", "card-kicker", stale ? stale.kicker : "On it"));
pane.appendChild(el("h2", "launch-title", stale ? stale.title : `Waking up ${l.title || "the next mode"}`));
pane.appendChild(el("p", "launch-quip", stale ? stale.quip : LAUNCH_QUIPS[0]));
@@ -130,6 +132,14 @@ export function renderLaunching(main) {
stale ? stale.hint : "This page turns into its home the moment it answers. No need to touch anything."
)
);
// Under the app a saved pick no agent collects gets a button that types
// continue in the terminal; the ticker shows and hides it with the hint.
if (page.inApp) {
const row = el("div", "launch-reconnect");
row.hidden = !stale;
row.appendChild(continueButton("Reconnect to agent", "btn primary"));
pane.appendChild(row);
}
startLaunchTicker();
}
@@ -211,7 +221,9 @@ function startLaunchTicker() {
return;
}
const elapsed = Date.now() - cur.at;
const stale = staleLaunchFeedback(cur.title, agentAdrift());
const stale = staleLaunchFeedback(cur.title, agentAdrift(), page.inApp);
const reconnect = document.querySelector(".launch-reconnect");
if (reconnect) reconnect.hidden = !stale;
if (kicker) kicker.textContent = stale ? stale.kicker : "On it";
if (title) title.textContent = stale ? stale.title : `Waking up ${cur.title || "the next mode"}`;
q.textContent = stale ? stale.quip : LAUNCH_QUIPS[Math.floor(elapsed / 2600) % LAUNCH_QUIPS.length];
+5
View File
@@ -149,6 +149,11 @@
.ask-actions .btn.primary { margin-left: auto; }
.ask-send-hint { margin-left: auto; font-size: 12px; color: var(--ink-3); white-space: nowrap; }
.ask-send-hint + .btn.primary { margin-left: 0; }
/* The wake-the-agent offer when nobody is there: a button (or, in a browser, a
line) pushed right so it sits directly left of Send. */
.ask-actions .ask-reconnect { margin-left: auto; }
.ask-actions .ask-reconnect + .btn.primary { margin-left: 0; }
p.ask-reconnect { margin-top: 0; margin-bottom: 0; font-size: 12.5px; }
.ask-count { font: 12px/1 var(--mono); color: var(--ink-3); }
.ask-count.is-over { color: var(--warn); font-weight: 700; }
.ask-error { color: var(--warn); font-size: 13px; margin: 8px 0 0; }
@@ -602,6 +602,9 @@
to { opacity: 1; transform: none; }
}
.launch-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); max-width: 46ch; }
/* Under the app, a saved pick nobody collected: the button that types continue. */
.launch-reconnect { margin-top: 14px; }
.launch-reconnect[hidden] { display: none; }
/* A line, never a banner: no border, no background, no icon. */
.approval-tip { max-width: 70ch; margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); }
+2 -1
View File
@@ -13,6 +13,7 @@ import fuseSfx from "./activities/fuse-sfx.js";
import hopSfx from "./activities/hop-sfx.js";
import bounceSfx from "./activities/bounce-sfx.js";
import ghoulSfx from "./activities/ghoul-rush/sfx/ghoul-sfx.js";
import flockSfx from "./activities/flock-sfx.js";
/* ------------------------------------------------------------- tones
@@ -376,7 +377,7 @@ const HUMS = hums({
// Every game's own extras, merged after the shared kit; a name may be
// defined only once across them all (the activities suite checks).
const GAME_SFX = Object.freeze([snakeSfx, golfSfx, trailsSfx, bugsSfx, driveSfx, stackSfx, bumperSfx, rapidsSfx, fuseSfx, hopSfx, bounceSfx, ghoulSfx]);
const GAME_SFX = Object.freeze([snakeSfx, golfSfx, trailsSfx, bugsSfx, driveSfx, stackSfx, bumperSfx, rapidsSfx, fuseSfx, hopSfx, bounceSfx, ghoulSfx, flockSfx]);
// A game file holds plain objects; they are frozen here, all the way down.
const deepFreeze = (o) => {
+27 -11
View File
@@ -132,6 +132,14 @@ const ROUTES = [
{ path: "/bye", origin: true, run: bye },
];
// events.ndjson is an advisory log: a transient lock or a full disk must not
// take a route (or the detached server) down after the real write landed.
function noteEvent(dir, event) {
try {
appendEvent(dir, event);
} catch {}
}
export function handle(req, res, ctx) {
const port = ctx.port();
const url = new URL(req.url, `http://127.0.0.1:${port}`);
@@ -149,7 +157,15 @@ export function handle(req, res, ctx) {
if (route.path !== undefined ? pathname !== route.path : !route.match(pathname, req)) continue;
if (route.method && req.method !== route.method) continue;
if (route.origin && !originOk(req, port)) return json(res, 403, { error: "bad origin" });
return route.run(req, res, ctx, url);
try {
return route.run(req, res, ctx, url);
} catch (e) {
if (!res.headersSent) return json(res, 500, { error: "server error" });
try {
res.end();
} catch {}
return undefined;
}
}
return json(res, 404, { error: "not found" });
}
@@ -540,7 +556,7 @@ function subagentsPost(req, res, ctx) {
}
if (unchanged) return json(res, 200, { ok: true, setting: current });
const setting = readSubagentSetting(ctx.dir);
appendEvent(ctx.dir, { type: "subagents", on, revision: setting.revision });
noteEvent(ctx.dir, { type: "subagents", on, revision: setting.revision });
ctx.pushState();
return json(res, 200, { ok: true, setting });
});
@@ -567,7 +583,7 @@ function prHost(req, res, ctx) {
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
appendEvent(ctx.dir, { type: "pr-host", host, kind });
noteEvent(ctx.dir, { type: "pr-host", host, kind });
return json(res, 200, { ok: true });
});
}
@@ -1184,7 +1200,7 @@ function upload(req, res, ctx) {
const saved = store(buf, "jpg");
if (!saved) return;
const { id, file } = saved;
appendEvent(ctx.dir, { type: "upload", id, kind: "image", bytes: buf.length });
noteEvent(ctx.dir, { type: "upload", id, kind: "image", bytes: buf.length });
return json(res, 200, {
ok: true,
id,
@@ -1213,7 +1229,7 @@ function upload(req, res, ctx) {
const saved = store(buf, ext);
if (!saved) return;
const { id, file } = saved;
appendEvent(ctx.dir, { type: "upload", id, kind: "file", bytes: buf.length });
noteEvent(ctx.dir, { type: "upload", id, kind: "file", bytes: buf.length });
return json(res, 200, { ok: true, id, kind: "file", path: file, name, size: buf.length });
});
}
@@ -1301,7 +1317,7 @@ function uploads(req, res, ctx, url) {
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
appendEvent(ctx.dir, { type: "upload-delete", id: m[1] });
noteEvent(ctx.dir, { type: "upload-delete", id: m[1] });
res.writeHead(204, baseHeaders());
return res.end();
}
@@ -1437,7 +1453,7 @@ function submit(req, res, ctx) {
});
}
if (refused) return json(res, 500, { error: refused });
appendEvent(ctx.dir, { type: "submit", rev: ctx.rev, count: body.actions.length });
noteEvent(ctx.dir, { type: "submit", rev: ctx.rev, count: body.actions.length });
if (written) {
// Account for our own write here rather than letting the watcher find
// it: the watcher reads a changed state.json as proof the AGENT is
@@ -1489,7 +1505,7 @@ function chat(req, res, ctx) {
workflow: state.workflow,
reason: "button",
});
appendEvent(ctx.dir, { type: "chat-reset", reason: "button" });
noteEvent(ctx.dir, { type: "chat-reset", reason: "button" });
ctx.rev++;
ctx.pushState();
return json(res, 200, { ok: true, seq: entry.seq, conversation: entry.conversation });
@@ -1527,7 +1543,7 @@ function chat(req, res, ctx) {
: undefined,
files: body.files ? body.files.map((f) => ({ path: f.path, name: cleanLabel(f.name, "file") })) : undefined,
});
appendEvent(ctx.dir, { type: "chat", seq: entry.seq });
noteEvent(ctx.dir, { type: "chat", seq: entry.seq });
ctx.rev++;
ctx.pushState();
return json(res, 200, { ok: true, seq: entry.seq, conversation: current });
@@ -1564,7 +1580,7 @@ function chatDecision(req, res, ctx) {
decision: body.decision,
text: text || undefined,
});
appendEvent(ctx.dir, { type: "chat-decision", decision: body.decision });
noteEvent(ctx.dir, { type: "chat-decision", decision: body.decision });
ctx.rev++;
ctx.pushState();
return json(res, 200, { ok: true, seq: entry.seq });
@@ -1734,7 +1750,7 @@ function cancel(req, res, ctx) {
return json(res, 500, { error: String(e.message) });
}
if (pending) return json(res, 409, { error: "pending", message: "A send is still on its way." });
appendEvent(ctx.dir, { type: "cancel", rev: ctx.rev });
noteEvent(ctx.dir, { type: "cancel", rev: ctx.rev });
ctx.broadcast("cancelled", { rev: ctx.rev });
return json(res, 200, { ok: true });
}
+18 -4
View File
@@ -529,11 +529,16 @@ setInterval(() => {
// Answers nobody has collected yet keep the server up (bounded by MAX_LIFE_MS):
// exiting would strand the tab and the send it holds.
if (idle > IDLE_MS && !resultFlags().pending) {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
// The log is advisory: a failed append must never keep an orphan server alive.
try {
appendEvent(DIR, { type: "exit", reason: "idle", idleMs: idle });
} catch {}
process.exit(0);
}
if (Date.now() - STARTED > MAX_LIFE_MS) {
appendEvent(DIR, { type: "exit", reason: "max-life" });
try {
appendEvent(DIR, { type: "exit", reason: "max-life" });
} catch {}
process.exit(0);
}
}, 20000).unref();
@@ -544,6 +549,14 @@ for (const sig of ["SIGINT", "SIGTERM", "SIGHUP"]) {
} catch {}
}
// A throw inside a request callback (a read or write failing on a locked file)
// must not end the detached server: note it and carry on. The page retries.
process.on("uncaughtException", (e) => {
try {
appendEvent(DIR, { type: "error", message: String(e?.message || e).slice(0, 200) });
} catch {}
});
// Every exit that gets to run code takes its handle file with it, so a pid
// left behind in the runtime dir cannot later be mistaken for this server once
// the number is reused. Only while the file still names THIS process: a
@@ -602,8 +615,9 @@ function onListening(port) {
stateDir: DIR,
startedAt: nowIso(),
};
ensureDir(path.dirname(handleFile(PROJECT, SID)));
writeJsonAtomic(handleFile(PROJECT, SID), handle);
// The handle holds the session token: private to this user on a shared /tmp.
ensureDir(path.dirname(handleFile(PROJECT, SID)), 0o700);
writeJsonAtomic(handleFile(PROJECT, SID), handle, 0o600);
appendEvent(DIR, { type: "listening", port, pid: process.pid });
checkState();
// A resume through a fresh server still starts a new conversation on a hop.
+6
View File
@@ -51,6 +51,7 @@ export const SERVABLE = new Set([
"mentions.js",
"favicon.js",
"app-bridge.js",
"continue-button.js",
"git-board.js",
"git-board-view.js",
"pr-url.js",
@@ -231,6 +232,11 @@ export const SERVABLE = new Set([
"activities/light-trails/3.mp3",
"activities/light-trails/4.mp3",
"activities/light-trails/5.mp3",
"activities/flock-dash/1.mp3",
"activities/flock-dash/2.mp3",
"activities/flock-dash/3.mp3",
"activities/flock-dash/4.mp3",
"activities/flock-dash/5.mp3",
"activities/bugs-sfx.js",
"activities/drive-sfx.js",
"activities/stack-sfx.js",
+8 -1
View File
@@ -231,7 +231,14 @@ export function serverWorkspace(ctx) {
}
function saveWorkspace(ws) {
writeWorkspace(dir, ws);
try {
writeWorkspace(dir, ws);
} catch (e) {
// The caller changed the cached object before saving: drop it, so the next
// read starts from what is on disk and a retry is not told "duplicate".
workspaceSeen = { stamp: null, ws: null };
throw e;
}
workspaceSeen = { stamp: fileStamp(WORKSPACE_PATH), ws };
}