Compare commits

..
7 Commits
67 changed files with 10902 additions and 116 deletions

No files matched your search

+19 -8
View File
@@ -220,6 +220,12 @@ 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 and module path) and `bestKey(id)`, the flat looks.json key for its best score (`activityBestSnake`, `activityBestGolf`); lists Snake and Mini golf, and documents the game contract including 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 |
| `public/activities/golf.js` | Mini golf: its rules and physics as plain exported functions (`newRound`, `strike`, `advance` on a fixed 4 ms sub-step, `nextHole`, `total`, `toPar`, `predictPath` for the spyglass, `moverAt`, `gateShut`), the `POWERUPS` held for the next putt (`round.held`, then `round.active` for that putt), the arcade swing (`startSwing`, `setPower`, `meterAt`, `meterZone`, `swingShot`: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in `advance()` that starts the meter after `SHOT_CLOCK_MS` and dribbles the ball after `METER_TRIPS` trips; all on the round's own clock), the pop-up gags, and the game contract with `pointer()` (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), `release()` (held arrows turn the aim, held space fast-forwards) and `lowerIsBetter`; deterministic (no `Math.random()`), a read-only `round` getter for the unit suite only |
| `public/activities/golf-draw.js` | Mini golf's drawing: `drawCourse(ctx, view)` from a plain view `golf.js` builds, each hole in its theme's fixed palette (`pirate`, or `cave` with its darkness and glows), and `readColors(canvas)`, which reads the `--golf-*` properties `styles/activities.css` mixes from the tokens for the ball, pills and scorecard; decides nothing |
| `public/activities/golf-decor.js` | Mini golf's scenery and props: each `decor` kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons; drawing only, moving with the round's clock |
| `public/activities/golf-holes.js` | Mini golf's course, data only (no DOM, no imports): `COURSE_W`, `COURSE_H`, `FRONT_NINE` and the eighteen frozen `HOLES` (theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, water, slopes, bridges, spinners, tunnels, movers, gates, powerups, decor); the front nine is pirate, the back nine cave |
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
@@ -234,6 +240,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
| `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' short Web Audio blips (`tone(name, level)` with an optional loudness from 0 to 1, `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), and the countdown's `count` and `go`), silent while Play sounds is off; separate from `sound.js`'s cue queue |
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry |
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
@@ -260,7 +267,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (19 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
@@ -268,18 +275,20 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
| `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, finished })` (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` (finished, `happy`); `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/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/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) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, `plan`, `revise-plan`, 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 |
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
| `public/screens/activities.js` | Activities: `#btn-activities` (the die right of the megaphone), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. The picker remembers the last pick as `lastActivity`; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads each listed game once with `import()` and keeps it for the page's life; `setActivityList()` lets a test list a stub second game, which brings up the picker |
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
| `public/styles/activities.css` | the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes |
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
@@ -342,12 +351,12 @@ Key design points:
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labeled "Notebook for <folder>" Line truncated
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and the agent's only when the person sends a tab.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** twelve, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) `/notepad/tab/last` (`{ id }`) and `/notepad/tab/sent` (`{ id, workflow, spec? }`, `markTabSent()`: sets `sent: { workflow, spec?, at }` on the tab, replacing an earlier one; `workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`, `spec` matching `^specs/[A-Za-z0-9._-]+$`, else 400 `bad-sent`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The eleven POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` and the `cmd-*.mjs` files never import `notepads.mjs` (a source test pins it; `sessions.mjs` loads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reaches `state.json` or anything `wait` prints except a tab the person sends (see **Send to a skill**). **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notLine truncated
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 18 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 19 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
@@ -385,9 +394,11 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
| CLI | Runs |
| --- | --- |
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
| Codex | `codex --dangerously-bypass-approvals-and-sandbox [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
| Claude Code | `claude /plan2code [--permission-mode bypassPermissions] [args]` |
| Devin | `devin [--permission-mode bypass] [args] -- /plan2code` |
| Codex | `codex [--dangerously-bypass-approvals-and-sandbox] [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` with Yes as the default; `--keep-permissions` (never forwarded) answers no, and with no TTY on stdin the prompts are off, as before. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
+1 -1
View File
@@ -21,7 +21,7 @@
- **`.claude/skills/` is tracked:** a new repo-local skill only needs `git add` (see Architecture → Repo-Local Skills). A correction that is a workflow belongs there as a skill, linked from AGENTS.md, not as a Failure log line.
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
- **Workflow file character limit:** All `src/plan2code-*.md` files (and the dashboard prompt `src/plan2code.md`) must be ≤ 20,000 characters (about 5k tokens, the usual Agent Skills guidance for a SKILL.md body). A husky pre-commit hook enforces this, and `plan2code-metrics` (`improver.ts`, `applier.ts`) applies the same number to proposed prompt edits, so change them together. History: 11,000 originally (headroom under Windsurf's old 12,000-char limit for platform-specific files, gone since 2.1.0's single-format build), 11,500 in 2.4.0, 20,000 in 2.4.1. The limit is now a prompt-size discipline only: the whole SKILL.md loads on every invocation while references load on demand, so situational detail still belongs in a reference file, and anything with one correct answer belongs in a script (see Skill scripts in the architecture doc).
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure with `node scripts/validate-char-count.js` before trusting a near-limit prompt.
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure with `node scripts/validate-char-count.js` before trusting a near-limit prompt. Git never writes CRLF here, but tools do (Python writing in text mode on Windows, some editors and generators), so `scripts/fix-line-endings.mjs` puts every text file git sees back to LF: `npm run fix:eol` by hand, `--check` to only list, and it runs by itself as npm's `pretest`, in the husky pre-commit before the char count, and after every Write or Edit through the PostToolUse hook in `.claude/settings.json`. In a Python script that writes repo files, open them with `newline="\n"` (or write bytes) anyway.
- **The pre-commit hook runs only the char-count check:** `.husky/pre-commit` is `node scripts/validate-char-count.js` alone. `skills/` drift, parse errors and test failures are caught only by `npm test`, so run it before committing. Sub-package tests are separate; see [Development Commands](./AGENTS-development-commands.md).
- **`skills/` is generated build output (gitignored):** edit `src/` only. The installer rebuilds `skills/` on every run, so it is always up to date at install time. `npm test` runs `install.js --build-skills` so a broken `SOURCE_PROMPTS` entry or unreadable source fails CI. Never hand-edit `skills/`; `install.js --verify-skills` can diff a stale tree against `src/` when diagnosing.
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
+16
View File
@@ -0,0 +1,16 @@
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit|MultiEdit|NotebookEdit",
"hooks": [
{
"type": "command",
"command": "node \"$CLAUDE_PROJECT_DIR/scripts/fix-line-endings.mjs\" --hook",
"timeout": 30
}
]
}
]
}
}
+1
View File
@@ -1 +1,2 @@
node scripts/fix-line-endings.mjs
node scripts/validate-char-count.js
+140 -9
View File
@@ -164,10 +164,12 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
favicon follows the line beside him: dashed amber while Plan2Code is
working or picking up your answers, solid green when it is your move, solid
red when it has gone quiet or the connection is lost (busy is dashed so the
states differ by pattern, not only color). A finished session goes back to
the plain icon, so a console left in a background tab can be checked at a
glance.
- **Help.** The **?** at the top right opens a Help dialog with 18 topics,
states differ by pattern, not only color). A finished session stays green
while it still offers a button to press (back to the dashboard, a review),
turns red if that press was never collected, and goes back to the plain
icon once nothing is left, so a console left in a background tab can be
checked at a glance.
- **Help.** The **?** at the top right opens a Help dialog with 19 topics,
one per tab down the left (across the top on a narrow window), opening on
the one for where you are. It is part of the page itself, so it still reads
fully when the page has lost its program.
@@ -222,7 +224,9 @@ and hides it while *Hide unavailable workflows* is on. Its chip has a visible
removes the folder (any other spec also asks you to type its name). Click a card and Planny
flies while it gets ready;
a few seconds later the same page is that skill's console, already running. No
command names to remember.
command names to remember. Pathfinder, Plan, Quick Task and Revise plan can also
start from one of your [Notebook](#your-notebook) tabs: see *Sent from the
dashboard* there.
Handoffs this checkout has not picked up yet follow the specs in the picker as
dashed **Handoff** chips, each with its title and age. Select one and the skill
@@ -456,13 +460,139 @@ working in.
folder per tab, `tabs/<id>/`, holding its `note.md` and `images/`. Two pages
open on one folder share it, and the last save wins.
- **Private.** It never goes into your project, your session or anything the
agent reads, so the agent never sees it. It stays on this machine.
agent reads, so the agent never sees it, unless you send a tab (next
bullet). It stays on this machine. A box filled from a tab is an ordinary
draft from then on: like anything you type, its text is kept with the
session's draft and its pictures with its uploads, unread until you send it.
- **Sent from the dashboard.** On a lit Pathfinder, Plan or Quick Task card
with *Start fresh*, and on a lit Revise plan card with a spec picked that has
no plan change waiting, the confirm pane offers **Start with a note from your
Notebook**. Turn it on and pick a tab: empty tabs are grayed, a tab you have
sent shows a small **sent** badge, and a preview shows the whole tab, its text
and its pictures. The first five pictures are ticked; at most five can be, so
untick one to tick another. A tab over 50 KB gets a *Long tab* note so you can
trim it first, and the pane's command line reads `+ note: <tab>`. Pressing
**Start** is the consent, and nothing is put on the launch itself. The skill's
first open text box marked `"fill": "note"` (the idea box, or Revise plan's
*What should change* box) then arrives filled, once, with the tab's text and
the ticked pictures attached, and you can edit it before you press **Send**. A
tab or picture deleted in between leaves the box empty (with a note) or skips
the picture. Only sending that box hands the agent the text: **Send**, or
**Stop** or **Back to the dashboard**, which take the answers you have ready
with them (their dialog says so). Start alone, then going back before the box
is sent, sends nothing and marks nothing. After it, the tab shows the **sent**
badge and a muted *Sent to <Skill> · <Date>* line under its text.
- **Removed only when you say.** No automatic cleanup touches it. Once the
newest file in a notebook is 30 days old or more, *User Preferences →
Cleanup* offers it as one item named after its folder's full path
(*Notebook for /home/sam/code/shop*),
and deleting it removes the whole notebook, every tab's text and pictures.
### Activities
The **die** in the top bar, right of the megaphone, opens **Activities**: small
games to play while you wait, say through a long build. Two ship today,
**Snake** and **Mini golf**. With two games the window shows a picker, one
button per game, and remembers your last pick. The header shows the current
game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet**.
- **Snake** speeds up as it grows: 120 ms a step at its starting three cells,
4 ms quicker for each cell beyond, never under 60 ms, and 3% quicker again
for each level. Every 5 foods is a new level, and the first few each bring
something new: **Rocks** at level 2 (a cell flashes before it turns to
stone, and never right ahead of the head), **Mystery boxes** at 3,
**Portals** at 4, **Comets** at 5 (into the head is a crash, through the
body cuts the tail there), **Chaos** at 6, where surprises also happen on
their own, and **Ice** at 7, where a turn slides on for two steps before it
takes (a frosty arrow off the head shows the turn coming; the ice melts at
level 8). Each level serves its own fruit (an apple, then cherries, an
orange, grapes, a banana, a strawberry, watermelon, a peach and, at level 9,
a glinting golden apple) on its own scenery: a plain garden, then a meadow,
a desert, a lagoon, a starry night, a carnival, ice, a volcano and gold,
each a faint tint and a scatter of small marks over the usual board. The
last food of every odd level from 3 on is a **boss fruit**: four cells big
and crowned, it takes three bites (a point a level each, and the head must
leave it between bites), and the last bite scores the food plus 5 points a
level. From level 2 a **runaway fruit** on two little feet sometimes turns
up in place of a power-up: once you are within three cells it hops up to two
cells away, rests two steps between hops and tires after seven, so corner it
or wear it out for 6 points a level before it runs off after 12 seconds. Food eaten within 2.6 seconds of the last builds a
combo (x2 up to x5). Power-ups turn up every few seconds and fade if left: **Shield**
(takes one crash: wraps through a wall, smashes a rock), **Turbo** (faster,
double points), **Slow-mo**, **Magnet** (food slides toward you),
**Ghost** (walls wrap) and **Scissors** (half the tail, a point per cell
cut). A mystery box holds one of ten surprises: Jackpot, Gold rush, Earthquake,
Meteor shower, Mirror world (flipped keys), Lights out, Disco fever (triple
points), Big snack, Incoming! (a comet) and Treasure. Passing your best
mid-round plays a fanfare. A power-up, surprise or level banner opens on
the half of the board away from the snake's head, and fades almost clear
while the head is under it or heading into it, so it never hides what you
are about to hit. The start and end screens show how many of the 24
power-ups, surprises, levels and specials you have ever found, and what to look for
next.
- **Mini golf** is eighteen hand-made, thoroughly silly holes seen from above.
The front nine, **Pirate Cove**, floats in a shark sea: Walk the Plank,
Shipwreck Cove, Cannon Alley, Treasure Beach, Kraken's Lagoon, Ghost Ship,
The Ship's Wheel, Skull Island and Captain's Plunder, with barrels,
cannonballs, a rolling powder keg, a scuttling crab, a kraken's tentacle and a
skull you putt through. The back nine, the **Caves of Doom**, is dark but for
the ball's own light and whatever glows: Into the Dark, Stalagmite Forest,
Lava Lake, Mine Cart Madness, Crystal Pinball, The Bottomless Pit, Glowworm
Grotto, Crusher Corridor and The Dragon's Hoard, with glowing pools, lava, a
bottomless pit, a bobbing fireball, runaway mine carts, stone crushers that
slam shut in turn, portals and a sleeping dragon. Each hole opens with a quip,
and splashes, bonks and tunnels pop up a word or two. Play is quick and
arcade style: the aim follows the mouse (or hold left or right to turn it,
slowly at first, then faster), and it points back at the cup each time the
ball stops. A click or space starts the power meter beside the ball; a second
sets the power. The needle crawls near the bottom, so soft putts are easy,
and races near the top: the gold **MAX** band just under full putts 1.15
times as hard, and the red band past it is an overswing that shanks the ball
off line at reduced power. A ring round the waiting ball is the shot clock:
after 6 seconds the meter starts by itself, and a meter left for three trips
dribbles the ball a few inches. Hold space or the mouse button while the ball
rolls to play it three times as fast. Par is set per hole (59 for the
round), the ball is picked up after 8 strokes, and the round shows its +/-
par. A scorecard (front nine and back nine) shows between holes; space, a
click or 1.5 seconds moves on.
- **Power-ups.** A glowing pad the ball rolls over is held for your next putt
only (the pill at the bottom right says which): a **Lucky Doubloon** makes the
putt free (a hole still scores at least 1), a **Cannonball** fires it 1.6
times as hard, a **Ghost Ball** floats over water, sand, bumpers and movers
(but sinks if it stops on water), a **Parrot Magnet** bends it toward the cup,
a **Rubber Duck** keeps its full speed off walls, a **Treasure Map** makes the
cup huge, and a **Spyglass** draws where the putt will roll while the meter
runs, following the needle. One
is held at a time, a new pad replaces it, and a held one carries over to the
next hole.
- **It never hides your turn.** A new question, a sign-off or a finish pauses
the game at once and shows a banner with **Go to it**, which closes the window
on that question. Hiding the page or clicking away from it pauses it too, and
nothing resumes by itself. Any game key (arrows, W/A/S/D, space, P) or, in
Mini golf, a click on the board plays on, and the banner stays down until the
next new question or finish.
- **A countdown first.** Every game counts down 3, 2, 1 before a round starts
and before it plays on after a pause, so nothing moves before you are ready.
P or Esc during the count pauses again.
- **Keys.** Arrows or W/A/S/D steer, space starts and plays, P pauses, Esc
closes the window with the game paused. A page with no mouse or trackpad
(touch only) shows "Activities need a keyboard." in place of the board.
- **Best scores** show beside the score while you play and after each round.
Snake keeps its highest score. Mini golf keeps its lowest full round, and a
half-played round never counts. **Reset best scores** clears them after a
second click to confirm.
The line under the board is a pair of colored chips, Score and Best, with a
meter between them filling toward the best (for a game where the highest
wins). Reaching the best makes its chip glow; passing it turns the line into
a rainbow with a NEW BEST tag and a burst of sparks, once a round. A round
that beats a saved best ends with **New best!** on the end screen, and Mini
golf, which only knows at the end, fires its sparks then. Reduced motion keeps
the colors and drops the movement.
- **Private.** Best scores, Snake's surprises found, the last pick and the **Show Activities** switch
(User Preferences, which hides the die everywhere) are saved in
`~/.plan2code/console/looks.json`. Nothing about Activities reaches the agent
or the session.
### Session meter
A small ring pill in the top bar — **Session: fresh** (green), **Session:
@@ -785,8 +915,8 @@ exception being the note attachments the agent keeps for a spec, above):
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
| `~/.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) | 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 | always |
| `~/.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 switch, the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` keys: `activityBestSnake`, `activityBestGolf`) and each game's memo (`activityMemo<Id>`: Snake's surprises found) | 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), read by the `plan2code` command and the desktop app | always |
@@ -879,7 +1009,7 @@ origin.
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
| `GET /notepad[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
| `GET /notepad[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name, sent? }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
| `POST /notepad/text?tab=<id>` | `{ text }`. Saves that tab's `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 404 `no-such-tab`, 413 `too-long` (over 1 MB). |
| `POST /notepad/image?tab=<id>` | Raw `image/jpeg` (the page re-encodes every picture first). Writes the tab's `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures in the tab). |
| `POST /notepad/thumb?id=<uuid>&tab=<id>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found` or `no-such-tab`, 415 `not-jpeg`, 413 `too-large`. |
@@ -889,6 +1019,7 @@ origin.
| `POST /notepad/tab/delete` | `{ id }`. Removes the tab from the index, then its folder (text and pictures); 404 `no-such-tab`. |
| `POST /notepad/tab/order` | `{ order: [id] }`, every current id exactly once; 400 `bad` otherwise. |
| `POST /notepad/tab/last` | `{ id }`. Remembers the open tab; 404 `no-such-tab`. |
| `POST /notepad/tab/sent` | `{ id, workflow, spec? }`. Records that the tab was sent (`workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`; `spec` like `specs/<name>`) as `sent: { workflow, spec?, at }` on its `tabs.json` entry, shown back in `GET /notepad`'s `tabs`. The page posts it only after the Send that carried the filled box; 400 `bad-sent`, 404 `no-such-tab`. |
| `GET /notepad/images/<tab>/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a tab id and a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
+2 -2
View File
@@ -42,7 +42,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`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder, Plan, Revise plan) 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 seven helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
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 (two small games, Snake and Mini golf, listed in `public/activities.js` with one module per game under `public/activities/`, a picker once two are listed, 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, best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found), never shown to the agent), a built-in 19-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder, Plan, Revise plan) 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 seven helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
## Skill Scripts
@@ -105,7 +105,7 @@ When you make a mistake, get corrected, or discover something about this codebas
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
- When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load.
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests").
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
- Never fix CRLF by hand, one file at a time: run `npm run fix:eol` (`scripts/fix-line-endings.mjs`). Windows Python in text mode, among other tools, writes CRLF into files git keeps as LF; a whole session's edits once came out CRLF and 14 other files were found the same way. It now also runs as `pretest`, in the pre-commit hook and after every agent Write or Edit (see the LF gotcha in Code Style).
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
+6 -2
View File
@@ -13,23 +13,27 @@ All notable changes to Plan2Code will be documented in this file.
- **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review.
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort".
- **web console**: picking a spec on the dashboard that is not documented yet now shows its main files as read-only tabs in the top bar, like the **Overview** tab of a documented spec: **Map** for a Pathfinder map (`pathfinder/map.md`) and **Plan draft** for Plan's live `PLAN-DRAFT-*.md`, each when it exists. Once the spec has an `overview.md`, Overview replaces them.
- **web console**: start Pathfinder, Plan or Quick Task (on **Start fresh**) or Revise plan (on a picked spec with no plan change waiting) from a Notebook tab. A lit card's confirm pane offers **Start with a note from your Notebook**, with the tab list, a preview of the whole tab and up to five ticked pictures (the first five start ticked; a tab over 50 KB says so). The skill's first box arrives filled with the tab's text and pictures, editable, and the agent reads it only once you send it; nothing about the tab rides the launch itself. The tab then shows a **sent** badge and a "Sent to <Skill> · <Date>" line in the Notebook, and the Notebook's privacy line now reads: the agent never reads your Notebook, and a tab reaches it only when you start a workflow with it.
- **web console**: **Activities**, a die in the top bar right of the megaphone, opens a window of small games to play while you wait, say through a long build. The first is **Snake**, built in-house from local files (arrows or WASD, space, P to pause, Esc to close). It speeds up as it grows and gets wilder each level: every 5 foods brings something new (rocks that flash before they land, mystery boxes, portals, tail-cutting comets, chaos, then ice, where a turn slides two steps before it takes), six power-ups turn up on their own (Shield, Turbo, Slow-mo, Magnet, Ghost, Scissors), a mystery box holds one of ten surprises (Jackpot, Gold rush, Mirror world, Lights out, Disco fever and more), each level serves its own fruit (an apple, then cherries, an orange, grapes, a banana, a strawberry, watermelon, a peach and a golden apple) on its own scenery (meadow, desert, lagoon, starry night, carnival, ice, volcano, gold), the last food of every odd level from 3 on is a crowned four-cell boss fruit that takes three bites, a runaway fruit on little feet hops away until you corner it or tire it out, quick eating builds a combo up to x5, and passing your best plays a fanfare. A level, power-up or surprise banner opens on the half of the board away from the snake and fades almost clear while the snake is under it or heading into it, so it never hides a crash. The start and end screens count the surprises you have found so far and hint at what waits next. The second is **Mini golf**: eighteen goofy holes seen from above, a pirate front nine (Pirate Cove: a shark sea, cannonballs, a kraken, a ghost ship, a skull to putt through) and a cave back nine (the Caves of Doom: dark but for the ball's light, with lava, a bottomless pit, mine carts, stone crushers and a sleeping dragon), played arcade style: the aim follows the mouse (or held arrows, turning faster the longer they are held) and points back at the cup after every stop, one click or space starts a power meter beside the ball and a second sets the power (slow near the bottom for soft putts, fast near the top, with a gold MAX band for a 1.15x putt and a red overswing band past it that shanks the ball), a 6 second shot clock starts the meter for you, a meter left running dribbles the ball, and holding space or the mouse fast-forwards the roll, with par per hole, at most 8 strokes a hole, and its best kept as the lowest full round. Glowing power-up pads help the next putt: a free putt, a cannon shot, a ghost ball that floats over water, a cup magnet, a rubber duck that keeps its speed off walls, a huge cup, and a spyglass that shows where the putt will roll. With two games, a picker chooses between them. A new question, a sign-off or a finish pauses the game at once and shows a banner with **Go to it**, so a game never hides your turn; hiding the page or clicking away pauses it too. Nothing resumes until you press a game key or click the board, and resuming puts the your-turn banner away until the next question. Every round start and every play-on after a pause counts down 3, 2, 1 first, so a game never moves before you are ready. The window's header shows the current game's best. Best scores (shown beside the score and after each round, cleared by **Reset best scores**; the score line is a pair of colored chips with a meter filling toward the best, which glows when you reach it, turns into a rainbow with a burst of sparks when you pass it, and ends the round with **New best!**) and the last pick are saved privately in `~/.plan2code/console/looks.json` and never reach the agent. **User Preferences → Activities → Show Activities** hides the die everywhere, and Help has a new Activities topic.
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
- **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli <id>` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed.
- **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app.
- **desktop app**: the taskbar entry now shows when Plan2Code needs you, mirroring the console's tab icon. Windows: a green dot on your move, a red dot on needs attention, none while busy or finished, and one short burst of flashes when the window is not focused (the button stays lit until focused). macOS: a red `!` dock badge on needs attention and one bounce (the system badge cannot be green). Linux: a count badge where the desktop supports it, plus the urgency hint. The dot clears when the agent ends, the page reloads or the page stops answering. **User Preferences → Desktop app** (inside the app only) has the switch **Show on the taskbar when Plan2Code needs me**, on by default and saved in the app's own `app.json`.
- **desktop app**: the taskbar entry now shows when Plan2Code needs you, mirroring the console's tab icon. Windows: a green dot on your move (a finished screen too, while it still offers a button to press, such as back to the dashboard or a review), a red dot on needs attention (or a finished screen whose press was never collected), none while busy or once nothing is left to press, and one short burst of flashes when the window is not focused (the button stays lit until focused). macOS: a red `!` dock badge on needs attention and one bounce (the system badge cannot be green). Linux: a count badge where the desktop supports it, plus the urgency hint. The dot clears when the agent ends, the page reloads or the page stops answering. **User Preferences → Desktop app** (inside the app only) has the switch **Show on the taskbar when Plan2Code needs me**, on by default and saved in the app's own `app.json`.
### 🔧 Changed
- **docs**: all prose, help text, skill prompts and comments now use US English spelling (color, gray, behavior, canceled, -ize), and `npm test` checks it (`scripts/test-us-english.mjs`).
- **web console**: **User Preferences → Highlight color** now offers 38 colors in two rows of nineteen, covering the range of a Paint-style picker: new **Maroon**, **Peach**, **Brown**, **Cream**, **Lemon**, **Forest**, **Mint**, **Aqua**, **Lavender**, **Pink** and **Mono** (near-black in light mode, near-white in dark). Five near twins were merged (Copper into Rust, Marigold into Gold, Mustard into Lemon, Jade into Emerald, Lilac into Violet); a saved choice of one of those keeps its twin instead of falling back to Ocean.
- **web console**: the **Subagents** dialog is wider and shorter, like the Notebook: Helpers and At most share a row, and the four Helper strength choices sit side by side, each wearing the Subagents tab's colored level badge (Thrifty light, Balanced standard, Best strongest, Match my session plain), now ordered from lightest to strongest.
- **launcher**: after you pick the agent, `plan2code` now asks whether to turn its permission prompts off (Yes by default, so pressing Enter starts it as before), and only for an agent that has a flag for it: every built-in does, a custom agent only when it has bypass arguments. `plan2code --keep-permissions` keeps the prompts without asking; with no terminal to ask on, prompts are off as before. The installer no longer prints its warning about the command starting agents with prompts off.
- **launcher**: when no agent CLI is installed, `plan2code` now prints each supported agent's install command and official page, and points at User Preferences → Agents for another CLI, before it exits.
- **desktop app**: a clean start is now one press. Pathfinder's **Start fresh** menu option reads **Start New Session** under the app, and sending it asks the app for its New Session (the resume command is copied first; declining the app's confirm leaves the usual finish). A finished step that names a skill to run next shows a **Start a New Session** button beside its command, also copying the command first. The plain web console keeps its wording and does neither. The app's console frame also now allows clipboard writes, so the copied command and every **Copy** button can reach the clipboard there.
- **desktop app**: the launch card's agent choice is built from the agents that are installed, so a machine with only Devin or Codex starts on it with Start enabled, instead of assuming Claude Code.
- **desktop app**: the window now opens maximized, filling the screen with the title bar and taskbar still showing; restoring it from maximized gives the old 1280x800 size.
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching how `plan2code` has always started an agent from the plain terminal. It previously defaulted off, the opposite of the terminal's own long-standing default; untick it for an agent that keeps its normal approval prompts.
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching the terminal's own default; untick it for an agent that keeps its normal approval prompts.
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight color. Its confirmation no longer claims "What it was doing is not saved" (not always true).
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
+1 -1
View File
@@ -23,7 +23,7 @@ The install command always opens a menu. Back at your prompt with no output at a
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent).
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`). Private: the agent never reads your Notebook. A tab reaches it only when you start a workflow with it.
## Commands
+9 -6
View File
@@ -82,9 +82,10 @@ Install (`I`) adds `plan2code` as a global command (Advanced `A` → `D` adds ju
dashboard opens right there, in **Claude Code**, **Devin** or **Codex**. With more than one installed it asks which and
remembers your pick; `plan2code --cli claude`, `--cli devin` or `--cli codex` skips the question, and `--model <name>`
chooses the model. It works in cmd, PowerShell, Git Bash, macOS and Linux shells, and needs the
Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permission prompts off
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex); run
`claude /plan2code` yourself if you want prompts. The installer then offers a desktop shortcut (answer `y`),
Claude Code, Devin or Codex CLI on your `PATH`. After you pick the agent it asks whether to turn its
permission prompts off (Yes by default; `--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass`
in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex, a custom agent's bypass arguments, and no question for a
custom agent that has none). `plan2code --keep-permissions` keeps the prompts without asking. The installer then offers a desktop shortcut (answer `y`),
which opens a folder picker first. Uninstalling (`U`) removes both.
</details>
@@ -123,7 +124,7 @@ installed skills disagree.
The first release is unsigned, so macOS (**Open Anyway** in System Settings, Privacy & Security) or
Windows (**More info**, then **Run anyway**) may ask you to allow it once. The app starts the agent
with its normal approval prompts unless you tick the launch card's permission-checks-off option (the
plain `plan2code` command above, without the app, still starts with checks off by default). Details:
plain `plan2code` command above, without the app, asks instead, with prompts off by default too). Details:
[docs/desktop-app.md](docs/desktop-app.md).
</details>
@@ -190,7 +191,9 @@ next check-in, and it never holds up your answers.
There is more on the page when you need it. Notes on any question can carry screenshots and
documents. The folder label in the bottom bar opens your workspace, where you add other folders
as read-only context and point at them by `@name`. The **Notebook** in the top bar is a private pad of your own for the
folder, in Markdown with pictures, that the agent never sees. The session meter in the top bar turns from green
folder, in Markdown with pictures, that the agent reads only when you start a workflow from one of its tabs on
the dashboard and send the box it fills. The **die** beside it opens **Activities**,
two small games (Snake and Mini golf) to play through a long wait, which pause the moment it is your turn. The session meter in the top bar turns from green
to red as a session grows long and suggests a fresh one. **Stop session** saves your place and gives
you the command to carry on later, and **Back to the dashboard** takes you home to pick the next
step in the same session.
@@ -457,7 +460,7 @@ edits out through the skills CLI.
Core reference:
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook in the top bar
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook and Activities in the top bar
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
+5 -4
View File
@@ -86,9 +86,10 @@ The taskbar entry also shows when Plan2Code needs you, the same states as the co
a browser. On Windows a green dot means it is your move and a red dot means it needs attention, with
one short burst of flashes when the window is not focused; on macOS the dock shows a red `!` badge on
needs attention and bounces once; on Linux a count badge appears where the desktop supports it. There
is no dot while the agent is busy or the step is finished, and it clears when the agent ends or the
page reloads. Turn it off with **Show on the taskbar when Plan2Code needs me** under **User
Preferences → Desktop app** (shown only inside the app). The per-system details are in
is no dot while the agent is busy or once a finished step has nothing left to press (a finished screen
that still offers a button, such as back to the dashboard, keeps the green dot), and it clears when
the agent ends or the page reloads. Turn it off with **Show on the taskbar when Plan2Code needs
me** under **User Preferences → Desktop app** (shown only inside the app). The per-system details are in
[plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar).
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
@@ -144,7 +145,7 @@ anyway**.
## Permission checks are off by default, same as the terminal
The launch card's permission-mode tick is **on by default** (checks off), matching `plan2code` run the
plain way: the agent starts with checks off (`--permission-mode bypassPermissions` in Claude Code,
plain way, where the same question defaults to prompts off: the agent starts with checks off (`--permission-mode bypassPermissions` in Claude Code,
`--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex), reading,
writing and running commands in your project folder without asking; the agent's amber **checks off** badge in
the top bar says so while that agent runs. Untick it before pressing Start agent to keep the agent's normal approval prompts instead.
+2 -3
View File
@@ -2317,8 +2317,8 @@ function uninstallPlan2CodeBot() {
/**
* `plan2code` typed in any directory opens the dashboard skill there in Claude Code
* (`claude /plan2code --permission-mode bypassPermissions`) or Devin
* (`devin --permission-mode bypass -- /plan2code`), asking which when both are installed.
* (`claude /plan2code`), Devin (`devin -- /plan2code`) or Codex (`codex $plan2code`), asking
* which when more than one is installed, then whether to turn permission prompts off.
* The launcher is copied out of the package into ~/.plan2code/bin/ because the installer
* normally runs from an npx cache directory that npm is free to delete; the shims in the bin
* directory point at that stable copy.
@@ -2730,7 +2730,6 @@ async function installLauncher({ quiet = false, unattended = false } = {}) {
recordInstalled('launcher');
// The shortcut is a convenience on top of the command, so a failure here only warns.
if (!unattended) await offerDesktopShortcut(binDir);
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The ${LAUNCHER_COMMAND} command starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin, ${COLORS.CYAN}--dangerously-bypass-approvals-and-sandbox${COLORS.RESET} in Codex). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
console.log('');
// Inside install() the final summary prints the steps once, after everything else.
if (!quiet) printGettingStarted({ commandInstalled: true });
+3 -1
View File
@@ -8,7 +8,9 @@
"scripts": {
"prepare": "husky",
"build:skills": "node install.js --build-skills",
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
"fix:eol": "node scripts/fix-line-endings.mjs",
"pretest": "node scripts/fix-line-endings.mjs",
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-activities.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
},
"devDependencies": {
"husky": "^9.0.0",
+1 -1
View File
@@ -18,7 +18,7 @@ The app is optional. The Node web console and the skills never depend on it, so
| macOS | no badge (the system badge cannot be green), one bounce when not focused | red `!` dock badge, and one bounce when not focused |
| Linux | the urgency hint when not focused | a count badge of 1 where the desktop supports it, and the urgency hint |
There is no dot while busy or finished. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
There is no dot while busy or once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
## Layout
+1 -1
View File
@@ -117,7 +117,7 @@ Do each of Claude Code, Devin and Codex for a few minutes:
- [ ] Each **Install page** link opens the right page in the default browser (Claude Code, Devin, Codex)
- [ ] Install an agent (or add a custom one), press **Check again**: it appears and Start turns on without restarting the app
- [ ] With only one agent installed and nothing remembered, the launch card starts on that agent, not Claude Code
- [ ] Windows: the taskbar button shows a green dot when it is your move and a red dot when Plan2Code needs attention, and no dot while the agent is busy or after it ends
- [ ] Windows: the taskbar button shows a green dot when it is your move and a red dot when Plan2Code needs attention, a green dot on a finished screen that still offers a button (back to the dashboard, a review), and no dot while the agent is busy, once a finished step has nothing left to press, or after the agent ends
- [ ] Windows: with the window unfocused, the button gives one short burst of flashes when it becomes your move or needs attention (not again on a repeat) and stays lit until the window gets focus
- [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background
- [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused
+1
View File
@@ -14,6 +14,7 @@
"title": "Plan2Code",
"width": 1280,
"height": 800,
"maximized": true,
"url": "index.html"
}
],
+109
View File
@@ -0,0 +1,109 @@
// Turn CRLF line endings back into LF in the working tree.
//
// .gitattributes stores every text file as LF and checks it out as LF, so git
// itself never puts a CRLF on disk. Tools do: a Python script writing in text
// mode on Windows, an editor, a generator. A CRLF file still commits clean
// (git normalizes it), but until then it inflates scripts/validate-char-count.js,
// fills `git diff` and `git status` with warnings, and trips tests that read the
// raw bytes. This puts the working tree back the way git would check it out.
//
// node scripts/fix-line-endings.mjs fix every text file git sees
// node scripts/fix-line-endings.mjs --check list them, exit 1 if any
// node scripts/fix-line-endings.mjs --hook fix the one file a Claude Code
// PostToolUse hook names on stdin
// --root <dir> work on another repo (tests)
//
// "Every text file git sees" is what is tracked plus what is untracked but not
// ignored, less anything .gitattributes marks binary or that holds a NUL byte.
// npm test runs the fix first (pretest), so every suite reads LF.
import fs from "node:fs";
import path from "node:path";
import { execFileSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const args = process.argv.slice(2);
const rootAt = args.indexOf("--root");
const ROOT = path.resolve(rootAt >= 0 ? args[rootAt + 1] : path.dirname(path.dirname(fileURLToPath(import.meta.url))));
const mode = args.includes("--hook") ? "hook" : args.includes("--check") ? "check" : "fix";
const git = (gitArgs, input) => execFileSync("git", ["-C", ROOT, ...gitArgs], { input, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
// The repo's files that are tracked, or untracked and not ignored, relative to
// ROOT with forward slashes.
function repoFiles() {
return git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"]).split("\0").filter(Boolean);
}
// The files .gitattributes marks binary (or -text), never to be touched.
function binaries(files) {
if (!files.length) return new Set();
const out = git(["check-attr", "-z", "--stdin", "binary", "text"], files.join("\0") + "\0").split("\0");
const skip = new Set();
for (let i = 0; i + 2 < out.length; i += 3) {
const [file, attr, value] = [out[i], out[i + 1], out[i + 2]];
if ((attr === "binary" && value === "set") || (attr === "text" && value === "unset")) skip.add(file);
}
return skip;
}
// Rewrites one file with LF endings if it has any CRLF. Returns whether it did.
function fixFile(abs, write) {
let bytes;
try {
if (!fs.statSync(abs).isFile()) return false;
bytes = fs.readFileSync(abs);
} catch {
return false;
}
if (bytes.includes(0) || !bytes.includes("\r\n")) return false;
if (write) fs.writeFileSync(abs, bytes.toString("latin1").replace(/\r\n/g, "\n"), "latin1");
return true;
}
// The file a PostToolUse hook for Write or Edit names, fixed if it is a text
// file inside the repo that git would check out. Never fails the tool call.
function hook() {
let file = "";
try {
const event = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
file = (event.tool_input && (event.tool_input.file_path || event.tool_input.notebook_path)) || (event.tool_response && event.tool_response.filePath) || "";
} catch {
return;
}
if (!file) return;
const abs = path.resolve(file);
const rel = path.relative(ROOT, abs);
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return;
const relGit = rel.split(path.sep).join("/");
try {
if (git(["check-ignore", "-q", "--no-index", relGit]) !== null) return;
} catch {
// check-ignore exits 1 when the path is not ignored: carry on.
}
if (binaries([relGit]).size) return;
if (fixFile(abs, true)) process.stdout.write(`fix-line-endings: ${relGit} had CRLF line endings, now LF\n`);
}
if (mode === "hook") {
try {
hook();
} catch {}
process.exit(0);
}
const files = repoFiles();
const skip = binaries(files);
const found = files.filter((f) => !skip.has(f) && fixFile(path.join(ROOT, f), mode === "fix"));
if (mode === "check") {
if (found.length) {
console.error(`${found.length} file(s) have CRLF line endings (run: npm run fix:eol):`);
for (const f of found) console.error(` ${f}`);
process.exit(1);
}
process.exit(0);
}
if (found.length) {
console.log(`fix-line-endings: ${found.length} file(s) turned from CRLF to LF:`);
for (const f of found) console.log(` ${f}`);
}
+30 -1
View File
@@ -156,6 +156,21 @@ test("launcher: Codex gets the bypass flag, the forwarded args, then the $plan2c
assert.deepEqual(box.argsOf("codex"), ["--dangerously-bypass-approvals-and-sandbox", "--verbose", "$plan2code"]);
});
test("launcher: --keep-permissions keeps every built-in's permission prompts, and is never forwarded", (t) => {
const box = sandbox(["claude", "devin", "codex"]);
t.after(box.cleanup);
const expected = {
claude: ["/plan2code", "--verbose"],
devin: ["--verbose", "--", "/plan2code"],
codex: ["--verbose", "$plan2code"],
};
for (const [cli, args] of Object.entries(expected)) {
const result = box.run(["--cli", cli, "--keep-permissions", "--verbose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf(cli), args, cli);
}
});
test("launcher: --cli codex picks Codex when it is installed beside another CLI", (t) => {
const box = sandbox(["claude", "codex"]);
t.after(box.cleanup);
@@ -672,6 +687,19 @@ test("launcher agents: --cli <custom id> starts it with args, the model through
// No model chosen and no models flag: the model arguments are left out.
assert.equal(box.run(["--cli=goose"]).status, 0);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code", "--bypass"]);
// --keep-permissions leaves bypassArgs out.
assert.equal(box.run(["--cli=goose", "--keep-permissions"]).status, 0);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code"]);
});
test("launcher agents: a custom agent with no bypassArgs is never asked about prompts and starts with its own", (t) => {
const box = sandbox(["goose"]);
t.after(box.cleanup);
writeAgents(box, goose({ bypassArgs: [] }));
const result = box.run(["--cli", "goose"]);
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("goose"), ["--yes", "/plan2code"]);
assert.doesNotMatch(result.stdout, /permission prompts off/);
});
test("launcher agents: the last pick can be a custom id, and the --cli error names custom ids", (t) => {
@@ -701,7 +729,8 @@ test("launcher agents: the model menu is the agent's own models, with no shipped
assert.equal(hasModelFlag(["--model", "x"], "goose"), true);
assert.equal(hasModelFlag(["-m", "x"], "goose"), false);
// A model given on the command line goes through modelArgs, once.
assert.deepEqual(cli.args(["--model=m2", "-x"]), ["--yes", "/plan2code", "--model", "m2", "--bypass", "-x"]);
assert.deepEqual(cli.args(["--model=m2", "-x"], { bypass: true }), ["--yes", "/plan2code", "--model", "m2", "--bypass", "-x"]);
assert.deepEqual(cli.args(["-x"]), ["--yes", "/plan2code", "-x"]);
});
test("launcher agents: the menu lists the built-ins found first, then the custom agents that resolve", (t) => {
+86
View File
@@ -0,0 +1,86 @@
// Tests for scripts/fix-line-endings.mjs: CRLF in the working tree goes back to LF.
// Run with: node --test scripts/test-line-endings.mjs
//
// Each test builds a throwaway git repo with this repo's .gitattributes and
// runs the script against it with --root, so the real tree is never touched.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { execFileSync, spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const HERE = path.dirname(fileURLToPath(import.meta.url));
const SCRIPT = path.join(HERE, "fix-line-endings.mjs");
const ATTRS = fs.readFileSync(path.join(HERE, "..", ".gitattributes"));
// A repo holding `files` (path to Buffer or string), none of them committed,
// and a .gitignore that ignores `ignored/`.
function repo(t, files) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-eol-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
execFileSync("git", ["init", "-q", dir]);
fs.writeFileSync(path.join(dir, ".gitattributes"), ATTRS);
fs.writeFileSync(path.join(dir, ".gitignore"), "ignored/\n");
for (const [rel, body] of Object.entries(files)) {
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
fs.writeFileSync(path.join(dir, rel), body);
}
return dir;
}
const run = (dir, args, input) => spawnSync(process.execPath, [SCRIPT, "--root", dir, ...args], { input, encoding: "utf8" });
const bytes = (dir, rel) => fs.readFileSync(path.join(dir, rel));
// Bytes that look like CRLF text but belong to a picture.
const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0x0d, 0x0a]);
test("--check lists every CRLF text file and changes nothing; a plain run fixes them", (t) => {
const dir = repo(t, {
"a.js": "one\r\ntwo\r\n",
"src/b.md": "# Title\r\n\r\nBody\r\n",
"ok.js": "fine\n",
"pic.png": PNG,
"ignored/c.js": "skip\r\n",
});
const check = run(dir, ["--check"]);
assert.equal(check.status, 1);
assert.match(check.stderr, /a\.js/);
assert.match(check.stderr, /src\/b\.md/);
assert.doesNotMatch(check.stderr, /ok\.js|pic\.png|ignored/);
assert.equal(bytes(dir, "a.js").toString(), "one\r\ntwo\r\n", "check only looks");
const fix = run(dir, []);
assert.equal(fix.status, 0);
assert.equal(bytes(dir, "a.js").toString(), "one\ntwo\n");
assert.equal(bytes(dir, "src/b.md").toString(), "# Title\n\nBody\n");
assert.deepEqual(bytes(dir, "pic.png"), PNG, "a binary file is never touched");
assert.equal(bytes(dir, "ignored/c.js").toString(), "skip\r\n", "an ignored file is left alone");
assert.equal(run(dir, ["--check"]).status, 0, "clean afterwards");
});
test("non-ASCII text survives the rewrite byte for byte", (t) => {
const dir = repo(t, { "u.md": "café ★ ✨\r\n" });
run(dir, []);
assert.equal(bytes(dir, "u.md").toString("utf8"), "café ★ ✨\n");
});
test("--hook fixes the file a Write or Edit names, and nothing outside the repo", (t) => {
const dir = repo(t, { "a.js": "x\r\n", "b.js": "y\r\n", "pic.png": PNG });
const out = run(dir, ["--hook"], JSON.stringify({ tool_name: "Write", tool_input: { file_path: path.join(dir, "a.js") } }));
assert.equal(out.status, 0);
assert.match(out.stdout, /a\.js/);
assert.equal(bytes(dir, "a.js").toString(), "x\n");
assert.equal(bytes(dir, "b.js").toString(), "y\r\n", "only the named file");
run(dir, ["--hook"], JSON.stringify({ tool_name: "Edit", tool_input: { file_path: path.join(dir, "pic.png") } }));
assert.deepEqual(bytes(dir, "pic.png"), PNG);
const outside = repo(t, { "z.js": "z\r\n" });
run(dir, ["--hook"], JSON.stringify({ tool_input: { file_path: path.join(outside, "z.js") } }));
assert.equal(bytes(outside, "z.js").toString(), "z\r\n", "a file in another folder is not ours");
for (const input of ["", "not json", "{}"]) assert.equal(run(dir, ["--hook"], input).status, 0, `never fails the tool call (${JSON.stringify(input)})`);
});
File diff suppressed because it is too large. Load diff
+21
View File
@@ -299,6 +299,27 @@ test("framed, the page tells the app its state once per change, never on a redra
assert.deepEqual((await toApp(s, "attention")).at(-1), { plan2code: "attention", state: "plain" });
});
test("framed, a finished screen with a button still to press is the person's move; one with nothing left is plain", async (t) => {
const browser = await pages.browser();
const last = async (s) => (await toApp(s, "attention")).at(-1)?.state;
// The finished screen that waits on a press once told the app plain, so the
// taskbar showed no dot while the person was needed.
// Both start busy, so the state read after the finish's line shows is the
// finish's own (the line and the message come from the same redraw).
const WORKING = { agent: { status: "working", activity: "Task 1 of 2" } };
const offered = await openSession(browser, { t, workflow: "quick-task", payload: WORKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
await until(async () => (await last(offered)) === "busy", 5000);
offered.post({ finish: { headline: "Quick task done", command: "git add -A && git commit -m x -m y", dashboard: true } });
await until(async () => (await offered.page.locator("#agent-text").textContent()).includes("Head back to the dashboard"), 5000);
assert.equal(await last(offered), "ready", "a finish offering the dashboard is the person's move");
const paused = await openSession(browser, { t, workflow: "implement", payload: WORKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
await until(async () => (await last(paused)) === "busy", 5000);
paused.post({ finish: { headline: "Paused at Phase 2", command: "/plan2code-3-implement specs/audit-export/overview.md" } });
await until(async () => (await paused.page.locator("#agent-text").textContent()).startsWith("Paused"), 5000);
assert.equal(await last(paused), "plain", "a paused finish has nothing left to press");
});
test("the Desktop app group shows only in the app's frame, reflects the app's saved switch and tells the app when it changes", async (t) => {
const browser = await pages.browser();
const plain = await openSession(browser, { t, workflow: "implement", payload: ASKING });
+58
View File
@@ -48,6 +48,11 @@ import {
handoffText,
launchReply,
launchTarget,
noteSwitchShows,
noteTabEmpty,
defaultNoteTicks,
toggleNoteTick,
NOTE_LONG_BYTES,
deleteAction,
deleteReply,
chipDetail,
@@ -1500,6 +1505,17 @@ test("validate: templates only as \"idea\", only on a text item", () => {
assert.ok(validate(item({ templates: "yes" })).includes(message));
});
test("validate: fill only as \"note\", only on a text item", () => {
const item = (extra) => ({ items: [{ id: "idea", kind: "text", title: "What's the idea?", ...extra }] });
const message = 'item "idea" has "fill": only a text item can carry it, and its only value is "note".';
assert.deepEqual(validate(item({ fill: "note" })), []);
assert.deepEqual(validate(item({ fill: "note", templates: "idea" })), []);
assert.ok(validate(item({ kind: "choice", options: [{ k: "A", text: "a" }], fill: "note" })).includes(message));
assert.ok(validate(item({ kind: "confirm", fill: "note" })).includes(message));
assert.ok(validate(item({ fill: "idea" })).includes(message));
assert.ok(validate(item({ fill: true })).includes(message));
});
test("attachmentName: slug of the original name, 8 characters of the upload id, the upload's own extension", () => {
const up = (uuid, ext) => path.join(HOME, "sessions", "x", "uploads", `${uuid}${ext}`);
const a = up("3f2b9c1e-8a4d-4f6e-9b7a-2c5d1e0f4a6b", ".jpg");
@@ -2320,3 +2336,45 @@ test("meter: the weights and labels built from the skill list are the ones writt
});
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
});
test("noteSwitchShows: Pathfinder, Plan and Quick Task on Start fresh, Revise plan on a picked spec with no brief waiting", () => {
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
const scan = { hasAgents: true, isGit: true, pending: 0, specs: [] };
const sel = (state, extra = {}) => ({ dir: "specs/x", name: "x", state, ...extra });
const fresh = ["plan2code-0-pathfinder", "plan2code-1-plan", "plan2code-quick-task"];
for (const skill of fresh) {
assert.equal(noteSwitchShows(entry(skill), scan, null), true, `${skill} on Start fresh`);
assert.equal(noteSwitchShows(entry(skill), scan, sel("exploring")), false, `${skill} on a picked spec`);
assert.equal(noteSwitchShows(entry(skill), scan, sel("exploring", { planChange: true })), false, `${skill} on a picked spec with a brief`);
}
const revise = entry("plan2code-1b-revise-plan");
assert.equal(noteSwitchShows(revise, scan, null), false, "Revise plan is grayed on Start fresh");
for (const state of ["documented", "building", "built"]) {
assert.equal(noteSwitchShows(revise, scan, sel(state)), true, `Revise plan on ${state}`);
assert.equal(noteSwitchShows(revise, scan, sel(state, { planChange: true })), false, `Revise plan on ${state} with a brief waiting`);
}
assert.equal(noteSwitchShows(revise, scan, sel("exploring")), false, "never on a grayed card");
for (const skill of ["plan2code-3-implement", "plan2code-2-document", "plan2code-git", "plan2code-xray"]) {
assert.equal(noteSwitchShows(entry(skill), scan, null), false, `${skill} on Start fresh`);
assert.equal(noteSwitchShows(entry(skill), scan, sel("documented")), false, `${skill} on a picked spec`);
}
assert.equal(noteSwitchShows(null, scan, null), false);
});
test("Notebook pick rules: an empty tab, the first five pictures ticked, and no sixth tick", () => {
assert.equal(noteTabEmpty({ text: "", images: [] }), true);
assert.equal(noteTabEmpty({ text: " \n", images: [] }), true, "whitespace is nothing to send");
assert.equal(noteTabEmpty({ text: "", images: [{ id: "a" }] }), false);
assert.equal(noteTabEmpty({ text: "idea", images: [] }), false);
assert.equal(noteTabEmpty(null), true);
const imgs = ["a", "b", "c", "d", "e", "f", "g"].map((id) => ({ id }));
assert.deepEqual(defaultNoteTicks(imgs), ["a", "b", "c", "d", "e"]);
assert.deepEqual(defaultNoteTicks(imgs.slice(0, 2)), ["a", "b"]);
assert.deepEqual(defaultNoteTicks(undefined), []);
const five = defaultNoteTicks(imgs);
assert.deepEqual(toggleNoteTick(five, "f"), five, "a sixth tick changes nothing");
const four = toggleNoteTick(five, "c");
assert.deepEqual(four, ["a", "b", "d", "e"]);
assert.deepEqual(toggleNoteTick(four, "f"), ["a", "b", "d", "e", "f"], "untick one to tick another");
assert.equal(NOTE_LONG_BYTES, 51200);
});
+73
View File
@@ -917,6 +917,79 @@ test("the tab routes refuse bad bodies, unknown tabs and every foreign caller",
assert.equal((await getJson(s, "/notepad")).body.last, other.id);
});
test("markTabSent records, replaces and validates a tab's last send, and listTabs and readNotepad return it", () => {
const folder = freshFolder();
const a = tabOf(folder, "A");
const b = tabOf(folder, "B");
assert.deepEqual(listTabs(folder).tabs, [{ id: a, name: "A" }, { id: b, name: "B" }], "no sent until a send");
const first = store.markTabSent(folder, a, { workflow: "plan" });
assert.equal(first.id, a);
assert.deepEqual(Object.keys(first.sent).sort(), ["at", "workflow"]);
assert.equal(first.sent.workflow, "plan");
assert.ok(!Number.isNaN(Date.parse(first.sent.at)));
assert.deepEqual(listTabs(folder).tabs[0], { id: a, name: "A", sent: first.sent });
assert.equal(listTabs(folder).tabs[1].sent, undefined, "only the sent tab carries it");
const second = store.markTabSent(folder, a, { workflow: "revise-plan", spec: "specs/lunch-vote" });
assert.deepEqual(second.sent, { workflow: "revise-plan", spec: "specs/lunch-vote", at: second.sent.at }, "replaces the earlier one");
const read = readNotepad(folder, a);
assert.deepEqual(read.tabs[0].sent, second.sent);
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(notepadFolder(folder), "tabs.json"), "utf8")).tabs[a].sent, second.sent);
// A rename keeps the record; it is the tab's, not the name's.
renameTab(folder, a, "A2");
assert.deepEqual(listTabs(folder).tabs[0].sent, second.sent);
for (const bad of [{}, { workflow: "implement" }, { workflow: "plan", spec: "lunch-vote" }, { workflow: "plan", spec: "specs/a/b" }, { workflow: "plan", spec: 5 }]) {
refusal(() => store.markTabSent(folder, b, bad), "bad-sent");
}
refusal(() => store.markTabSent(folder, "ffffffffffff", { workflow: "plan" }), "no-such-tab");
refusal(() => store.markTabSent(folder, "nope", { workflow: "plan" }), "no-such-tab");
assert.equal(listTabs(folder).tabs[1].sent, undefined, "refusals recorded nothing");
});
test("a sent record that does not hold up is dropped on read, never the index", () => {
const folder = freshFolder();
const a = tabOf(folder, "A");
const file = path.join(notepadFolder(folder), "tabs.json");
const index = JSON.parse(fs.readFileSync(file, "utf8"));
index.tabs[a].sent = { workflow: "implement", at: "2026-10-27T00:00:00.000Z" };
fs.writeFileSync(file, JSON.stringify(index));
assert.deepEqual(listTabs(folder).tabs, [{ id: a, name: "A" }]);
});
test("POST /notepad/tab/sent answers 200, 400 and 404, and GET /notepad carries the record", async (t) => {
const s = openSession();
t.after(() => fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true }));
fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true });
const post = async (body) => {
const res = await s.send("/notepad/tab/sent", body);
return { status: res.status, body: await res.json() };
};
const id = (await (await s.send("/notepad/tab", { name: "Idea" })).json()).id;
const ok = await post({ id, workflow: "quick-task" });
assert.equal(ok.status, 200);
assert.equal(ok.body.ok, true);
assert.equal(ok.body.sent.workflow, "quick-task");
assert.deepEqual((await getJson(s, "/notepad")).body.tabs, [{ id, name: "Idea", sent: ok.body.sent }]);
assert.deepEqual(await post({ id, workflow: "document" }), { status: 400, body: { error: "bad-sent" } });
assert.deepEqual(await post({ id, workflow: "revise-plan", spec: "../x" }), { status: 400, body: { error: "bad-sent" } });
assert.deepEqual(await post({ id: "ffffffffffff", workflow: "plan" }), { status: 404, body: { error: "no-such-tab" } });
assert.deepEqual(await post({ workflow: "plan" }), { status: 404, body: { error: "no-such-tab" } });
const body = JSON.stringify({ id, workflow: "plan" });
const noCookie = await fetch(`${s.base}/notepad/tab/sent`, { method: "POST", headers: { "content-type": "application/json", connection: "close" }, body });
assert.equal(noCookie.status, 403);
const foreign = await fetch(`${s.base}/notepad/tab/sent`, {
method: "POST",
headers: { "content-type": "application/json", cookie: s.cookie, origin: "http://evil.example", connection: "close" },
body,
});
assert.equal(foreign.status, 403);
assert.equal((await getJson(s, "/notepad")).body.tabs[0].sent.workflow, "quick-task", "the refused calls changed nothing");
});
test("pictures through ?tab=: upload, thumb, fetch and delete, each under the tab that holds it", async (t) => {
const s = openSession();
t.after(() => fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true }));
File diff suppressed because it is too large. Load diff
+139 -1
View File
@@ -12,7 +12,8 @@ import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, textOf, styleOf } from "./page-test-helpers.mjs";
import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs";
import { cli, until, CONSOLE_CLI, HOME, JPEG } from "./web-console-test-helpers.mjs";
import { addImage, createTab, deleteTab, markTabSent, saveNote } from "../src/web-console/notepads.mjs";
const suite = pageSuite(test);
@@ -537,3 +538,140 @@ test("a quick-task build's waiting pane points at its Plan tab, and a plan sessi
await otherPane.waitFor();
assert.equal(await otherPane.getByRole("button", { name: "Plan", exact: true }).count(), 0, "a plan session has no live task list to point at");
});
// A project with a drafted plan (demo), a documented spec (ready) and one
// paused mid-build with a Plan change brief waiting (paused).
const NOTE_PROJECT = {
...DRAFT_PROJECT,
"specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n",
"specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n",
"specs/paused/overview.md": "# Overview\n\n## Phase Checklist\n\n- [/] Phase 1: One\n",
"specs/paused/phase-1.md":
"# Phase 1\n\n- [x] **Task 1.1:** One\n- [ ] **Task 1.2:** Two\n\n## Notes\n\n### Paused 2026-10-27\n**Plan change:** add a phase first\n",
};
const noteSwitch = (main) => main.getByRole("checkbox", { name: "Start with a note from your Notebook" });
// Picks `chip` in the picker, opens `command`'s card and says whether its
// confirm pane offers the switch; Back returns to the menu.
async function offersNote(main, chip, command) {
await chipFor(main, chip).click();
await pickedChip(main, chip).waitFor();
const card = lightOf(main, command);
if (!(await card.isVisible()) || (await card.isDisabled())) return null;
await card.click();
await main.getByRole("button", { name: "Back" }).waitFor();
const shows = (await noteSwitch(main).count()) === 1;
await main.getByRole("button", { name: "Back" }).click();
await main.getByRole("heading", { name: "What are we doing today?" }).waitFor();
return shows;
}
test("the Notebook switch shows on Start fresh for Pathfinder, Plan and Quick Task, and on Revise plan only with no brief waiting", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(NOTE_PROJECT) });
const main = await toTheMenu(s);
await hideUnavailable(main, false);
for (const command of ["/plan2code-0-pathfinder", "/plan2code-1-plan", "/plan2code-quick-task"]) {
assert.equal(await offersNote(main, "Start from scratch", command), true, `${command} on Start fresh`);
}
assert.equal(await offersNote(main, "demo", "/plan2code-1-plan"), false, "Plan on a picked spec");
assert.equal(await offersNote(main, "ready", "/plan2code-1b-revise-plan"), true, "Revise plan with no brief waiting");
assert.equal(await offersNote(main, "paused", "/plan2code-1b-revise-plan"), false, "Revise plan with a brief waiting");
assert.equal(await offersNote(main, "ready", "/plan2code-3-implement"), false, "Implement never");
assert.equal(await offersNote(main, "Start from scratch", "/plan2code-xray"), false, "a utility never");
});
test("the switch lists the Notebook's tabs beside a preview: an empty tab grayed, five ticks at most, a Long tab note, and + note: on the command", async (t) => {
const project = tempProject(DRAFT_PROJECT);
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
createTab(s.project, "Empty");
const big = createTab(s.project, "Big").id;
const small = createTab(s.project, "Small").id;
saveNote(s.project, big, "# Big idea\n\n" + "x".repeat(52 * 1024));
for (let i = 0; i < 7; i++) addImage(s.project, big, JPEG);
saveNote(s.project, small, "A small **idea**.");
markTabSent(s.project, small, { workflow: "plan" });
const main = await toTheMenu(s);
await chipFor(main, "Start from scratch").click();
await pickedChip(main, "Start from scratch").waitFor();
await lightOf(main, "/plan2code-0-pathfinder").click();
const toggle = noteSwitch(main);
assert.equal(await toggle.isChecked(), false, "off by default");
const cmd = main.locator(".confirm-cmd");
assert.equal(await cmd.locator(".confirm-cmd-note").isHidden(), true);
await toggle.check();
const tabs = main.locator(".confirm-note-tabs");
await tabs.locator(".confirm-note-tab").nth(2).waitFor();
const tab = (name) => tabs.locator(".confirm-note-tab", { has: s.page.locator(".confirm-note-tab-name", { hasText: new RegExp(`^${name}$`) }) });
assert.equal(await tab("Empty").isDisabled(), true, "an empty tab cannot be picked");
assert.ok(parseFloat(await styleOf(tab("Empty"), "opacity")) < 1, "and is grayed");
assert.equal(await tab("Big").isEnabled(), true);
assert.equal(await tab("Small").locator(".notepad-sent-badge").count(), 1, "a sent tab shows its badge");
assert.equal(await tab("Big").locator(".notepad-sent-badge").count(), 0);
// Small: its text, rendered, and no Long tab note.
await tab("Small").click();
const preview = main.locator(".confirm-note-preview");
await preview.locator("strong", { hasText: "idea" }).waitFor();
assert.equal(await preview.locator(".confirm-note-long").count(), 0);
assert.equal(await textOf(cmd.locator(".confirm-cmd-note")), "+ note: Small");
// Big: over 50 KB, seven pictures, the first five ticked.
await tab("Big").click();
await preview.locator(".md-h", { hasText: "Big idea" }).waitFor();
assert.match(await textOf(preview.locator(".confirm-note-long")), /^Long tab: /);
assert.equal(await textOf(cmd.locator(".confirm-cmd-note")), "+ note: Big");
const ticks = preview.locator(".confirm-note-pic input[type=checkbox]");
assert.equal(await ticks.count(), 7);
const states = async () => ticks.evaluateAll((bs) => bs.map((b) => (b.checked ? "x" : b.disabled ? "-" : "o")).join(""));
assert.equal(await states(), "xxxxx--", "the first five ticked, no more can be");
await ticks.nth(1).uncheck();
await until(async () => (await states()) === "xoxxxoo", 3000);
await ticks.nth(6).check();
await until(async () => (await states()) === "x-xxx-x", 3000);
// Off again: no note on the command line.
await noteSwitch(main).uncheck();
await until(async () => await cmd.locator(".confirm-cmd-note").isHidden(), 3000);
assert.equal(await tabs.count(), 0);
});
test("the switch reads the Notebook again when it closes, and starts off again after Back", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
const keep = createTab(s.project, "Keep").id;
const gone = createTab(s.project, "Gone").id;
saveNote(s.project, keep, "first words");
saveNote(s.project, gone, "soon deleted");
const main = await toTheMenu(s);
await chipFor(main, "Start from scratch").click();
await pickedChip(main, "Start from scratch").waitFor();
await lightOf(main, "/plan2code-1-plan").click();
await noteSwitch(main).check();
const tabs = main.locator(".confirm-note-tabs");
const tab = (name) => tabs.locator(".confirm-note-tab", { has: s.page.locator(".confirm-note-tab-name", { hasText: new RegExp(`^${name}$`) }) });
await tab("Keep").click();
const preview = main.locator(".confirm-note-preview");
await preview.getByText("first words").waitFor();
assert.equal(await preview.getAttribute("role"), "region");
// Changed in the Notebook while the pane is open: closing it reads again.
saveNote(s.project, keep, "second words");
deleteTab(s.project, gone);
await s.page.click("#btn-notepad");
await s.page.locator("#notepad-modal[open]").waitFor();
await s.page.click("#notepad-close");
await preview.getByText("second words").waitFor();
await until(async () => (await tab("Gone").count()) === 0, 5000);
assert.equal(await textOf(main.locator(".confirm-cmd-note")), "+ note: Keep", "the pick survives a read that still has its tab");
// Back, then the same card again: the switch is off and nothing is picked.
await main.getByRole("button", { name: "Back" }).click();
await main.getByRole("heading", { name: "What are we doing today?" }).waitFor();
await lightOf(main, "/plan2code-1-plan").click();
assert.equal(await noteSwitch(main).isChecked(), false);
assert.equal(await main.locator(".confirm-cmd-note").isHidden(), true);
assert.equal(await tabs.count(), 0);
});
+37
View File
@@ -31,6 +31,7 @@ import {
defaultTabId,
deleteTab,
listTabs,
markTabSent,
notepadFolder,
notepadKey,
readNotepad,
@@ -1173,3 +1174,39 @@ test("Help's Getting around panel describes the notepad", async (t) => {
assert.ok(text.includes(words), `the panel mentions ${words}`);
}
});
test("a sent tab wears a badge after its name, and the open tab shows Sent to <Skill> · <Date>", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
const sent = createTab(s.project, "Sent one").id;
createTab(s.project, "Plain");
saveNoteTo(s.project, sent, "an idea");
const { sent: record } = markTabSent(s.project, sent, { workflow: "revise-plan", spec: "specs/lunch-vote" });
// The page draws its own short date; the line must carry the same one.
const day = await s.page.evaluate((at) => new Date(at).toLocaleDateString(undefined, { month: "short", day: "numeric" }), record.at);
const line = s.page.locator("#notepad-sent");
await openNotepad(s);
// Plain was made last, so it opens first: no badge, no line.
assert.equal(await selectedName(s).then((n) => n.join()), "Plain");
assert.equal(await line.isHidden(), true, "no Sent to line on a tab never sent");
const badges = s.page.locator("#notepad-tabs .notepad-sent-badge");
assert.equal(await badges.count(), 1, "one badge, on the sent tab only");
assert.equal(await badges.first().textContent(), "sent");
const wrapOf = (name) => s.page.locator("#notepad-tabs .notepad-tabwrap").filter({ has: s.page.locator(".notepad-tab", { hasText: new RegExp(`^${name}$`) }) });
assert.equal(await wrapOf("Sent one").locator(".notepad-sent-badge").count(), 1);
assert.equal(await wrapOf("Plain").locator(".notepad-sent-badge").count(), 0);
assert.equal(await tabNamed(s, "Sent one").getAttribute("aria-label"), "Sent one, sent");
assert.equal(await tabNamed(s, "Plain").getAttribute("aria-label"), null);
assert.ok(parseFloat(await styleOf(badges.first(), "font-size")) < 13, "the badge is small");
await tabNamed(s, "Sent one").click();
assert.equal(await shows(s, "an idea"), "an idea");
await line.waitFor({ state: "visible" });
assert.equal(await line.textContent(), `Sent to Revise plan (lunch-vote) · ${day}`);
// Under the editor and above the pictures.
const order = await s.page.evaluate(() => [...document.getElementById("notepad-body").children].map((c) => c.id));
assert.ok(order.indexOf("notepad-sent") === order.indexOf("notepad-editor") + 1 && order.indexOf("notepad-sent") < order.indexOf("notepad-images"), order.join(", "));
await tabNamed(s, "Plain").click();
await line.waitFor({ state: "hidden" });
});
+253
View File
@@ -0,0 +1,253 @@
// Page tests for starting a skill with a Notebook tab: the dashboard's confirm
// pane picks a tab, Start launches, the launched skill's `fill: "note"` box
// arrives filled with the tab's text and ticked pictures, and only the Send
// of that box reaches the agent and marks the tab sent. Run with:
// node --test scripts/test-web-console-page-send.mjs
//
// Each test drives the real console in a real Chrome or Edge through
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
// session per test.
import fs from "node:fs";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, drawn, sendAndCollect, itemCard } from "./page-test-helpers.mjs";
import { cli, until, CONSOLE_CLI } from "./web-console-test-helpers.mjs";
import { addImage, createTab, deleteTab, listTabs, readNotepad, removeImage, saveNote } from "../src/web-console/notepads.mjs";
const suite = pageSuite(test);
// Set up (AGENTS.md), with one documented spec for Revise plan to target.
const PROJECT = {
"AGENTS.md": "# AGENTS.md\n\nA small demo project.\n",
"specs/ready/overview.md": "# Overview\n\n## Phase Checklist\n\n- [ ] Phase 1: One\n",
"specs/ready/phase-1.md": "# Phase 1\n\n- [ ] **Task 1.1:** One\n",
};
const MENU = { menu: { note: "Ready when you are." }, agent: { status: "waiting" } };
// Words no screen or file holds unless the tab put them there.
const MARKER = "Lunch vote by emoji, idea 7Q2X";
const TEXT = `# Lunch vote\n\n${MARKER}.\n`;
// A real JPEG drawn in the page, one color per call: the box re-encodes each
// picture the way a pasted one is, so a stub that only looks like a JPEG
// would never attach.
const jpeg = async (s, color) =>
Buffer.from(
await s.page.evaluate(async (fill) => {
const c = document.createElement("canvas");
c.width = 160;
c.height = 100;
const ctx = c.getContext("2d");
ctx.fillStyle = fill;
ctx.fillRect(0, 0, 160, 100);
const blob = await new Promise((resolve) => c.toBlob(resolve, "image/jpeg"));
let bin = "";
for (const b of new Uint8Array(await blob.arrayBuffer())) bin += String.fromCharCode(b);
return btoa(bin);
}, color),
"base64"
);
// A Notebook tab named `name` holding `text` and `pictures` real pictures.
async function noteTab(s, name, text, pictures) {
const id = createTab(s.project, name).id;
if (text) saveNote(s.project, id, text);
for (let i = 0; i < pictures; i++) addImage(s.project, id, await jpeg(s, `hsl(${i * 40}, 60%, 50%)`));
return id;
}
// Past Planny's wake-up and, on this console home's first run, the Welcome,
// to the menu.
async function toTheMenu(s) {
const skip = s.page.getByRole("button", { name: "Skip the intro" });
await skip.click();
await skip.waitFor({ state: "hidden" });
const main = s.page.locator("#main");
await main.getByRole("heading", { name: "What are we doing today?" }).waitFor();
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
if (await welcomeDone.isVisible()) {
await welcomeDone.click();
await welcomeDone.waitFor({ state: "hidden" });
}
return main;
}
const chipFor = (main, name) => main.getByRole("button").filter({ hasText: new RegExp(`^${name}`) });
const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { hasText: new RegExp(`^${name}`) });
const lightOf = (main, command) => main.getByRole("button").filter({ has: main.page().locator("code", { hasText: new RegExp(`^${command}$`) }) });
// Every file under the session folder that holds `words`.
function filesHolding(dir, words) {
const found = [];
for (const entry of fs.readdirSync(dir, { withFileTypes: true, recursive: true })) {
if (!entry.isFile()) continue;
const file = path.join(entry.parentPath ?? entry.path, entry.name);
if (fs.readFileSync(file).includes(words)) found.push(path.relative(dir, file));
}
return found;
}
const sentOf = (project, tab) => (listTabs(project).tabs.find((t) => t.id === tab) || {}).sent || null;
// From the menu: picks `chip`, opens `command`'s card, switches the Notebook
// on, picks `tabName` and presses Start; then collects the launch and runs its
// resume, as the dashboard agent does. Returns the launch send.
async function startWith(s, main, { chip, command, tabName }) {
await chipFor(main, chip).click();
await pickedChip(main, chip).waitFor();
await lightOf(main, command).click();
await main.getByRole("checkbox", { name: "Start with a note from your Notebook" }).check();
const tab = main.locator(".confirm-note-tab", { has: s.page.locator(".confirm-note-tab-name", { hasText: new RegExp(`^${tabName}$`) }) });
await tab.click();
await main.locator(".confirm-cmd-note", { hasText: `+ note: ${tabName}` }).waitFor();
await main.locator(".confirm-actions .btn.primary").click();
const got = s.wait(10);
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
const head = `node "${CONSOLE_CLI}" `;
assert.ok(got.resume.startsWith(head), `resume runs this console: ${got.resume}`);
const r = cli(got.resume.slice(head.length).split(" "), { cwd: s.project });
assert.equal(r.status, 0, `resume failed: ${r.stderr}`);
return got;
}
// The launched skill's first card: the box the page fills.
const BOX = { items: [{ id: "idea", kind: "text", title: "What should change", body: "Say it in your own words.", fill: "note" }] };
const boxOf = (s) => s.page.locator("#text-idea");
const readyPictures = (s) => itemCard(s.page, "idea").locator(".attach-thumb.is-ready");
const CASES = [
{ workflow: "pathfinder", chip: "Start from scratch", command: "/plan2code-0-pathfinder" },
{ workflow: "plan", chip: "Start from scratch", command: "/plan2code-1-plan" },
{ workflow: "quick-task", chip: "Start from scratch", command: "/plan2code-quick-task" },
{ workflow: "revise-plan", chip: "ready", command: "/plan2code-1b-revise-plan", spec: "specs/ready" },
];
for (const c of CASES) {
test(`${c.workflow}: the box arrives with the tab's text and five pictures, the agent reads it only on Send, and only then is the tab marked sent`, async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
const tab = await noteTab(s, "Idea", TEXT, 7);
const main = await toTheMenu(s);
const launch = await startWith(s, main, { chip: c.chip, command: c.command, tabName: "Idea" });
// Nothing of the tab rides the launch, and nothing of it is in the session.
assert.ok(!JSON.stringify(launch).includes(MARKER), "the launch send carries no tab text");
assert.deepEqual(filesHolding(s.session, MARKER), [], "no session file holds the tab's text after Start");
assert.equal(sentOf(s.project, tab), null, "Start alone marks nothing");
s.post(BOX);
await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000);
await until(async () => (await readyPictures(s).count()) === 5, 15000);
assert.equal(await boxOf(s).isEditable(), true, "the filled box stays editable");
// Still nothing for the agent before Send.
const result = path.join(s.session, "result.json");
assert.ok(!fs.existsSync(result) || !fs.readFileSync(result, "utf8").includes(MARKER), "result.json holds no tab text before Send");
assert.equal(s.wait(1).code, 10, "the agent has nothing to collect before Send");
assert.equal(sentOf(s.project, tab), null);
const got = await sendAndCollect(s);
assert.ok(got.reply.includes(MARKER), `the send carries the box: ${got.reply}`);
const note = got.actions.find((a) => a.i === "idea" && a.type === "comment");
assert.equal(note && note.images.length, 5, "the five pictures go with it");
await until(() => sentOf(s.project, tab) !== null, 5000);
const sent = sentOf(s.project, tab);
assert.equal(sent.workflow, c.workflow);
assert.equal(sent.spec, c.spec);
});
}
test("a pictures-only tab arrives as an empty box with its pictures, and its Send marks the tab sent", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
const tab = await noteTab(s, "Shots", "", 2);
const main = await toTheMenu(s);
await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-1-plan", tabName: "Shots" });
s.post(BOX);
await until(async () => (await readyPictures(s).count()) === 2, 15000);
assert.equal(await boxOf(s).inputValue(), "");
const got = await sendAndCollect(s);
const note = got.actions.find((a) => a.i === "idea" && a.type === "comment");
assert.equal(note && note.images.length, 2, "the pictures go on their own");
await until(() => sentOf(s.project, tab) !== null, 5000);
assert.equal(sentOf(s.project, tab).workflow, "plan");
});
test("a picture deleted between Start and the box is skipped, and the rest still attach", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
const tab = await noteTab(s, "Idea", TEXT, 3);
const main = await toTheMenu(s);
await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-1-plan", tabName: "Idea" });
const first = readNotepad(s.project, tab).images[0].id;
removeImage(s.project, tab, first);
s.post(BOX);
await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000);
await until(async () => (await readyPictures(s).count()) === 2, 15000);
assert.equal(await itemCard(s.page, "idea").locator(".attach-thumb").count(), 2, "no failed or empty slot for the missing one");
});
test("Back to the dashboard after the box fills takes the box with it, as its dialog says, and marks the tab sent", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
const tab = await noteTab(s, "Idea", TEXT, 0);
const main = await toTheMenu(s);
await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-0-pathfinder", tabName: "Idea" });
s.post(BOX);
await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000);
await s.page.click("#btn-home");
await s.page.locator("#home-modal[open]").waitFor();
await s.page.click("#home-go");
const got = s.wait(10);
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
assert.ok(got.actions.some((a) => a.i === "__dashboard"), "the send goes home");
assert.ok(got.reply.includes(MARKER), "and carries the filled box");
await until(() => sentOf(s.project, tab) !== null, 5000);
});
test("the box is filled once: a redraw or a reload keeps what the person typed, and the pictures are not added again", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
await noteTab(s, "Idea", TEXT, 3);
const main = await toTheMenu(s);
await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-0-pathfinder", tabName: "Idea" });
s.post(BOX);
await until(async () => (await readyPictures(s).count()) === 3, 15000);
await boxOf(s).fill("My own words now.");
s.post({ agent: { status: "waiting", activity: "Still here" } });
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await boxOf(s).waitFor();
assert.equal(await boxOf(s).inputValue(), "My own words now.");
await until(async () => (await readyPictures(s).count()) === 3, 5000);
// A second marked box later in the session is left alone.
s.post({ items: [{ id: "idea2", kind: "text", title: "Anything else", fill: "note" }] });
await s.page.locator("#text-idea2").waitFor();
assert.equal(await s.page.locator("#text-idea2").inputValue(), "");
});
test("a launch that goes back to the dashboard before Send marks nothing", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
const tab = await noteTab(s, "Idea", TEXT, 1);
const main = await toTheMenu(s);
await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-quick-task", tabName: "Idea" });
s.post(BOX);
await until(async () => (await boxOf(s).inputValue()) === TEXT, 10000);
const r = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "dashboard"], { cwd: s.project });
assert.equal(r.status, 0, `resume failed: ${r.stderr}`);
s.post(MENU);
await main.getByRole("heading", { name: "What are we doing today?" }).waitFor();
assert.equal(sentOf(s.project, tab), null);
});
test("a tab deleted between Start and the box leaves the box empty, with a banner", async (t) => {
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(PROJECT) });
const tab = await noteTab(s, "Idea", TEXT, 1);
const main = await toTheMenu(s);
await startWith(s, main, { chip: "Start from scratch", command: "/plan2code-1-plan", tabName: "Idea" });
deleteTab(s.project, tab);
s.post(BOX);
await s.page.locator("#banner", { hasText: "That Notebook tab is gone; the box starts empty." }).waitFor();
assert.equal(await boxOf(s).inputValue(), "");
assert.equal(await readyPictures(s).count(), 0);
});
+9 -3
View File
@@ -644,16 +644,22 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
/* ---------------------------------------------------------------- help */
test("help: 18 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 18);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 18);
test("help: 19 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 19);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 19);
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
const ids = HELP_TABS.map((t) => t.id);
assert.equal(ids.indexOf("git"), ids.indexOf("build") + 1, "The git board comes right after Watching a build");
assert.equal(HELP_TABS[ids.indexOf("git")].label, "The git board");
assert.equal(helpTabFor({ workflow: "git" }), "git");
assert.equal(ids.indexOf("activities"), ids.indexOf("ask") + 1, "Activities comes right after Ask a quick question");
assert.equal(HELP_TABS[ids.indexOf("activities")].label, "Activities");
const tpl = helpTemplate();
for (const id of ids) assert.match(tpl, new RegExp(`<section class="help-panel" data-tab="${id}">`), `${id} has a section`);
// The die sits right of the megaphone, so the megaphone is no longer the far-right button.
assert.doesNotMatch(tpl, /far right/, "no line calls a top-bar button the far-right one");
const around = tpl.match(/<section class="help-panel" data-tab="around">([\s\S]*?)<\/section>/)[1];
assert.match(around, /<strong>die<\/strong>[\s\S]*?"Activities"/, "Finding your way around points the die at the Activities topic");
});
test("help: the template's icons and panels match HELP_TABS in order, headed by their labels", () => {
+1 -1
View File
@@ -187,7 +187,7 @@ const ROUTE_ORDER = [
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/cleanup", "/upload",
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/",
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/",
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace",
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
];
+51 -4
View File
@@ -32,15 +32,16 @@ import { joinedCss } from "./css-helpers.mjs";
test("favicon: the dot follows the status line -- busy, ready, attention, plain", () => {
// Anything with the spinning ring is busy, even a finished screen opening the dashboard.
assert.equal(faviconState({ mood: "work", spin: true }), "busy");
assert.equal(faviconState({ mood: "work", spin: true, finished: true }), "busy");
// Pointing is the person's move, a finished screen with a press on offer too.
assert.equal(faviconState({ mood: "point" }), "ready");
// A working mood without the ring is the stale line; adrift and gone need a look too.
// A working mood without the ring is the stale line; adrift (a finished
// screen's stranded press among them) and gone need a look too.
assert.equal(faviconState({ mood: "work" }), "attention");
assert.equal(faviconState({ mood: "adrift" }), "attention");
assert.equal(faviconState({ mood: "gone" }), "attention");
assert.equal(faviconState({ mood: "happy" }), "plain");
assert.equal(faviconState({ mood: "done", finished: true }), "plain");
assert.equal(faviconState({ mood: "point", finished: true }), "plain");
// All done or paused, nothing left to press.
assert.equal(faviconState({ mood: "done" }), "plain");
assert.equal(faviconState(), "plain");
});
@@ -420,3 +421,49 @@ test("getting started: the new help, status and finished-screen strings carry no
const fresh = stuck.slice(0, stuck.indexOf("<h4>Not running, or not connected?</h4>"));
assert.ok(!fresh.includes(EM), "the callout and rows have no em dash");
});
// Every relative module a file pulls in, as `{ file, dynamic, names }`: static
// `import`/`export ... from` lines, and `import("./x")` calls with the names
// destructured from them when the call reads `const { a, b } = await import(...)`.
function relativeImports(file) {
const text = fs.readFileSync(file, "utf8");
const found = [];
for (const m of text.matchAll(/(?:^|[\s;])(?:import|export)\s+(?:[^"';]*?\sfrom\s+)?["'](\.{1,2}\/[^"']+)["']/g)) {
found.push({ file: path.resolve(path.dirname(file), m[1]), dynamic: false, names: null });
}
for (const m of text.matchAll(/(?:const\s*\{([^}]*)\}\s*=\s*await\s+)?import\(\s*["'](\.{1,2}\/[^"']+)["']\s*\)/g)) {
const names = m[1] ? m[1].split(",").map((n) => n.trim().split(/\s*:\s*/)[0]).filter(Boolean) : null;
found.push({ file: path.resolve(path.dirname(file), m[2]), dynamic: true, names, from: file });
}
return found;
}
test("no agent CLI module imports notepads.mjs, directly or through a module it imports", () => {
const dir = path.join(ROOT, "src", "web-console");
const store = path.join(dir, "notepads.mjs");
const starts = ["console.mjs", ...fs.readdirSync(dir).filter((n) => /^cmd-.*\.mjs$/.test(n))].map((n) => path.join(dir, n));
assert.ok(starts.length > 1, "found the agent CLI's modules");
const seen = new Set();
const lazy = [];
const queue = [...starts];
while (queue.length) {
const file = queue.shift();
if (seen.has(file) || !fs.existsSync(file)) continue;
seen.add(file);
for (const dep of relativeImports(file)) {
if (dep.file === store) {
assert.ok(dep.dynamic, `${path.relative(ROOT, file)} imports notepads.mjs at the top`);
lazy.push(dep);
} else queue.push(dep.file);
}
}
assert.ok(seen.size > 5, "walked the import graph");
assert.equal(seen.has(store), false, "the store is never loaded at the top of an agent-side module");
// The one way in is Cleanup (User Preferences, reached only through the
// page's /cleanup route), which lists stale notepads and removes one whole,
// never reading a note's text.
for (const dep of lazy) {
assert.equal(path.basename(dep.from), "sessions.mjs", "only Cleanup loads the store, lazily");
assert.ok(dep.names && dep.names.every((n) => n === "staleNotepads" || n === "removeNotepad"), `Cleanup takes only staleNotepads and removeNotepad, not ${dep.names}`);
}
});
+40
View File
@@ -442,6 +442,46 @@ test("the scan: an assumed task counts as done and is named, and numbered task l
}
});
test("the scan: planChange is true for a waiting Plan change brief, and absent once it is applied or dropped", () => {
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-brief-"));
const notes = (line) => "# Phase 1\n\n- [x] **Task 1.1:** One\n- [ ] **Task 1.2:** Two\n\n## Notes\n\n### Paused 2026-10-27\n" + line + "\n\n## Phase Completion Summary\n";
const checklist = (mark) => `# Overview\n\n## Phase Checklist\n\n- [${mark}] Phase 1: One\n- [ ] Phase 2: Two\n`;
const specs = {
waiting: { "overview.md": checklist("/"), "phase-1.md": notes("**Plan change:** add a phase first"), "phase-2.md": PHASE([false]) },
applied: { "overview.md": checklist("/"), "phase-1.md": notes("**Plan change (applied 2026-10-27):** add a phase first"), "phase-2.md": PHASE([false]) },
dropped: { "overview.md": checklist("/"), "phase-1.md": notes("**Plan change (dropped 2026-10-27):** add a phase first"), "phase-2.md": PHASE([false]) },
// No phase marked [/]: every phase file is read.
unmarked: { "overview.md": checklist(" "), "phase-1.md": PHASE([false]), "phase-2.md": notes("**Plan change:** rename a task") },
// A brief in a phase that is not the one in progress is not waiting on it.
otherPhase: { "overview.md": checklist("/"), "phase-1.md": notes("Nothing to change."), "phase-2.md": notes("**Plan change:** later") },
// Outside the Notes section it is only prose.
notInNotes: { "overview.md": checklist("/"), "phase-1.md": "# Phase 1\n\n**Plan change:** quoted in the overview\n\n- [ ] **Task 1.1:** One\n", "phase-2.md": PHASE([false]) },
built: { "overview.md": checklist("x"), "phase-1.md": notes("**Plan change:** found in the last checks").replace("- [ ] **Task 1.2:**", "- [x] **Task 1.2:**"), "phase-2.md": PHASE([true]) },
planned: { "PLAN-DRAFT-20261027.md": "# Plan draft\n\n**Status:** Draft\n\n## Notes\n\n**Plan change:** not a phased spec\n" },
};
try {
for (const [name, files] of Object.entries(specs))
for (const [rel, text] of Object.entries(files)) {
fs.mkdirSync(path.join(root, "specs", name), { recursive: true });
fs.writeFileSync(path.join(root, "specs", name, rel), text);
}
const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp]));
assert.equal(by.waiting.planChange, true);
assert.equal(by.waiting.state, "building");
assert.equal("planChange" in by.applied, false);
assert.equal("planChange" in by.dropped, false);
assert.equal(by.unmarked.planChange, true);
assert.equal(by.unmarked.state, "building");
assert.equal("planChange" in by.otherPhase, false);
assert.equal("planChange" in by.notInNotes, false);
assert.equal(by.built.state, "built");
assert.equal(by.built.planChange, true, "a built spec can still have a brief waiting");
assert.equal("planChange" in by.planned, false);
} finally {
fs.rmSync(root, { recursive: true, force: true });
}
});
// The states no card names in its `states` list: a card that is on for "any"
// spec does not count, since it would take a state nobody thought about. A
// finished state is taken by no card on purpose.
+2
View File
@@ -22,6 +22,8 @@ test("state: page starts as app.js always started it", () => {
homeward: null,
launching: null,
deleting: null,
noteSend: null,
noteSent: null,
retract: {},
chat: { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null },
});
+55 -13
View File
@@ -5,17 +5,20 @@
* `plan2code`: open the Plan2Code dashboard skill in Claude Code, Devin or Codex, in the
* current directory.
*
* Runs one of:
* claude /plan2code --permission-mode bypassPermissions [extra args]
* devin --permission-mode bypass [extra args] -- /plan2code
* codex --dangerously-bypass-approvals-and-sandbox [extra args] $plan2code
* Runs one of (the bracketed flags only when permission prompts are turned off):
* claude /plan2code [--permission-mode bypassPermissions] [extra args]
* devin [--permission-mode bypass] [extra args] -- /plan2code
* codex [--dangerously-bypass-approvals-and-sandbox] [extra args] $plan2code
*
* Codex starts a skill with `$name` rather than `/name`. When more than one CLI is installed
* it asks which one, with the last pick as the default; with only one installed it uses that.
* `--cli claude` / `--cli devin` / `--cli codex` skips the question. Before starting it asks
* which model to run, from the curated list in models.json (shipped with every install) plus
* any models the user added in User Preferences; Enter keeps the model the CLI last used, and
* `--model` (or Codex's `-m`) skips the question. Any other arguments are forwarded to the CLI.
* `--model` (or Codex's `-m`) skips the question. Right after the agent is chosen, when it has a
* flag for skipping permission prompts (every built-in does; a custom agent only with bypassArgs),
* it asks whether to turn them off, Yes by default; `--keep-permissions` answers no, and with no
* terminal to ask on they are off. Any other arguments are forwarded to the CLI.
* Self-contained, Node built-ins only: install.js copies this file to ~/.plan2code/bin/ and
* points the global shims at it.
*
@@ -51,6 +54,7 @@ const IS_MAC = process.platform === 'darwin';
const PICK_FOLDER_FLAG = '--pick-folder';
const CLI_FLAG = '--cli';
const CLASSIC_FLAG = '--classic';
const KEEP_PERMISSIONS_FLAG = '--keep-permissions';
// Where install.js puts the desktop app, and the one file in it the launcher starts.
// PLAN2CODE_APP names a different executable (the tests start a stand-in this way).
const APP_DIR = path.join(os.homedir(), '.plan2code', 'app');
@@ -127,7 +131,10 @@ function printIntro() {
console.log('');
}
/** The CLIs that can open the dashboard, in menu order. `args` builds the full argument list. */
/**
* The CLIs that can open the dashboard, in menu order. `args(extra, { bypass })` builds the full
* argument list, with `bypassArgs` in it only when permission prompts are off.
*/
const CLIS = [
{
id: 'claude',
@@ -135,7 +142,10 @@ const CLIS = [
install: 'npm i -g @anthropic-ai/claude-code',
installUrl: 'https://code.claude.com/docs/en/setup',
prompt: '/plan2code',
args: (extra) => ['/plan2code', '--permission-mode', 'bypassPermissions', ...extra],
bypassArgs: ['--permission-mode', 'bypassPermissions'],
args(extra, { bypass } = {}) {
return ['/plan2code', ...(bypass ? this.bypassArgs : []), ...extra];
},
},
{
id: 'devin',
@@ -143,7 +153,10 @@ const CLIS = [
install: 'https://devin.ai',
installUrl: 'https://docs.devin.ai/work-with-devin/devin-cli',
prompt: '/plan2code',
args: (extra) => ['--permission-mode', 'bypass', ...extra, '--', '/plan2code'],
bypassArgs: ['--permission-mode', 'bypass'],
args(extra, { bypass } = {}) {
return [...(bypass ? this.bypassArgs : []), ...extra, '--', '/plan2code'];
},
},
{
id: 'codex',
@@ -151,8 +164,11 @@ const CLIS = [
install: 'npm i -g @openai/codex',
installUrl: 'https://github.com/openai/codex',
prompt: '$plan2code',
bypassArgs: ['--dangerously-bypass-approvals-and-sandbox'],
// Codex mentions a skill with `$name`; the prompt is its one positional argument.
args: (extra) => ['--dangerously-bypass-approvals-and-sandbox', ...extra, '$plan2code'],
args(extra, { bypass } = {}) {
return [...(bypass ? this.bypassArgs : []), ...extra, '$plan2code'];
},
},
];
@@ -347,7 +363,8 @@ function customClis(file = USER_AGENTS_FILE, print = Boolean(process.stderr.isTT
prompt: entry.prompt,
custom: true,
entry,
args: (extra) => [...buildArgs(entry, { bypass: true, model: modelFrom(extra, entry.id) }), ...withoutModelFlag(extra)],
bypassArgs: entry.bypassArgs,
args: (extra, { bypass } = {}) => [...buildArgs(entry, { bypass, model: modelFrom(extra, entry.id) }), ...withoutModelFlag(extra)],
}));
}
@@ -708,6 +725,25 @@ async function chooseCli(requested) {
}
}
/**
* Whether to start the agent with permission prompts off. Asked only for an agent that has a flag
* for it (a custom agent may have none), with Yes as the default; `--keep-permissions` answers no
* without asking, and with no terminal to ask on the prompts are off.
*/
async function chooseBypass(cli, keep) {
if (!cli.bypassArgs || !cli.bypassArgs.length || keep) return false;
if (!process.stdin.isTTY) return true;
console.log('');
console.log(c.bright(`Turn ${cli.label}'s permission prompts off?`));
console.log(c.dim(`It would read, edit and run commands in this project without asking (${cli.bypassArgs.join(' ')}).`));
for (;;) {
const answer = (await ask(`Prompts off? ${c.green('[Y/n]')}: `)).trim().toLowerCase();
if (!answer || answer === 'y' || answer === 'yes') return true;
if (answer === 'n' || answer === 'no') return false;
console.log(c.yellow('Type n to keep the prompts, or press Enter to turn them off.'));
}
}
/**
* True when the forwarded arguments already pick a model: `--model <name>` / `--model=<name>`,
* and for Codex also its short form, `-m <name>` / `-m=<name>` / `-m<name>`.
@@ -1117,8 +1153,9 @@ async function launch() {
}
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
const classic = argv.includes(CLASSIC_FLAG);
const keepPermissions = argv.includes(KEEP_PERMISSIONS_FLAG);
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(
argv.filter((arg) => arg !== PICK_FOLDER_FLAG && arg !== CLASSIC_FLAG)
argv.filter((arg) => arg !== PICK_FOLDER_FLAG && arg !== CLASSIC_FLAG && arg !== KEEP_PERMISSIONS_FLAG)
);
printIntro();
@@ -1127,6 +1164,11 @@ async function launch() {
if (!cli) return exitWith(code, fromShortcut);
saveState({ lastCli: cli.id });
// The app has its own permission tick on its launch card, so the question is only for the
// terminal flow (asked late if the app fails to start).
const app = !classic && hasDisplay() ? findApp() : null;
let bypass = app ? null : await chooseBypass(cli, keepPermissions);
let cwd = process.cwd();
if (fromShortcut) {
const folder = await pickFolder();
@@ -1145,13 +1187,13 @@ async function launch() {
if (!hasModelFlag(extraArgs, cli.id)) await chooseModel(cli, extraArgs);
// The app takes over from here when it is installed, a window can open and --classic is absent.
const app = !classic && hasDisplay() ? findApp() : null;
if (app && (await startApp(app, { cwd, cliId: cli.id, model: modelFrom(extraArgs, cli.id) }))) {
console.log(`Opened the Plan2Code app in ${c.cyan(cwd)} ${c.dim('(run `plan2code --classic` to stay in this terminal)')}`);
return process.exit(0);
}
if (bypass === null) bypass = await chooseBypass(cli, keepPermissions);
const args = cli.args(extraArgs);
const args = cli.args(extraArgs, { bypass });
const options = { cwd, stdio: 'inherit', ...(cli.fullPath ? { fromFullPath: true } : {}) };
const child = spawnCommand(cli.path, args, options);
+5
View File
@@ -320,6 +320,11 @@ An option is `{ "k": "A", "text": "short label", "detail": "the trade-off", "rec
it, with a one-line summary in `placeholder`. A resumed map, PLAN-DRAFT or
checkpoint gets no idea card. Only the box's text comes back; never mention
templates in the terminal.
- **Fill from a Notebook tab:** on a `text` item, `"fill": "note"` (its only
value; any other kind or value is exit 3) has the page fill the first open one
once, with the tab's text and ticked pictures, when the person started from a
Notebook tab. You read it only when they send that box (Send, or Stop or
Back to the dashboard, which carry ready answers).
- **Recommend only when you genuinely know better and can say why.** "Which
format survives Excel?" is yours; "Who is this for?" is not — there a
recommendation is an anchor people rubber-stamp. At most one per question.
+51 -10
View File
@@ -5,8 +5,8 @@
//
// ~/.plan2code/notepads/<folder-name>-<12 hex>/
// meta.json { v: 2, folder, created }
// tabs.json { v: 1, order: [id], last: id|null, tabs: { id: { name, created } } }
// tabs/<id>/note.md the tab's text, UTF-8, written atomically
// tabs.json { v: 1, order: [id], last: id|null, tabs: { id: { name, created, sent? } } }
// tabs/<id>/note.md the tab's text, UTF-8, written atomically
// tabs/<id>/images/<uuid>.jpg a picture, JPEG from the page
// tabs/<id>/images/<uuid>.thumb.jpg its thumbnail, when the page sent one
//
@@ -17,7 +17,8 @@
//
// This module is the only code that names, reads, writes, lists and removes
// them. The page reaches it through the /notepad routes; the agent CLI never
// imports it, so nothing in a notepad can reach the agent. Reading never
// imports it, so a tab leaves it only through a send the person starts on the
// dashboard (a test checks the imports). Reading never
// creates or touches a file, so only a person's own edits age a notepad.
// PLAN2CODE_NOTEPADS_DIR moves the folder, for tests.
//
@@ -48,7 +49,7 @@ export const LEGACY_TAB_ID = "0000000000a1";
// A refusal the routes turn into `{ error: code }` with this status. Codes:
// bad, too-long, too-many, not-jpeg, not-found, and for tabs bad-name (400),
// duplicate-name (409), too-many-tabs (409), no-such-tab (404).
// bad-sent (400), duplicate-name (409), too-many-tabs (409), no-such-tab (404).
export class NotepadError extends Error {
constructor(code, status) {
super(code);
@@ -111,8 +112,21 @@ const isFile = (p) => {
}
};
// `{ order, last, tabs: { id: { name, created } } }` from tabs.json with every
// part of its shape checked, or null when it is missing or does not hold up.
// The workflows a tab can be sent to from the dashboard, and the spec a Revise
// plan send names.
export const SENT_WORKFLOWS = ["pathfinder", "plan", "quick-task", "revise-plan"];
const SENT_SPEC_RE = /^specs\/[A-Za-z0-9._-]+$/;
// A tab's `sent` record as stored, or null when it does not hold up.
function readSent(sent) {
if (!sent || typeof sent !== "object" || !SENT_WORKFLOWS.includes(sent.workflow) || typeof sent.at !== "string") return null;
if (sent.spec !== undefined && !(typeof sent.spec === "string" && SENT_SPEC_RE.test(sent.spec))) return null;
return { workflow: sent.workflow, ...(sent.spec ? { spec: sent.spec } : {}), at: sent.at };
}
// `{ order, last, tabs: { id: { name, created, sent? } } }` from tabs.json with
// every part of its shape checked, or null when it is missing or does not hold
// up. A `sent` record that does not hold up is dropped, never the whole index.
function readIndex(dir) {
const raw = readJson(path.join(dir, INDEX_FILE));
if (!raw || typeof raw !== "object" || !Array.isArray(raw.order)) return null;
@@ -125,6 +139,8 @@ function readIndex(dir) {
if (!t || typeof t !== "object") return null;
try {
tabs[id] = { name: normalizeTabName(t.name), created: typeof t.created === "string" ? t.created : null };
const sent = readSent(t.sent);
if (sent) tabs[id].sent = sent;
} catch {
return null;
}
@@ -333,14 +349,18 @@ function imageEntries(dirs) {
const imageUrl = (tab, id, thumb) => "/notepad/images/" + tab + "/" + id + (thumb ? ".thumb" : "") + ".jpg";
/**
* The tabs, as `[{ id, name }]` in order, and the one last used. Read only; a
* notepad still in the first shape answers one virtual tab, Notes.
* The tabs, as `[{ id, name, sent? }]` in order (`sent` only on a tab sent
* from the dashboard), and the one last used. Read only; a notepad still in
* the first shape answers one virtual tab, Notes, never sent.
*/
export function listTabs(folder) {
const dir = notepadFolder(folder);
if (!fs.existsSync(dir)) return { tabs: [], last: null };
const index = readIndex(dir);
if (index) return { tabs: index.order.map((id) => ({ id, name: index.tabs[id].name })), last: index.last };
if (index) {
const tabs = index.order.map((id) => ({ id, name: index.tabs[id].name, ...(index.tabs[id].sent ? { sent: index.tabs[id].sent } : {}) }));
return { tabs, last: index.last };
}
if (legacyShape(dir)) return { tabs: [{ id: LEGACY_TAB_ID, name: "Notes" }], last: LEGACY_TAB_ID };
return { tabs: [], last: null };
}
@@ -353,7 +373,8 @@ export function defaultTabId(folder) {
/**
* What the page shows:
* `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images } | null }`
* `{ tabs: [{ id, name, sent? }], last, tab: { id, text, savedAt, images } | null }`
* (`sent` is `{ workflow, spec?, at }`, the tab's last send from the dashboard)
* for the tab asked for (else the default one), plus that tab's `text`,
* `savedAt` and `images` at the top, where the first page read them. A named
* tab that does not exist is a `no-such-tab` refusal. Never creates or writes
@@ -426,6 +447,26 @@ export function renameTab(folder, id, name) {
});
}
/**
* Record that a tab was sent to a workflow from the dashboard, replacing any
* earlier record. `workflow` is one of SENT_WORKFLOWS and `spec`, when given,
* a `specs/<name>` path. Resolves to `{ id, sent }`.
*/
export function markTabSent(folder, tab, { workflow, spec } = {}) {
requireTab(folder, tab);
return withNotepad(folder, (dir, index) => {
if (!Object.hasOwn(index.tabs, tab)) throw new NotepadError("no-such-tab", 404);
if (!SENT_WORKFLOWS.includes(workflow)) throw new NotepadError("bad-sent", 400);
if (spec !== undefined && spec !== null && !(typeof spec === "string" && SENT_SPEC_RE.test(spec))) {
throw new NotepadError("bad-sent", 400);
}
const sent = { workflow, ...(spec ? { spec } : {}), at: nowIso() };
index.tabs[tab].sent = sent;
commit(dir, index);
return { id: tab, sent };
});
}
/** Remember which tab was open last. */
export function setLastTab(folder, id) {
requireTab(folder, id);
+1 -1
View File
@@ -7,7 +7,7 @@ Workflow notes for `pathfinder`, part of the web console contract (`console.md`)
once it does, and `"specDir": "specs/<idea>"` when the folder is created
(`console-stop.md` → Saying what stopping would cost).
- The menu after a decision is a `menu` card: its `options` are `trail --form C`'s, and the `Start fresh` one keeps its `"fresh": true` (the page words it "Start New Session" under the desktop app and asks the app for one on Send). Set the card's `command` to the resume command printed under `OR START FRESH`: the page copies it first. A declined confirm leaves you the pick: carry on as for any `Start fresh`.
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one.
- A doc that is a file exactly as written (the map once it is on disk, a
brief) goes up as a `file` block (`{ "id": "body", "file":
"specs/<idea>/pathfinder/map.md" }`) rather than pasted. Keep `md` blocks
+1 -1
View File
@@ -4,7 +4,7 @@ Workflow notes for `plan`, part of the web console contract (`console.md`).
- Open with `--workflow plan`, first thing. Every question and sign-off gate
goes through the page, phase breakdowns as an editable `list`.
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
- The fresh-idea card carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one.
- Planning has no mid-session save before the Large checkpoint or Phase 7, so for
a stop before then say plainly in `finish.body` that nothing was kept, and use
`"command": "/plan2code-1-plan"`. After the checkpoint, post
+1 -1
View File
@@ -7,7 +7,7 @@ Workflow notes for `quick-task`, part of the web console contract
- Open with the first clarifying question. Clarifying questions go out as
`text` or `choice`, at most three at a time. The first, asking what to build,
carries `"templates": "idea"` (`console.md` → The kinds).
carries `"templates": "idea"` and `"fill": "note"` (`console.md` → The kinds): the page fills that box from a Notebook tab when the person started with one.
- Post `"stopWarning": "A quick task saves nothing until it is built, so stopping now loses what we have worked out."`
at the start, and `"stopWarning": ""` once the build is under way.
- **Scope check:** a `choice`, "Too big for a quick task?", options
+1 -1
View File
@@ -6,7 +6,7 @@ Revision is a short run of gates, and each maps onto a kind you already know:
| Step | On the page |
| --- | --- |
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. |
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. With none waiting, the first card is a `text` item titled "What should change", `"fill": "note"`, asking what to change; its answer feeds the "Is this the change?" recap. |
| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." |
| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. |
| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. |
+4
View File
@@ -648,6 +648,10 @@ export function validate(state) {
if (item.templates != null && (item.kind !== "text" || item.templates !== "idea")) {
problems.push(`item "${item.id}" has "templates": only a text item can carry it, and its only value is "idea".`);
}
// The box the page fills from a Notebook tab picked at Start.
if (item.fill != null && (item.kind !== "text" || item.fill !== "note")) {
problems.push(`item "${item.id}" has "fill": only a text item can carry it, and its only value is "note".`);
}
// The page compiles it as the person types, and a pattern that does not
// compile throws there, on every keystroke, with nothing on screen to say why.
if (item.pattern != null) {
+31
View File
@@ -0,0 +1,31 @@
// Plan2Code Web Console - the list of activities: the games the Activities window can open.
//
// The source of truth for which games exist. The window (screens/activities.js)
// knows only this list; each game is its own module under activities/, loaded
// with import() the first time it is opened, and answers the same calls:
// create({ canvas, tone, onScore }) returning start, pause, resume, key, tick
// and resize, plus score and state (scripts/test-web-console-activities.mjs
// checks every listed game against it). create() is also handed best(), the
// saved best, and memo, a number kept between sessions; a game may ignore
// both. Three parts are optional: pointer(type,
// x, y) for a game played by mouse, release(name) for a game that acts on a
// key held down (handed the same names as key() when the key is let go), and
// lowerIsBetter on the module's export for a game whose best is its lowest
// round. Adding a game is one file and
// one line here. No DOM access and no imports: the page and `node --test` both
// import this file.
const entry = (id, title) => Object.freeze({ id, title, module: `/activities/${id}.js` });
export const ACTIVITIES = Object.freeze([entry("snake", "Snake"), entry("golf", "Mini golf")]);
// The looks.json key that holds a game's best score: activityBestSnake for
// snake. Built the way soundKey() builds the per-sound switches, so every key
// stays flat (cleanLooks() drops nested objects).
export const bestKey = (id) => "activityBest" + id[0].toUpperCase() + id.slice(1);
// The looks.json key that holds a game's memo: one whole number the game may
// keep between sessions (Snake keeps its tally of surprises found as bits).
// Handed to create() as memo { get, set }; a game that has no use for it
// leaves it at 0.
export const memoKey = (id) => "activityMemo" + id[0].toUpperCase() + id.slice(1);
@@ -0,0 +1,825 @@
// Plan2Code Web Console - mini golf's scenery and props: the sharks, bats and torches round the course, the looks of what the ball hits, and the power-up icons.
//
// Drawing only, like golf-draw.js, which calls in here: no rules and no state.
// Every piece is drawn in course units around its own point, and anything
// that moves (a fin circling, a wing flapping, a flame) follows the round's
// clock, never Math.random(), so a paused frame stays still. The palette `p`
// is the hole's theme from golf-draw.js.
/* --------------------------------------------------------------- helpers */
export function polygon(ctx, points) {
ctx.beginPath();
points.forEach((q, i) => (i ? ctx.lineTo(q.x, q.y) : ctx.moveTo(q.x, q.y)));
ctx.closePath();
}
export function circle(ctx, x, y, r) {
ctx.beginPath();
ctx.arc(x, y, Math.max(0.01, r), 0, Math.PI * 2);
}
export function ellipse(ctx, x, y, rx, ry, rot = 0) {
ctx.beginPath();
if (typeof ctx.ellipse === "function") ctx.ellipse(x, y, Math.max(0.01, rx), Math.max(0.01, ry), rot, 0, Math.PI * 2);
else ctx.arc(x, y, Math.max(0.01, rx), 0, Math.PI * 2);
}
// A radial gradient, or null where the context makes none (a stub in Node):
// the caller then fills flat or skips the glow.
export function radial(ctx, x, y, r0, r1, stops) {
if (typeof ctx.createRadialGradient !== "function") return null;
let g = null;
try {
g = ctx.createRadialGradient(x, y, r0, x, y, r1);
} catch {
return null;
}
if (!g || typeof g.addColorStop !== "function") return null;
for (const [at, color] of stops) g.addColorStop(at, color);
return g;
}
const fill = (ctx, color) => {
ctx.fillStyle = color;
ctx.fill();
};
const stroke = (ctx, color, width) => {
ctx.strokeStyle = color;
ctx.lineWidth = width;
ctx.stroke();
};
function line(ctx, x1, y1, x2, y2, color, width) {
ctx.beginPath();
ctx.moveTo(x1, y1);
ctx.lineTo(x2, y2);
stroke(ctx, color, width);
}
function label(ctx, str, x, y, size, color, font) {
ctx.font = `700 ${size}px ${font || "sans-serif"}`;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = color;
ctx.fillText(str, x, y);
}
// Turns the context to draw along an angle around a point, for the callback.
function turned(ctx, x, y, angle, draw) {
ctx.save();
ctx.translate(x, y);
ctx.rotate(angle);
draw();
ctx.restore();
}
const t = (clock) => clock / 1000;
/* ---------------------------------------------------------------- props */
// The looks of a bumper, by `look` or the theme's own.
export function drawBumperLook(ctx, p, b, clock) {
const look = b.look || (p.theme === "cave" ? "mushroom" : "barrel");
const { x, y, r } = b;
circle(ctx, x + 1.5, y + 2, r);
fill(ctx, p.shadow);
if (look === "barrel") {
circle(ctx, x, y, r);
fill(ctx, "#94602e");
circle(ctx, x, y, r * 0.72);
stroke(ctx, "#3a2a1c", 1.4);
circle(ctx, x, y, r * 0.38);
fill(ctx, "#6f4520");
circle(ctx, x, y, r);
stroke(ctx, "#3a2a1c", 1.6);
} else if (look === "cannonball") {
circle(ctx, x, y, r);
fill(ctx, "#25252c");
circle(ctx, x - r * 0.35, y - r * 0.35, r * 0.3);
fill(ctx, "#6d6d7a");
} else if (look === "chest") {
const s = r * 1.5;
ctx.fillStyle = "#7a4a1e";
ctx.fillRect(x - s / 2, y - s / 2, s, s);
ctx.fillStyle = "#d9a520";
ctx.fillRect(x - s / 2, y - 1.2, s, 2.4);
ctx.fillRect(x - 1.5, y - 2.5, 3, 5);
ctx.strokeStyle = "#3a2410";
ctx.lineWidth = 1;
ctx.strokeRect(x - s / 2, y - s / 2, s, s);
} else if (look === "coin") {
const shine = 0.5 + 0.5 * Math.sin(t(clock) * 3 + x);
circle(ctx, x, y, r);
fill(ctx, "#e8b923");
circle(ctx, x, y, r * 0.7);
stroke(ctx, "#a87a0c", 1.3);
label(ctx, "$", x, y + 0.5, r * 1.1, "#a87a0c");
circle(ctx, x - r * 0.4, y - r * 0.4, r * 0.18 + shine * 0.6);
fill(ctx, "#fff6c9");
} else if (look === "mushroom") {
const squish = 1 + Math.sin(t(clock) * 4 + y) * 0.04;
circle(ctx, x, y, r * squish);
fill(ctx, "#e0468a");
for (const [dx, dy, s] of [[-0.4, -0.3, 0.22], [0.35, -0.2, 0.18], [0, 0.4, 0.2], [0.45, 0.35, 0.13]]) {
circle(ctx, x + dx * r, y + dy * r, s * r);
fill(ctx, "#ffe3f1");
}
} else if (look === "rock") {
circle(ctx, x, y, r);
fill(ctx, "#5a5468");
circle(ctx, x - r * 0.15, y - r * 0.15, r * 0.62);
fill(ctx, "#77708a");
circle(ctx, x - r * 0.25, y - r * 0.25, r * 0.25);
fill(ctx, "#a49dba");
} else if (look === "crystal") {
const pts = [];
for (let i = 0; i < 6; i++) {
const a = (i / 6) * Math.PI * 2 + Math.PI / 6;
pts.push({ x: x + Math.cos(a) * r, y: y + Math.sin(a) * r });
}
polygon(ctx, pts);
fill(ctx, "#8a66ee");
polygon(ctx, [pts[0], pts[2], pts[4]]);
fill(ctx, "#b59cff");
circle(ctx, x - r * 0.25, y - r * 0.3, r * 0.2);
fill(ctx, "#f1ebff");
} else {
circle(ctx, x, y, r);
fill(ctx, "#9c3327");
}
}
// A mover at its place this moment.
export function drawMoverLook(ctx, p, m, clock) {
const { x, y, r } = m;
const look = m.look || "barrel";
ellipse(ctx, x + 1.5, y + 2.5, r, r * 0.9);
fill(ctx, p.shadow);
if (look === "barrel") {
// Rolls the way it travels: the hoops slide past.
const roll = (m.y * 0.4 + m.x * 0.4) % 6;
circle(ctx, x, y, r);
fill(ctx, "#a06a34");
ctx.save();
circle(ctx, x, y, r);
ctx.clip();
for (let k = -2; k <= 2; k++) line(ctx, x - r, y + k * 6 + roll - 3, x + r, y + k * 6 + roll - 3, "#3a2a1c", 1.5);
ctx.restore();
label(ctx, "TNT", x, y, r * 0.6, "#ffe9b0");
} else if (look === "crab") {
const wig = Math.sin(t(clock) * 14) * 1.5;
for (const side of [-1, 1]) {
for (let k = 0; k < 3; k++) line(ctx, x + side * r * 0.6, y - 2 + k * 2.5, x + side * (r + 3), y - 3 + k * 3 + wig * side, "#a8261b", 1.2);
circle(ctx, x + side * (r + 1), y - r * 0.9 + wig, r * 0.42);
fill(ctx, "#e1402d");
}
ellipse(ctx, x, y, r, r * 0.75);
fill(ctx, "#e1402d");
for (const side of [-1, 1]) {
circle(ctx, x + side * 2.2, y - r * 0.55, 1.6);
fill(ctx, "#ffffff");
circle(ctx, x + side * 2.2, y - r * 0.55, 0.8);
fill(ctx, "#111111");
}
} else if (look === "cart") {
const s = r * 1.6;
ctx.fillStyle = "#3d3a44";
ctx.fillRect(x - s / 2 - 2, y - s / 2 + 1, 3, s - 2);
ctx.fillRect(x + s / 2 - 1, y - s / 2 + 1, 3, s - 2);
ctx.fillStyle = "#6b6373";
ctx.fillRect(x - s / 2, y - s / 2, s, s);
ctx.strokeStyle = "#2a2730";
ctx.lineWidth = 1.2;
ctx.strokeRect(x - s / 2, y - s / 2, s, s);
for (const [dx, dy, c] of [[-3, -2, "#f2c84b"], [3, 1, "#7fe6ff"], [-1, 3, "#f2c84b"], [2, -4, "#ff7ad9"]]) {
circle(ctx, x + dx, y + dy, 2.2);
fill(ctx, c);
}
} else if (look === "fireball") {
const flick = 1 + Math.sin(t(clock) * 25) * 0.08;
const glow = radial(ctx, x, y, 0, r * 2.4, [[0, "rgba(255,220,120,0.9)"], [0.4, "rgba(255,120,30,0.6)"], [1, "rgba(255,60,0,0)"]]);
if (glow) {
circle(ctx, x, y, r * 2.4);
fill(ctx, glow);
}
circle(ctx, x, y, r * flick);
fill(ctx, "#ff7a1a");
circle(ctx, x - 1, y - 1, r * 0.55 * flick);
fill(ctx, "#ffe08a");
// A goofy face, because why not.
circle(ctx, x - 2.5, y - 1, 1);
fill(ctx, "#3a1200");
circle(ctx, x + 2.5, y - 1, 1);
fill(ctx, "#3a1200");
}
}
// A spinner's bar, with its look: a ship's wheel spoke, a kraken tentacle, a
// dragon's tail, or a plain plank.
export function drawSpinnerLook(ctx, p, s, clock) {
const look = s.look || "plank";
const angle = Math.atan2(s.y2 - s.y1, s.x2 - s.x1);
const arm = Math.hypot(s.x2 - s.x1, s.y2 - s.y1) / 2;
ctx.lineCap = "round";
line(ctx, s.x1 + 1.5, s.y1 + 2, s.x2 + 1.5, s.y2 + 2, p.shadow, 6);
if (look === "wheel") {
line(ctx, s.x1, s.y1, s.x2, s.y2, "#7a4a22", 4.5);
line(ctx, s.x1, s.y1, s.x2, s.y2, "#b07a43", 1.6);
for (const [ex, ey] of [[s.x1, s.y1], [s.x2, s.y2]]) {
circle(ctx, ex, ey, 3.2);
fill(ctx, "#6b3f1d");
}
circle(ctx, s.x, s.y, 13);
stroke(ctx, "#7a4a22", 3);
circle(ctx, s.x, s.y, 5);
fill(ctx, "#e0b030");
} else if (look === "tentacle" || look === "tail") {
const tentacle = look === "tentacle";
turned(ctx, s.x, s.y, angle, () => {
for (const dir of [-1, 1]) {
ctx.beginPath();
for (let i = 0; i <= 12; i++) {
const u = i / 12;
const w = Math.sin(u * 6 + t(clock) * 5) * 2.2 * u;
if (i === 0) ctx.moveTo(0, 0);
else ctx.lineTo(dir * u * arm, w);
}
stroke(ctx, tentacle ? "#8e3fa8" : "#b5262a", 5.5);
for (let i = 2; i < 11; i += 2) {
const u = i / 12;
circle(ctx, dir * u * arm, Math.sin(u * 6 + t(clock) * 5) * 2.2 * u + (tentacle ? 1.5 : -1.5), tentacle ? 1.2 : 1.6);
fill(ctx, tentacle ? "#f0b7ff" : "#f2c84b");
}
}
});
circle(ctx, s.x, s.y, 6);
fill(ctx, tentacle ? "#6c2a82" : "#7d1418");
} else {
line(ctx, s.x1, s.y1, s.x2, s.y2, p.spinner, 4);
circle(ctx, s.x, s.y, 5);
fill(ctx, p.hub);
}
}
// A power-up's icon, `r` across, centered on x, y.
export function drawPowerIcon(ctx, kind, x, y, r) {
if (kind === "doubloon") {
circle(ctx, x, y, r);
fill(ctx, "#f0c22c");
circle(ctx, x, y, r * 0.7);
stroke(ctx, "#a87a0c", r * 0.18);
label(ctx, "1", x, y + r * 0.05, r * 1.1, "#a87a0c");
} else if (kind === "cannon") {
circle(ctx, x - r * 0.15, y + r * 0.15, r * 0.8);
fill(ctx, "#25252c");
line(ctx, x + r * 0.35, y - r * 0.35, x + r * 0.75, y - r * 0.85, "#c8a26a", r * 0.18);
circle(ctx, x + r * 0.8, y - r * 0.9, r * 0.25);
fill(ctx, "#ffb020");
} else if (kind === "ghost") {
ctx.beginPath();
ctx.arc(x, y - r * 0.15, r * 0.75, Math.PI, 0);
ctx.lineTo(x + r * 0.75, y + r * 0.8);
for (let i = 0; i < 4; i++) ctx.lineTo(x + r * 0.75 - (i + 0.5) * r * 0.375, y + (i % 2 ? r * 0.8 : r * 0.5));
ctx.lineTo(x - r * 0.75, y + r * 0.8);
ctx.closePath();
fill(ctx, "#f4f7ff");
for (const dx of [-0.28, 0.28]) {
circle(ctx, x + dx * r, y - r * 0.2, r * 0.15);
fill(ctx, "#1c1c2a");
}
} else if (kind === "magnet") {
ctx.beginPath();
ctx.arc(x, y - r * 0.05, r * 0.6, Math.PI, 0, false);
stroke(ctx, "#d4342a", r * 0.45);
ctx.fillStyle = "#d9d9e3";
ctx.fillRect(x - r * 0.83, y, r * 0.45, r * 0.55);
ctx.fillRect(x + r * 0.38, y, r * 0.45, r * 0.55);
} else if (kind === "bouncy") {
ellipse(ctx, x, y + r * 0.25, r * 0.85, r * 0.55);
fill(ctx, "#ffd43b");
circle(ctx, x - r * 0.35, y - r * 0.35, r * 0.42);
fill(ctx, "#ffd43b");
polygon(ctx, [{ x: x - r * 0.75, y: y - r * 0.4 }, { x: x - r * 1.05, y: y - r * 0.25 }, { x: x - r * 0.72, y: y - r * 0.18 }]);
fill(ctx, "#ff8a1f");
circle(ctx, x - r * 0.42, y - r * 0.45, r * 0.1);
fill(ctx, "#111111");
} else if (kind === "bigcup") {
ctx.fillStyle = "#efdcae";
ctx.fillRect(x - r * 0.85, y - r * 0.7, r * 1.7, r * 1.4);
ctx.strokeStyle = "#a7834c";
ctx.lineWidth = r * 0.1;
ctx.strokeRect(x - r * 0.85, y - r * 0.7, r * 1.7, r * 1.4);
line(ctx, x - r * 0.35, y - r * 0.3, x + r * 0.35, y + r * 0.3, "#d4342a", r * 0.22);
line(ctx, x + r * 0.35, y - r * 0.3, x - r * 0.35, y + r * 0.3, "#d4342a", r * 0.22);
} else if (kind === "spyglass") {
ctx.lineCap = "round";
line(ctx, x - r * 0.75, y + r * 0.55, x + r * 0.55, y - r * 0.45, "#a8792b", r * 0.42);
line(ctx, x - r * 0.2, y + r * 0.12, x + r * 0.55, y - r * 0.45, "#d9a94a", r * 0.55);
circle(ctx, x + r * 0.62, y - r * 0.5, r * 0.3);
fill(ctx, "#bfe8ff");
}
}
/* --------------------------------------------------------------- scenery */
// Each kind of scenery: the layer it goes on ("low" under the walls, "high"
// over the ball, "glow" over a cave's darkness) and how it is drawn. `light`
// is the glow a cave casts around it, if any.
const DECOR = {
/* pirate */
shark: {
layer: "low",
draw(ctx, p, d, clock) {
const a = t(clock) * 0.9 * (d.s > 0.85 ? 1 : -1) + d.x;
const x = d.x + Math.cos(a) * 32 * d.s;
const y = d.y + Math.sin(a) * 9 * d.s;
const dir = Math.sign(-Math.sin(a) * (d.s > 0.85 ? 1 : -1)) || 1;
ctx.lineCap = "round";
line(ctx, x - dir * 4, y + 4, x - dir * 18, y + 5, "rgba(255,255,255,0.55)", 1.2);
polygon(ctx, [{ x: x - 5 * d.s, y: y + 4 }, { x: x + 5 * d.s, y: y + 4 }, { x: x - dir * 3 * d.s, y: y - 9 * d.s }]);
fill(ctx, "#5d6b78");
},
},
ship: {
layer: "low",
draw(ctx, p, d, clock) {
const bob = Math.sin(t(clock) * 1.6) * 1.5;
const y = d.y + bob;
polygon(ctx, [{ x: d.x - 22, y: y }, { x: d.x + 22, y: y }, { x: d.x + 15, y: y + 9 }, { x: d.x - 16, y: y + 9 }]);
fill(ctx, "#5c3416");
line(ctx, d.x, y, d.x, y - 30, "#3a2410", 1.6);
polygon(ctx, [{ x: d.x - 13, y: y - 26 }, { x: d.x + 13, y: y - 26 }, { x: d.x + 11, y: y - 6 }, { x: d.x - 11, y: y - 6 }]);
fill(ctx, "#f1ead6");
ctx.fillStyle = "#111111";
ctx.fillRect(d.x, y - 36, 9, 6);
circle(ctx, d.x + 4.5, y - 33, 1.5);
fill(ctx, "#ffffff");
},
},
bottle: {
layer: "low",
draw(ctx, p, d, clock) {
const a = Math.sin(t(clock) * 2 + d.x) * 0.5;
turned(ctx, d.x, d.y + Math.sin(t(clock) * 1.7) * 1.5, a, () => {
ellipse(ctx, 0, 0, 7, 3);
fill(ctx, "rgba(90,170,110,0.85)");
ctx.fillStyle = "#f4ead0";
ctx.fillRect(-3, -1.2, 5, 2.4);
ctx.fillStyle = "#8a5a2b";
ctx.fillRect(6, -1.3, 3, 2.6);
});
},
},
palm: {
layer: "low",
draw(ctx, p, d, clock) {
const s = d.s;
ellipse(ctx, d.x, d.y + 4 * s, 16 * s, 8 * s);
fill(ctx, "#ecd79c");
const sway = Math.sin(t(clock) * 1.3 + d.x) * 0.12;
line(ctx, d.x, d.y + 4 * s, d.x + 4 * s, d.y - 14 * s, "#8a5a2b", 2.5 * s);
for (let i = 0; i < 5; i++) {
const a = (i / 5) * Math.PI * 2 + sway;
ctx.beginPath();
ctx.moveTo(d.x + 4 * s, d.y - 14 * s);
ctx.quadraticCurveTo(d.x + 4 * s + Math.cos(a) * 9 * s, d.y - 18 * s + Math.sin(a) * 6 * s, d.x + 4 * s + Math.cos(a) * 15 * s, d.y - 12 * s + Math.sin(a) * 8 * s);
stroke(ctx, "#2f8f3c", 3 * s);
}
circle(ctx, d.x + 3 * s, d.y - 12 * s, 1.8 * s);
fill(ctx, "#6b4a2a");
},
},
wreck: {
layer: "low",
draw(ctx, p, d, clock) {
const tilt = -0.35 + Math.sin(t(clock) * 0.8) * 0.03;
turned(ctx, d.x, d.y, tilt, () => {
polygon(ctx, [{ x: -50, y: -6 }, { x: 40, y: -10 }, { x: 52, y: 4 }, { x: 30, y: 14 }, { x: -44, y: 12 }]);
fill(ctx, "#5c3416");
for (let x = -40; x < 40; x += 10) line(ctx, x, -6, x + 3, 12, "#3a2410", 1);
polygon(ctx, [{ x: -8, y: -8 }, { x: 6, y: -9 }, { x: 0, y: 6 }]);
fill(ctx, "#1b6d99");
line(ctx, 10, -8, 22, -46, "#3a2410", 2);
polygon(ctx, [{ x: 13, y: -40 }, { x: 34, y: -36 }, { x: 18, y: -24 }]);
fill(ctx, "rgba(241,234,214,0.8)");
});
},
},
crab: {
layer: "low",
draw(ctx, p, d, clock) {
drawMoverLook(ctx, p, { x: d.x + Math.sin(t(clock) * 1.5) * 10, y: d.y, r: 6 * d.s, look: "crab" }, clock);
},
},
parrot: {
layer: "high",
draw(ctx, p, d, clock) {
const bob = Math.abs(Math.sin(t(clock) * 3)) * -3;
const y = d.y + bob;
ellipse(ctx, d.x, y, 5, 8);
fill(ctx, "#e4312b");
ellipse(ctx, d.x + 3, y + 2, 3, 6, 0.3);
fill(ctx, "#2f7fd8");
circle(ctx, d.x, y - 8, 4);
fill(ctx, "#e4312b");
polygon(ctx, [{ x: d.x - 3, y: y - 8 }, { x: d.x - 7, y: y - 6 }, { x: d.x - 3, y: y - 5 }]);
fill(ctx, "#f2c84b");
circle(ctx, d.x - 1, y - 9, 1);
fill(ctx, "#111111");
polygon(ctx, [{ x: d.x - 2, y: y + 7 }, { x: d.x + 2, y: y + 7 }, { x: d.x + 1, y: y + 15 }]);
fill(ctx, "#2e9e48");
// Squawks now and then.
if (Math.floor(t(clock) / 2.5) % 3 === 0) label(ctx, "SQUAWK!", d.x, y - 18, 6, "#fff6c9");
},
},
island: {
layer: "low",
draw(ctx, p, d) {
ellipse(ctx, d.x, d.y, 18 * d.s, 9 * d.s);
fill(ctx, "#ecd79c");
line(ctx, d.x - 3, d.y - 3, d.x + 3, d.y + 3, "#d4342a", 1.6);
line(ctx, d.x + 3, d.y - 3, d.x - 3, d.y + 3, "#d4342a", 1.6);
},
},
cannon: {
layer: "low",
draw(ctx, p, d, clock) {
const dir = d.s < 0 ? -1 : 1;
ctx.fillStyle = "#6b3f1d";
ctx.fillRect(d.x - 8, d.y - 3, 16, 7);
turned(ctx, d.x, d.y, dir * Math.PI / 2, () => {
ctx.fillStyle = "#2b2b30";
ctx.fillRect(-4, -4, 18, 8);
circle(ctx, -4, 0, 5);
fill(ctx, "#2b2b30");
});
// A puff of smoke every few seconds.
const k = (t(clock) + d.x / 50) % 3;
if (k < 0.8) {
const r = 3 + k * 9;
circle(ctx, d.x, d.y + dir * (16 + k * 10), r);
fill(ctx, `rgba(230,230,230,${0.8 - k})`);
if (k < 0.15) label(ctx, "BOOM!", d.x, d.y + dir * 30, 7, "#ffb020");
}
},
},
anchor: {
layer: "low",
draw(ctx, p, d) {
ctx.lineCap = "round";
line(ctx, d.x, d.y - 10, d.x, d.y + 8, "#5b6470", 2.2);
line(ctx, d.x - 5, d.y - 6, d.x + 5, d.y - 6, "#5b6470", 2);
ctx.beginPath();
ctx.arc(d.x, d.y + 1, 7, 0.2, Math.PI - 0.2);
stroke(ctx, "#5b6470", 2.2);
circle(ctx, d.x, d.y - 12, 2.2);
stroke(ctx, "#5b6470", 1.5);
},
},
tentacle: {
layer: "low",
draw(ctx, p, d, clock) {
const s = d.s;
ctx.lineCap = "round";
ctx.beginPath();
for (let i = 0; i <= 10; i++) {
const u = i / 10;
const x = d.x + Math.sin(u * 4 + t(clock) * 2 + d.y) * 6 * s * u;
const y = d.y + 10 * s - u * 26 * s;
if (i === 0) ctx.moveTo(x, y);
else ctx.lineTo(x, y);
}
stroke(ctx, "#8e3fa8", 5 * s);
ellipse(ctx, d.x, d.y + 10 * s, 7 * s, 2.5 * s);
stroke(ctx, "rgba(255,255,255,0.5)", 1);
},
},
kraken: {
layer: "low",
draw(ctx, p, d, clock) {
ellipse(ctx, d.x, d.y + 6, 40, 16);
fill(ctx, "#6c2a82");
const blink = Math.floor(t(clock) * 10) % 40 === 0;
for (const dx of [-16, 16]) {
ellipse(ctx, d.x + dx, d.y - 2, 8, blink ? 1 : 7);
fill(ctx, "#fff6c9");
if (!blink) {
circle(ctx, d.x + dx + Math.sin(t(clock)) * 2, d.y - 1, 3);
fill(ctx, "#111111");
}
}
},
},
ghost: {
layer: "high",
draw(ctx, p, d, clock) {
const y = d.y + Math.sin(t(clock) * 1.8 + d.x) * 5;
const x = d.x + Math.sin(t(clock) * 0.7 + d.y) * 14;
ctx.globalAlpha = 0.6 + Math.sin(t(clock) * 2.3) * 0.2;
drawPowerIcon(ctx, "ghost", x, y, 12 * d.s);
if (Math.floor(t(clock) / 3) % 2 === 0) label(ctx, "Booo!", x + 16 * d.s, y - 12 * d.s, 6, "#f4f7ff");
ctx.globalAlpha = 1;
},
},
jolly: {
layer: "low",
draw(ctx, p, d, clock) {
const wave = Math.sin(t(clock) * 4) * 1.5;
line(ctx, d.x, d.y + 14, d.x, d.y - 14, "#3a2410", 1.5);
ctx.beginPath();
ctx.moveTo(d.x, d.y - 14);
ctx.quadraticCurveTo(d.x + 9, d.y - 16 + wave, d.x + 18, d.y - 14 + wave);
ctx.lineTo(d.x + 18, d.y - 2 + wave);
ctx.quadraticCurveTo(d.x + 9, d.y - 4 + wave, d.x, d.y - 2);
ctx.closePath();
fill(ctx, "#111111");
circle(ctx, d.x + 9, d.y - 9 + wave * 0.6, 2.5);
fill(ctx, "#f4f1ea");
},
},
skullrock: {
layer: "low",
draw(ctx, p, d, clock) {
ellipse(ctx, d.x, d.y + 40, 70, 20);
fill(ctx, "#ecd79c");
ellipse(ctx, d.x, d.y, 42, 38);
fill(ctx, "#8a8478");
ellipse(ctx, d.x, d.y - 4, 36, 30);
fill(ctx, "#a29c8f");
const glow = 0.5 + 0.5 * Math.sin(t(clock) * 2);
for (const dx of [-14, 14]) {
ellipse(ctx, d.x + dx, d.y - 6, 9, 10);
fill(ctx, "#1d1a17");
circle(ctx, d.x + dx, d.y - 5, 2 + glow);
fill(ctx, `rgba(255,80,40,${0.5 + glow * 0.5})`);
}
polygon(ctx, [{ x: d.x, y: d.y + 2 }, { x: d.x - 4, y: d.y + 10 }, { x: d.x + 4, y: d.y + 10 }]);
fill(ctx, "#1d1a17");
for (let i = -3; i <= 3; i++) {
ctx.fillStyle = "#f1ead6";
ctx.fillRect(d.x + i * 5 - 2, d.y + 16, 4, 6);
}
},
},
chest: {
layer: "low",
draw(ctx, p, d, clock) {
ctx.fillStyle = "#7a4a1e";
ctx.fillRect(d.x - 12, d.y - 4, 24, 14);
ctx.fillStyle = "#5c3416";
ctx.fillRect(d.x - 12, d.y - 14, 24, 8);
for (let i = 0; i < 6; i++) {
circle(ctx, d.x - 9 + i * 3.6, d.y - 4 - (i % 2) * 2, 2.4);
fill(ctx, "#f0c22c");
}
const sparkle = Math.floor(t(clock) * 4) % 6;
circle(ctx, d.x - 8 + sparkle * 3, d.y - 8, 1.2);
fill(ctx, "#ffffff");
},
},
/* cave */
bat: {
layer: "high",
draw(ctx, p, d, clock) {
const s = d.s;
const a = t(clock) * 1.1 + d.x;
const x = d.x + Math.sin(a) * 40 * s;
const y = d.y + Math.sin(a * 2) * 12 * s;
const flap = Math.sin(t(clock) * 18 + d.y) * 5 * s;
for (const dir of [-1, 1]) {
polygon(ctx, [{ x, y }, { x: x + dir * 6 * s, y: y - 4 * s - flap }, { x: x + dir * 13 * s, y: y - 1 * s - flap * 0.6 }, { x: x + dir * 9 * s, y: y + 2 * s }, { x: x + dir * 5 * s, y: y + 1 * s }]);
fill(ctx, "#0b0910");
}
circle(ctx, x, y, 3 * s);
fill(ctx, "#0b0910");
for (const dir of [-1, 1]) {
circle(ctx, x + dir * 1.2 * s, y - 0.6 * s, 0.7 * s);
fill(ctx, "#ff4d4d");
}
},
},
stalactite: {
layer: "high",
draw(ctx, p, d) {
const s = d.s;
for (const [dx, h, w] of [[-14, 18, 6], [0, 30, 8], [12, 14, 5], [24, 22, 6]]) {
polygon(ctx, [{ x: d.x + dx * s - w * s, y: d.y }, { x: d.x + dx * s + w * s, y: d.y }, { x: d.x + dx * s, y: d.y + h * s }]);
fill(ctx, "#3d3747");
polygon(ctx, [{ x: d.x + dx * s - w * s * 0.3, y: d.y }, { x: d.x + dx * s + w * s * 0.2, y: d.y }, { x: d.x + dx * s, y: d.y + h * s * 0.85 }]);
fill(ctx, "#5d566a");
}
},
},
crystal: {
layer: "glow",
light: { r: 34, color: "rgba(150,110,255,0.45)" },
draw(ctx, p, d, clock) {
const s = d.s;
const pulse = 0.8 + Math.sin(t(clock) * 2 + d.x) * 0.2;
for (const [dx, h, a, c] of [[-6, 16, -0.4, "#7b5cf0"], [0, 22, 0, "#a68cff"], [6, 14, 0.45, "#5fd3ff"]]) {
turned(ctx, d.x + dx * s, d.y, a, () => {
polygon(ctx, [{ x: -3 * s, y: 0 }, { x: 3 * s, y: 0 }, { x: 2 * s, y: -h * s }, { x: 0, y: -(h + 4) * s }, { x: -2 * s, y: -h * s }]);
ctx.globalAlpha = pulse;
fill(ctx, c);
ctx.globalAlpha = 1;
});
}
},
},
torch: {
layer: "glow",
light: { r: 60, color: "rgba(255,170,60,0.5)" },
draw(ctx, p, d, clock) {
ctx.lineCap = "round";
line(ctx, d.x, d.y + 10, d.x, d.y - 2, "#6b4a2a", 2.5);
const f = Math.sin(t(clock) * 21 + d.x) * 1.2 + Math.sin(t(clock) * 13) * 0.8;
polygon(ctx, [{ x: d.x - 4, y: d.y - 2 }, { x: d.x + 4, y: d.y - 2 }, { x: d.x + f * 0.6, y: d.y - 13 - f }]);
fill(ctx, "#ff8a1f");
polygon(ctx, [{ x: d.x - 2, y: d.y - 2 }, { x: d.x + 2, y: d.y - 2 }, { x: d.x + f * 0.3, y: d.y - 8 - f * 0.5 }]);
fill(ctx, "#ffe08a");
},
},
lantern: {
layer: "glow",
light: { r: 50, color: "rgba(255,210,110,0.45)" },
draw(ctx, p, d, clock) {
const swing = Math.sin(t(clock) * 1.5) * 4;
line(ctx, d.x, 0, d.x + swing, d.y + 4, "#3d3747", 1);
ctx.fillStyle = "#3d3747";
ctx.fillRect(d.x + swing - 4, d.y + 4, 8, 10);
ctx.fillStyle = "#ffd36b";
ctx.fillRect(d.x + swing - 2.5, d.y + 6, 5, 6);
},
},
eyes: {
layer: "glow",
draw(ctx, p, d, clock) {
// Two eyes in the dark that blink, and now and then look at you.
const k = Math.floor(t(clock) * 8 + d.x) % 30;
const open = k > 1 ? 1 : 0.15;
const look = Math.sin(t(clock) * 0.6 + d.y) * 1.5;
for (const dx of [-5, 5]) {
ellipse(ctx, d.x + dx * d.s, d.y, 3.2 * d.s, 2.2 * d.s * open);
fill(ctx, "#ffe14d");
if (open > 0.5) {
ellipse(ctx, d.x + dx * d.s + look, d.y, 0.9 * d.s, 2 * d.s);
fill(ctx, "#111111");
}
}
},
},
skeleton: {
layer: "low",
draw(ctx, p, d, clock) {
ctx.lineCap = "round";
line(ctx, d.x - 9, d.y + 6, d.x + 9, d.y - 2, "#d8d2c2", 2.2);
line(ctx, d.x - 9, d.y - 2, d.x + 9, d.y + 6, "#d8d2c2", 2.2);
circle(ctx, d.x, d.y - 8, 6);
fill(ctx, "#ece6d6");
// The jaw chatters.
const jaw = Math.abs(Math.sin(t(clock) * 6)) * 1.5;
ctx.fillStyle = "#ece6d6";
ctx.fillRect(d.x - 3.5, d.y - 3 + jaw, 7, 2.5);
for (const dx of [-2.2, 2.2]) {
circle(ctx, d.x + dx, d.y - 9, 1.6);
fill(ctx, "#1d1a17");
}
},
},
rails: {
layer: "low",
draw(ctx, p, d) {
for (let y = d.y - 105; y <= d.y + 105; y += 9) {
ctx.fillStyle = "#4a3a2a";
ctx.fillRect(d.x - 10, y, 20, 3);
}
line(ctx, d.x - 6, d.y - 108, d.x - 6, d.y + 108, "#8b8796", 1.6);
line(ctx, d.x + 6, d.y - 108, d.x + 6, d.y + 108, "#8b8796", 1.6);
},
},
gems: {
layer: "glow",
light: { r: 26, color: "rgba(255,120,220,0.35)" },
draw(ctx, p, d) {
const s = d.s;
for (const [dx, dy, c] of [[-6, 2, "#ff5bd6"], [4, 3, "#4de3ff"], [-1, -3, "#f2c84b"], [8, -2, "#5bff9a"], [-9, -4, "#f2c84b"]]) {
polygon(ctx, [{ x: d.x + dx * s, y: d.y + (dy - 3) * s }, { x: d.x + (dx + 3) * s, y: d.y + dy * s }, { x: d.x + dx * s, y: d.y + (dy + 3) * s }, { x: d.x + (dx - 3) * s, y: d.y + dy * s }]);
fill(ctx, c);
}
},
},
spider: {
layer: "high",
draw(ctx, p, d, clock) {
const y = d.y + Math.sin(t(clock) * 1.2) * 18;
line(ctx, d.x, 0, d.x, y, "rgba(220,220,230,0.6)", 0.6);
for (const dir of [-1, 1]) {
for (let k = 0; k < 4; k++) {
ctx.beginPath();
ctx.moveTo(d.x, y);
ctx.lineTo(d.x + dir * 5, y - 3 + k * 2);
ctx.lineTo(d.x + dir * 8, y + k * 2.4);
stroke(ctx, "#15121b", 1);
}
}
circle(ctx, d.x, y, 3.5);
fill(ctx, "#15121b");
for (const dir of [-1, 1]) {
circle(ctx, d.x + dir * 1.3, y - 1, 0.8);
fill(ctx, "#ff4d4d");
}
},
},
web: {
layer: "low",
draw(ctx, p, d) {
ctx.strokeStyle = "rgba(220,220,235,0.35)";
ctx.lineWidth = 0.6;
for (let i = 0; i < 8; i++) {
const a = (i / 8) * Math.PI * 2;
ctx.beginPath();
ctx.moveTo(d.x, d.y);
ctx.lineTo(d.x + Math.cos(a) * 26, d.y + Math.sin(a) * 26);
ctx.stroke();
}
for (const r of [8, 15, 22]) {
circle(ctx, d.x, d.y, r);
ctx.stroke();
}
},
},
glowworms: {
layer: "glow",
light: { r: 40, color: "rgba(110,255,200,0.3)" },
draw(ctx, p, d, clock) {
for (let i = 0; i < 9; i++) {
const x = d.x - 40 + i * 10 + Math.sin(t(clock) + i) * 3;
const y = d.y + Math.sin(t(clock) * 1.4 + i * 0.9) * 6;
circle(ctx, x, y, 1.4 + (Math.sin(t(clock) * 3 + i) + 1) * 0.5);
fill(ctx, "#8cffd9");
}
},
},
mushroom: {
layer: "glow",
light: { r: 30, color: "rgba(255,90,180,0.35)" },
draw(ctx, p, d) {
for (const [dx, dy, r] of [[-5, 3, 5], [4, -2, 6.5], [7, 6, 3.5]]) {
circle(ctx, d.x + dx, d.y + dy, r);
fill(ctx, "#e0468a");
circle(ctx, d.x + dx - r * 0.3, d.y + dy - r * 0.3, r * 0.25);
fill(ctx, "#ffe3f1");
}
},
},
dragon: {
layer: "glow",
light: { r: 70, color: "rgba(255,90,40,0.3)" },
draw(ctx, p, d, clock) {
// A sleeping dragon's head poking in from the right edge, snoring.
const cx = d.x - 6;
const breathe = Math.sin(t(clock) * 1.4) * 1.5;
ellipse(ctx, cx, d.y, 44 + breathe, 32);
fill(ctx, "#a3202a");
for (let i = 0; i < 4; i++) {
polygon(ctx, [{ x: cx - 26 + i * 12, y: d.y - 28 + i * 2 }, { x: cx - 20 + i * 12, y: d.y - 40 + i * 2 }, { x: cx - 14 + i * 12, y: d.y - 27 + i * 2 }]);
fill(ctx, "#f2c84b");
}
// The closed eye, a sleepy curve.
ctx.beginPath();
ctx.arc(cx - 14, d.y - 12, 6, 0.2, Math.PI - 0.2);
stroke(ctx, "#1d0608", 1.8);
for (const dy of [-2, 6]) {
circle(ctx, cx - 36 - breathe, d.y + dy, 2);
fill(ctx, "#1d0608");
}
const k = (t(clock) % 3) / 3;
label(ctx, "Z", cx - 46 - k * 14, d.y - 10 - k * 26, 7 + k * 5, `rgba(255,240,200,${1 - k})`);
label(ctx, "z", cx - 52 - k * 8, d.y - 2 - k * 14, 5 + k * 3, `rgba(255,240,200,${0.8 - k * 0.8})`);
},
},
};
export const DECOR_KINDS = Object.freeze(Object.keys(DECOR));
// Draws the hole's scenery that belongs on `layer`.
export function drawDecor(ctx, p, decor, clock, layer) {
for (const d of decor) {
const kind = DECOR[d.kind];
if (kind && kind.layer === layer) kind.draw(ctx, p, d, clock);
}
}
// The glows the scenery casts, for a cave's darkness: { x, y, r, color }.
export function decorLights(decor) {
const lights = [];
for (const d of decor) {
const kind = DECOR[d.kind];
if (kind && kind.light) lights.push({ x: d.x, y: d.y - 4, r: kind.light.r * (d.s || 1), color: kind.light.color });
if (d.kind === "eyes") lights.push({ x: d.x, y: d.y, r: 12, color: "rgba(255,225,80,0.25)" });
}
return lights;
}
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,444 @@
// Plan2Code Web Console - mini golf's course: the eighteen holes as data, in course units.
//
// Data only: no DOM and no imports, so the game (activities/golf.js) and the
// unit suite both read it as it is. Every hole is drawn on a fixed course of
// COURSE_W by COURSE_H units, scaled to the board like Snake's fixed grid, so
// a resize never moves a ball.
//
// The front nine is Pirate Cove: greens afloat in a shark sea, wooden rails,
// barrels and cannonballs. The back nine is the Caves of Doom: mossy stone in
// the dark, glowing pools, lava, a bottomless pit, mine carts and crushers.
//
// A hole is { name, par, theme, quip, ground, liquid, tee, cup, outline,
// walls, bumpers, sand, water, slopes, bridges, spinners, tunnels, movers,
// gates, powerups, decor }:
// theme "pirate" or "cave": the palette, the lighting and the gags
// quip a line shown as the hole starts
// ground how the green is drawn: "grass", "deck", "moss" or "stone"
// liquid what the water is: "sea", "pool", "lava" or "chasm" (the rule
// is the same, a stroke and back where the putt began)
// tee, cup points { x, y }
// outline the playing area as a polygon; its edges are the course edge,
// and they lead the walls list
// walls line segments { x1, y1, x2, y2 }
// bumpers circles { x, y, r, look? } that kick the ball back faster
// sand polygons that slow the ball several times over
// water polygons that cost a stroke, unless the ball is on a bridge
// slopes { points, push: { x, y } }: a polygon that pushes the ball each
// moment it is inside, in units per second per second (ramps,
// currents and updrafts too)
// bridges rectangles { x, y, w, h }: safe ground over water
// spinners { x, y, arm, speed, look? }: a windmill-style bar through its
// center, arm units each way, turning speed radians a second
// tunnels { a, b }: two mouths; entering one sends the ball out of the
// other with its speed kept
// movers { x, y, r, dx, dy, period, phase?, look? }: a bumper that swings
// dx, dy units each way from x, y, once every period ms
// gates { x1, y1, x2, y2, period, open, offset?, look? }: a wall that is
// there for the last (1 - open) of every period ms
// powerups { x, y, kind }: a pad the rolling ball picks up, for its next
// putt (the kinds are POWERUPS in golf.js)
// decor { kind, x, y, s? }: scenery that never touches the ball
// A polygon is a list of points { x, y }.
export const COURSE_W = 400;
export const COURSE_H = 300;
const pt = (x, y) => ({ x, y });
const rect = (x, y, w, h) => [pt(x, y), pt(x + w, y), pt(x + w, y + h), pt(x, y + h)];
const wall = (x1, y1, x2, y2) => ({ x1, y1, x2, y2 });
const bump = (x, y, r, look) => (look ? { x, y, r, look } : { x, y, r });
const pad = (x, y, kind) => ({ x, y, kind });
const deco = (kind, x, y, s = 1) => ({ kind, x, y, s });
// The outline's edges, closing back to its first point.
const edges = (outline) => outline.map((p, i) => {
const q = outline[(i + 1) % outline.length];
return wall(p.x, p.y, q.x, q.y);
});
function freezeDeep(value) {
if (value && typeof value === "object") {
Object.values(value).forEach(freezeDeep);
Object.freeze(value);
}
return value;
}
// Fills the empty lists and puts the outline's edges first among the walls.
function hole(def) {
const theme = def.theme || "pirate";
return {
name: def.name,
par: def.par,
theme,
quip: def.quip || "",
ground: def.ground || (theme === "cave" ? "moss" : "grass"),
liquid: def.liquid || (theme === "cave" ? "pool" : "sea"),
tee: def.tee,
cup: def.cup,
outline: def.outline,
walls: [...edges(def.outline), ...(def.walls || [])],
bumpers: def.bumpers || [],
sand: def.sand || [],
water: def.water || [],
slopes: def.slopes || [],
bridges: def.bridges || [],
spinners: def.spinners || [],
tunnels: def.tunnels || [],
movers: def.movers || [],
gates: def.gates || [],
powerups: def.powerups || [],
decor: def.decor || [],
};
}
const pirate = (def) => hole({ ...def, theme: "pirate" });
const cave = (def) => hole({ ...def, theme: "cave" });
export const HOLES = freezeDeep([
/* ------------------------------------------- front nine: Pirate Cove */
// 1: a straight plank over the sea, to learn the putt. The sharks wait.
pirate({
name: "Walk the Plank",
par: 2,
quip: "Arr! Straight down the plank, matey. The sharks be hungry.",
ground: "deck",
tee: pt(90, 150),
cup: pt(310, 150),
outline: rect(60, 110, 280, 80),
decor: [deco("shark", 200, 62, 1), deco("shark", 140, 244, 0.8), deco("ship", 345, 52), deco("bottle", 40, 250), deco("palm", 30, 70, 0.8)],
}),
// 2: an L that turns left; a barrel splits the lane, and a doubloon waits in
// the corner for whoever banks it there.
pirate({
name: "Shipwreck Cove",
par: 3,
quip: "Bank it off the corner. That doubloon makes yer next putt free!",
tee: pt(75, 228),
cup: pt(268, 75),
outline: [pt(40, 195), pt(232, 195), pt(232, 40), pt(305, 40), pt(305, 262), pt(40, 262)],
bumpers: [bump(268, 142, 10, "barrel")],
powerups: [pad(268, 228, "doubloon")],
decor: [deco("wreck", 125, 110), deco("crab", 70, 282), deco("parrot", 345, 70), deco("shark", 355, 200, 0.7), deco("palm", 20, 175, 0.9)],
}),
// 3: cannonballs across the straight line, a powder barrel rolling the
// lane, and cannons firing from the shore.
pirate({
name: "Cannon Alley",
par: 3,
quip: "Fire in the hole! Grab the cannonball for a mighty blast.",
tee: pt(70, 150),
cup: pt(330, 150),
outline: rect(40, 60, 320, 180),
bumpers: [
bump(160, 108, 12, "cannonball"),
bump(160, 192, 12, "cannonball"),
bump(222, 150, 14, "cannonball"),
bump(278, 98, 10, "cannonball"),
bump(278, 202, 10, "cannonball"),
],
movers: [{ x: 110, y: 150, r: 9, dx: 0, dy: 62, period: 2600, look: "barrel" }],
powerups: [pad(92, 80, "cannon")],
decor: [deco("cannon", 120, 42), deco("cannon", 280, 42), deco("cannon", 200, 262, -1), deco("anchor", 380, 270)],
}),
// 4: two staggered traps; the straight line crosses both, a weave misses
// them, and the treasure map waits beyond the second.
pirate({
name: "Treasure Beach",
par: 3,
quip: "X marks the spot! The map makes the next cup HUGE.",
tee: pt(70, 150),
cup: pt(330, 150),
outline: rect(40, 70, 320, 160),
sand: [
rect(135, 112, 60, 118),
rect(235, 70, 60, 118),
],
bumpers: [bump(215, 150, 9, "chest")],
powerups: [pad(165, 195, "doubloon"), pad(265, 210, "bigcup")],
decor: [deco("palm", 28, 52), deco("palm", 372, 252), deco("crab", 200, 254), deco("island", 350, 40), deco("bottle", 60, 262)],
}),
// 5: the lagoon runs wall to wall; the bridge is the only dry way over, and
// the kraken's tentacle sweeps the far bank. The ghost floats right across.
pirate({
name: "Kraken's Lagoon",
par: 4,
quip: "Release the kraken! Or grab the ghost ball and float over it.",
tee: pt(65, 80),
cup: pt(330, 80),
outline: rect(30, 40, 340, 220),
water: [rect(165, 40, 80, 220)],
bridges: [{ x: 165, y: 190, w: 80, h: 40 }],
spinners: [{ x: 305, y: 172, arm: 34, speed: -1.9, look: "tentacle" }],
powerups: [pad(90, 240, "ghost")],
decor: [deco("tentacle", 205, 95), deco("tentacle", 190, 150, 0.8), deco("kraken", 205, 280), deco("shark", 380, 140, 0.6)],
}),
// 6: a ghost ship's deck with an open hold amidships; around it by the
// rails, or a rubber duck's bounce off them.
pirate({
name: "Ghost Ship",
par: 3,
quip: "Ooooo, a haunted deck. Mind the hold, it goes straight to the sea.",
ground: "deck",
tee: pt(75, 150),
cup: pt(330, 150),
outline: [pt(40, 90), pt(280, 70), pt(370, 150), pt(280, 230), pt(40, 210)],
water: [rect(150, 118, 90, 64)],
powerups: [pad(105, 118, "bouncy"), pad(105, 182, "magnet")],
decor: [deco("ghost", 200, 40), deco("ghost", 300, 262, 0.7), deco("tentacle", 195, 160), deco("jolly", 60, 40)],
}),
// 7: a ship's wheel turns across the way to the cup; walls close the way
// around it.
pirate({
name: "The Ship's Wheel",
par: 3,
quip: "Hard to starboard! Time yer putt through the spinning wheel.",
tee: pt(70, 150),
cup: pt(330, 150),
outline: rect(40, 80, 320, 140),
walls: [
wall(240, 80, 240, 107),
wall(240, 193, 240, 220),
],
spinners: [{ x: 240, y: 150, arm: 40, speed: 1.6, look: "wheel" }],
powerups: [pad(130, 105, "bouncy")],
decor: [deco("parrot", 240, 60), deco("anchor", 30, 260), deco("shark", 200, 262, 0.9), deco("island", 360, 45)],
}),
// 8: a long U the slow way round, past a scuttling crab, or the skull's
// tunnel straight across.
pirate({
name: "Skull Island",
par: 3,
quip: "Into the skull's mouth and out its ear. Totally normal.",
tee: pt(75, 65),
cup: pt(325, 125),
outline: [pt(40, 40), pt(110, 40), pt(110, 195), pt(290, 195), pt(290, 40), pt(360, 40), pt(360, 262), pt(40, 262)],
tunnels: [
{ a: pt(75, 170), b: pt(325, 62) },
],
movers: [{ x: 200, y: 245, r: 8, dx: 60, dy: 0, period: 3000, look: "crab" }],
powerups: [pad(160, 214, "magnet")],
decor: [deco("skullrock", 200, 115), deco("shark", 200, 45, 0.7), deco("palm", 148, 175, 0.7), deco("palm", 255, 172, 0.8)],
}),
// 9: up the ramp, over the bridge, through the gold to the cup.
pirate({
name: "Captain's Plunder",
par: 4,
quip: "The captain's own treasure! Ramp, bridge, gold. Go!",
tee: pt(70, 240),
cup: pt(340, 60),
outline: rect(30, 30, 340, 240),
// The ramp climbs to the bridge: too soft a putt rolls back down it.
slopes: [
{ points: rect(95, 55, 55, 50), push: pt(-110, 0) },
],
water: [
rect(150, 30, 90, 240),
],
bridges: [
{ x: 150, y: 55, w: 90, h: 50 },
],
bumpers: [
bump(288, 118, 12, "coin"),
bump(336, 132, 10, "coin"),
bump(296, 200, 12, "coin"),
bump(270, 40, 8, "coin"),
],
movers: [{ x: 320, y: 250, r: 7, dx: 30, dy: 0, period: 2400, look: "crab" }],
powerups: [pad(60, 150, "spyglass"), pad(270, 160, "doubloon")],
decor: [deco("tentacle", 195, 180), deco("tentacle", 210, 240, 0.7), deco("chest", 385, 80), deco("jolly", 385, 250)],
}),
/* ---------------------------------------- back nine: Caves of Doom */
// 10: a winding passage into the dark past a glowing pool, a mushroom on
// the bend.
cave({
name: "Into the Dark",
par: 3,
quip: "Welcome to the Caves of Doom. Your ball is the only light. Gulp.",
tee: pt(60, 230),
cup: pt(340, 80),
outline: [pt(30, 200), pt(230, 200), pt(230, 40), pt(370, 40), pt(370, 120), pt(300, 120), pt(300, 260), pt(30, 260)],
water: [rect(115, 236, 75, 24)],
bumpers: [bump(265, 160, 9, "mushroom")],
powerups: [pad(265, 232, "spyglass")],
decor: [deco("bat", 110, 90), deco("bat", 160, 130, 0.8), deco("eyes", 90, 150), deco("torch", 30, 185), deco("stalactite", 330, 0), deco("crystal", 380, 200), deco("eyes", 345, 230, 0.7)],
}),
// 11: a forest of stalagmites, with gaps a ball can thread.
cave({
name: "Stalagmite Forest",
par: 3,
quip: "Pointy rocks everywhere. Bounce through like a pinball.",
ground: "stone",
tee: pt(70, 150),
cup: pt(335, 150),
outline: rect(40, 50, 320, 200),
bumpers: [
bump(120, 90, 9, "rock"), bump(120, 150, 9, "rock"), bump(120, 210, 9, "rock"),
bump(162, 120, 9, "rock"), bump(162, 180, 9, "rock"),
bump(204, 90, 9, "rock"), bump(204, 150, 9, "rock"), bump(204, 210, 9, "rock"),
bump(246, 120, 9, "rock"), bump(246, 180, 9, "rock"),
bump(288, 90, 9, "rock"), bump(288, 210, 9, "rock"),
],
powerups: [pad(225, 236, "bouncy")],
decor: [deco("bat", 100, 30), deco("bat", 300, 270, 0.8), deco("stalactite", 80, 0), deco("stalactite", 250, 0, 1.2), deco("crystal", 20, 270), deco("skeleton", 375, 40)],
}),
// 12: a lava lake wall to wall, two thin stone bridges, and a fireball
// bobbing up and down across both of them.
cave({
name: "Lava Lake",
par: 4,
quip: "The floor is lava. No, really. Fireball incoming!",
liquid: "lava",
ground: "stone",
tee: pt(65, 150),
cup: pt(335, 150),
outline: rect(30, 40, 340, 220),
water: [rect(130, 40, 140, 220)],
bridges: [
{ x: 130, y: 70, w: 140, h: 28 },
{ x: 130, y: 205, w: 140, h: 28 },
],
movers: [{ x: 200, y: 150, r: 8, dx: 0, dy: 95, period: 3600, look: "fireball" }],
powerups: [pad(85, 235, "ghost")],
decor: [deco("torch", 20, 100), deco("torch", 380, 100), deco("skeleton", 375, 270), deco("stalactite", 200, 0, 0.8)],
}),
// 13: three mine carts rattle up and down across the straight line.
cave({
name: "Mine Cart Madness",
par: 3,
quip: "Runaway mine carts! Time it... or blast through with the cannon.",
ground: "stone",
tee: pt(60, 150),
cup: pt(345, 150),
outline: rect(30, 40, 340, 220),
movers: [
{ x: 140, y: 150, r: 12, dx: 0, dy: 85, period: 2200, look: "cart" },
{ x: 220, y: 150, r: 12, dx: 0, dy: 85, period: 2800, phase: 0.3, look: "cart" },
{ x: 300, y: 150, r: 12, dx: 0, dy: 85, period: 2000, phase: 0.6, look: "cart" },
],
powerups: [pad(60, 70, "cannon")],
decor: [deco("rails", 140, 150), deco("rails", 220, 150), deco("rails", 300, 150), deco("lantern", 20, 40), deco("gems", 385, 270), deco("bat", 200, 20)],
}),
// 14: crystals everywhere and two slingshot walls: pure pinball.
cave({
name: "Crystal Pinball",
par: 3,
quip: "TILT! Crystals, bumpers and a big treasure-map cup.",
tee: pt(70, 230),
cup: pt(330, 70),
outline: rect(40, 40, 320, 220),
walls: [
wall(300, 252, 350, 215),
wall(48, 150, 85, 122),
],
bumpers: [
bump(130, 110, 11, "crystal"),
bump(200, 80, 11, "crystal"),
bump(200, 170, 13, "crystal"),
bump(270, 140, 11, "crystal"),
bump(140, 200, 10, "crystal"),
bump(330, 140, 9, "crystal"),
],
powerups: [pad(205, 238, "bigcup")],
decor: [deco("crystal", 22, 210, 1.2), deco("crystal", 380, 280), deco("crystal", 385, 120, 0.8), deco("bat", 200, 280, 0.7)],
}),
// 15: a bottomless pit wall to wall, one rope bridge over it, and an
// updraft blowing across the bridge.
cave({
name: "The Bottomless Pit",
par: 3,
quip: "Don't look down. Seriously. There's an updraft on the bridge.",
liquid: "chasm",
ground: "stone",
tee: pt(75, 150),
cup: pt(325, 150),
outline: rect(40, 50, 320, 200),
water: [rect(150, 50, 100, 200)],
bridges: [{ x: 150, y: 132, w: 100, h: 36 }],
slopes: [{ points: rect(150, 132, 100, 36), push: pt(0, 70) }],
powerups: [pad(100, 80, "magnet")],
decor: [deco("spider", 330, 70), deco("web", 360, 230), deco("skeleton", 60, 230), deco("torch", 30, 150), deco("torch", 370, 150)],
}),
// 16: a winding grotto; the glowworm current carries the ball up and over.
cave({
name: "Glowworm Grotto",
par: 3,
quip: "Ride the glowworm current. They're friendly. Probably.",
tee: pt(70, 90),
cup: pt(310, 200),
outline: rect(30, 60, 340, 180),
walls: [
wall(130, 60, 130, 180),
wall(250, 120, 250, 240),
],
slopes: [{ points: rect(140, 70, 100, 100), push: pt(0, -90) }],
bumpers: [bump(190, 215, 10, "mushroom"), bump(310, 90, 10, "mushroom")],
powerups: [pad(165, 195, "spyglass")],
decor: [deco("glowworms", 200, 30), deco("glowworms", 100, 270), deco("mushroom", 20, 250), deco("mushroom", 385, 50), deco("eyes", 300, 270)],
}),
// 17: a corridor of stone crushers slamming down in turn, lava in its
// corners.
cave({
name: "Crusher Corridor",
par: 4,
quip: "SMASH! SMASH! SMASH! Run the crushers... if you dare.",
ground: "stone",
liquid: "lava",
tee: pt(60, 150),
cup: pt(345, 150),
outline: rect(30, 90, 340, 120),
water: [rect(160, 90, 30, 24), rect(240, 186, 30, 24)],
gates: [
{ x1: 130, y1: 90, x2: 130, y2: 210, period: 2400, open: 0.55, offset: 0, look: "crusher" },
{ x1: 210, y1: 90, x2: 210, y2: 210, period: 2400, open: 0.55, offset: 0.33, look: "crusher" },
{ x1: 290, y1: 90, x2: 290, y2: 210, period: 2400, open: 0.55, offset: 0.66, look: "crusher" },
],
powerups: [pad(95, 195, "cannon"), pad(250, 105, "doubloon")],
decor: [deco("skeleton", 200, 245), deco("torch", 100, 70), deco("torch", 300, 70), deco("stalactite", 200, 0, 1.3), deco("bat", 60, 260, 0.8)],
}),
// 18: the dragon's hoard: a lava lake, a portal over it, the dragon's tail
// sweeping, gold everywhere, and the dragon himself asleep at the edge.
cave({
name: "The Dragon's Hoard",
par: 5,
quip: "SHHH! The dragon is sleeping. Grab the gold and sink it.",
liquid: "lava",
tee: pt(60, 240),
cup: pt(305, 75),
outline: rect(20, 45, 325, 230),
water: [rect(130, 45, 80, 160)],
tunnels: [{ a: pt(70, 80), b: pt(245, 70) }],
spinners: [{ x: 275, y: 160, arm: 34, speed: 2.2, look: "tail" }],
bumpers: [bump(300, 220, 9, "coin"), bump(235, 112, 9, "coin"), bump(95, 145, 9, "coin")],
powerups: [pad(170, 240, "bigcup"), pad(65, 180, "ghost")],
decor: [deco("dragon", 400, 160), deco("gems", 30, 290), deco("gems", 372, 270, 0.8), deco("torch", 10, 160), deco("stalactite", 200, 0)],
}),
]);
// Where the front nine ends: the scorecard after it heads into the caves.
export const FRONT_NINE = 9;
+954
View File
@@ -0,0 +1,954 @@
// Plan2Code Web Console - Mini golf, the second activity: eighteen holes seen from above, rules, physics and the game contract.
//
// The Activities window (screens/activities.js) drives everything, as it does
// for Snake: it ticks the game, hands it keys, key releases and pointer
// events, and pauses it. Play is arcade quick: the aim follows the pointer
// (or held arrows), one press starts the power meter and a second sets the
// power, and a shot clock starts the meter for a player who dawdles. The
// rules are plain functions over a round object (newRound, startSwing,
// setPower, strike, advance and helpers), exported so the unit suite can play
// exact shots without a canvas. Physics runs on a fixed sub-step and never reads the
// clock or Math.random(), so the same shot always rolls the same way. The
// course is data (golf-holes.js); the drawing lives in golf-draw.js and its
// scenery in golf-decor.js.
import { COURSE_W, COURSE_H, FRONT_NINE, HOLES } from "./golf-holes.js";
import { drawCourse, readColors } from "./golf-draw.js";
export { COURSE_W, COURSE_H, FRONT_NINE, HOLES };
// One physics step, in ms. tick() runs as many as the elapsed time holds and
// carries the rest to the next tick.
export const SUB_STEP_MS = 4;
// The most time one tick() plays, matching the window's own frame cap.
export const MAX_TICK_MS = 250;
export const BALL_R = 4;
export const CUP_R = 7;
export const TUNNEL_R = 9;
export const POWERUP_R = 9;
// The fastest a ball ever moves, in units a second. At SUB_STEP_MS it covers
// 2.4 units a step, under BALL_R, so no step can carry it through a wall. A
// cannon shot may go faster, still under BALL_R a step.
export const MAX_SPEED = 600;
export const CANNON_MAX = 900;
// A full-power putt's speed, in units a second. A MAX putt (MAX_BOOST) comes
// to 598, just under MAX_SPEED.
export const STRIKE_SPEED = 520;
// Rolling: a steady slowing plus a share of the speed, both multiplied in sand.
const FRICTION = 40;
const DRAG = 1.2;
export const SAND_FACTOR = 4;
// Under this speed, off any slope, the ball has stopped. High enough to cut
// the slow creep at the end of a roll.
const STOP_SPEED = 8;
// Over the cup under this speed, the ball drops; faster, it rolls over.
export const CAPTURE_SPEED = 130;
// The share of its speed into a wall the ball keeps coming off it.
const WALL_KEEP = 0.7;
// The speed a bumper adds on top of a full bounce.
const BUMPER_KICK = 60;
// A hit into a wall this fast or more gets the wall tone.
const FIRM_HIT = 60;
export const MAX_STROKES = 8;
// How long the scorecard waits between holes before moving on by itself.
export const CARD_MS = 1500;
// The power-ups: a pad the rolling ball runs over is held for the next putt,
// and that putt alone gets its help. One is held at a time; a new pad
// replaces the one held. A held power-up carries over to the next hole.
export const POWERUPS = Object.freeze({
doubloon: Object.freeze({ name: "Lucky Doubloon", blurb: "the next putt is free" }),
cannon: Object.freeze({ name: "Cannonball", blurb: "the next putt fires 1.6x as hard" }),
ghost: Object.freeze({ name: "Ghost Ball", blurb: "the next putt floats over water, sand and bumpers" }),
magnet: Object.freeze({ name: "Parrot Magnet", blurb: "the next putt homes in on the cup" }),
bouncy: Object.freeze({ name: "Rubber Duck", blurb: "the next putt bounces off walls at full speed" }),
bigcup: Object.freeze({ name: "Treasure Map", blurb: "the next putt aims at a HUGE cup" }),
spyglass: Object.freeze({ name: "Spyglass", blurb: "see where the next putt will roll" }),
});
export const CANNON_BOOST = 1.6;
export const BIG_CUP = 2.4;
// The magnet turns the ball toward the cup inside this reach, by up to this
// many radians a second, never adding speed, so a ball under it still stops.
export const MAGNET_R = 110;
const MAGNET_TURN = 7;
// The magnet and the big cup let a faster ball drop.
const HELPED_CAPTURE = 1.7;
// How far ahead the spyglass looks, in ms of rolling.
const PREDICT_MS = 3000;
// The swing. A press starts the power meter and a second sets the power. The
// needle runs from empty to past full and back once every METER_MS, slow at
// the bottom and fast at the top (METER_CURVE), so a soft putt is easy to
// catch and a full one is not. The MAX band, just under full, putts
// MAX_BOOST as hard. Past full is the overswing: OVER_POWER, pulled off line
// by up to OVER_PULL, the more the deeper into it.
export const METER_MS = 1750;
const METER_CURVE = 1.6;
export const MAX_BAND = 0.12;
export const MAX_BOOST = 1.15;
export const OVER_BAND = 0.1;
export const OVER_POWER = 0.7;
const OVER_PULL = (14 * Math.PI) / 180;
// The softest putt a press can set.
const MIN_POWER = 0.03;
// The shot clock: a ball this long at rest starts the meter by itself, and a
// meter left running METER_TRIPS trips dribbles the ball off at DRIBBLE_POWER.
export const SHOT_CLOCK_MS = 6000;
export const METER_TRIPS = 3;
const DRIBBLE_POWER = 0.06;
// Holding the action key or the pointer down while the ball rolls plays the
// roll this many times as fast.
export const FAST_FORWARD = 3;
// Keyboard aiming: a press nudges the aim by AIM_NUDGE, and held, it turns
// from TURN_SLOW up to TURN_FAST radians a second over TURN_RAMP_MS.
const AIM_NUDGE = Math.PI / 180;
const TURN_SLOW = (35 * Math.PI) / 180;
const TURN_FAST = (220 * Math.PI) / 180;
const TURN_RAMP_MS = 700;
// Below this many CSS pixels the course is too small to play.
export const MIN_W = 320;
export const MIN_H = 240;
// How many recent positions the rolling ball's trail keeps.
const TRAIL = 12;
// How long a popped-up word stays on the board, in ms of the round's clock.
const TOAST_MS = 1300;
/* --------------------------------------------------------------- geometry */
const dist = (ax, ay, bx, by) => Math.hypot(ax - bx, ay - by);
export function inPolygon(points, x, y) {
let inside = false;
for (let i = 0, j = points.length - 1; i < points.length; j = i++) {
const a = points[i];
const b = points[j];
if ((a.y > y) !== (b.y > y) && x < ((b.x - a.x) * (y - a.y)) / (b.y - a.y) + a.x) inside = !inside;
}
return inside;
}
const inRect = (r, x, y) => x >= r.x && x <= r.x + r.w && y >= r.y && y <= r.y + r.h;
// The point on segment a-b closest to p.
function closest(x1, y1, x2, y2, px, py) {
const dx = x2 - x1;
const dy = y2 - y1;
const len = dx * dx + dy * dy;
const t = len ? Math.max(0, Math.min(1, ((px - x1) * dx + (py - y1) * dy) / len)) : 0;
return { x: x1 + t * dx, y: y1 + t * dy };
}
// A spinner's bar as a segment at the round's clock.
export function spinnerEnds(s, clockMs) {
const a = s.speed * (clockMs / 1000);
const cx = Math.cos(a) * s.arm;
const cy = Math.sin(a) * s.arm;
return { x1: s.x - cx, y1: s.y - cy, x2: s.x + cx, y2: s.y + cy };
}
// A mover's center and velocity at the round's clock: a smooth swing either
// side of where it rests.
export function moverAt(m, clockMs) {
const turn = (2 * Math.PI) / m.period;
const a = turn * clockMs + 2 * Math.PI * (m.phase || 0);
const s = Math.sin(a);
const c = Math.cos(a) * turn * 1000;
return { x: m.x + m.dx * s, y: m.y + m.dy * s, vx: m.dx * c, vy: m.dy * c, r: m.r };
}
// How far through its period a gate is, 0 to 1, and whether it is shut.
export const gatePhase = (g, clockMs) => (((clockMs / g.period + (g.offset || 0)) % 1) + 1) % 1;
export const gateShut = (g, clockMs) => gatePhase(g, clockMs) >= g.open;
export const onSlope = (hole, x, y) => hole.slopes.some((s) => inPolygon(s.points, x, y));
export const inSand = (hole, x, y) => hole.sand.some((p) => inPolygon(p, x, y));
export const onBridge = (hole, x, y) => hole.bridges.some((r) => inRect(r, x, y));
export const inWater = (hole, x, y) => hole.water.some((p) => inPolygon(p, x, y)) && !onBridge(hole, x, y);
/* ------------------------------------------------------------------ rules */
const parTotal = (upTo) => HOLES.slice(0, upTo).reduce((n, h) => n + h.par, 0);
// The ball at rest, waiting for a putt: the shot clock starts again and the
// aim turns back toward the cup, so a straight putt needs no aiming at all.
function atRest(round) {
const hole = HOLES[round.hole];
round.phase = "aim";
round.restMs = 0;
round.aimAngle = Math.atan2(hole.cup.y - round.ball.y, hole.cup.x - round.ball.x);
}
function placeOnTee(round) {
const hole = HOLES[round.hole];
round.ball = { x: hole.tee.x, y: hole.tee.y, vx: 0, vy: 0, moving: false };
round.from = { x: hole.tee.x, y: hole.tee.y };
round.strokes = 0;
round.putts = 0;
round.tunnelLock = null;
round.trail = [];
round.active = null;
round.taken = [];
round.holeStart = round.clock;
atRest(round);
}
// Hole 1, the ball on its tee, nothing scored. `phase` is "aim" (the ball at
// rest, waiting for a putt), "swing" (the power meter running), "rolling",
// "card" (the scorecard between holes) or "done" (the round is over).
// `restMs` is how long the ball has waited (the shot clock), `swingMs` how
// long the meter has run, `swingAngle` the aim it locked, and `lastSwing`
// where the needle stopped last time. `held` is the power-up waiting for the
// next putt, `active` the one helping the putt in play, and `taken` the pads
// this hole has used up.
export function newRound() {
const round = {
hole: 0,
card: [],
clock: 0,
cardMs: 0,
sunk: null,
swingMs: 0,
swingAngle: 0,
lastSwing: null,
held: null,
};
placeOnTee(round);
return round;
}
// Every finished hole's strokes plus the hole in play.
export const total = (round) => round.card.reduce((n, s) => n + s, 0) + (round.phase === "card" || round.phase === "done" ? 0 : round.strokes);
// Against par for the holes played so far, the one in play counted once it is
// finished: negative is under par.
export const toPar = (round) => round.card.reduce((n, s) => n + s, 0) - parTotal(round.card.length);
// Putts from where the ball rests: power 0 to MAX_BOOST of STRIKE_SPEED, at
// an angle in radians (0 is along +x). A held power-up goes into this putt.
// Returns whether a putt was taken (a Lucky Doubloon putt is taken but not
// counted).
export function strike(round, angle, power) {
if ((round.phase !== "aim" && round.phase !== "swing") || round.ball.moving || !(power > 0)) return false;
round.active = round.held;
round.held = null;
const boost = round.active === "cannon" ? CANNON_BOOST : 1;
const speed = STRIKE_SPEED * Math.min(MAX_BOOST, power) * boost;
const ball = round.ball;
round.from = { x: ball.x, y: ball.y };
ball.vx = Math.cos(angle) * speed;
ball.vy = Math.sin(angle) * speed;
ball.moving = true;
round.putts += 1;
if (round.active !== "doubloon") round.strokes += 1;
round.phase = "rolling";
round.trail = [];
return true;
}
// The needle `ms` into a swing: from 0 (empty) up to 1 + OVER_BAND (the top
// of the overswing) and back, once every METER_MS.
export function meterAt(ms) {
const t = ((ms % METER_MS) + METER_MS) % METER_MS / METER_MS;
const u = t < 0.5 ? t * 2 : 2 - t * 2;
return (1 + OVER_BAND) * u ** METER_CURVE;
}
export const meterZone = (pos) => (pos > 1 ? "over" : pos >= 1 - MAX_BAND ? "max" : "normal");
// What a press at needle `pos` puts on a ball aimed at `angle`: { zone,
// angle, power }. An overswing pulls left and right on alternate putts (`n`),
// so the same swing always goes the same way.
export function swingShot(pos, angle, n) {
const zone = meterZone(pos);
if (zone === "max") return { zone, angle, power: MAX_BOOST };
if (zone === "over") {
const depth = Math.min(1, (pos - 1) / OVER_BAND);
return { zone, angle: angle + (n % 2 ? 1 : -1) * (0.4 + 0.6 * depth) * OVER_PULL, power: OVER_POWER };
}
return { zone, angle, power: Math.max(MIN_POWER, pos) };
}
// Starts the power meter on a ball at rest, the aim locked where it points.
export function startSwing(round) {
if (round.phase !== "aim" || round.ball.moving) return false;
round.phase = "swing";
round.swingMs = 0;
round.swingAngle = round.aimAngle;
return true;
}
// Sets the power where the needle is and putts. Returns the shot swingShot()
// made of it, or null when no meter was running.
export function setPower(round) {
if (round.phase !== "swing") return null;
const pos = meterAt(round.swingMs);
const shot = swingShot(pos, round.swingAngle, round.putts);
if (!strike(round, shot.angle, shot.power)) return null;
round.lastSwing = pos;
return shot;
}
// The scorecard for a finished hole, or the end of the round after the last.
// A water penalty on the last stroke can take the count past the cap, so the
// hole in play is capped too, not only its card entry. A hole always scores
// at least 1, however many doubloons went into it.
function finishHole(round, strokes, events) {
round.strokes = Math.max(1, Math.min(round.strokes, MAX_STROKES));
round.card.push(Math.max(1, Math.min(strokes, MAX_STROKES)));
round.ball.vx = 0;
round.ball.vy = 0;
round.ball.moving = false;
round.active = null;
round.cardMs = 0;
round.phase = round.hole === HOLES.length - 1 ? "done" : "card";
if (round.phase === "done") events.push("done");
}
// Leaves the scorecard for the next hole's tee.
export function nextHole(round) {
if (round.phase !== "card") return false;
round.hole += 1;
round.sunk = null;
placeOnTee(round);
return true;
}
// The ball off a fixed segment or a moving bar: pushed clear, and bounced
// with `keep` of its speed into the surface. `sx`, `sy` is how fast the
// surface itself moves at the contact (a spinner), 0 for a wall.
function bounceOffSegment(ball, seg, events, keep = WALL_KEEP, sx = 0, sy = 0) {
const p = closest(seg.x1, seg.y1, seg.x2, seg.y2, ball.x, ball.y);
let nx = ball.x - p.x;
let ny = ball.y - p.y;
let d = Math.hypot(nx, ny);
if (d >= BALL_R) return false;
if (d === 0) {
// Dead on the line: back out the way it came, or, at rest, square off it.
const v = Math.hypot(ball.vx, ball.vy);
const len = Math.hypot(seg.x2 - seg.x1, seg.y2 - seg.y1) || 1;
nx = v ? -ball.vx / v : -(seg.y2 - seg.y1) / len;
ny = v ? -ball.vy / v : (seg.x2 - seg.x1) / len;
d = 1;
} else {
nx /= d;
ny /= d;
}
ball.x = p.x + nx * BALL_R;
ball.y = p.y + ny * BALL_R;
const into = (ball.vx - sx) * nx + (ball.vy - sy) * ny;
if (into < 0) {
ball.vx -= (1 + keep) * into * nx;
ball.vy -= (1 + keep) * into * ny;
if (-into >= FIRM_HIT) events.push("wall");
}
return true;
}
// A ball off a round bumper, standing or moving at (bvx, bvy): a full bounce
// plus a kick.
function bounceOffRound(ball, b, events, bvx = 0, bvy = 0) {
let nx = ball.x - b.x;
let ny = ball.y - b.y;
const d = Math.hypot(nx, ny);
if (d >= b.r + BALL_R || d === 0) return false;
nx /= d;
ny /= d;
ball.x = b.x + nx * (b.r + BALL_R);
ball.y = b.y + ny * (b.r + BALL_R);
const into = (ball.vx - bvx) * nx + (ball.vy - bvy) * ny;
if (into < 0) {
ball.vx -= 2 * into * nx;
ball.vy -= 2 * into * ny;
}
ball.vx += nx * BUMPER_KICK;
ball.vy += ny * BUMPER_KICK;
events.push("bump");
return true;
}
// Sets a resting ball that something knocked off rolling.
function knocked(round) {
const ball = round.ball;
if (!ball.moving && Math.hypot(ball.vx, ball.vy) >= STOP_SPEED) {
ball.moving = true;
round.phase = "rolling";
}
}
// What moves by itself sweeps a resting ball too, so this runs on every step:
// spinners' bars, movers and shut gates. A ghost ball slips through movers.
function sweepers(round, hole, events) {
const ball = round.ball;
for (const s of hole.spinners) {
const seg = spinnerEnds(s, round.clock);
const p = closest(seg.x1, seg.y1, seg.x2, seg.y2, ball.x, ball.y);
// The bar's own speed where it touches: the turn rate times the distance
// from the center, at right angles to it.
const sx = -s.speed * (p.y - s.y);
const sy = s.speed * (p.x - s.x);
if (bounceOffSegment(ball, seg, events, WALL_KEEP, sx, sy)) knocked(round);
}
if (round.active !== "ghost") {
for (const m of hole.movers) {
const at = moverAt(m, round.clock);
if (bounceOffRound(ball, at, events, at.vx, at.vy)) knocked(round);
}
}
for (const g of hole.gates) {
if (gateShut(g, round.clock)) bounceOffSegment(ball, g, events, wallKeep(round));
}
}
const wallKeep = (round) => (round.active === "bouncy" ? 1 : WALL_KEEP);
function tunnels(round, hole, events) {
const ball = round.ball;
if (round.tunnelLock) {
// Out of the mouth it came from before it can go in again.
if (dist(ball.x, ball.y, round.tunnelLock.x, round.tunnelLock.y) < TUNNEL_R) return;
round.tunnelLock = null;
}
for (const t of hole.tunnels) {
for (const [from, to] of [[t.a, t.b], [t.b, t.a]]) {
if (dist(ball.x, ball.y, from.x, from.y) < TUNNEL_R) {
ball.x = to.x;
ball.y = to.y;
round.tunnelLock = to;
round.trail = [];
events.push("tunnel");
return;
}
}
}
}
// A pad the ball runs over is used up for the hole and held for the next putt.
function powerups(round, hole, events) {
const ball = round.ball;
hole.powerups.forEach((p, i) => {
if (round.taken.includes(i) || dist(ball.x, ball.y, p.x, p.y) >= POWERUP_R) return;
round.taken.push(i);
round.held = p.kind;
events.push("powerup");
});
}
// The magnet bends the ball's path toward the cup without speeding it up.
function magnet(round, hole, dt) {
const ball = round.ball;
const speed = Math.hypot(ball.vx, ball.vy);
const dx = hole.cup.x - ball.x;
const dy = hole.cup.y - ball.y;
const d = Math.hypot(dx, dy);
if (!speed || !d || d > MAGNET_R) return;
const pull = MAGNET_TURN * dt * (1 - d / MAGNET_R) * speed;
const vx = ball.vx + (dx / d) * pull;
const vy = ball.vy + (dy / d) * pull;
const v = Math.hypot(vx, vy) || 1;
ball.vx = (vx / v) * speed;
ball.vy = (vy / v) * speed;
}
// The hole is over at MAX_STROKES without the ball in the cup: picked up.
function pickUpAtCap(round, events) {
if (round.strokes < MAX_STROKES) return;
events.push("pickup");
finishHole(round, MAX_STROKES, events);
}
// How wide the cup is, and how slow a ball must be to drop, for this putt.
export const cupReach = (round) => CUP_R * (round.active === "bigcup" ? BIG_CUP : 1);
const captureSpeed = (round) => CAPTURE_SPEED * (round.active === "bigcup" || round.active === "magnet" ? HELPED_CAPTURE : 1);
// One physics step of `dtMs` (SUB_STEP_MS from tick()). Returns what happened,
// as event names: "clock" (the shot clock started the meter), "dribble" (the
// meter ran out), "wall", "bump", "tunnel", "powerup", "splash", "cup",
// "ace", "stop", "pickup", "done", "hole".
export function advance(round, dtMs) {
const events = [];
if (round.phase === "done") return events;
round.clock += dtMs;
if (round.phase === "card") {
round.cardMs += dtMs;
if (round.cardMs >= CARD_MS && nextHole(round)) events.push("hole");
return events;
}
const hole = HOLES[round.hole];
const ball = round.ball;
const dt = dtMs / 1000;
const ghost = round.active === "ghost";
sweepers(round, hole, events);
if (!ball.moving) {
if (round.phase === "aim") {
round.restMs += dtMs;
if (round.restMs >= SHOT_CLOCK_MS && startSwing(round)) events.push("clock");
} else if (round.phase === "swing") {
round.swingMs += dtMs;
if (round.swingMs >= METER_TRIPS * METER_MS) {
strike(round, round.swingAngle, DRIBBLE_POWER);
events.push("dribble");
return events;
}
}
// A ball left on a slope rolls off it by itself.
if (!onSlope(hole, ball.x, ball.y)) return events;
ball.moving = true;
round.phase = "rolling";
}
for (const s of hole.slopes) {
if (inPolygon(s.points, ball.x, ball.y)) {
ball.vx += s.push.x * dt;
ball.vy += s.push.y * dt;
}
}
let speed = Math.hypot(ball.vx, ball.vy);
const top = round.active === "cannon" ? CANNON_MAX : MAX_SPEED;
if (speed > 0) {
const slow = (FRICTION + DRAG * speed) * (!ghost && inSand(hole, ball.x, ball.y) ? SAND_FACTOR : 1) * dt;
const next = Math.min(top, Math.max(0, speed - slow));
ball.vx *= next / speed;
ball.vy *= next / speed;
speed = next;
}
if (round.active === "magnet") magnet(round, hole, dt);
ball.x += ball.vx * dt;
ball.y += ball.vy * dt;
for (const w of hole.walls) bounceOffSegment(ball, w, events, wallKeep(round));
if (!ghost) for (const b of hole.bumpers) bounceOffRound(ball, b, events);
sweepers(round, hole, events);
speed = Math.hypot(ball.vx, ball.vy);
if (speed > top) {
ball.vx *= top / speed;
ball.vy *= top / speed;
speed = top;
}
tunnels(round, hole, events);
powerups(round, hole, events);
round.trail.push({ x: ball.x, y: ball.y });
if (round.trail.length > TRAIL) round.trail.shift();
if (dist(ball.x, ball.y, hole.cup.x, hole.cup.y) < cupReach(round) && speed < captureSpeed(round)) {
events.push(round.putts === 1 ? "ace" : "cup");
round.sunk = { x: ball.x, y: ball.y };
ball.x = hole.cup.x;
ball.y = hole.cup.y;
finishHole(round, round.strokes, events);
return events;
}
const stopping = speed < STOP_SPEED && !onSlope(hole, ball.x, ball.y);
// A ghost ball floats over water, but not once it runs out of puff there.
if (inWater(hole, ball.x, ball.y) && (!ghost || stopping)) {
events.push("splash");
round.strokes += 1;
ball.x = round.from.x;
ball.y = round.from.y;
ball.vx = 0;
ball.vy = 0;
ball.moving = false;
atRest(round);
round.active = null;
round.tunnelLock = null;
round.trail = [];
pickUpAtCap(round, events);
return events;
}
if (stopping) {
ball.vx = 0;
ball.vy = 0;
ball.moving = false;
atRest(round);
round.active = null;
events.push("stop");
pickUpAtCap(round, events);
}
return events;
}
// Where a putt at `angle` and `power` would roll from the ball as it rests
// now, as points along its path (null where a tunnel jumps it), for the
// spyglass. Plays a copy of the round, so the round itself never changes.
export function predictPath(round, angle, power) {
const sim = structuredClone(round);
// The spyglass itself goes into the putt and does nothing to the roll.
if (sim.held === "spyglass") sim.held = null;
if (!strike(sim, angle, power)) return [];
const points = [{ x: sim.ball.x, y: sim.ball.y }];
for (let t = 0, n = 0; t < PREDICT_MS && sim.phase === "rolling"; t += SUB_STEP_MS, n++) {
const events = advance(sim, SUB_STEP_MS);
if (events.includes("splash")) break;
if (events.includes("tunnel")) points.push(null);
if (n % 5 === 0 || sim.phase !== "rolling") points.push({ x: sim.ball.x, y: sim.ball.y });
}
return points;
}
/* ------------------------------------------------------------------ gags */
// The words that pop up on the board, picked by a count so the same round
// always says the same things.
const SPLASH_WORDS = Object.freeze({
sea: ["SPLOOSH! Davy Jones says thanks", "Shark snack! Yum", "Man overboard!"],
pool: ["Bloop!", "Glub glub glub", "Something down there liked that"],
lava: ["SIZZLE! Extra crispy", "Toasty!", "Marshmallow, anyone?"],
chasm: ["Aaaaaaaaa...", "Bye bye, ball!", "Still falling..."],
});
const BUMP_WORDS = Object.freeze({
pirate: ["Bonk!", "Arr!", "Clunk!", "Yo ho!"],
cave: ["Boing!", "Clang!", "Ping!", "Bwomp!"],
});
const TUNNEL_WORDS = ["Whoosh!", "Wheee!", "Where'd it go?!"];
const MAX_WORDS = ["MAX POWER!", "CRUSHED IT!", "KA-BLAM!"];
const SHANK_WORDS = ["Overswing! Shanked it", "Whoa, too hard!", "Wild swing!"];
const DRIBBLE_WORDS = ["Too slow! Dribbled it", "Asleep at the tiller!", "Zzz... plop"];
const pick = (list, n) => list[n % list.length];
/* --------------------------------------------------------------- contract */
const TONE_FOR = Object.freeze({ wall: "wall", bump: "bump", cup: "cup", ace: "ace", tunnel: "tunnel", powerup: "power" });
const SPLASH_TONE = Object.freeze({ sea: "splash", pool: "splash", lava: "sizzle", chasm: "fall" });
function create({ canvas, tone = () => {}, onScore = () => {} }) {
const ctx = canvas.getContext("2d");
let colors = null;
let round = newRound();
let state = "ready";
let scale = 1;
let carry = 0;
// How long each arrow has been held, in ms (0 is up), and whether the roll
// is being fast-forwarded (the action key or the pointer held down).
const held = { left: 0, right: 0 };
let fast = false;
// Words popped up on the board, and how many of each kind so far.
let toasts = [];
let said = 0;
let lastBump = -Infinity;
// The ball is at rest on a hole and waiting for a putt.
const aiming = () => state === "running" && round.phase === "aim";
const say = (text, x, y, big = false) => {
toasts.push({ text, x, y, at: round.clock, big });
said += 1;
};
// A round on screen: running, or paused where it stood.
const live = () => state === "running" || state === "paused";
// The aim in play, or null: { angle, needle, zone }, with the needle and
// its zone only while the meter runs. Shown from the start of each hole, so
// the first press is never blind.
const currentAim = () => {
if (!live()) return null;
if (round.phase === "aim") return { angle: round.aimAngle, needle: null, zone: null };
if (round.phase !== "swing") return null;
const needle = meterAt(round.swingMs);
return { angle: round.swingAngle, needle, zone: meterZone(needle) };
};
// What the drawing needs of this moment, worked out here so golf-draw.js
// decides nothing.
const view = () => {
const hole = HOLES[round.hole];
const ball = round.ball;
const aimView = currentAim();
const card = round.phase === "card";
// The ball waits for a putt: aimed, or the meter running.
const waiting = round.phase === "aim" || round.phase === "swing";
toasts = toasts.filter((t) => round.clock - t.at < TOAST_MS);
// The spyglass follows the needle: the roll this press would make.
const spyShot = aimView && aimView.needle !== null && round.held === "spyglass" ? swingShot(aimView.needle, aimView.angle, round.putts) : null;
const spy = spyShot ? predictPath(round, spyShot.angle, spyShot.power) : null;
return {
course: { w: COURSE_W, h: COURSE_H },
hole,
holeNo: round.hole + 1,
clock: round.clock,
holeMs: round.clock - round.holeStart,
spinners: hole.spinners.map((s) => ({ ...spinnerEnds(s, round.clock), x: s.x, y: s.y, look: s.look })),
movers: hole.movers.map((m) => ({ ...moverAt(m, round.clock), look: m.look })),
gates: hole.gates.map((g) => ({ ...g, shut: gateShut(g, round.clock), phase: gatePhase(g, round.clock) })),
pads: hole.powerups.map((p, i) => ({ ...p, taken: round.taken.includes(i) })),
ball,
ballR: BALL_R,
cupR: CUP_R,
// The cup as this putt, or the one being aimed, will find it.
cupDraw: round.active === "bigcup" || (round.held === "bigcup" && waiting) ? CUP_R * BIG_CUP : CUP_R,
magnetR: round.active === "magnet" || (round.held === "magnet" && waiting) ? MAGNET_R : 0,
tunnelR: TUNNEL_R,
padR: POWERUP_R,
trail: round.phase === "rolling" ? round.trail : [],
aim: aimView,
// The power meter while it runs: the needle, the top of the overswing,
// where the MAX band starts, where the last swing stopped, and the
// trips left before the ball dribbles.
meter: aimView && aimView.needle !== null
? { needle: aimView.needle, zone: aimView.zone, top: 1 + OVER_BAND, maxFrom: 1 - MAX_BAND, last: round.lastSwing, tripsLeft: METER_TRIPS - Math.floor(round.swingMs / METER_MS) }
: null,
// The shot clock's share left, 1 to 0, while the ball waits.
shotClock: live() && round.phase === "aim" ? Math.max(0, 1 - round.restMs / SHOT_CLOCK_MS) : null,
fast: fast && round.phase === "rolling" ? FAST_FORWARD : 0,
spy,
held: round.held ? { kind: round.held, ...POWERUPS[round.held] } : null,
active: round.active,
toasts: toasts.map((t) => ({ ...t, age: (round.clock - t.at) / TOAST_MS })),
// A picked-up ball is simply gone; a sunk one shrinks into the cup.
sinking: card ? (round.sunk ? Math.min(1, round.cardMs / 350) : 1) : null,
phase: round.phase,
cardMs: round.cardMs,
card: HOLES.map((h, i) => ({ par: h.par, strokes: i < round.card.length ? round.card[i] : null })),
frontNine: FRONT_NINE,
// The card after the front nine heads into the caves.
turn: card && round.hole === FRONT_NINE - 1,
total: total(round),
parTotal: parTotal(HOLES.length),
toPar: toPar(round),
strokes: round.strokes,
pickedUp: card && !round.sunk,
ace: card && round.sunk !== null && round.card.at(-1) === 1,
state,
colors,
};
};
const paint = () => {
if (!ctx) return;
colors ||= readColors(canvas);
drawCourse(ctx, view());
};
const start = () => {
colors = null;
round = newRound();
carry = 0;
held.left = 0;
held.right = 0;
fast = false;
toasts = [];
said = 0;
lastBump = -Infinity;
state = "running";
paint();
};
const play = (events) => {
const hole = HOLES[round.hole];
const { x, y } = round.ball;
for (const e of events) {
if (e === "splash") {
tone(SPLASH_TONE[hole.liquid] || "splash");
say(`${pick(SPLASH_WORDS[hole.liquid] || SPLASH_WORDS.sea, said)} (+1)`, x, y);
continue;
}
if (e === "clock") {
tone("swing");
say("Shot clock! Swing!", x, y - 14, true);
}
if (e === "dribble") {
tone("shank");
say(pick(DRIBBLE_WORDS, said), x, y - 12);
}
if (TONE_FOR[e]) tone(TONE_FOR[e]);
if (e === "bump" && round.clock - lastBump > 450) {
lastBump = round.clock;
say(pick(BUMP_WORDS[hole.theme] || BUMP_WORDS.pirate, said), x, y - 8);
}
if (e === "tunnel") say(pick(TUNNEL_WORDS, said), x, y - 8);
if (e === "powerup" && round.held) say(`${POWERUPS[round.held].name}!`, x, y - 10, true);
// High, over the scorecard that is about to show.
if (e === "ace") say(hole.theme === "cave" ? "HOLE IN ONE! The cave echoes: one... one... one..." : "SHIVER ME TIMBERS! HOLE IN ONE!", COURSE_W / 2, 54, true);
}
// A fast-forward ends with the roll.
if (round.phase !== "rolling") fast = false;
if (events.includes("done") && state === "running") {
state = "over";
onScore(total(round));
}
};
// The first press starts the meter, the second sets the power and putts.
const swing = () => {
if (round.phase === "aim") {
if (!startSwing(round)) return false;
tone("swing");
paint();
return true;
}
const shot = setPower(round);
if (!shot) return false;
const { x, y } = round.ball;
tone(round.active === "cannon" ? "boom" : "putt", 0.4 + 0.6 * Math.min(1, shot.power));
if (shot.zone === "max") {
tone("max");
say(pick(MAX_WORDS, said), x, y - 12, true);
}
if (shot.zone === "over") {
tone("shank");
say(pick(SHANK_WORDS, said), x, y - 12);
}
if (round.active && POWERUPS[round.active]) say(round.active === "doubloon" ? "Free putt!" : `${POWERUPS[round.active].name} away!`, x, y - (shot.zone === "normal" ? 12 : 26));
paint();
return true;
};
const skipCard = () => {
if (state !== "running" || round.phase !== "card") return false;
nextHole(round);
paint();
return true;
};
// Held arrows turn the aim, slowly at first and faster the longer they are
// held.
const turn = (ms) => {
const dir = (held.right ? 1 : 0) - (held.left ? 1 : 0);
const ramp = Math.min(1, Math.max(held.left, held.right) / TURN_RAMP_MS);
if (held.left) held.left += ms;
if (held.right) held.right += ms;
if (!dir || round.phase !== "aim") return;
round.aimAngle += dir * (TURN_SLOW + (TURN_FAST - TURN_SLOW) * ramp * ramp) * (ms / 1000);
};
return {
get score() {
return total(round);
},
get state() {
return state;
},
// Not part of the contract: the round in play, so the unit suite can set
// up a shot on any hole. The window never reads it.
get round() {
return round;
},
start,
pause() {
if (state !== "running") return;
state = "paused";
// Nothing held carries over a pause: its release may never arrive.
held.left = 0;
held.right = 0;
fast = false;
paint();
},
resume() {
if (state === "paused") state = "running";
},
key(name) {
if (name === "action") {
if (state === "ready" || state === "over") start();
else if (state === "paused") state = "running";
else if (skipCard()) return true;
else if (round.phase === "rolling") fast = true;
else swing();
return true;
}
if (name !== "left" && name !== "right") return false;
if (!aiming()) return false;
// A press nudges at once; the window's key repeats change nothing, as
// the hold already turns the aim each tick.
if (!held[name]) {
held[name] = 1;
round.aimAngle += (name === "left" ? -1 : 1) * AIM_NUDGE;
paint();
}
return true;
},
release(name) {
if (name === "action") fast = false;
else if (name === "left" || name === "right") held[name] = 0;
else return false;
return true;
},
pointer(type, x, y) {
const cx = x / scale;
const cy = y / scale;
// The aim points from the ball at the pointer, wherever it is.
const aimAt = () => {
const { ball } = round;
if (!aiming() || Math.hypot(cx - ball.x, cy - ball.y) < 1) return false;
round.aimAngle = Math.atan2(cy - ball.y, cx - ball.x);
return true;
};
if (type === "up" || type === "cancel") {
fast = false;
return true;
}
if (type === "move") {
if (!aimAt()) return false;
paint();
return true;
}
if (type !== "down") return false;
if (state === "ready" || state === "over") {
start();
return true;
}
if (state !== "running") return false;
if (skipCard()) return true;
if (round.phase === "rolling") {
fast = true;
return true;
}
aimAt();
return swing();
},
tick(ms) {
if (state !== "running") return;
const step = Math.min(Math.max(0, ms), MAX_TICK_MS);
turn(step);
carry += step * (fast && round.phase === "rolling" ? FAST_FORWARD : 1);
while (carry >= SUB_STEP_MS && state === "running") {
carry -= SUB_STEP_MS;
play(advance(round, SUB_STEP_MS));
}
paint();
},
resize(w, h) {
if (!(w >= MIN_W && h >= MIN_H)) return false;
scale = Math.min(w / COURSE_W, h / COURSE_H);
colors = null;
const ratio = (typeof devicePixelRatio === "number" && devicePixelRatio > 0) ? devicePixelRatio : 1;
const cssW = COURSE_W * scale;
const cssH = COURSE_H * scale;
canvas.width = Math.round(cssW * ratio);
canvas.height = Math.round(cssH * ratio);
if (canvas.style) {
canvas.style.width = `${cssW}px`;
canvas.style.height = `${cssH}px`;
}
// Everything is drawn in course units.
if (ctx && typeof ctx.setTransform === "function") ctx.setTransform(ratio * scale, 0, 0, ratio * scale, 0, 0);
paint();
return true;
},
};
}
export default Object.freeze({ id: "golf", title: "Mini golf", lowerIsBetter: true, create });
File diff suppressed because it is too large. Load diff
+43
View File
@@ -695,6 +695,49 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
return off(rule.greyed[taken] || (lookup(taken)?.finished && rule.greyed.finished) || rule.greyed.default);
}
// The cards whose confirm pane offers "Start with a note from your Notebook"
// on Start fresh: the three that open on an idea box.
const NOTE_FRESH_CARDS = new Set(["plan2code-0-pathfinder", "plan2code-1-plan", "plan2code-quick-task"]);
/**
* Whether a lit card's confirm pane offers the Notebook switch: Pathfinder,
* Plan and Quick Task on Start fresh (no spec picked), and Revise plan on a
* picked spec with no plan change brief waiting (a waiting brief is what that
* revision is about). Never on a grayed card, never on any other card.
*/
export function noteSwitchShows(entry, scan, sel) {
if (!entry || !cardAvailability(entry, scan, sel).on) return false;
if (NOTE_FRESH_CARDS.has(entry.skill)) return !sel;
if (entry.skill === "plan2code-1b-revise-plan") return Boolean(sel) && sel.planChange !== true;
return false;
}
// A Notebook tab's text over this many UTF-8 bytes gets a "Long tab" note in
// the confirm pane's preview, so the person can trim it before it is sent.
export const NOTE_LONG_BYTES = 51200;
/** Whether a Notebook tab, as GET /notepad?tab= reads it, holds nothing to send. */
export function noteTabEmpty(tab) {
const text = tab && typeof tab.text === "string" ? tab.text : "";
const images = tab && Array.isArray(tab.images) ? tab.images : [];
return text.trim() === "" && images.length === 0;
}
/** The pictures ticked when a tab is first picked: its first MAX_ATTACHMENTS, in its own order. */
export function defaultNoteTicks(images) {
return (Array.isArray(images) ? images : []).slice(0, MAX_ATTACHMENTS).map((img) => img.id);
}
/**
* The ticked ids after a click on `id`: unticked if it was ticked, else ticked
* while fewer than MAX_ATTACHMENTS are; past that the click changes nothing.
*/
export function toggleNoteTick(ticked, id) {
const list = Array.isArray(ticked) ? ticked : [];
if (list.includes(id)) return list.filter((t) => t !== id);
return list.length < MAX_ATTACHMENTS ? [...list, id] : list;
}
/**
* The spec a card's launch carries: the picker's selection for the cards that
* take a spec, and for Quick Task only a diagnosed bug, whose write-up it reads
+2 -1
View File
@@ -22,7 +22,7 @@ import {
adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
wireHelp, wireLooks, wireNotepad, wireWorkspace,
wireActivities, wireHelp, wireLooks, wireNotepad, wireWorkspace,
} from "./screens/core.js";
import { sound } from "./sound.js";
@@ -50,6 +50,7 @@ wireCleanup();
wireDocs();
wireAsk();
wireNotepad();
wireActivities();
wireChrome();
startClock();
+7 -6
View File
@@ -2,8 +2,8 @@
//
// The favicon follows the status line with a bar along its bottom edge: dashed
// amber while Plan2Code is busy, solid green when it is the person's move,
// solid red when it needs attention, and none (the plain Planny) once the
// session is finished. It reads from the same calls
// solid red when it needs attention, and none (the plain Planny) once nothing
// is left for anyone to do. It reads from the same calls
// renderStatus() already makes for Planny's mood, so the icon and the line
// beside him can never disagree. No DOM access at module scope: `node --test`
// imports this file.
@@ -26,12 +26,13 @@ export const FAVICON_COLORS = Object.freeze({
* handed to say(): `spin` marks something really happening at the other end
* right now, so that is busy. A working mood without the spin is the stale
* line ("has not checked in for a few minutes"), which, like adrift and gone,
* needs attention. `point` is the person's move. A finished session is plain
* unless it is visibly busy again (opening the dashboard, starting a review).
* needs attention. `point` is the person's move. A finished screen follows the
* same moods: it points while a press is still on offer (back to the
* dashboard, a review), is adrift when a press was never collected, and is
* `done` (plain) once nothing is left.
*/
export function faviconState({ mood, spin = false, finished = false } = {}) {
export function faviconState({ mood, spin = false } = {}) {
if (spin) return "busy";
if (finished) return "plain";
if (mood === "adrift" || mood === "gone" || mood === "work") return "attention";
if (mood === "point") return "ready";
return "plain";
+1
View File
@@ -25,6 +25,7 @@ export const HELP_TABS = Object.freeze([
tab("git", "The git board", false),
tab("subagents", "Helpers (subagents)", false),
tab("ask", "Ask a quick question", false),
tab("activities", "Activities", false),
tab("finishing", "Stopping and finishing", false),
tab("prefs", "Keyboard and preferences", false),
tab("privacy", "Privacy and where things are saved", false),
+199 -15
View File
@@ -35,6 +35,9 @@
<link rel="modulepreload" href="/screens/workspace.js" />
<link rel="modulepreload" href="/screens/ask.js" />
<link rel="modulepreload" href="/screens/notepad.js" />
<link rel="modulepreload" href="/screens/activities.js" />
<link rel="modulepreload" href="/activities.js" />
<link rel="modulepreload" href="/tones.js" />
<link rel="modulepreload" href="/net.js" />
<link rel="modulepreload" href="/render.js" />
<link rel="modulepreload" href="/palette.js" />
@@ -184,6 +187,19 @@
<path class="mg-line" d="M4.6 9.8l.9 3.4h1.6l-.6-2.7M12.4 6.1a2.6 2.6 0 0 1 0 3.8M13.8 4.5a5 5 0 0 1 0 7" />
</svg>
</a>
<!-- Activities: small games for a long wait. Opens a dialog that pauses
the moment Plan2Code needs the person; nothing in it reaches the agent. -->
<button type="button" class="icon-btn" id="btn-activities" title="Activities" aria-label="Activities">
<!-- A die: a rounded square and five pips. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
<rect class="dc-body" x="2" y="2" width="12" height="12" rx="2.6" />
<circle class="dc-pip" cx="5.4" cy="5.4" r="1" />
<circle class="dc-pip" cx="10.6" cy="5.4" r="1" />
<circle class="dc-pip" cx="8" cy="8" r="1" />
<circle class="dc-pip" cx="5.4" cy="10.6" r="1" />
<circle class="dc-pip" cx="10.6" cy="10.6" r="1" />
</svg>
</button>
</div>
<div class="topbar-row second">
<div class="row-left">
@@ -216,7 +232,8 @@
</svg>
</button>
<!-- Notebook: every screen, never hidden. The person's private notes for this
folder; nothing in it reaches the agent. -->
folder; a tab reaches the agent only through a send the person
starts on the dashboard. -->
<button type="button" class="btn ghost small notepad-btn" id="btn-notepad" title="Notebook" aria-label="Notebook">
<!-- A pocket notebook: a closed cover with a spine line and an elastic band. -->
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
@@ -778,6 +795,10 @@
<path d="M4 5h16v11H10l-4 4v-4H4z" />
<path d="M8 9.5h8M8 12.5h5" />
</symbol>
<symbol id="hi-activities" viewBox="0 0 24 24" fill="none">
<rect x="4" y="4" width="16" height="16" rx="3.5" />
<path d="M8.5 8.5h.01M15.5 8.5h.01M12 12h.01M8.5 15.5h.01M15.5 15.5h.01" />
</symbol>
<symbol id="hi-finishing" viewBox="0 0 24 24" fill="none">
<path d="M6 21V4" />
<path d="M6 4h11l-2 4 2 4H6" />
@@ -1144,16 +1165,20 @@
<li>
The <strong>?</strong> button opens this Help, and the gear button
beside it opens <strong>User Preferences</strong>: your role first,
then your colors, theme, card width and sounds.
then your colors, theme, card width, sounds and whether Activities shows.
</li>
<li class="for-browser">
The <strong>megaphone</strong> button at the far right opens GitHub in a
The <strong>megaphone</strong> button opens GitHub in a
new tab, where you can report a bug or suggest an idea.
</li>
<li class="for-app">
The <strong>megaphone</strong> button at the far right opens Plan2Code's
The <strong>megaphone</strong> button opens Plan2Code's
GitHub issues, where you can report a bug or suggest an idea.
</li>
<li>
The <strong>die</strong> beside it opens <strong>Activities</strong>,
small games to play while you wait. See "Activities".
</li>
<li>
<strong>Stop session</strong> ends the session and saves your place.
See "Stopping and finishing".
@@ -1248,8 +1273,16 @@
folder per tab on disk. There is no Save button.
</li>
<li>
It is private to this machine and never sent to Plan2Code. Nothing
in it is shown to the agent.
It is private to this machine and never sent to Plan2Code.
Private: the agent never reads your Notebook. A tab reaches it only
when you start a workflow with it.
</li>
<li>
A lit card's confirm pane can offer <strong>Start with a note from
your Notebook</strong>. On the dashboard, Pathfinder, Plan and Quick
Task offer it on Start fresh, and Revise plan on a picked spec with
no plan change waiting. A tab you started a workflow with wears a
small <strong>sent</strong> badge.
</li>
<li>
Two open pages on the same folder share one notebook. If both change
@@ -2253,7 +2286,120 @@
</p>
</section>
<!-- Tab 16: Stopping and finishing -->
<!-- Tab 16: Activities -->
<section class="help-panel" data-tab="activities">
<h3>Activities</h3>
<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. Two games ship: <strong>Snake</strong> and
<strong>Mini golf</strong>. Pick one with the buttons above the board;
the window opens on your last pick next time. Nothing you do in it
reaches Plan2Code.
</p>
<h4>The games</h4>
<ul>
<li>
<strong>Snake</strong>: steer to the food and grow. The snake speeds
up as it grows, and a wall, a rock, a comet or your own tail ends
the round. Food eaten quickly builds a combo of up to x5. Every 5
foods is a new level, and each of the first few brings something
new: rocks (a flashing cell turns to stone), mystery boxes, portals,
comets that cut your tail, then chaos. Power-ups turn up on their
own: Shield, Turbo, Slow-mo, Magnet, Ghost and Scissors, and a
mystery box can hold any of ten surprises, good or bad. The start
and end screens count how many of them you have found so far.
</li>
<li>
<strong>Mini golf</strong>: eighteen silly holes seen from above.
The front nine is <strong>Pirate Cove</strong>, greens afloat in a
shark sea with cannonballs, barrels, a kraken and a ghost ship. The
back nine is the <strong>Caves of Doom</strong>, lit only around
your ball, with lava, a bottomless pit, mine carts and stone
crushers. The aim follows your mouse. Click (or press
<kbd>Space</kbd>) to start the power meter, then click again to
set the power: the gold <strong>MAX</strong> band near the top
gives a boosted putt, but go past it into the red and you shank it.
Dawdle for 6 seconds and the meter starts by itself. Hold the mouse
button or <kbd>Space</kbd> while the ball rolls to speed it up.
Each hole has a par, and after 8
strokes the ball is picked up. The scorecard between holes shows how
the round stands against par.
</li>
<li>
<strong>Power-ups</strong>: roll over a glowing pad to hold it for
your next putt. A <strong>Lucky Doubloon</strong> makes it free, a
<strong>Cannonball</strong> fires it 1.6 times as hard, a
<strong>Ghost Ball</strong> floats over water, sand and bumpers, a
<strong>Parrot Magnet</strong> bends it toward the cup, a
<strong>Rubber Duck</strong> bounces off walls at full speed, a
<strong>Treasure Map</strong> makes the cup huge, and a
<strong>Spyglass</strong> shows where it will roll while the meter runs.
You hold one at a time, and it carries over to the next hole.
</li>
</ul>
<h4>It never hides your turn</h4>
<ul>
<li>
A new question, a sign-off or a finish pauses the game at once, and
a banner above the board says Plan2Code needs you.
<strong>Go to it</strong> closes the window on that question.
</li>
<li class="for-browser">
Switching to another tab, or clicking outside the page, also pauses it.
</li>
<li class="for-app">
Hiding the window, or clicking outside the page (the app's own bar
too), also pauses it.
</li>
<li>
Nothing resumes by itself. Any game key plays on, and so does a
click on the Mini golf board. Playing on puts the banner away until
the next new question.
</li>
<li>
Starting a round, and playing on after a pause, counts down 3, 2, 1
first, so the game never moves before you are ready.
</li>
</ul>
<h4>Keys</h4>
<ul>
<li>
Snake: the arrow keys, or <kbd>W</kbd> <kbd>A</kbd> <kbd>S</kbd>
<kbd>D</kbd>, steer.
</li>
<li>
Mini golf: hold left or right to turn the aim (faster the longer
you hold), press <kbd>Space</kbd> once to start the power meter and
again to set the power, and hold <kbd>Space</kbd> while the ball
rolls to speed it up.
</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>Esc</kbd> closes the window, with the game paused where it was.</li>
</ul>
<p>Activities need a keyboard: on a touch-only screen the window says so instead of showing the board.</p>
<h4>Best scores</h4>
<p>
The window's title shows the best for the game on screen, and the
line under the board shows it beside your score. For Snake the best
is your highest score; for Mini golf it is your lowest full round of
eighteen holes, and a round left halfway never counts.
<strong>Reset best scores</strong>, at the bottom of the window,
clears both after a second click to confirm.
</p>
<h4>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.
</p>
<p>
Best scores, Snake's surprises found, your last pick and that switch are saved privately on
this machine, with your other preferences, and never sent anywhere.
</p>
</section>
<!-- Tab 17: Stopping and finishing -->
<section class="help-panel" data-tab="finishing">
<h3>Stopping and finishing</h3>
<p class="help-lead">
@@ -2360,7 +2506,7 @@
</p>
</section>
<!-- Tab 17: Keyboard and preferences -->
<!-- Tab 18: Keyboard and preferences -->
<section class="help-panel" data-tab="prefs">
<h3>Keyboard and preferences</h3>
<p class="help-lead">
@@ -2441,6 +2587,11 @@
joining the strip. Keep only the ones you want; ticking a box plays
its sound.
</li>
<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.
</li>
<li>
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
lists what Plan2Code doesn't need in your
@@ -2457,7 +2608,9 @@
</li>
<li>
<strong>Back to default</strong> puts everything back as it was, and
sets Role back to Not set.
sets Role back to Not set. Your Activities best scores stay: only
<strong>Reset best scores</strong>, in the Activities window, clears
them.
</li>
</ul>
<p>
@@ -2481,7 +2634,7 @@
</ul>
</section>
<!-- Tab 18: Privacy and where things are saved -->
<!-- Tab 19: Privacy and where things are saved -->
<section class="help-panel" data-tab="privacy">
<h3>Privacy and where things are saved</h3>
<p class="help-lead">
@@ -2533,8 +2686,9 @@
and attachments");
</li>
<li>
your role, theme, colors, card width and sounds, in
<code>looks.json</code>;
your role, theme, colors, card width and sounds, the Show
Activities switch, the last activity you picked and your best
scores, in <code>looks.json</code>;
</li>
<li>
your Subagents switch for each project and skill, in
@@ -2620,6 +2774,11 @@
</div>
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
</fieldset>
<fieldset class="modal-ranges looks-activities">
<legend>Activities</legend>
<label><input type="checkbox" id="looks-activities" checked /> <span>Show Activities</span></label>
<p class="help">The die in the top bar opens small games to play while you wait.</p>
</fieldset>
<fieldset class="modal-ranges looks-cleanup">
<legend>Cleanup</legend>
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. It also lists this project's <code>specs--completed/</code> folders nobody has touched for 30 days; deleting one is permanent, since that folder is usually gitignored and git can't restore it. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
@@ -2744,11 +2903,12 @@
<!-- The Notebook: the person's own notes for this folder, autosaved under
~/.plan2code/notepads/ by the /notepad routes. Never part of the
session, so nothing in it reaches the agent. screens/notepad.js fills
the editor on open. -->
session, and the agent CLI never imports the store: a tab leaves it
only through a send the person starts on the dashboard. screens/notepad.js
fills the editor on open. -->
<dialog class="modal notepad" id="notepad-modal" aria-labelledby="notepad-title">
<h2 id="notepad-title">Notebook</h2>
<p class="modal-blurb">A private space to keep track of notes and uploaded images related to your in-progress work on this project. Saved on this machine and <strong class="private-note">never shared to the AI Agent</strong>.</p>
<p class="modal-blurb">A private space to keep track of notes and uploaded images related to your in-progress work on this project. Saved on this machine. <strong class="private-note">Private</strong>: the agent never reads your Notebook. A tab reaches it only when you start a workflow with it.</p>
<div class="notepad-tabbar">
<div class="notepad-tabs" id="notepad-tabs" role="tablist" aria-label="Notebook tabs"></div>
<button type="button" class="btn small ghost notepad-tab-new" id="notepad-tab-new">+ New tab</button>
@@ -2759,6 +2919,7 @@
</div>
<div class="notepad-body" id="notepad-body">
<div class="notepad-editor" id="notepad-editor"></div>
<p class="help notepad-sent" id="notepad-sent" hidden></p>
<div class="notepad-images" id="notepad-images">
<button type="button" class="btn small ghost notepad-add" id="notepad-add">Add image</button>
<input type="file" accept="image/*" multiple id="notepad-file" hidden />
@@ -2807,6 +2968,29 @@
</div>
</dialog>
<!-- Activities: small built-in games for a long wait. Play is private to
this page and never reaches the agent; screens/activities.js runs the
game, and pauses it whenever Plan2Code needs the person. -->
<dialog class="modal activities" id="activities-modal" aria-labelledby="activities-title">
<h2 id="activities-title">Activities<span id="activities-title-best" class="activities-title-best"></span></h2>
<p class="modal-blurb">Something to play while you wait. Private to this page, and it pauses whenever Plan2Code needs you.</p>
<div class="activities-banner" id="activities-banner" role="status" hidden>
<span class="activities-banner-text" id="activities-banner-text"></span>
<button type="button" class="btn small primary" id="activities-goto">Go to it</button>
</div>
<div class="activities-picker" id="activities-picker" role="group" aria-label="Pick an activity" hidden></div>
<div class="activities-board" id="activities-board" tabindex="-1">
<canvas id="activities-canvas"></canvas>
<div class="activities-overlay" id="activities-overlay"></div>
</div>
<p class="activities-score" id="activities-score"></p>
<p class="help activities-note" id="activities-note" aria-live="polite" hidden></p>
<div class="modal-actions">
<button type="button" class="btn ghost" id="activities-reset">Reset best scores</button>
<button type="button" class="btn ghost" id="activities-close">Close</button>
</div>
</dialog>
<!-- The Workspace: the folder this session started in plus any added as
context. The list is drawn by app.js from the frame's `workspace`;
every change goes through the server's /workspace routes. -->
+27 -2
View File
@@ -9,6 +9,7 @@ import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
import { bootData, hooks } from "./state.js";
import { el } from "./render.js";
import { tellApp } from "./app-bridge.js";
import { ACTIVITIES, bestKey, memoKey } from "./activities.js";
const $ = (id) => document.getElementById(id);
@@ -30,6 +31,13 @@ export const DEFAULT_LOOKS = {
...soundPrefs(null),
width: DEFAULT_CARD_WIDTH,
hideUnavailable: true,
// Activities: the top bar's die, the game last picked, and one best score
// per listed game (activityBestSnake), each a flat key for cleanLooks().
hideActivities: false,
lastActivity: "",
...Object.fromEntries(ACTIVITIES.map((a) => [bestKey(a.id), 0])),
// And one memo per game (activityMemoSnake): Snake's surprises found.
...Object.fromEntries(ACTIVITIES.map((a) => [memoKey(a.id), 0])),
};
export let looks = { ...DEFAULT_LOOKS };
@@ -46,6 +54,16 @@ export function adoptLooks(saved) {
Object.assign(looks, soundPrefs(looks));
if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable;
looks.width = cardWidth(looks.width);
if (typeof looks.hideActivities !== "boolean") looks.hideActivities = DEFAULT_LOOKS.hideActivities;
if (typeof looks.lastActivity !== "string") looks.lastActivity = DEFAULT_LOOKS.lastActivity;
// A best score is a whole number of points, never below none.
for (const a of ACTIVITIES) {
const key = bestKey(a.id);
const n = Number(looks[key]);
looks[key] = Number.isFinite(n) && n > 0 ? Math.floor(n) : 0;
const memo = Number(looks[memoKey(a.id)]);
looks[memoKey(a.id)] = Number.isFinite(memo) && memo > 0 ? Math.floor(memo) : 0;
}
if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role);
else delete looks.role;
}
@@ -212,10 +230,17 @@ export function renderSwatches() {
box.disabled = !looks.sound;
}
$("looks-role").value = looks.role ?? ROLE_NOT_SET;
$("looks-activities").checked = !looks.hideActivities;
}
// "Back to default": every look returns to its default, but the role is
// marked as asked and the welcome stays seen.
// marked as asked, the welcome stays seen, and the Activities' best scores
// and last pick stay (only Reset best scores clears those).
export function resetLooks() {
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
const kept = { lastActivity: looks.lastActivity };
for (const a of ACTIVITIES) {
kept[bestKey(a.id)] = looks[bestKey(a.id)];
kept[memoKey(a.id)] = looks[memoKey(a.id)];
}
looks = { ...DEFAULT_LOOKS, ...kept, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
}
+12 -2
View File
@@ -1,6 +1,6 @@
// Plan2Code Web Console - the Notebook's tab bar.
//
// Draws #notepad-tabs from a list of { id, name } and tells screens/notepad.js
// Draws #notepad-tabs from a list of { id, name, sent? } and tells screens/notepad.js
// what the person did: pick a tab (onSwitch), reorder with a drag, ask to
// rename (a double-click or F2) or ask to delete (the x beside the name, or the
// Delete key) (onChange). No fetches here: the screen owns every request, and
@@ -96,7 +96,17 @@ export function createTabs({ onSwitch, onChange }) {
x.addEventListener("click", () => onChange({ type: "delete", id: tab.id }));
const wrap = el("div", "notepad-tabwrap");
wrap.setAttribute("role", "presentation");
wrap.append(b, x);
wrap.append(b);
// A tab sent from the dashboard wears a small badge after its name, outside
// the button so a long name's ellipsis never cuts it; the button's name
// says it for a screen reader.
if (tab.sent) {
b.setAttribute("aria-label", tab.name + ", sent");
const badge = el("span", "notepad-sent-badge", "sent");
badge.setAttribute("aria-hidden", "true");
wrap.append(badge);
}
wrap.append(x);
wrap.addEventListener("dragover", (e) => {
if (dragging === null) return;
e.preventDefault();
+2
View File
@@ -25,6 +25,7 @@ export const ERROR_CODES = Object.freeze([
"too-many",
"not-found",
"bad-name",
"bad-sent",
"duplicate-name",
"too-many-tabs",
"no-such-tab",
@@ -136,6 +137,7 @@ const ERROR_SENTENCES = Object.freeze({
"too-many": `This notepad already holds ${NOTEPAD_MAX_IMAGES} pictures, the most it can keep. Delete one to add another.`,
"not-found": "That picture is no longer in this notepad.",
"bad-name": `A tab name needs 1 to ${TAB_NAME_MAX} characters, with no control characters.`,
"bad-sent": "Plan2Code could not record where that tab was sent, so nothing was changed.",
"duplicate-name": "There is already a tab with that name.",
"too-many-tabs": `This notepad already has ${NOTEPAD_MAX_TABS} tabs, the most it can have. Delete one to add another.`,
"no-such-tab": "That tab is no longer in this notepad.",
@@ -0,0 +1,714 @@
// Plan2Code Web Console - Activities: the top bar's die, its dialog, the frame timer, the keys and every pause rule.
//
// Small games for a long wait. The list of games is activities.js; each game
// is its own module under activities/, loaded with import() the first time it
// is opened, and answers the calls the list's header names. This file owns
// everything around a game: the dialog, the one frame timer, the keys and the
// pauses. A game never runs a timer of its own, so a paused game cannot move:
// pausing is this file not ticking plus the game's own paused state. Nothing
// here talks to the agent or the session; it only reads whose turn it is, so
// a question, a sign-off or a finish always pauses play and says so.
import { page, redraw } from "../state.js";
import { finish, myTurn } from "../selectors.js";
import { looks, saveLooks } from "../looks.js";
import { el, lightDismiss } from "../render.js";
import { ACTIVITIES, bestKey, memoKey } from "../activities.js";
import { tone, unlockTones } from "../tones.js";
const $ = (id) => document.getElementById(id);
const NOT_LOADED = "This activity could not be loaded. Close and open Activities to try again.";
const NEED_KEYBOARD = "Activities need a keyboard.";
const TOO_SMALL = "Make the window bigger to play.";
const TURN_BANNER = "Plan2Code needs you: a question is waiting.";
const FINISH_BANNER = "Plan2Code is finished.";
const RESET_LABEL = "Reset best scores";
const RESET_CONFIRM = "Reset? Click again";
// How long Reset waits for its second click before going back to its label.
const RESET_CONFIRM_MS = 4000;
// A frame that arrives after a long gap (a slow machine, a debugger) is
// counted as this much at most, so the snake never jumps several cells at once.
const MAX_FRAME_MS = 250;
// Every start and every play-on counts down 3, 2, 1 before the game moves,
// so a round never begins or picks up before the person is ready. The game
// is already running while the count shows; this file just does not tick it.
const COUNT_FROM = 3;
// The game keys: arrows and W/A/S/D steer, space is the game's action.
const KEYS = Object.freeze({
ArrowUp: "up",
ArrowDown: "down",
ArrowLeft: "left",
ArrowRight: "right",
w: "up",
s: "down",
a: "left",
d: "right",
" ": "action",
});
// The list the window shows, and where frames come from. Both are swapped
// only by the page tests (setActivityList, setTickSource).
let list = ACTIVITIES;
let tickSource = (fn) => requestAnimationFrame(fn);
// How long each number of the countdown shows, in ms. Swapped only by the
// page tests (setCountdownMs); 0 skips the countdown.
let countStepMs = 700;
// One game object per listed game for the page's life, so a closed and
// reopened window, or a skill change on the same page, resumes the same round.
const games = new Map();
// A load in flight per game id, so two quick opens share one import().
const loading = new Map();
let currentId = null;
// The games that keep their lowest round as the best (their export says
// lowerIsBetter), not their highest.
const lowerIsBetter = new Set();
// The frame timer. `gen` counts starts and stops, so a frame asked for before
// a stop does nothing when it arrives, whatever the tick source is.
let gen = 0;
let looping = false;
let lastFrame = null;
// The ms left of the countdown while one is showing, else 0. Game keys,
// clicks and presses on the board wait for it; P and Esc still pause.
let counting = 0;
// What renderActivities saw last time: the ids that were the person's to
// answer, and whether a finish was up. Null until the first render.
let seenTurn = null;
let seenFinish = false;
// Set when the person plays on after a turn or finish pause: the banner stays
// down until the next new question or finish.
let bannerDismissed = false;
// Reset's confirm: the timer that puts its label back, while one is waiting.
let resetTimer = null;
// Go to it closes the window onto a question, so the close must not hand
// focus back to the die.
let goingTo = false;
export function setTickSource(fn) {
tickSource = fn;
}
export function setCountdownMs(ms) {
countStepMs = ms;
}
export function setActivityList(next) {
list = next;
if (!list.some((e) => e.id === currentId)) currentId = null;
}
const game = () => (currentId ? games.get(currentId) || null : null);
/* ----------------------------------------------------------- the notes */
function showNote(text) {
const note = $("activities-note");
note.textContent = text;
note.hidden = !text;
}
const hasKeyboard = () => typeof matchMedia !== "function" || matchMedia("(any-pointer: fine)").matches;
/* ------------------------------------------------------------ drawing */
const best = (id) => looks[bestKey(id)] || 0;
// The header's " · Snake best: 12" for the game on screen, or "no best yet"
// before its first full round.
function paintTitle() {
const entry = list.find((e) => e.id === currentId);
const n = entry ? best(entry.id) : 0;
const text = entry ? (n ? ` · ${entry.title} best: ${n}` : ` · ${entry.title}: no best yet`) : "";
const span = $("activities-title-best");
if (span.textContent !== text) span.textContent = text;
}
// The round on screen, for the best-score effects: which game, the state it
// was last painted in, whether this round has passed the best (the sparks
// fire once a round), and whether its end set a new best.
const watched = { g: null, state: null, passed: false, record: false };
// A new round has begun when the game on screen changed, or went back to
// running from anything but a pause.
function watchRound(g) {
if (g !== watched.g || (g && g.state === "running" && watched.state !== "running" && watched.state !== "paused")) {
watched.passed = false;
watched.record = false;
}
watched.g = g;
watched.state = g ? g.state : null;
}
const SPARK_COLORS = Object.freeze(["#ff4fa3", "#f5b301", "#1fb6d9", "#57b54a", "#a466ff", "#ff8a1f"]);
const SPARKS = 22;
const SPARK_MS = 1100;
const calm = () => typeof matchMedia === "function" && matchMedia("(prefers-reduced-motion: reduce)").matches;
// A fan of colored sparks up out of the score line's chips. They live on the
// dialog, not the line, since the line is rebuilt at every new score. Nothing
// under reduced motion; the colors alone mark the record there.
function sparks(line) {
const dialog = $("activities-modal");
if (!line || !dialog || calm()) return;
const chips = line.firstElementChild;
const x = line.offsetLeft + (chips ? chips.offsetLeft + chips.offsetWidth / 2 : 40);
const y = line.offsetTop + line.offsetHeight / 2;
for (let i = 0; i < SPARKS; i++) {
const a = Math.PI + (Math.PI * i) / (SPARKS - 1) + (Math.random() - 0.5) * 0.3;
const d = 50 + Math.random() * 70;
const s = el("span", "activities-spark");
s.setAttribute("aria-hidden", "true");
s.style.left = `${Math.round(x)}px`;
s.style.top = `${Math.round(y)}px`;
s.style.setProperty("--dx", `${Math.round(Math.cos(a) * d)}px`);
s.style.setProperty("--dy", `${Math.round(Math.sin(a) * d)}px`);
s.style.setProperty("--spin", `${Math.round((Math.random() - 0.5) * 720)}deg`);
s.style.setProperty("--c", SPARK_COLORS[i % SPARK_COLORS.length]);
dialog.append(s);
setTimeout(() => s.remove(), SPARK_MS);
}
}
// Plays the burst again from its start, even mid-burst.
function replay(node, cls) {
node.classList.remove(cls);
void node.offsetWidth;
node.classList.add(cls);
}
// The line under the board, once a round has started: a score chip, a meter
// filling toward the best (for a game where the highest wins and a best is
// saved), then a best chip. Reaching the best lights it; passing it turns the
// line into a rainbow and fires the sparks, once a round. The chips are only
// styling: the line still reads "Score: 3 · Best: 9". Set only when it
// changes, since every frame asks. A lowest-wins game with no best yet says
// so: "Best: 0" would read as a perfect round.
function paintScore() {
const g = game();
watchRound(g);
const line = $("activities-score");
const running = Boolean(g && g.state !== "ready");
const n = currentId ? best(currentId) : 0;
const lower = lowerIsBetter.has(currentId);
const score = running ? g.score : 0;
// A lowest-wins game only knows it beat its best when the round ends.
const chase = running && !lower && n > 0;
const mood = !running ? "" : chase && score > n ? "passed" : chase && score === n ? "tied" : watched.record ? "passed" : "";
const key = running ? `${score}|${n}|${lower}|${mood}` : "";
if (line.dataset.key === key) return;
line.dataset.key = key;
line.classList.toggle("tied", mood === "tied");
line.classList.toggle("passed", mood === "passed");
if (!running) return line.replaceChildren();
const chip = (cls, name, value) => {
const c = el("span", `activities-chip ${cls}`, `${name}: `);
c.append(el("b", null, value));
return c;
};
const parts = [chip("score", "Score", String(score))];
if (chase) {
const meter = el("span", "activities-meter");
meter.setAttribute("aria-hidden", "true");
meter.style.setProperty("--fill", String(Math.min(1, score / n)));
parts.push(meter);
}
parts.push(el("span", "activities-sep", " · "), chip("best", "Best", !n && lower ? "none yet" : String(n)));
line.replaceChildren(...parts);
if (mood === "passed" && !watched.passed) {
watched.passed = true;
replay(line, "burst");
sparks(line);
}
}
function paintOverlay() {
const g = game();
const overlay = $("activities-overlay");
// A game played by pointer also starts and plays on with a click.
const click = g && typeof g.pointer === "function";
let text = "";
if (g && g.state === "running" && counting > 0) text = String(Math.ceil(counting / countStepMs));
else if (g && g.state === "ready") text = click ? "Press space or click to start" : "Press space to start";
else if (g && g.state === "paused") text = click ? "Paused. Press space, P or click to play" : "Paused. Press space or P to play";
else if (g && g.state === "over") text = `Score: ${g.score}\nBest: ${best(currentId)}\n${click ? "Press space or click to play again" : "Press space to play again"}`;
if (overlay.textContent !== text) overlay.textContent = text;
overlay.classList.toggle("count", g !== null && g.state === "running" && counting > 0);
paintScore();
// Read after paintScore, which forgets the last round's record once a new one starts.
overlay.classList.toggle("record", Boolean(g && g.state === "over" && watched.record));
}
/* ------------------------------------------------------------ best scores */
// Called only when a round ends, so a half-played round is never saved. A
// save that does not land stays in the page and its local copy, and the next
// save carries it (looks.js sends every key it has not heard back about).
// A best of 0 means none yet, so a lowerIsBetter game's first round always
// counts.
// A round that beats a best already saved is a record: the end screen says so
// and, for a lowest-wins game (which could not tell mid-round), the sparks fire
// now. A first best is only a best.
function recordScore(id, score) {
const was = best(id);
if (!(lowerIsBetter.has(id) ? !was || score < was : score > was)) return;
looks[bestKey(id)] = score;
saveLooks();
paintTitle();
if (!was || id !== currentId) return;
watched.record = true;
if (lowerIsBetter.has(id)) {
tone("best");
watched.passed = true;
replay($("activities-score"), "burst");
sparks($("activities-score"));
}
}
function disarmReset() {
clearTimeout(resetTimer);
resetTimer = null;
$("activities-reset").textContent = RESET_LABEL;
}
// The first click asks, inside the window; a second within a few seconds
// writes 0 to every listed game's best (the server refuses null).
function resetBest() {
if (!resetTimer) {
$("activities-reset").textContent = RESET_CONFIRM;
resetTimer = setTimeout(disarmReset, RESET_CONFIRM_MS);
return;
}
disarmReset();
for (const entry of list) looks[bestKey(entry.id)] = 0;
saveLooks();
paintOverlay();
paintTitle();
}
// Sizes the game to the board. A board too small to play, or a page with no
// keyboard, shows its note in place of the board. A game that no longer fits
// stops moving, since nobody can see it.
function layout() {
const board = $("activities-board");
const g = game();
if (!hasKeyboard()) {
board.hidden = true;
return showNote(NEED_KEYBOARD);
}
if (!g) return;
board.hidden = false;
if (g.resize(board.clientWidth, board.clientHeight) === false) {
board.hidden = true;
pauseAll("hidden");
return showNote(TOO_SMALL);
}
showNote("");
}
/* -------------------------------------------------------- frame timer */
function stopLoop() {
gen++;
looping = false;
counting = 0;
}
// Runs only while the dialog is open and the game is running, and stops
// itself the moment either is no longer true.
function startLoop() {
const g = game();
if (looping || !g || g.state !== "running" || !$("activities-modal").open) return;
looping = true;
lastFrame = null;
counting = COUNT_FROM * countStepMs;
if (counting > 0) tone("count");
paintOverlay();
const mine = ++gen;
const frame = (now) => {
if (mine !== gen) return;
const t = typeof now === "number" ? now : performance.now();
if (!$("activities-modal").open || g !== game() || g.state !== "running") {
looping = false;
counting = 0;
return paintOverlay();
}
// The countdown's time is never handed to the game: its first tick comes
// a frame after the count ends.
if (counting > 0) {
const shown = Math.ceil(counting / countStepMs);
if (lastFrame !== null) counting -= Math.min(Math.max(0, t - lastFrame), MAX_FRAME_MS);
lastFrame = t;
if (counting <= 0) {
counting = 0;
tone("go");
} else if (Math.ceil(counting / countStepMs) !== shown) tone("count");
paintOverlay();
return tickSource(frame);
}
if (lastFrame !== null) g.tick(Math.min(Math.max(0, t - lastFrame), MAX_FRAME_MS));
lastFrame = t;
paintScore();
if (g.state !== "running") {
looping = false;
return paintOverlay();
}
tickSource(frame);
};
tickSource(frame);
}
// After anything the person does: the timer follows the game's state.
function follow() {
const g = game();
if (g && g.state === "running") startLoop();
else stopLoop();
paintOverlay();
}
// Runs what the person did to the game; when it took a paused game back to
// running, the banner goes away until the next new question or finish.
function play(g, act) {
const was = g.state;
act();
if (was === "paused" && g.state === "running") dismissBanner();
}
/* ------------------------------------------------------------- pauses */
// Every pause goes through here: "turn", "finish", "hidden", "blur" and
// "closed". None of them ever resumes or starts a round; only the person
// does: space, P or any other game key, a click on the overlay, or for a
// game that takes the pointer, a press on the board. A pause also drops a
// drag in progress.
function pauseAll(reason) {
const g = game();
if (g && g.state === "running") g.pause();
dragging = false;
if (g && typeof g.pointer === "function") g.pointer("cancel", 0, 0);
stopLoop();
paintOverlay();
}
/* ------------------------------------------------------------ loading */
async function loadGame(entry) {
if (games.has(entry.id)) return games.get(entry.id);
if (!loading.has(entry.id)) {
const made = (async () => {
const def = entry.game || (await import(entry.module)).default;
if (def.lowerIsBetter) lowerIsBetter.add(entry.id);
else lowerIsBetter.delete(entry.id);
const onScore = (score) => {
recordScore(entry.id, score);
paintOverlay();
};
// The game's memo is saved like a best score: privately, in looks.json.
const memo = {
get: () => looks[memoKey(entry.id)] || 0,
set: (n) => {
if (looks[memoKey(entry.id)] === n) return;
looks[memoKey(entry.id)] = n;
saveLooks();
},
};
const g = def.create({ canvas: $("activities-canvas"), tone, onScore, best: () => best(entry.id), memo });
games.set(entry.id, g);
return g;
})();
// A failed load is forgotten, so the next open tries again.
loading.set(entry.id, made);
made.finally(() => loading.delete(entry.id)).catch(() => {});
}
return loading.get(entry.id);
}
// Makes `id` the game on screen: the one before it is paused, then the new
// one is loaded, sized and drawn.
async function showGame(id) {
const entry = list.find((e) => e.id === id);
if (!entry) return;
if (currentId && currentId !== id) pauseAll("closed");
currentId = id;
drawPicker();
paintTitle();
try {
await loadGame(entry);
} catch {
if (currentId !== id) return;
$("activities-board").hidden = true;
return showNote(NOT_LOADED);
}
if (currentId !== id) return;
layout();
paintOverlay();
// Keys go to the game next, not to the picker button just pressed.
if (!$("activities-board").hidden) $("activities-board").focus({ preventScroll: true });
}
/* ------------------------------------------------------------- picker */
// Shown only once two or more games are listed; with one, the window opens
// straight into it.
function drawPicker() {
const picker = $("activities-picker");
if (list.length < 2) {
picker.hidden = true;
picker.replaceChildren();
return;
}
picker.hidden = false;
picker.replaceChildren(
...list.map((entry) => {
const b = el("button", "btn small ghost", entry.title);
b.type = "button";
b.dataset.activity = entry.id;
b.setAttribute("aria-pressed", String(entry.id === currentId));
b.addEventListener("click", () => pick(entry.id));
return b;
})
);
}
function pick(id) {
if (looks.lastActivity !== id) {
looks.lastActivity = id;
saveLooks();
}
showGame(id);
}
/* ------------------------------------------------------------ opening */
function startingId() {
if (currentId && list.some((e) => e.id === currentId)) return currentId;
if (list.length > 1 && list.some((e) => e.id === looks.lastActivity)) return looks.lastActivity;
return list.length ? list[0].id : null;
}
export async function openActivities() {
unlockTones();
const dlg = $("activities-modal");
showNote("");
if (!dlg.open) dlg.showModal();
renderBanner();
paintTitle();
$("activities-board").focus({ preventScroll: true });
const id = startingId();
if (id) await showGame(id);
}
function closeActivities() {
pauseAll("closed");
const dlg = $("activities-modal");
if (dlg.open) dlg.close();
}
/* --------------------------------------------------------------- keys */
function onKey(e) {
if (e.ctrlKey || e.metaKey || e.altKey) return;
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
const onButton = document.activeElement instanceof HTMLButtonElement && e.currentTarget.contains(document.activeElement);
// A window button keeps its own space and Enter.
if (onButton && (key === " " || key === "Enter")) return;
if (key === "Escape") {
e.preventDefault();
e.stopPropagation();
return closeActivities();
}
const g = game();
const hidden = $("activities-board").hidden;
if (key === "p") {
e.preventDefault();
e.stopPropagation();
// A held P would flicker between the two; and a board nobody can see
// never plays.
if (e.repeat) return;
if (g && g.state === "running") pauseAll("key");
else if (g && g.state === "paused" && !hidden) play(g, () => g.resume());
return follow();
}
if (!Object.hasOwn(KEYS, key)) return;
e.preventDefault();
e.stopPropagation();
// A held space would restart a round the moment the last one ends; arrows
// may repeat.
if (e.repeat && KEYS[key] === "action") return;
if (!g || hidden || counting > 0) return follow();
if (g.state !== "paused") g.key(KEYS[key]);
// Any game key plays on from a pause, a held one excepted. A direction is
// passed on too, so one press resumes and steers; space only resumes, so it
// never also starts a new round.
else if (!e.repeat)
play(g, () => {
g.resume();
if (KEYS[key] !== "action") g.key(KEYS[key]);
});
follow();
}
// For a game with release(): a game key let go, so a game can act on a key
// held down (Mini golf's fast-forward and its turning aim). Always passed on,
// paused or not, so nothing is left held; a game's pause() drops whatever it
// holds anyway, since a release can be lost to a blur.
function onKeyUp(e) {
const key = e.key.length === 1 ? e.key.toLowerCase() : e.key;
if (!Object.hasOwn(KEYS, key)) return;
const g = game();
if (g && typeof g.release === "function") g.release(KEYS[key]);
}
/* ------------------------------------------------------------ pointer */
const POINTER = Object.freeze({ pointerdown: "down", pointermove: "move", pointerup: "up", pointercancel: "cancel" });
// True from a down passed on to the game until its up, cancel or a pause, so
// the release of a press that only played on, or of a drag a pause dropped,
// never reaches the game.
let dragging = false;
// For a game with pointer(): positions in CSS pixels from the canvas's
// top-left. A press on a paused board plays on and starts nothing else; on a
// ready or finished game it is passed on, so the game can start a round.
function onPointer(e) {
const g = game();
if (!g || typeof g.pointer !== "function" || $("activities-board").hidden) return;
const canvas = $("activities-canvas");
const type = POINTER[e.type];
// The countdown holds the board still: a press waits for it, and only the
// release of a press made before it gets through.
if (counting > 0 && type !== "up" && type !== "cancel") {
if (type === "down") e.preventDefault();
return;
}
if (type === "down") {
if (e.button !== 0) return;
e.preventDefault();
$("activities-board").focus({ preventScroll: true });
if (g.state === "paused") {
play(g, () => g.resume());
return follow();
}
// A drag that leaves the canvas still ends here with an up.
try {
canvas.setPointerCapture(e.pointerId);
} catch {}
dragging = true;
} else if (type === "up" || type === "cancel") {
if (!dragging) return;
dragging = false;
}
const r = canvas.getBoundingClientRect();
const used = g.pointer(type, e.clientX - r.left, e.clientY - r.top);
if (type !== "move" || used) follow();
}
/* ------------------------------------------------------- whose turn */
// The banner takes height from the board, so the game is laid out again
// whenever it comes or goes; otherwise the board would clip the canvas.
function renderBanner() {
const banner = $("activities-banner");
const text = bannerDismissed ? "" : myTurn().length ? TURN_BANNER : finish() ? FINISH_BANNER : "";
$("activities-banner-text").textContent = text;
if (banner.hidden === !text) return;
banner.hidden = !text;
if ($("activities-modal").open) layout();
}
// From the render pass: a question that was not the person's a render ago,
// or a finish that was not up, pauses play. A stopped session or a dropped
// connection is not a reason; only the person's turn is.
export function renderActivities() {
// The gear's Show Activities switch: off hides the die everywhere, and
// closes a window left open, paused.
$("btn-activities").hidden = looks.hideActivities;
if (looks.hideActivities && $("activities-modal").open) closeActivities();
const turn = new Set(myTurn().map((i) => i.id));
const done = Boolean(finish());
if (seenTurn) {
if ([...turn].some((id) => !seenTurn.has(id))) {
bannerDismissed = false;
pauseAll("turn");
}
if (done && !seenFinish) {
bannerDismissed = false;
pauseAll("finish");
}
}
seenTurn = turn;
seenFinish = done;
renderBanner();
}
function dismissBanner() {
if (bannerDismissed) return;
bannerDismissed = true;
renderBanner();
}
// Closes the window and, for a question, lands on the first one that is the
// person's, the way the page's own question list does.
function goToIt() {
const first = myTurn()[0];
goingTo = Boolean(first);
closeActivities();
if (!first) return;
page.selected = first.id;
page.view = "questions";
redraw();
const m = $("main");
m.focus();
m.scrollTop = 0;
}
/* -------------------------------------------------------------- wiring */
export function wireActivities() {
const dlg = $("activities-modal");
lightDismiss(dlg);
$("btn-activities").addEventListener("click", openActivities);
$("activities-close").addEventListener("click", closeActivities);
$("activities-reset").addEventListener("click", resetBest);
$("activities-goto").addEventListener("click", goToIt);
$("activities-overlay").addEventListener("click", () => {
const g = game();
if (!g || counting > 0) return;
play(g, () => g.key("action"));
follow();
$("activities-board").focus({ preventScroll: true });
});
dlg.addEventListener("keydown", onKey);
dlg.addEventListener("keyup", onKeyUp);
for (const type of Object.keys(POINTER)) $("activities-canvas").addEventListener(type, onPointer);
// Esc, and any other way the browser cancels the dialog, takes the same
// path as Close.
dlg.addEventListener("cancel", (e) => {
e.preventDefault();
closeActivities();
});
dlg.addEventListener("close", () => {
pauseAll("closed");
disarmReset();
if (!goingTo) $("btn-activities").focus();
goingTo = false;
});
document.addEventListener("visibilitychange", () => {
if (document.hidden) pauseAll("hidden");
});
window.addEventListener("blur", () => pauseAll("blur"));
window.addEventListener("resize", () => {
if (dlg.open) layout();
});
}
+4 -2
View File
@@ -1000,8 +1000,10 @@ function buildText(card, item, staged) {
wrap.appendChild(templateRow(item, input, templatesFor(page.S.workflow, looks.role), check));
}
wrap.appendChild(input);
// Fresh-idea boxes take files as context, the same ones the note pane holds.
if (!single && TEMPLATE_WORKFLOWS.includes(page.S.workflow)) {
// Fresh-idea boxes take files as context, the same ones the note pane holds,
// and so does any box the page fills from a Notebook tab (Revise plan's
// "What should change"), whose ticked pictures land here.
if (!single && (TEMPLATE_WORKFLOWS.includes(page.S.workflow) || item.fill === "note")) {
input.addEventListener("paste", (e) => {
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
if (!files.length) return;
+74 -3
View File
@@ -59,7 +59,7 @@ import {
import { sound } from "../sound.js";
import { renderConfirm, renderDashboard } from "./dashboard.js";
import { renderLaunching, renderWaiting } from "./starting.js";
import { heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
import { attachFiles, heldNotes, noteImages, pendingNotes, removeImage } from "../uploads.js";
import { closeMentions } from "../mention-box.js";
import { buildPager, fitGrowBox, markFor, markMore, renderCard, renderEndItem, renderNotice } from "./cards.js";
import { sendState } from "../send-state.js";
@@ -71,6 +71,7 @@ import { linkLeavesPage, startNewSession, tellApp } from "../app-bridge.js";
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
import { renderNotepadButton } from "./notepad.js";
import { renderActivities } from "./activities.js";
// What the entry needs from the screens at start-up, handed on from here: only
// the core imports a screen.
@@ -85,6 +86,7 @@ export { wireCleanup } from "./cleanup.js";
export { startLooks, wireLooks } from "./looks.js";
export { wireEnding } from "./ending.js";
export { wireNotepad } from "./notepad.js";
export { wireActivities } from "./activities.js";
const $ = (id) => document.getElementById(id);
@@ -176,6 +178,53 @@ function settleStaleUploads() {
}
}
// A Notebook tab picked at Start (dashboard.js) fills the launched skill's
// first open `fill: "note"` box, once. It is claimed before anything is
// fetched, so a redraw or a reload never fills the box a second time.
function fillNoteBox() {
const ns = page.local.noteSend;
if (!ns || isDashboard() || finish() || page.S.workflow !== ns.workflow) return;
const item = items().find((i) => i.kind === "text" && i.fill === "note" && i.status === "open");
if (!item) return;
page.local.noteSend = null;
save();
seedNoteBox(item, ns);
}
// The tab's text as the box's draft and staged answer, then its ticked
// pictures through the same path a pasted picture takes. A tab deleted since
// Start leaves the box empty; a picture deleted since is skipped.
async function seedNoteBox(item, ns) {
const tab = encodeURIComponent(ns.tab);
try {
const res = await fetch("/notepad?tab=" + tab, { cache: "no-store" });
if (res.status === 404) {
banner("That Notebook tab is gone; the box starts empty.", "warn");
return;
}
} catch {}
const text = typeof ns.text === "string" ? ns.text : "";
if (text.trim()) {
page.local.drafts["text-" + item.id] = text;
page.local.staged[item.id] = { type: "answer", kind: "text", text: text.trim() };
}
page.local.noteSent = { item: item.id, tab: ns.tab, workflow: ns.workflow, ...(ns.spec ? { spec: ns.spec } : {}) };
save();
redraw();
const files = await Promise.all(
(ns.pictures || []).map(async (id) => {
try {
const r = await fetch("/notepad/images/" + tab + "/" + encodeURIComponent(id) + ".jpg", { cache: "no-store" });
return r.ok ? new File([await r.blob()], id + ".jpg", { type: "image/jpeg" }) : null;
} catch {
return null;
}
}),
);
const found = files.filter(Boolean);
if (found.length) attachFiles(item.id, found);
}
async function pushDraft() {
try {
await fetch("/draft", {
@@ -276,7 +325,16 @@ export function adopt(body) {
// the dashboard, the picker starts on the most recently touched spec still
// in play, the one the agent's fresh menu recommends for.
const keepPick = page.S.workflow !== "dashboard" && "specSel" in page.local;
page.local = { ...fresh(), launching: page.local.launching, ...(keepPick ? { specSel: page.local.specSel } : {}) };
// A Notebook tab picked at Start rides into the skill it was picked for,
// and nowhere else: back home, or a hop to another skill, drops it.
const ns = page.local.noteSend;
const keepNote = Boolean(ns) && page.S.workflow !== "dashboard" && page.S.workflow === ns.workflow;
page.local = {
...fresh(),
launching: page.local.launching,
...(keepPick ? { specSel: page.local.specSel } : {}),
...(keepNote ? { noteSend: ns } : {}),
};
save();
page.selected = null;
page.view = "questions";
@@ -395,6 +453,7 @@ export function adopt(body) {
(r === "any" || (item.submitted && item.submitted.at === r));
if (!live) delete page.local.retract[id];
}
fillNoteBox();
// New work: a question that is theirs to answer now and was not a moment ago.
// That covers a brand new question and one the agent reopened or answered
@@ -707,6 +766,7 @@ export function render() {
renderSubagentsButton();
renderStopButton();
renderNotepadButton();
renderActivities();
renderHomeButton();
tabAdded = renderViews();
renderSidebar();
@@ -1105,7 +1165,7 @@ export function renderStatus() {
$("dock").classList.toggle("is-flying", Boolean(spin));
// The tab icon's bar says the same thing from another tab (favicon.js),
// and the app's taskbar entry from another window.
const icon = faviconState({ mood, spin, finished: Boolean(finish()) });
const icon = faviconState({ mood, spin });
setFavicon(icon);
tellAttention(icon);
};
@@ -1794,6 +1854,17 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) {
page.local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
}
page.local.staged = {};
// The box a Notebook tab filled went with this send: only now does the
// Notebook say the tab was sent. A failed mark is not worth a banner.
const ns = page.local.noteSent;
if (ns && sentIds.has(ns.item)) {
page.local.noteSent = null;
fetch("/notepad/tab/sent", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ id: ns.tab, workflow: ns.workflow, ...(ns.spec ? { spec: ns.spec } : {}) }),
}).catch(() => {});
}
save();
}
+277 -2
View File
@@ -39,6 +39,13 @@ import {
deleteHandoffReply,
deleteAction,
deleteReply,
noteSwitchShows,
noteTabEmpty,
defaultNoteTicks,
toggleNoteTick,
formatBytes,
NOTE_LONG_BYTES,
MAX_ATTACHMENTS,
} from "../answers.js";
import { stateFor } from "../spec-states.js";
import { sound, soundOn, fadeSound, dropSounds } from "../sound.js";
@@ -139,6 +146,9 @@ function openUpdateModal() {
export function renderDashboard(main) {
maybeWake();
// The menu is up, so the confirm pane was left: its Notebook switch starts
// off again, with nothing picked, the next time a card is opened.
note = null;
// First, so nothing below reads a pick whose handoff has left the scan, and
// a delete the agent's rescan has finished stops holding the buttons.
selHandoff();
@@ -689,6 +699,220 @@ function dashCard(entry, menu) {
return b;
}
// "Start with a note from your Notebook": the switch a lit card's confirm
// pane offers when noteSwitchShows() says so. The pane is rebuilt on every
// state frame, so what the person did lives here, keyed to the card and the
// picked spec it was done for: `on`, the tabs as read (`null` until then,
// each with its text and pictures once fetched), the picked tab and its
// ticked picture ids. `pick` is the pending pick Phase 2 reads at Start.
let note = null;
const noteKey = (entry) => entry.skill + "|" + ((selSpec() && selSpec().dir) || "");
function noteFor(entry) {
const key = noteKey(entry);
if (!note || note.key !== key) note = { key, on: false, tabs: null, failed: false, picked: null, ticked: [] };
return note;
}
/**
* The tab the confirm pane has picked for this card, as `{ tab, name, text,
* images }` with only the ticked pictures, or null when the switch is off or
* no tab is picked.
*/
export function pendingNotePick(entry) {
if (!entry || !note || note.key !== noteKey(entry) || !note.on || !note.picked || !note.tabs) return null;
const tab = note.tabs.find((t) => t.id === note.picked);
if (!tab || !tab.read) return null;
return {
tab: tab.id,
name: tab.name,
text: tab.read.text,
images: tab.read.images.filter((img) => note.ticked.includes(img.id)),
};
}
// Every tab, then each tab's text and pictures (the list shows an empty tab
// grayed, so each must be read). Read only: GET /notepad never writes.
async function readNoteTabs(state) {
try {
const res = await fetch("/notepad", { cache: "no-store" });
if (!res.ok) throw new Error(String(res.status));
const body = await res.json();
const tabs = Array.isArray(body.tabs) ? body.tabs : [];
const read = await Promise.all(
tabs.map(async (t) => {
try {
const r = await fetch("/notepad?tab=" + encodeURIComponent(t.id), { cache: "no-store" });
if (!r.ok) return null;
const b = await r.json();
return b && b.tab ? { text: typeof b.tab.text === "string" ? b.tab.text : "", images: Array.isArray(b.tab.images) ? b.tab.images : [] } : null;
} catch {
return null;
}
}),
);
state.tabs = tabs.map((t, i) => ({ id: t.id, name: t.name, sent: t.sent || null, read: read[i] }));
state.failed = false;
} catch {
state.tabs = [];
state.failed = true;
}
}
// Read the tabs again (`fresh` shows "Reading…" meanwhile, for a first read).
// The pick survives only while its tab is still there with something in it,
// and its ticks only for pictures still in that tab, so what Start reads is
// never older than the last time the Notebook was closed.
async function refreshNoteTabs(state, fresh = false) {
if (state.reading) return;
state.reading = true;
if (fresh) {
state.tabs = null;
redraw();
}
await readNoteTabs(state);
state.reading = false;
const tab = state.tabs.find((t) => t.id === state.picked);
if (!tab || !tab.read || noteTabEmpty(tab.read)) {
state.picked = null;
state.ticked = [];
} else {
const ids = tab.read.images.map((img) => img.id);
state.ticked = state.ticked.filter((id) => ids.includes(id));
}
// A state frame may have rebuilt the pane while the read was out, so the
// whole page redraws rather than a (perhaps detached) box.
if (note === state) redraw();
}
// The switch, the tab list and the preview, drawn into `box`; `cmdNote` is the
// command line's `+ note: <tab>` span. Each change redraws only this box, so
// the rest of the pane (and the focus on it) stays put.
function drawNoteBox(entry, box, cmdNote) {
const state = noteFor(entry);
const focusKey = document.activeElement && box.contains(document.activeElement) ? document.activeElement.dataset.noteFocus : null;
const again = () => drawNoteBox(entry, box, cmdNote);
box.replaceChildren();
const label = el("label", "confirm-note-switch");
const toggle = el("input");
toggle.type = "checkbox";
toggle.id = "confirm-note-switch";
toggle.dataset.noteFocus = "switch";
toggle.checked = state.on;
toggle.addEventListener("change", () => {
state.on = toggle.checked;
again();
if (state.on && (state.tabs === null || state.failed)) refreshNoteTabs(state, true);
});
label.append(toggle, el("span", null, "Start with a note from your Notebook"));
box.appendChild(label);
const picked = state.on && state.tabs ? state.tabs.find((t) => t.id === state.picked && t.read) : null;
cmdNote.textContent = picked ? " + note: " + picked.name : "";
cmdNote.hidden = !picked;
if (!state.on) return;
const wrap = el("div", "confirm-note");
if (state.tabs === null) {
wrap.appendChild(el("p", "confirm-note-msg", "Reading your Notebook…"));
} else if (state.failed) {
wrap.appendChild(el("p", "confirm-note-msg", "Your Notebook could not be read. Turn the switch off and on to try again."));
} else if (!state.tabs.length) {
wrap.appendChild(el("p", "confirm-note-msg", "Your Notebook has no tabs yet. Open it from the top bar to write one."));
} else {
const list = el("div", "confirm-note-tabs");
list.setAttribute("role", "group");
list.setAttribute("aria-label", "Notebook tabs");
for (const t of state.tabs) {
const empty = !t.read || noteTabEmpty(t.read);
const b = el("button", "confirm-note-tab" + (t.id === state.picked ? " is-picked" : ""));
b.type = "button";
b.dataset.noteFocus = "tab-" + t.id;
b.disabled = empty;
b.setAttribute("aria-pressed", String(t.id === state.picked));
b.appendChild(el("span", "confirm-note-tab-name", t.name));
if (t.sent) {
const badge = el("span", "notepad-sent-badge", "sent");
badge.setAttribute("aria-hidden", "true");
b.appendChild(badge);
}
b.setAttribute("aria-label", t.name + (t.sent ? ", sent" : "") + (empty ? ", empty" : ""));
if (empty) b.title = t.read ? "This tab has no text or pictures." : "This tab could not be read.";
b.addEventListener("click", () => {
if (state.picked === t.id) return;
state.picked = t.id;
state.ticked = defaultNoteTicks(t.read.images);
again();
});
list.appendChild(b);
}
wrap.appendChild(list);
wrap.appendChild(notePreview(picked, state, again));
}
box.appendChild(wrap);
if (focusKey) {
const back = box.querySelector(`[data-note-focus="${focusKey}"]`);
if (back && !back.disabled) back.focus();
}
}
// The picked tab in full: a "Long tab" note over NOTE_LONG_BYTES, its text as
// Markdown, and its pictures, each with a tick (at most MAX_ATTACHMENTS).
function notePreview(picked, state, again) {
const pane = el("div", "confirm-note-preview");
pane.setAttribute("role", "region");
pane.setAttribute("aria-label", "Preview of the picked tab");
if (!picked) {
pane.appendChild(el("p", "confirm-note-msg", "Pick a tab to see it here."));
return pane;
}
const bytes = new TextEncoder().encode(picked.read.text).length;
if (bytes > NOTE_LONG_BYTES) pane.appendChild(el("p", "confirm-note-long", "Long tab: " + formatBytes(bytes)));
const text = el("div", "confirm-note-text md");
if (picked.read.text.trim()) mdInto(text, picked.read.text);
else text.appendChild(el("p", "confirm-note-msg", "No text, only pictures."));
pane.appendChild(text);
const images = picked.read.images;
if (images.length) {
const full = state.ticked.length >= MAX_ATTACHMENTS;
pane.appendChild(
el(
"p",
"confirm-note-msg",
images.length > MAX_ATTACHMENTS
? `Up to ${MAX_ATTACHMENTS} pictures go with it. Untick one to tick another.`
: "Untick a picture to leave it out.",
),
);
const strip = el("ul", "confirm-note-pics");
images.forEach((img, i) => {
const li = el("li", "confirm-note-pic");
const lab = el("label");
const tick = el("input");
tick.type = "checkbox";
tick.dataset.noteFocus = "pic-" + img.id;
tick.checked = state.ticked.includes(img.id);
tick.disabled = !tick.checked && full;
tick.setAttribute("aria-label", `Picture ${i + 1} of ${images.length}`);
tick.addEventListener("change", () => {
state.ticked = toggleNoteTick(state.ticked, img.id);
again();
});
const pic = el("img");
pic.src = img.thumb || img.url;
pic.alt = "";
pic.loading = "lazy";
lab.append(tick, pic);
li.appendChild(lab);
strip.appendChild(li);
});
pane.appendChild(strip);
}
return pane;
}
// The confirm pane. A card or rail click lands here rather than launching
// straight away: picking a skill is the one irreversible-feeling click on the
// dashboard, and it deserves a beat: what it is, what it will do, and a
@@ -757,9 +981,26 @@ export function renderConfirm(main, entry) {
pane.appendChild(label);
}
// The Notebook switch, on the cards and specs noteSwitchShows() names.
const cmdNote = el("span", "confirm-cmd-note");
cmdNote.hidden = true;
if (noteSwitchShows(entry, scan(), selSpec())) {
pane.appendChild(el("hr", "confirm-rule"));
const box = el("div", "confirm-note-box");
// Which control in the box has the focus, so a rebuild of the whole pane
// can hand it back (see the end of this function).
box.addEventListener("focusin", (e) => (noteFor(entry).focus = e.target.dataset.noteFocus || null));
box.addEventListener("focusout", (e) => {
if (e.relatedTarget && !box.contains(e.relatedTarget)) noteFor(entry).focus = null;
});
drawNoteBox(entry, box, cmdNote);
pane.appendChild(box);
}
const cmd = el("p", "confirm-cmd");
const cmdCode = el("code", null, launchVariant(entry, !review || review.checked).command);
cmd.appendChild(cmdCode);
cmd.appendChild(cmdNote);
pane.appendChild(cmd);
const actions = el("div", "confirm-actions");
@@ -780,8 +1021,12 @@ export function renderConfirm(main, entry) {
main.appendChild(pane);
// Focus lands on START after a pick (the clicked control was rebuilt away,
// leaving focus on <body>), but never yanked back from a deliberate click
// elsewhere: a state frame can re-render this pane at any time.
if (document.activeElement === document.body) start.focus();
// elsewhere: a state frame can re-render this pane at any time. A control
// in the Notebook box gets its focus back instead.
if (document.activeElement === document.body) {
const held = note && note.key === noteKey(entry) && note.focus ? pane.querySelector(`[data-note-focus="${note.focus}"]`) : null;
(held && !held.disabled ? held : start).focus();
}
}
// A pick is a send like a brief or a stop: it names no question, so `__launch`
@@ -809,6 +1054,22 @@ async function launchSkill(entry) {
// cards that take no spec (utilities, setup) launch untargeted even while
// a spec is selected, save Quick Task on a diagnosed bug.
if (target) action.spec = target.dir;
// A Notebook tab picked in the pane rides the hop in this page only, never
// on the action: the launched skill's `fill: "note"` box is filled from it
// (core.js), and the agent reads it only when that box is sent.
// Set either way, so a pick left from a launch that never hopped cannot
// fill this one.
const pick = pendingNotePick(entry);
page.local.noteSend = pick
? {
tab: pick.tab,
text: pick.text,
pictures: pick.images.map((img) => img.id),
workflow: entry.workflow,
...(target ? { spec: target.dir } : {}),
}
: null;
saveNow();
// The skill opens on the folders remembered for what it was launched for.
// Held until the launch is in flight: the swap's own frame re-renders the
// dashboard, which would otherwise sync back to the picker's spec.
@@ -825,6 +1086,7 @@ async function launchSkill(entry) {
});
if (res.status === 409) {
page.launchScoping = false;
dropNoteSend();
page.pendingResult = true;
hooks.banner("Your last pick is still being picked up. One moment.", "info");
return;
@@ -838,10 +1100,18 @@ async function launchSkill(entry) {
redraw();
} catch {
page.launchScoping = false;
dropNoteSend();
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
}
}
// A launch that did not go through takes no Notebook tab anywhere.
function dropNoteSend() {
if (!page.local.noteSend) return;
page.local.noteSend = null;
saveNow();
}
// The picker's Delete: a dialog in two steps. The first says what goes and
// that it is for good; "Delete this spec…" then reveals the second, which
// enables the final button only once the spec's name is typed exactly. A
@@ -1007,6 +1277,11 @@ async function sendDelete(spec) {
// The dialogs' buttons, wired once at start-up: the update notice's Done, the
// handoff preview's close, and the delete dialog's Cancel, name box and go.
export function wireDashboard() {
// Closing the Notebook over an open confirm pane with the switch on reads
// the tabs again, so an edit or a delete made there shows in the preview.
$("notepad-modal").addEventListener("close", () => {
if (note && note.on && page.dashPick) refreshNoteTabs(note);
});
$("update-done").addEventListener("click", () => $("update-modal").close());
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
$("handoff-close").addEventListener("click", () => $("handoff-modal").close());
+7
View File
@@ -515,6 +515,13 @@ export function wireLooks() {
const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn);
if (preview) sound(preview);
});
$("looks-activities").addEventListener("change", (e) => {
looks.hideActivities = !e.target.checked;
saveLooks();
// The die comes and goes with the next render, which also closes an open
// Activities window, paused.
redraw();
});
for (const box of document.querySelectorAll("input[data-sound]")) {
box.addEventListener("change", () => {
const event = box.dataset.sound;
+29 -3
View File
@@ -2,7 +2,8 @@
//
// The person's own notes for the folder this session runs in, kept by the
// server under ~/.plan2code/notepads/ through the /notepad routes, never in
// the session, so nothing typed here reaches the agent. A notepad is a row of
// the session. The agent CLI never imports the store: a tab leaves it only
// through a send the person starts on the dashboard. A notepad is a row of
// tabs, each its own note with its own pictures; one tab is on screen. The
// editor is CodeMirror (notepad-editor.js), loaded the first time the Notebook
// opens. When to save, what the status line says, the tab name rules and the
@@ -34,6 +35,7 @@ import { el, lightDismiss } from "../render.js";
import { postJson } from "../net.js";
import { reencode } from "../uploads.js";
import { createTabs } from "../notepad-tabs.js";
import { skillFor } from "../skills.js";
const $ = (id) => document.getElementById(id);
@@ -245,8 +247,32 @@ async function readNote(tab) {
const nameOf = (id) => (tabs.find((t) => t.id === id) || {}).name || "";
// A tab as the bar and the sent line keep it: `sent` only on a tab sent from
// the dashboard.
const tabEntry = (t) => ({ id: t.id, name: t.name, ...(t.sent ? { sent: t.sent } : {}) });
// "Sent to Plan · Oct 27", or "Sent to Revise plan (lunch-vote) · Oct 27",
// for a tab's last send; "" when it has none.
export function sentLine(sent) {
if (!sent || typeof sent.workflow !== "string") return "";
const skill = skillFor(sent.workflow);
const at = new Date(sent.at);
if (!skill || Number.isNaN(at.getTime())) return "";
const spec = typeof sent.spec === "string" && sent.spec ? " (" + sent.spec.replace(/^specs\//, "") + ")" : "";
return "Sent to " + skill.name + spec + " · " + at.toLocaleDateString(undefined, { month: "short", day: "numeric" });
}
// The muted line under the editor for the tab on screen.
function drawSent() {
const line = $("notepad-sent");
const text = sentLine((tabs.find((t) => t.id === activeId) || {}).sent);
line.textContent = text;
line.hidden = !text;
}
function drawTabs() {
tabBar.draw(tabs, activeId);
drawSent();
$("notepad-tab-new").disabled = busy;
$("notepad-empty-new").disabled = busy;
$("notepad-name-save").disabled = busy;
@@ -256,7 +282,7 @@ function drawTabs() {
// the text and the tab alone (the notepad was only reopened while text was
// still unsaved), taking the bar and the pictures from the server.
function show(body, keep = false) {
tabs = body.tabs.map((t) => ({ id: t.id, name: t.name }));
tabs = body.tabs.map(tabEntry);
const tab = body.tab;
if (keep) {
takeStored(tab && tab.id === activeId ? tab.images : [], activeId);
@@ -328,7 +354,7 @@ async function reorder(order, focus) {
inform("");
tell(errorSentence(res.status === 0 ? null : res.body && res.body.error));
const again = await readNote(activeId);
if (again.ok) tabs = again.body.tabs.map((t) => ({ id: t.id, name: t.name }));
if (again.ok) tabs = again.body.tabs.map(tabEntry);
drawTabs();
}
+6
View File
@@ -46,6 +46,12 @@ export function fresh() {
launching: null,
// A picker Delete sent and not yet answered by a rescan: { dir, scanAt }.
deleting: null,
// A Notebook tab picked at Start, riding the hop until the launched
// skill's `fill: "note"` box takes it: { tab, text, pictures, workflow, spec? }.
noteSend: null,
// The box it filled, until a send carrying that box marks the tab sent:
// { item, tab, workflow, spec? }.
noteSent: null,
retract: {},
chat: freshChat(),
};
@@ -0,0 +1,245 @@
/* Activities: the top bar's die, the dialog, the board, its overlay, the
your-turn banner and the notes. The game draws its own board on the canvas. */
/* The top bar's die, drawn and lit like the megaphone and the gear beside it. */
.icon-btn .dc-body { fill: none; stroke: var(--ink-3); stroke-width: 1.4; }
.icon-btn .dc-pip { fill: var(--ink-2); stroke: none; }
.icon-btn:hover .dc-body { stroke: var(--accent); }
.icon-btn:hover .dc-pip { fill: var(--accent); }
/* Show Activities off in User Preferences: .icon-btn's grid would beat the
attribute's own display. */
#btn-activities[hidden] { display: none; }
/* The dialog: Notebook-sized, with the board taking whatever height the
title, the banner, the picker, the note and the actions leave. */
.modal.activities {
width: min(1200px, 90vw);
height: min(900px, 85vh);
max-width: none;
max-height: none;
flex-direction: column;
}
.modal.activities[open] { display: flex; }
.modal.activities h2,
.modal.activities .modal-blurb,
.modal.activities .modal-actions { flex: none; }
.modal.activities .modal-blurb { margin-bottom: 12px; }
/* Plan2Code needs the person: an attention strip in the highlight color,
above the board, that never covers it. */
.activities-banner {
flex: none;
display: flex;
align-items: center;
gap: 12px;
margin-bottom: 12px;
padding: 8px 12px;
border: 1px solid var(--accent);
border-radius: 8px;
background: var(--accent-soft);
color: var(--ink);
}
.activities-banner[hidden] { display: none; }
.activities-banner-text { flex: 1 1 auto; font-weight: 600; }
.activities-banner .btn.primary { flex: none; background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
/* The picker: one button per game, shown only once two are listed. */
.activities-picker {
flex: none;
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 12px;
}
.activities-picker[hidden] { display: none; }
.activities-picker .btn[aria-pressed="true"] { background: var(--accent-soft); border-color: var(--accent-line); color: var(--ink); }
/* The board: fills the free space and centers the canvas, with the state
text laid over its middle. */
.activities-board {
position: relative;
flex: 1 1 auto;
min-height: 0;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
border: 1px solid var(--rule-2);
background: var(--panel-2);
}
.activities-board:focus { outline: none; }
.activities-board:focus-visible { border-color: var(--accent-line); }
.activities-board[hidden] { display: none; }
.activities-board canvas { display: block; }
/* Mini golf's page colors (activities/golf-draw.js reads them off the
canvas) for its ball, aim, pills and scorecard, all mixed from the page's
tokens so they look right in light and dark and follow a picked highlight.
The course itself (a pirate sea, a dark cave) keeps its own fixed colors.
The canvas takes color-mix() as it is. */
.activities-board canvas {
--golf-shadow: color-mix(in srgb, black 24%, transparent);
--golf-pole: color-mix(in srgb, white 90%, var(--stage));
--golf-ball: color-mix(in srgb, white 96%, var(--stage));
--golf-aim: var(--golf-ball);
--golf-power: var(--accent);
--golf-card: var(--panel);
--golf-ink: var(--ink);
--golf-ink2: var(--ink-2);
--golf-under: var(--ok);
--golf-over: var(--warn);
--golf-burst: var(--stage);
}
.activities-overlay {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
max-width: 80%;
padding: 10px 16px;
border-radius: 8px;
background: var(--panel);
color: var(--ink);
box-shadow: var(--shadow);
font-weight: 600;
text-align: center;
white-space: pre-line;
cursor: pointer;
}
/* The 3, 2, 1 before play: a big number, not a note, and nothing to click. */
.activities-overlay.count {
min-width: 2.4em;
font-size: 48px;
line-height: 1;
font-variant-numeric: tabular-nums;
cursor: default;
}
.activities-overlay:empty,
.activities-overlay[hidden] { display: none; }
/* The header's best for the game on screen: quieter than the title. */
.activities-title-best { font-weight: 400; color: var(--ink-2); font-variant-numeric: tabular-nums; }
/* The round's score beside the best, under the board, as colored chips with
a meter between them (screens/activities.js builds them). Its height is
fixed, empty or not, so the board does not jump the moment a round starts. */
.activities-score {
--score-gold: color-mix(in srgb, var(--stage) 80%, #f5b301);
flex: none;
height: 30px;
margin: 8px 0 0;
display: block;
line-height: 30px;
color: var(--ink-2);
font-variant-numeric: tabular-nums;
white-space: nowrap;
}
.activities-chip {
display: inline-block;
padding: 0 12px;
line-height: 26px;
border-radius: 999px;
border: 1px solid;
font-weight: 600;
vertical-align: middle;
}
.activities-chip b { font-weight: 800; font-size: 1.08em; }
.activities-chip.score {
border-color: var(--accent-line);
background: linear-gradient(135deg, var(--accent-soft), color-mix(in srgb, var(--accent) 22%, var(--panel)));
color: var(--ink);
}
.activities-chip.score b { color: var(--accent); }
.activities-chip.best {
border-color: color-mix(in srgb, var(--score-gold) 55%, transparent);
background: linear-gradient(135deg, color-mix(in srgb, var(--score-gold) 14%, var(--panel)), color-mix(in srgb, var(--score-gold) 28%, var(--panel)));
color: var(--ink);
}
.activities-chip.best b { color: var(--score-gold); }
/* The " · " between them stays in the text (a plain inline span, so its
spaces count) but takes no room; the best chip keeps its own gap. */
.activities-sep { font-size: 0; }
.activities-chip.best { margin-left: 8px; }
/* The meter: how far the score has come toward the best. */
.activities-meter {
display: inline-block;
width: 120px;
height: 8px;
margin: 0 2px 0 10px;
border-radius: 999px;
background: linear-gradient(90deg, var(--accent), var(--score-gold)) no-repeat var(--rule-2);
background-size: calc(var(--fill, 0) * 100%) 100%;
vertical-align: middle;
transition: background-size 200ms ease-out;
}
/* Reaching the best: the best chip glows. */
.activities-score.tied .activities-chip.best {
border-color: var(--score-gold);
box-shadow: 0 0 0 3px color-mix(in srgb, var(--score-gold) 30%, transparent);
}
/* Past it: a rainbow line and a NEW BEST tag (drawn by CSS, so the line still
reads as its plain text). */
.activities-score.passed .activities-chip,
.activities-score.passed .activities-meter {
background: linear-gradient(90deg, #ff4fa3, #f5b301, #57b54a, #1fb6d9, #a466ff, #ff4fa3);
background-size: 300% 100%;
border-color: transparent;
color: #ffffff;
}
.activities-score.passed .activities-chip b { color: #ffffff; }
.activities-score.passed .activities-chip { text-shadow: 0 1px 2px rgba(0, 0, 0, 0.45); }
.activities-score.passed .activities-chip.score::after {
content: "NEW BEST";
margin-left: 8px;
padding: 1px 6px;
border-radius: 999px;
background: rgba(0, 0, 0, 0.28);
font-size: 0.72em;
font-weight: 800;
letter-spacing: 0.06em;
}
/* The sparks fanning up out of the chips as the best is passed. */
.activities-spark {
position: absolute;
width: 8px;
height: 8px;
margin: -4px 0 0 -4px;
border-radius: 2px;
background: var(--c);
pointer-events: none;
opacity: 0;
z-index: 2;
}
/* The end of a round that set a new best: the overlay says so in rainbow. */
.activities-overlay.record { border: 2px solid transparent; background: linear-gradient(var(--panel), var(--panel)) padding-box, linear-gradient(90deg, #ff4fa3, #f5b301, #57b54a, #1fb6d9, #a466ff) border-box; }
.activities-overlay.record::before {
content: "New best!";
display: block;
margin-bottom: 4px;
font-size: 22px;
font-weight: 800;
background: linear-gradient(90deg, #ff4fa3, #f5b301, #1fb6d9, #a466ff);
-webkit-background-clip: text;
background-clip: text;
color: transparent;
}
@media (prefers-reduced-motion: no-preference) {
.activities-score.tied .activities-chip.best { animation: activities-glow 900ms ease-in-out infinite alternate; }
.activities-score.passed .activities-chip,
.activities-score.passed .activities-meter { animation: activities-rainbow 2.4s linear infinite; }
.activities-score.burst .activities-chip { animation: activities-rainbow 2.4s linear infinite, activities-pop 600ms cubic-bezier(0.3, 1.6, 0.5, 1); }
.activities-spark { animation: activities-spark 1s cubic-bezier(0.2, 0.7, 0.4, 1) forwards; }
.activities-overlay.record::before { animation: activities-pop 600ms cubic-bezier(0.3, 1.6, 0.5, 1); }
}
@keyframes activities-glow { to { box-shadow: 0 0 0 6px color-mix(in srgb, var(--score-gold) 12%, transparent), 0 0 16px color-mix(in srgb, var(--score-gold) 60%, transparent); } }
@keyframes activities-rainbow { to { background-position: 300% 0; } }
@keyframes activities-pop { 0% { transform: scale(0.8); } 60% { transform: scale(1.18); } 100% { transform: scale(1); } }
@keyframes activities-spark {
0% { opacity: 1; transform: translate(0, 0) rotate(0); }
70% { opacity: 1; }
100% { opacity: 0; transform: translate(var(--dx), calc(var(--dy) + 30px)) rotate(var(--spin)); }
}
/* The keyboard, bigger-window and load-failure notes: shown in place of play. */
.activities-note { flex: none; margin: 12px 0 0; color: var(--ink-2); }
.activities-note[hidden] { display: none; }
@@ -423,8 +423,60 @@
border-radius: 6px;
padding: 4px 10px;
}
.confirm-cmd-note { margin-left: 8px; font-family: var(--mono); font-size: 12.5px; color: var(--accent); }
.confirm-actions { display: flex; gap: 10px; margin-top: 10px; }
/* "Start with a note from your Notebook": the switch, then the tabs beside a
preview of the picked one, its pictures each with a tick. */
.confirm-note-box { display: grid; gap: 8px; }
.confirm-note-switch { display: flex; gap: 8px; align-items: center; color: var(--ink-2); cursor: pointer; }
.confirm-note-switch input { accent-color: var(--accent, currentColor); }
.confirm-note { display: grid; grid-template-columns: minmax(130px, 200px) minmax(0, 1fr); gap: 10px; }
.confirm-note > .confirm-note-msg { grid-column: 1 / -1; }
.confirm-note-msg { margin: 0; font-size: 13px; color: var(--ink-3); }
.confirm-note-tabs { display: flex; flex-direction: column; gap: 4px; max-height: 320px; overflow-y: auto; }
.confirm-note-tab {
display: flex;
align-items: center;
gap: 6px;
padding: 6px 10px;
border: 1px solid var(--rule-2);
border-radius: 8px;
background: var(--panel-2);
color: var(--ink-2);
font: inherit;
font-size: 13px;
text-align: left;
cursor: pointer;
}
.confirm-note-tab:hover:not(:disabled) { border-color: var(--accent-line); color: var(--accent); }
.confirm-note-tab.is-picked { border-color: var(--accent); background: var(--accent-soft); color: var(--ink); font-weight: 600; }
.confirm-note-tab:disabled { opacity: 0.5; cursor: not-allowed; }
.confirm-note-tab:focus-visible { outline: 2px solid var(--accent); outline-offset: 1px; }
.confirm-note-tab-name { min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.confirm-note-preview {
display: grid;
gap: 8px;
align-content: start;
min-width: 0;
max-height: 320px;
overflow-y: auto;
padding: 8px 10px;
border: 1px solid var(--rule-2);
border-radius: 8px;
background: var(--panel);
}
.confirm-note-text { font-size: 13.5px; }
.confirm-note-long { margin: 0; font-size: 12.5px; font-weight: 600; color: var(--warn); }
.confirm-note-pics { display: flex; flex-wrap: wrap; gap: 8px; margin: 0; padding: 0; list-style: none; }
.confirm-note-pic label { position: relative; display: block; cursor: pointer; }
.confirm-note-pic img { display: block; width: 72px; height: 72px; object-fit: cover; border: 1px solid var(--rule-2); border-radius: 6px; }
.confirm-note-pic input { position: absolute; top: 4px; left: 4px; margin: 0; accent-color: var(--accent, currentColor); }
.confirm-note-pic input:disabled + img { opacity: 0.45; }
@media (max-width: 560px) {
.confirm-note { grid-template-columns: minmax(0, 1fr); }
}
/* ------------------------------------------------------- launching pane */
.launching {
+14
View File
@@ -43,6 +43,9 @@
background: var(--panel);
}
.notepad-editor:focus-within { border-color: var(--accent-line); }
/* The open tab's last send from the dashboard, muted under the editor. */
.notepad-sent { flex: none; margin: 6px 0 0; font-size: 12.5px; color: var(--ink-3); }
.notepad-sent[hidden] { display: none; }
/* The pictures under the editor: the Add image button, then the thumbnails,
wrapping. Capped at two rows, so 200 pictures never squeeze the editor
away; the strip scrolls instead. The whole region lights while pictures are
@@ -203,6 +206,17 @@
white-space: nowrap;
}
.notepad-tab[aria-selected="true"] { font-weight: 600; }
.notepad-sent-badge {
flex: none;
margin: 0 2px 0 2px;
padding: 1px 5px;
border: 1px solid var(--rule-2);
border-radius: 999px;
color: var(--ink-3);
font-size: 10.5px;
line-height: 1.3;
white-space: nowrap;
}
.notepad-tab-x {
flex: none;
width: 20px;
+122
View File
@@ -0,0 +1,122 @@
// Plan2Code Web Console - the tones: short synthesized blips for the activities, silent when Play sounds is off; defines only.
import { looks } from "./looks.js";
/* ------------------------------------------------------------- tones
Blips made in the browser, so there is no audio file to fetch. They are
not the main sounds in sound.js: the master Play sounds switch gates them,
and they have no switch of their own and no queue. A browser will not
make noise before the person has touched the page, so unlockTones() runs
from the click that opens Activities. A tone asked for before that stays
silent rather than throwing.
Every sound here is short (a quarter second at most) and quiet, so a cue
never outlasts the moment it belongs to. A tone either sweeps from one
pitch to another, or plays `notes` one after another in its time. */
const TONES = Object.freeze({
eat: Object.freeze({ type: "triangle", from: 660, to: 880, seconds: 0.12 }),
crash: Object.freeze({ type: "sawtooth", from: 220, to: 80, seconds: 0.2 }),
// The 3, 2, 1 before a round starts or plays on: a tick per number, then a
// higher one as play begins.
count: Object.freeze({ type: "sine", from: 440, to: 440, seconds: 0.08 }),
go: Object.freeze({ type: "sine", from: 880, to: 880, seconds: 0.14 }),
// Mini golf: the club on the ball, the ball off a wall or a bumper, into
// the cup, a hole in one (a little three-note rise), and into the water.
putt: Object.freeze({ type: "triangle", from: 520, to: 400, seconds: 0.06 }),
wall: Object.freeze({ type: "triangle", from: 300, to: 200, seconds: 0.07 }),
bump: Object.freeze({ type: "sine", from: 700, to: 1000, seconds: 0.09 }),
cup: Object.freeze({ type: "triangle", from: 520, to: 1040, seconds: 0.16 }),
ace: Object.freeze({ type: "triangle", notes: Object.freeze([523, 659, 784]), seconds: 0.24 }),
splash: Object.freeze({ type: "sine", from: 420, to: 120, seconds: 0.2 }),
// Mini golf's gags: a power-up grabbed (a sparkly rise), a tunnel's whoosh,
// a cannonball putt, the ball into lava, and the ball down the pit.
power: Object.freeze({ type: "square", notes: Object.freeze([784, 988, 1319]), seconds: 0.18 }),
tunnel: Object.freeze({ type: "sine", from: 200, to: 900, seconds: 0.16 }),
boom: Object.freeze({ type: "sawtooth", from: 160, to: 45, seconds: 0.22 }),
sizzle: Object.freeze({ type: "sawtooth", from: 900, to: 300, seconds: 0.2 }),
fall: Object.freeze({ type: "sine", from: 700, to: 60, seconds: 0.25 }),
// Mini golf's swing: the meter starting, a putt caught in the MAX band (a
// bright two-note hit), and an overswing's sour buzz.
swing: Object.freeze({ type: "square", from: 620, to: 660, seconds: 0.04 }),
max: Object.freeze({ type: "square", notes: Object.freeze([880, 1320]), seconds: 0.16 }),
shank: Object.freeze({ type: "sawtooth", from: 240, to: 110, seconds: 0.18 }),
// Snake's extras: a combo's quick chirp, a coin, a mystery box opening, a
// new level (a four-note climb), a shield taking a hit, a comet cutting
// the tail, and a new best mid-round. A grabbed power-up uses `power`, a
// smashed rock `boom` and a portal `tunnel`.
combo: Object.freeze({ type: "square", from: 880, to: 1320, seconds: 0.07 }),
coin: Object.freeze({ type: "square", notes: Object.freeze([988, 1319]), seconds: 0.1 }),
mystery: Object.freeze({ type: "triangle", notes: Object.freeze([392, 523, 466, 698]), seconds: 0.24 }),
levelup: Object.freeze({ type: "square", notes: Object.freeze([523, 659, 784, 1047]), seconds: 0.25 }),
shield: Object.freeze({ type: "sine", from: 1200, to: 500, seconds: 0.14 }),
zap: Object.freeze({ type: "sawtooth", from: 1400, to: 200, seconds: 0.15 }),
best: Object.freeze({ type: "triangle", notes: Object.freeze([784, 988, 1175, 1568]), seconds: 0.25 }),
});
// Peak gain, kept modest so a blip sits under the page rather than over it.
const PEAK = 0.08;
// A quick attack avoids a click at the start; the decay is exponential, which
// needs a non-zero floor, so the envelope stops at a tiny value, not zero.
const ATTACK = 0.01;
const FLOOR = 0.0001;
let ctx = null;
// Made on first use, not at load, so importing this file in Node is harmless.
// A missing AudioContext or a constructor that throws both give null.
function audioContext() {
if (ctx) return ctx;
if (typeof globalThis.AudioContext === "undefined") return null;
try {
ctx = new globalThis.AudioContext();
} catch {
ctx = null;
}
return ctx;
}
// Called from the click that opens Activities. A browser keeps a new context
// suspended until a gesture, and a rejected resume is not an error the page
// can act on, so every failure is swallowed.
export function unlockTones() {
try {
const c = audioContext();
if (c) Promise.resolve(c.resume()).catch(() => {});
} catch {}
}
// One oscillator from t0 for `seconds`, sweeping from one pitch to another.
function blip(c, type, from, to, t0, seconds, peak) {
const end = t0 + seconds;
const osc = c.createOscillator();
const gain = c.createGain();
osc.type = type;
osc.frequency.setValueAtTime(from, t0);
osc.frequency.exponentialRampToValueAtTime(to, end);
gain.gain.setValueAtTime(FLOOR, t0);
gain.gain.exponentialRampToValueAtTime(peak, t0 + ATTACK);
gain.gain.exponentialRampToValueAtTime(FLOOR, end);
osc.connect(gain);
gain.connect(c.destination);
osc.start(t0);
osc.stop(end);
}
// Plays one named blip, at `level` (0 to 1) of the usual loudness: a soft
// putt sounds soft. An unknown name, Play sounds off, or a context that is
// missing, suspended or closed all mean silence, not an error.
export function tone(name, level = 1) {
try {
const spec = Object.hasOwn(TONES, name) ? TONES[name] : null;
if (!spec || !looks.sound) return;
const c = audioContext();
if (!c || c.state !== "running") return;
const peak = Math.max(FLOOR * 10, PEAK * Math.min(1, Number(level) || 0));
const t0 = c.currentTime;
if (!spec.notes) return blip(c, spec.type, spec.from, spec.to, t0, spec.seconds, peak);
const each = spec.seconds / spec.notes.length;
spec.notes.forEach((f, i) => blip(c, spec.type, f, f, t0 + i * each, each, peak));
} catch {}
}
+7 -1
View File
@@ -54,6 +54,7 @@ import {
defaultTabId,
deleteTab,
imagePath,
markTabSent,
readNotepad,
removeImage,
renameTab,
@@ -101,6 +102,7 @@ const ROUTES = [
{ path: "/notepad/tab/delete", method: "POST", origin: true, run: notepadTabDelete },
{ path: "/notepad/tab/order", method: "POST", origin: true, run: notepadTabOrder },
{ path: "/notepad/tab/last", method: "POST", origin: true, run: notepadTabLast },
{ path: "/notepad/tab/sent", method: "POST", origin: true, run: notepadTabSent },
{ match: (p, req) => p.startsWith("/notepad/images/") || req.url.startsWith("/notepad/images/"), method: "GET", run: notepadImageGet },
{ match: (p, req) => p.startsWith("/attachments/") || req.url.startsWith("/attachments/"), run: attachment },
{ match: (p, req) => p.startsWith("/shots/") || req.url.startsWith("/shots/"), run: shot },
@@ -652,7 +654,8 @@ function cleanup(req, res, ctx) {
// The person's private notepad for the folder this session runs in, kept by
// notepads.mjs outside the session. Nothing here writes to ctx.dir or the
// event log: the agent reads both, and the notepad is never the agent's.
// event log: the agent reads both, and the agent CLI never imports the store.
// A tab leaves it only through a send the person starts on the dashboard.
const notepadRoot = (ctx) => ctx.worktree() || ctx.project;
function notepadFail(res, e) {
@@ -766,6 +769,9 @@ function notepadTabOrder(req, res, ctx) {
function notepadTabLast(req, res, ctx) {
return notepadTabRoute((root, body) => setLastTab(root, body.id))(req, res, ctx);
}
function notepadTabSent(req, res, ctx) {
return notepadTabRoute((root, body) => markTabSent(root, body.id, { workflow: body.workflow, spec: body.spec }))(req, res, ctx);
}
// Matched on the raw request line too, as /uploads/ is: URL parsing folds
// `..` away, and nothing that needed folding is a notepad picture.
+29 -2
View File
@@ -58,6 +58,29 @@ function maxMtime(dir, depth = 4, budget = { n: 400 }, tally = null) {
return best;
}
// A waiting Revise plan brief: a `**Plan change:**` line in a phase file's
// Notes. Applied or dropped, it reads `**Plan change (applied <date>):**` or
// `(dropped <date>)`, which this never matches.
const PLAN_CHANGE_RE = /^\s*\*\*Plan change:\*\*/m;
// The Notes section of a phase file: from its `## Notes` heading to the next
// `## ` heading, or "" when it has none.
function notesOf(text) {
const at = text.search(/^## Notes\b/m);
if (at < 0) return "";
const rest = text.slice(at).replace(/^## Notes[^\n]*\n?/, "");
const end = rest.search(/^## /m);
return end < 0 ? rest : rest.slice(0, end);
}
// Whether a phased spec has a brief waiting for Revise plan: in the phase file
// overview.md marks `[/]`, or in each phase file when none is marked.
function planChangeWaiting(dir, phases) {
const marked = [...readText(path.join(dir, "overview.md")).matchAll(/^\s*-\s*\[\/\]\s*Phase\s+(\d+)\b/gim)].map((m) => Number(m[1]));
const files = marked.length ? phases.filter((f) => marked.includes(Number((f.match(/^phase-0*(\d+)\.md$/i) || [])[1]))) : phases;
return files.some((f) => PLAN_CHANGE_RE.test(notesOf(readText(path.join(dir, f)))));
}
// A spec folder's pipeline position, from its files alone. Furthest artifact
// wins: an overview beats a draft beats a map, so a spec mid-way through two
// stages reports the later one.
@@ -89,11 +112,15 @@ function classifySpec(dir, names) {
const finished = done + assumed;
const total = finished + open;
const suffix = assumed > 0 ? `, ${assumed} assumed` : "";
if (open === 0 && finished > 0) return { state: "built", detail: `all tasks done${suffix}` };
if (finished > 0) return { state: "building", detail: `${finished} of ${total} tasks done${suffix}` };
// Documented, building and built specs all land here: each says whether a
// Revise plan brief is waiting, and only when one is.
const brief = planChangeWaiting(dir, phases) ? { planChange: true } : {};
if (open === 0 && finished > 0) return { state: "built", detail: `all tasks done${suffix}`, ...brief };
if (finished > 0) return { state: "building", detail: `${finished} of ${total} tasks done${suffix}`, ...brief };
return {
state: "documented",
detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`,
...brief,
};
}
// An overview with no phase files means Document was interrupted mid-write;
+9 -1
View File
@@ -71,6 +71,14 @@ export const SERVABLE = new Set([
"screens/workspace.js",
"screens/ask.js",
"screens/notepad.js",
"screens/activities.js",
"activities.js",
"activities/snake.js",
"activities/golf.js",
"activities/golf-holes.js",
"activities/golf-draw.js",
"activities/golf-decor.js",
"tones.js",
"notepad-tabs.js",
"net.js",
"notepad.js",
@@ -87,7 +95,7 @@ export const SERVABLE = new Set([
// Layers first, then one file per screen, then responsive and print last so
// its overrides still come after everything they override. The files are not
// on SERVABLE: they reach the page only through /app.css.
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "git.css", "responsive.css"];
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "activities.css", "git.css", "responsive.css"];
// The files joined with one newline between them (each file's own last newline
// is that one), as the server serves them before the accent rules. The test