mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 12:45:33 -08:00
Split the web console into by-job files, add page tests and a docs-table test, plus docs
AI Assisted
This commit is contained in:
1 parent
699a827cae
commit
3edb4468a8
121 files changed
+25603
-20145
No files matched your search
@@ -44,16 +44,18 @@ plan2code/
|
||||
│ └── plan2code.ico # Desktop shortcut icon (Windows)
|
||||
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
|
||||
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
|
||||
│ ├── server.mjs, lib.mjs, picker.mjs
|
||||
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings)
|
||||
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
|
||||
│ └── public/ # Page assets served to the browser
|
||||
├── scripts/ # Development scripts
|
||||
│ ├── bench-web-console.mjs # Start-path timing
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
|
||||
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
|
||||
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
|
||||
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
|
||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area, and their shared setup
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
|
||||
│ └── validate-char-count.js # Pre-commit character count validator
|
||||
@@ -148,7 +150,7 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
|
||||
| Script | Skills | Does |
|
||||
|---|---|---|
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/scan.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
|
||||
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
|
||||
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
|
||||
@@ -182,26 +184,78 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
|---|---|
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
|
||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `git-board.js`, `git-board-view.js`, `pr-url.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import `answers.js`, `palette.js`, `labels.js`, `boot.js`, `chat.js`, `help.js` and `starters.js`) parses them as ES modules without a reparse warning |
|
||||
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
|
||||
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser |
|
||||
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop |
|
||||
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
|
||||
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
|
||||
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
|
||||
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` and `removeSpec()` |
|
||||
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
|
||||
| `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/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/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
|
||||
| `public/mention-box.js` | the @name suggestions popover under a text box |
|
||||
| `public/net.js` | the page talking to its own server |
|
||||
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
|
||||
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
|
||||
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
|
||||
| `public/send-state.js` | whether Send is available, and what its button says |
|
||||
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it |
|
||||
| `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/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 |
|
||||
| `public/screens/cleanup.js` | User Preferences, Cleanup tab |
|
||||
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
|
||||
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
|
||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
|
||||
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js) |
|
||||
| `public/screens/looks.js` | User Preferences: looks, sounds and the launcher's model menus |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
|
||||
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
|
||||
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
|
||||
| `public/styles/docs.css` | Documents and the doc tools |
|
||||
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
|
||||
| `public/styles/git.css` | The git board |
|
||||
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
|
||||
| `public/styles/looks.css` | The looks button and the highlight swatches |
|
||||
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
|
||||
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
|
||||
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
|
||||
| `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` | Colours, 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 |
|
||||
| `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 `console.mjs` and `lib.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
|
||||
| `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; `app.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
|
||||
| `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` |
|
||||
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
|
||||
| `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, `console.mjs`, `lib.mjs` and the page |
|
||||
| `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, no imports: the session meter. `WEIGHTS` (the one place per-event points live; 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/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `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, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `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 |
|
||||
| `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 |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
|
||||
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
|
||||
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
|
||||
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
|
||||
@@ -209,35 +263,35 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
|
||||
Key design points:
|
||||
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `app.js`.
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
|
||||
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (`server.mjs` `/version` route). `renderHelpVersion()` in `app.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `server.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `lib.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `lib.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `console.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `lib.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
||||
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
|
||||
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
|
||||
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
|
||||
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
|
||||
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
||||
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
|
||||
|
||||
| File | Writer | Holds |
|
||||
@@ -249,7 +303,7 @@ Key design points:
|
||||
|
||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
|
||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
|
||||
- **A finished quick task's review button is a request through the wait loop**, like the brief: `{ "i": "__review" }` or `{ "i": "__done" }`. The agent keeps waiting after posting a finish that carries `review`, and takes the review up by posting `"finish": null`, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.
|
||||
@@ -257,16 +311,16 @@ Key design points:
|
||||
- **`__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`).
|
||||
- **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 `lib.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 `lib.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 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 17 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, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.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 17 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, 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.
|
||||
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-git`, `-qa`, `-speed`, `-hardening`). Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
|
||||
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
|
||||
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files table above, which the docs-table test (same file) checks.
|
||||
|
||||
## Status Line
|
||||
|
||||
|
||||
@@ -26,9 +26,9 @@
|
||||
- **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.
|
||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
||||
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` in `server.mjs` calls `req.destroy()` past `MAX_BODY`, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, as `readRaw()` (the `POST /upload` reader) does; memory still stays capped.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `lib.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/app.css`. No test ties them together.
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
```bash
|
||||
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
|
||||
# below needs its own npm install, Node 18+)
|
||||
# below needs its own npm install. Running `npm test` needs Node 20+; users of
|
||||
# the installed skills still need only Node 18+)
|
||||
npm install
|
||||
|
||||
# Run the interactive installer
|
||||
@@ -21,16 +22,22 @@ npm test
|
||||
# One web console or launcher test
|
||||
node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
|
||||
|
||||
# Web console start-up benchmark (puppeteer-core optional)
|
||||
# Web console start-up benchmark (the paint columns use a local Chrome or Edge through
|
||||
# playwright-core, which `npm install` already provides)
|
||||
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
|
||||
|
||||
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
|
||||
# Rerun after any change a person would see on the console page, and open every image
|
||||
# before committing: right screen, both themes, no username or home path in frame.
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
# PLAN2CODE_TEST_BROWSER=chrome|msedge forces which browser the page tests and these scripts use
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
|
||||
|
||||
# Compare every element's computed style on every screen before and after a stylesheet change
|
||||
# (dev-only, not in npm test): take a baseline first, then compare after each move
|
||||
node scripts/css-snapshot.mjs --out before.json
|
||||
node scripts/css-snapshot.mjs --compare before.json
|
||||
|
||||
# Plan2Code Loop
|
||||
cd plan2code-loop && npm install # First time setup
|
||||
cd plan2code-loop && npm run build # Build the CLI
|
||||
@@ -51,7 +58,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
|
||||
| Variable | Effect |
|
||||
|----------|--------|
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/lib.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/files.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_NO_BROWSER` | `open` does not launch a browser (`NO_BROWSER` also works). |
|
||||
| `PLAN2CODE_BROWSER` | Browser command line to run with the link appended, instead of the system default. |
|
||||
| `PLAN2CODE_MODELS_DIR` | Moves the launcher model menus (`bin/models.json`, `models.json`) away from `~/.plan2code`, for tests. |
|
||||
@@ -136,14 +143,15 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
|
||||
|
||||
1. Create `src/plan2code-<name>.md` with body content only and keep it under 20,000 characters.
|
||||
2. Register it in `SOURCE_PROMPTS` in `install.js` (with the web-console `additionalReferences` entry every skill carries); add a `generateStepLabel()` case when needed. List any shared scripts it runs in `scripts: [...]`, and put its own scripts in `src/plan2code-<name>-scripts/` (with a `scripts/test-script-<name>.mjs` added to `package.json`'s `test` list).
|
||||
3. Register it with the web console, every one of these (the tests fail on a miss, but not all at once):
|
||||
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (checked by `scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
|
||||
- `src/web-console/public/answers.js`: `WORKFLOW_LABEL`, `CONSOLE_WORKFLOWS`, `resumeCommand()`, a `SKILL_CATALOG` card (utilities go in group `"extra"` before Changelog: tests pin Changelog, Git, then Handoff last), `START_POSES` and `cardAvailability()`.
|
||||
- `src/web-console/public/meter.js`: `WEIGHTS`, `LAUNCH_COUNTED` (if its launch scores), `WORKFLOW_NAMES`, `LAUNCH_LABELS`, `RUN_LABELS`; and in `src/web-console/console-meter.md` the event list, plus the sentence near its top naming the skills that score on launch (when it joins `LAUNCH_COUNTED`).
|
||||
- `src/web-console/public/index.html`: a start-pose `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `app.css`), and a line in Help's About list.
|
||||
- `src/web-console/notes/<workflow>.md`, named in the skill's Interface line.
|
||||
- `src/web-console/console.mjs` usage text, and `src/web-console/console.md` (the `open --workflow` list and the `notes/<workflow>.md` row).
|
||||
- Tests: `notesFor` in `scripts/test-web-console-speed.mjs` and `CONSOLE_WORKFLOW_LIST` in `scripts/test-web-console-logic.mjs`.
|
||||
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general") and `SUBAGENT_WORKFLOWS` in `public/subagents.js` (only for skills that offer helpers).
|
||||
3. Register it with the web console (a short list; `npm test` names anything missed):
|
||||
- `src/web-console/public/skills.js`: one entry (workflow, label, start pose, flags, subagents line) with its card, and the card's `states` and `greyed`. Utilities go in group `"extra"` before Changelog.
|
||||
- `src/web-console/public/meter.js`: a `WEIGHTS` entry if its launch scores.
|
||||
- `src/web-console/public/index.html`: its start pose, an `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `public/styles/poses.css`).
|
||||
- Its help topic: a `src/web-console/notes/<workflow>.md` (named in the skill's Interface line) or a `HELP_TOPICS` alias in `src/web-console/cmd-help.mjs`.
|
||||
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (`scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
|
||||
- `console.md` (the `open --workflow` list and the `notes/<workflow>.md` row) and the `console.mjs` usage text.
|
||||
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general").
|
||||
|
||||
**Adding a spec state** is shorter: one entry in `src/web-console/public/spec-states.js`, the detection in `classifySpec()` in `src/web-console/scan.mjs`, the `states` of each card in `skills.js` that takes it, and a line in the dashboard skill (`src/plan2code.md`); then `npm test`.
|
||||
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md` (prompt table, own-script rows, notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
|
||||
5. Run `npm run build:skills` and `npm test`.
|
||||
@@ -90,12 +90,12 @@ Both are cheap to enforce mechanically in the server's write path.
|
||||
```
|
||||
src/web-console/
|
||||
console.mjs CLI: open | post | wait | status | stop
|
||||
server.mjs the HTTP server (spawned detached by `open`)
|
||||
lib.mjs paths, atomic writes, patch merge, validate()
|
||||
server.mjs the HTTP server (spawned detached by `open`); routes.mjs lists its URLs
|
||||
files.mjs, sessions.mjs, patches.mjs, scan.mjs, ... paths, atomic writes, patch merge, validate(), the repo scan
|
||||
console.md the agent-facing contract
|
||||
public/index.html markup shell only
|
||||
public/app.js the client (no inline script, see CSP below)
|
||||
public/app.css
|
||||
public/app.js the client's entry (no inline script, see CSP below); screens/ and state.js hold the rest
|
||||
public/styles/ the stylesheet, joined by the server into /app.css
|
||||
public/render.js markdown tokens to DOM nodes
|
||||
public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only
|
||||
```
|
||||
|
||||
@@ -803,13 +803,13 @@ origin.
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Source | `src/web-console/` |
|
||||
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
|
||||
| Ships as | `skills/<every skill>/references/web-console/` |
|
||||
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/answers.js` (`SKILL_CATALOG`) |
|
||||
| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/<workflow>.md`, and `building.md` / `building-review.md` for the builds; `console.mjs help <topic>` prints any of them |
|
||||
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs `puppeteer-core` and a local Chrome or Edge for the paint columns; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs `puppeteer-core` and a local Chrome or Edge) |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only |
|
||||
|
||||
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
|
||||
@@ -882,7 +882,6 @@ after any change a person would see on the page: a new layout, a renamed
|
||||
button, a different colour.
|
||||
|
||||
```bash
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen
|
||||
```
|
||||
|
||||
@@ -67,7 +67,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
|
||||
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `app.js` switches mood with a single class, so the drawing stays in the markup and the styling in `app.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
|
||||
```
|
||||
╭───╮
|
||||
@@ -102,5 +102,6 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed).
|
||||
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
|
||||
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
|
||||
- When you move a dashboard card, update every test that pins `SKILL_CATALOG` order (`scripts/test-web-console-source.mjs` and `scripts/test-web-console-git.mjs`): the Handoff move once updated only one and left `npm test` red.
|
||||
- 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 `npm test` fails only timing-bound suites (the chat stress test, then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split.
|
||||
- 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`.
|
||||
@@ -38,6 +38,10 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **init**, **init-update**: the *Keeping this file current* section they write into `AGENTS.md` gains three rules: a rule broken twice becomes an automated check, a new Failure log line first looks for one on the same topic to sharpen instead, and the log holds 17 entries at most (over the cap, merge entries that share a cause, then drop the lowest-value ones). Init update offers the missing rules to an existing section and tidies the log on every run, showing each merge and removal for a yes before it writes.
|
||||
- **contributors**: this repo's `AGENTS.md` follows the same Failure log rules, and its three post-sync grep entries are merged into one.
|
||||
|
||||
- **contributors**: the web console's source is split by job: `lib.mjs`, `server.mjs`, `console.mjs`, `app.js` and `app.css` become `routes.mjs`, `static.mjs`, `cmd-*.mjs`, the by-job Node files, `public/screens/` and `public/styles/`. Nothing a person sees changes, and the page starts faster (ready in about 280 ms, was 450 ms).
|
||||
- **contributors**: the per-skill and per-spec-state tables live in two data files, `public/skills.js` and `public/spec-states.js`, so adding a skill or a state is a short list in `.agents-docs/AGENTS-development-commands.md` and `npm test` names anything missed. This replaces the long add-a-skill checklist noted above.
|
||||
- **contributors**: page tests drive the real console in Chrome or Edge through `playwright-core` inside `npm test` (running it needs Node 20 or newer; installed skills still need only Node 18). The screenshot and speed scripts use it too, with no hand install, and `scripts/css-snapshot.mjs` compares every computed style across a stylesheet change.
|
||||
- **contributors**: a test keeps the files table in `.agents-docs/AGENTS-architecture.md` complete: every console file needs a one-line row.
|
||||
### 🗑️ Removed
|
||||
|
||||
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favour of `console.mjs handoff new`, which every skill can reach.
|
||||
|
||||
+1
-1
@@ -2840,4 +2840,4 @@ if (require.main === module) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { update, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled };
|
||||
module.exports = { update, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
|
||||
+3
-2
@@ -8,9 +8,10 @@
|
||||
"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 --test 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-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-handoffs.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.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 --test 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-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-handoffs.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"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0"
|
||||
"husky": "^9.0.0",
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
}
|
||||
@@ -16,15 +16,17 @@
|
||||
// fcp first contentful paint: the person sees something
|
||||
// ready the session is drawn from real state (the menu, or a question)
|
||||
//
|
||||
// plus the bytes and request count the page cost. Needs puppeteer-core in
|
||||
// node_modules and a local Chrome or Edge for the browser columns; without
|
||||
// them it still reports url/cliExit and an HTTP-only waterfall.
|
||||
// plus the bytes and request count the page cost. The browser columns need
|
||||
// playwright-core (from `npm install`) and a local Chrome or Edge, picked by
|
||||
// scripts/browser.mjs; without a browser it still reports url/cliExit and an
|
||||
// HTTP-only waterfall.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -44,20 +46,6 @@ const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER
|
||||
// so a slow GitHub never colours the timings.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
function findBrowser() {
|
||||
if (args.browser === "none") return null;
|
||||
if (typeof args.browser === "string") return args.browser;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
// Resolves at the first stdout line carrying a url, and again at exit.
|
||||
// --launch hook (default): `open` launches "the browser" the way it would for
|
||||
// a person, through PLAN2CODE_BROWSER, and the hook just writes the link to
|
||||
@@ -211,18 +199,22 @@ async function roundtrip() {
|
||||
|
||||
async function main() {
|
||||
if (args.roundtrip) return roundtrip();
|
||||
const browserPath = findBrowser();
|
||||
let puppeteer = null;
|
||||
if (browserPath) {
|
||||
// --browser none: no launch at all. --browser <path>: that executable.
|
||||
// Otherwise the helper's pick; a browser problem is one line, then the
|
||||
// HTTP-only waterfall.
|
||||
let browser = null;
|
||||
let browserName = null;
|
||||
if (args.browser !== "none") {
|
||||
const custom = typeof args.browser === "string" ? args.browser : null;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
console.error("puppeteer-core not installed; browser columns skipped");
|
||||
browser = await launchBrowser(custom ? { executablePath: custom } : {});
|
||||
const found = custom ? null : findBrowser();
|
||||
browserName = found ? `${found.channel} (${found.path})` : custom;
|
||||
} catch (e) {
|
||||
if (!e.browserProblem) throw e;
|
||||
console.error(e.message);
|
||||
}
|
||||
}
|
||||
const browser = puppeteer
|
||||
? await puppeteer.launch({ executablePath: browserPath, headless: true, args: ["--no-first-run", "--no-default-browser-check"] })
|
||||
: null;
|
||||
|
||||
const rows = [];
|
||||
// One throwaway run so disk caches and the Node binary are warm; the person
|
||||
@@ -231,7 +223,7 @@ async function main() {
|
||||
stopAll();
|
||||
// The tab exists before the clock starts: a person's browser is already
|
||||
// running, and creating a context is the harness's cost, not the page's.
|
||||
const ctx = browser ? await browser.createBrowserContext() : null;
|
||||
const ctx = browser ? await browser.newContext() : null;
|
||||
const page = ctx ? await ctx.newPage() : null;
|
||||
const { t0, urlP, exitP, openP } = runOpen();
|
||||
const o = await openP;
|
||||
@@ -246,7 +238,7 @@ async function main() {
|
||||
page.on("response", async (res) => {
|
||||
requests++;
|
||||
try {
|
||||
bytes += (await res.buffer()).length;
|
||||
bytes += (await res.body()).length;
|
||||
} catch {}
|
||||
});
|
||||
if (BROWSER_DELAY) await new Promise((r) => setTimeout(r, Math.max(0, o.at + BROWSER_DELAY - Date.now())));
|
||||
@@ -303,7 +295,7 @@ async function main() {
|
||||
};
|
||||
const summary = Object.fromEntries(cols.map((k) => [k, stat(k)]));
|
||||
console.log(`web console start-up, ${RUNS} runs, workflow=${WORKFLOW}, cwd=${CWD}`);
|
||||
console.log(`browser: ${browser ? browserPath : "none (HTTP-only waterfall)"}`);
|
||||
console.log(`browser: ${browser ? browserName : "none (HTTP-only waterfall)"}`);
|
||||
console.log("metric".padEnd(10) + "median".padStart(9) + "min".padStart(9) + "max".padStart(9));
|
||||
for (const k of cols) {
|
||||
const s = summary[k];
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Picks and launches the browser for page tests and the dev scripts. Dev-only:
|
||||
// lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// The first installed of Chrome then Edge, through playwright-core (a root
|
||||
// devDependency); PLAN2CODE_TEST_BROWSER=chrome or msedge forces one. Every
|
||||
// failure is one line in our own words, never Playwright's install hint.
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
// The fixed places each browser installs to, probed in order on every
|
||||
// platform (a path that cannot exist here is simply not found).
|
||||
export const BROWSER_PATHS = {
|
||||
chrome: [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/google-chrome-stable",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
],
|
||||
msedge: [
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/microsoft-edge",
|
||||
"/usr/bin/microsoft-edge-stable",
|
||||
],
|
||||
};
|
||||
|
||||
const CHANNELS = Object.keys(BROWSER_PATHS);
|
||||
|
||||
// Returns { channel, path } for the first browser found, or null. Either way
|
||||
// findBrowser.checked lists every path this call looked at.
|
||||
export function findBrowser({ env = process.env, exists = fs.existsSync } = {}) {
|
||||
const forced = env.PLAN2CODE_TEST_BROWSER;
|
||||
if (forced && !CHANNELS.includes(forced)) {
|
||||
throw new Error(`PLAN2CODE_TEST_BROWSER must be ${CHANNELS.join(" or ")} (it is "${forced}").`);
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
for (const channel of forced ? [forced] : CHANNELS) {
|
||||
for (const p of BROWSER_PATHS[channel]) {
|
||||
findBrowser.checked.push(p);
|
||||
if (exists(p)) return { channel, path: p };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
|
||||
// null when page tests can run here, otherwise the one line that says why
|
||||
// not. `checked` defaults to the paths the last findBrowser() call probed.
|
||||
export function browserProblem({ nodeVersion = process.versions.node, found, checked = findBrowser.checked } = {}) {
|
||||
if (Number(nodeVersion.split(".")[0]) < 20) {
|
||||
return `Page tests need Node 20 or newer (this is ${nodeVersion}). Users of Plan2Code still only need Node 18.`;
|
||||
}
|
||||
if (!found) {
|
||||
return `Page tests need Chrome or Edge. Looked in: ${checked.join(", ")}. Install either one, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Launches the browser findBrowser() picks, headless. `options` go to
|
||||
// Playwright's chromium.launch() as they are (an `executablePath` there skips
|
||||
// the pick); `find` hands findBrowser() its env and exists, for tests. A
|
||||
// problem rejects with an Error whose message is our one line and whose
|
||||
// `browserProblem` is true, never Playwright's own launch text.
|
||||
export async function launchBrowser(options = {}, find = {}) {
|
||||
const found = options.executablePath ? { channel: null, path: options.executablePath } : findBrowser(find);
|
||||
const problem = browserProblem({ found });
|
||||
if (problem) throw Object.assign(new Error(problem), { browserProblem: true });
|
||||
let chromium;
|
||||
try {
|
||||
({ chromium } = await import("playwright-core"));
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("Page tests need playwright-core: run npm install.", { cause: e }), { browserProblem: true });
|
||||
}
|
||||
try {
|
||||
return await chromium.launch({
|
||||
executablePath: found.path,
|
||||
headless: true,
|
||||
args: ["--no-first-run", "--no-default-browser-check"],
|
||||
...options,
|
||||
});
|
||||
} catch (e) {
|
||||
// Playwright's own text stays out of the message, but is kept as the
|
||||
// cause for whoever needs to debug a real launch failure.
|
||||
const line = `Page tests could not start the browser at ${found.path}. Install Chrome or Edge, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
throw Object.assign(new Error(line, { cause: e }), { browserProblem: true });
|
||||
}
|
||||
}
|
||||
+197
-51
@@ -3,7 +3,7 @@
|
||||
// it never ships inside a skill.
|
||||
//
|
||||
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
|
||||
// [--out <dir>]
|
||||
// [--out <dir>] [--compare]
|
||||
//
|
||||
// Every shot is staged with no agent: a throwaway sample project called
|
||||
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
|
||||
@@ -14,16 +14,27 @@
|
||||
// it is the console's nearest to the Plan2Code blue the site and README use.
|
||||
//
|
||||
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask, git.
|
||||
// --compare adds workspace, stop, delete, help, prefs and cleanup: screens the
|
||||
// docs never show, for checking a change by eye against a "before" set. Its
|
||||
// --out must be outside docs/screenshots/, so the set is never published.
|
||||
//
|
||||
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
|
||||
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
|
||||
// folders and --out.
|
||||
// --snapshot <file> (used by scripts/css-snapshot.mjs) takes no pictures: it
|
||||
// writes every element's computed style, per screen, theme and width, to <file>.
|
||||
// It sees what these shots stage: choice, multi, text, review and confirm cards;
|
||||
// a checklist, list, recap or menu card is not staged, so a rule only they use
|
||||
// is not covered.
|
||||
//
|
||||
// Needs playwright-core (a root devDependency, so `npm install` brings it) and
|
||||
// a local Chrome or Edge, launched through scripts/browser.mjs. Playwright has
|
||||
// no WebP screenshots, so each shot is taken over CDP. Writes nothing outside
|
||||
// its temp folders and --out.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -72,6 +83,82 @@ const SHOTS = {
|
||||
git: { workflow: "git", posts: ["git"], repo: true },
|
||||
};
|
||||
|
||||
// --compare only: the screens the docs never show, shot so a change to the
|
||||
// console can be checked against a "before" set by eye. `open` runs on the
|
||||
// page after every load and clicks through to the screen. Never published.
|
||||
const COMPARE_SHOTS = {
|
||||
// The confirm dialog, with the handoff choice beside plain stop.
|
||||
stop: {
|
||||
workflow: "implement",
|
||||
posts: ["stop"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-stop");
|
||||
await page.waitForSelector("#stop-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// The first step of a spec chip's delete.
|
||||
delete: {
|
||||
workflow: "dashboard",
|
||||
posts: ["delete"],
|
||||
open: async (page) => {
|
||||
await page.locator(".spec-chip-del").first().click({ force: true });
|
||||
await page.waitForSelector("#delete-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Help on its first tab, whatever topic it opened on.
|
||||
help: {
|
||||
workflow: "plan",
|
||||
posts: ["help"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-about");
|
||||
await page.locator("#help-tabs .help-tab").first().click();
|
||||
await page.waitForSelector("#help-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
prefs: {
|
||||
workflow: "plan",
|
||||
posts: ["prefs"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Preferences scrolled to Cleanup once its scan has answered.
|
||||
cleanup: {
|
||||
workflow: "plan",
|
||||
posts: ["cleanup"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
await page.locator(".looks-cleanup").scrollIntoViewIfNeeded();
|
||||
await page.click("#cleanup-scan");
|
||||
await page.waitForFunction(() => document.getElementById("cleanup-status").textContent.trim() !== "", null, { timeout: 15000 }).catch(() => {});
|
||||
},
|
||||
},
|
||||
// The panel open with two folders: the project and a sibling added once.
|
||||
// Last, since the console remembers the folder for the project and every
|
||||
// later shot's footer would count it.
|
||||
workspace: {
|
||||
workflow: "plan",
|
||||
posts: ["workspace"],
|
||||
open: async (page) => {
|
||||
const extra = makeExtraFolder();
|
||||
await page.evaluate(async (dir) => {
|
||||
const now = await (await fetch("/workspace", { cache: "no-store" })).json();
|
||||
if ((now.folders || []).length < 2) {
|
||||
await fetch("/workspace/add", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ path: dir, name: "task-web", description: "The web app that calls the API" }),
|
||||
});
|
||||
}
|
||||
}, extra);
|
||||
await page.click("#footer-where");
|
||||
await page.waitForSelector("#workspace-modal[open] #workspace-list li:nth-child(2)", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// On Windows the temp dir sits under the user's profile, and the page can
|
||||
// show the project's path, so the sample project goes at the drive root
|
||||
// instead. Elsewhere the temp dir carries no username. Each run makes its own
|
||||
@@ -89,21 +176,6 @@ function fail(message) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
function phaseFile(n, name, tasks, done) {
|
||||
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
|
||||
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
|
||||
@@ -169,6 +241,14 @@ function makeSampleProject() {
|
||||
return project;
|
||||
}
|
||||
|
||||
// The Workspace shot's second folder, beside the sample project.
|
||||
function makeExtraFolder() {
|
||||
const dir = path.join(SCRATCH, "task-web");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "README.md"), "# task-web\n\nThe web app that lists and edits a team's tasks.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
function git(cwd, ...gitArgs) {
|
||||
const r = spawnSync("git", gitArgs, { cwd, env: ENV, encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`git ${gitArgs.join(" ")} failed: ${(r.stderr || "").trim()}`);
|
||||
@@ -225,8 +305,7 @@ function post(project, sid, name) {
|
||||
}
|
||||
|
||||
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
|
||||
function stage(project, shot) {
|
||||
const spec = SHOTS[shot];
|
||||
function stage(project, spec) {
|
||||
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
|
||||
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
|
||||
for (const name of spec.posts) post(project, r.out.sid, name);
|
||||
@@ -236,9 +315,9 @@ function stage(project, shot) {
|
||||
// Waits for the page to draw real state, then lets the animations finish
|
||||
// (the dashboard's wake-up is the longest).
|
||||
async function settle(page) {
|
||||
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
|
||||
await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc, .git-board", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(3500);
|
||||
await sleep(args.snapshot ? 1800 : 3500);
|
||||
}
|
||||
|
||||
async function openTab(page, label) {
|
||||
@@ -251,7 +330,7 @@ async function openTab(page, label) {
|
||||
|
||||
async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const problem = await page.evaluate(
|
||||
(topSel, showSel) => {
|
||||
([topSel, showSel]) => {
|
||||
const find = (sel) =>
|
||||
sel.startsWith("cmd:")
|
||||
? [...document.querySelectorAll(".dash-card")].find((c) => c.querySelector(".dash-card-cmd")?.textContent.trim() === sel.slice(4))
|
||||
@@ -265,24 +344,95 @@ async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const r = show.getBoundingClientRect();
|
||||
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
|
||||
},
|
||||
top,
|
||||
mustShow || null
|
||||
[top, mustShow || null]
|
||||
);
|
||||
if (problem) console.log(` warning: ${problem}`);
|
||||
await sleep(300);
|
||||
}
|
||||
|
||||
// The properties that change how a stylesheet move would look.
|
||||
const SNAP_PROPS = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
// Recorded after the properties above, for every element: what names its animation.
|
||||
// A property a running animation is moving is recorded as "~" (it differs from run
|
||||
// to run), so a rule that adds or removes an animation shows in these fields instead.
|
||||
const SNAP_ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
const SNAP = {};
|
||||
|
||||
async function snapshotNow(page) {
|
||||
return page.evaluate(
|
||||
([props, animation]) => {
|
||||
const out = {};
|
||||
const seen = new Map();
|
||||
for (const el of document.querySelectorAll("*")) {
|
||||
const parent = el.parentElement;
|
||||
const key = parent ? (seen.get(parent) || "") : "";
|
||||
const sib = parent ? [...parent.children].indexOf(el) : 0;
|
||||
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 3).join(".") : "";
|
||||
const path = (parent ? key + ">" : "") + el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (cls ? "." + cls : "") + "[" + sib + "]";
|
||||
seen.set(el, path);
|
||||
const cs = getComputedStyle(el);
|
||||
const moving = new Set();
|
||||
for (const a of el.getAnimations ? el.getAnimations() : []) {
|
||||
for (const kf of a.effect && a.effect.getKeyframes ? a.effect.getKeyframes() : []) {
|
||||
for (const k of Object.keys(kf)) if (!["offset", "easing", "composite", "computedOffset"].includes(k)) moving.add(k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()));
|
||||
}
|
||||
}
|
||||
out[path] = props.map((p) => (moving.has(p) ? "~" : cs.getPropertyValue(p))).concat(animation.map((p) => cs.getPropertyValue(p))).join("|");
|
||||
}
|
||||
return out;
|
||||
},
|
||||
[SNAP_PROPS, SNAP_ANIMATION]
|
||||
);
|
||||
}
|
||||
|
||||
async function snapshotShot(page, name, theme) {
|
||||
for (const [w, h] of [[1280, 800], [390, 844]]) {
|
||||
await page.setViewportSize({ width: w, height: h });
|
||||
await sleep(1500);
|
||||
SNAP[`${name}/${theme}/${w}`] = await snapshotNow(page);
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const written = [];
|
||||
// Math.random picks Planny's mood variants; pinned so two runs draw the same page.
|
||||
if (args.snapshot) await page.addInitScript(() => { Math.random = () => 0.5; });
|
||||
for (const theme of THEMES) {
|
||||
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
|
||||
await page.emulateMedia({ colorScheme: theme });
|
||||
// The theme is applied at load, so reload rather than trust a live switch.
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
if (page.__tab) await openTab(page, page.__tab);
|
||||
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
|
||||
if (page.__open) {
|
||||
await page.__open(page);
|
||||
await sleep(600);
|
||||
}
|
||||
if (args.snapshot) {
|
||||
await snapshotShot(page, name, theme);
|
||||
continue;
|
||||
}
|
||||
const file = path.join(OUT, `${name}-${theme}.webp`);
|
||||
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
// Without a clip the capture comes out in CSS pixels; a clip of the
|
||||
// viewport at scale 2 is the twice-density shot (byte for byte what
|
||||
// Playwright's own PNG screenshot takes).
|
||||
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
|
||||
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: QUALITY, captureBeyondViewport: false, clip });
|
||||
await cdp.detach();
|
||||
fs.writeFileSync(file, Buffer.from(data, "base64"));
|
||||
const kb = Math.round(fs.statSync(file).size / 1024);
|
||||
console.log(`${path.basename(file)} ${kb} KB`);
|
||||
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
|
||||
@@ -292,15 +442,15 @@ async function shoot(page, name) {
|
||||
}
|
||||
|
||||
// Opens the page for a staged session and saves both themes.
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow, open }) {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
page.__tab = tab || null;
|
||||
page.__scroll = { scrollTo: top, mustShow };
|
||||
page.__open = open || null;
|
||||
return await shoot(page, name);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
@@ -310,15 +460,14 @@ async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
// The Ask shot: a question typed and sent on the page, collected with `chat`
|
||||
// the way an agent would, and answered with a posted reply.
|
||||
async function captureAsk(browser, project, sid, url, question) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
await openTab(page, "Ask");
|
||||
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
|
||||
await page.type("#ask-input", question);
|
||||
await page.locator("#ask-input").pressSequentially(question);
|
||||
await page.evaluate(() => {
|
||||
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
|
||||
if (send) send.click();
|
||||
@@ -360,17 +509,14 @@ async function captureAsk(browser, project, sid, url, question) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const names = args.only ? [args.only] : Object.keys(SHOTS);
|
||||
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
|
||||
|
||||
let puppeteer;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
|
||||
const docs = path.join(ROOT, "docs", "screenshots");
|
||||
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
||||
if (args.compare && (fold(OUT) === fold(docs) || fold(OUT).startsWith(fold(docs) + path.sep))) {
|
||||
fail(`--compare never writes into ${path.relative(ROOT, docs)}: pass --out with a folder outside it.`);
|
||||
}
|
||||
const browserPath = findBrowser();
|
||||
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
|
||||
const table = args.compare ? { ...SHOTS, ...COMPARE_SHOTS } : SHOTS;
|
||||
const names = args.only ? [args.only] : Object.keys(table);
|
||||
for (const n of names) if (!table[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(table).join(", ")}`);
|
||||
|
||||
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
|
||||
HOME = path.join(SCRATCH, "console-home");
|
||||
@@ -385,21 +531,21 @@ async function main() {
|
||||
// and the Ocean highlight is the console's nearest to the Plan2Code blue
|
||||
// the landing page uses.
|
||||
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean", welcomeSeen: true } }));
|
||||
browser = await puppeteer.launch({
|
||||
executablePath: browserPath,
|
||||
headless: true,
|
||||
browser = await launchBrowser({
|
||||
...(typeof args.browser === "string" ? { executablePath: args.browser } : {}),
|
||||
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
|
||||
});
|
||||
for (const name of names) {
|
||||
const where = SHOTS[name].repo ? makeGitProject() : project;
|
||||
const { sid, url } = stage(where, name);
|
||||
const where = table[name].repo ? makeGitProject() : project;
|
||||
const { sid, url } = stage(where, table[name]);
|
||||
try {
|
||||
if (SHOTS[name].ask) await captureAsk(browser, where, sid, url, SHOTS[name].ask);
|
||||
else await capture(browser, url, name, SHOTS[name]);
|
||||
if (table[name].ask) await captureAsk(browser, where, sid, url, table[name].ask);
|
||||
else await capture(browser, url, name, table[name]);
|
||||
} finally {
|
||||
cli(where, "stop", "--session", sid);
|
||||
}
|
||||
}
|
||||
if (args.snapshot) fs.writeFileSync(path.resolve(String(args.snapshot)), JSON.stringify(SNAP));
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (project) cli(project, "stop", "--all");
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
// The console's stylesheet as the tests read it: the files under
|
||||
// public/styles/ joined in the server's own order, without the accent rules.
|
||||
// A rule moving between files never breaks a test; only a rule that changes
|
||||
// or vanishes does.
|
||||
|
||||
import { joinedStyles } from "../src/web-console/static.mjs";
|
||||
|
||||
export function joinedCss() {
|
||||
return joinedStyles().toString("utf8");
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env node
|
||||
// The cheapest check for a stylesheet move: every element's computed style, on
|
||||
// every screen the console has, in both themes, at desktop and phone width.
|
||||
// Dev-only, not in `npm test`. Stages the screens the way
|
||||
// scripts/capture-screenshots.mjs does (its --snapshot mode), so the sample
|
||||
// project and payloads are the same.
|
||||
//
|
||||
// node scripts/css-snapshot.mjs [--out <file>] write a snapshot
|
||||
// node scripts/css-snapshot.mjs --compare <file> take one now and print every difference
|
||||
//
|
||||
// Take a baseline before moving any rule, then compare after each move. Two
|
||||
// runs in a row on the same stylesheet report nothing: Math.random is pinned,
|
||||
// a property a running animation is moving is recorded as "~" (its animation
|
||||
// fields are still compared), and heights within 4px are ignored (see jitter).
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
|
||||
}
|
||||
|
||||
function take(file) {
|
||||
// The screenshot script wants a folder to exist for --compare; nothing is written to it.
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-css-snap-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--snapshot", file, "--out", out], { stdio: ["ignore", "inherit", "inherit"] });
|
||||
if (r.status !== 0) {
|
||||
console.error("the snapshot run failed");
|
||||
process.exit(1);
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const NAMES = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
const ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
// A growing answer box at phone width settles a few pixels either way from one
|
||||
// run to the next with the same stylesheet; the heights it carries up the page
|
||||
// (and the transform origin, which is half of one) are not a stylesheet's doing.
|
||||
const JITTER = new Set(["height", "min-height", "transform-origin"]);
|
||||
function jitter(name, a, b) {
|
||||
if (!JITTER.has(name)) return false;
|
||||
const na = a.match(/-?\d+(?:\.\d+)?/g);
|
||||
const nb = b.match(/-?\d+(?:\.\d+)?/g);
|
||||
return !!na && !!nb && na.length === nb.length && na.every((n, i) => Math.abs(n - nb[i]) <= 4);
|
||||
}
|
||||
|
||||
function compare(before, after) {
|
||||
const diffs = [];
|
||||
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
||||
const a = before[key];
|
||||
const b = after[key];
|
||||
if (!a || !b) {
|
||||
diffs.push(`${key}: screen ${a ? "missing from the new run" : "is new"}`);
|
||||
continue;
|
||||
}
|
||||
for (const el of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[el] === b[el] || el.includes("p.dock-say")) continue; // the one line of Planny that types itself in, so its width moves
|
||||
if (a[el] === undefined || b[el] === undefined) {
|
||||
diffs.push(`${key} ${el}: element ${a[el] === undefined ? "added" : "gone"}`);
|
||||
continue;
|
||||
}
|
||||
const x = a[el].split("|");
|
||||
const y = b[el].split("|");
|
||||
const names = NAMES.concat(ANIMATION);
|
||||
x.forEach((v, i) => {
|
||||
if (v !== y[i] && v !== "~" && y[i] !== "~" && !jitter(names[i], v, y[i])) diffs.push(`${key} ${el} ${names[i] ?? i}: ${v} -> ${y[i]}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (args.compare === true) {
|
||||
console.error("usage: node scripts/css-snapshot.mjs --compare <snapshot file> (or --out <file> to take one)");
|
||||
process.exit(1);
|
||||
} else if (typeof args.compare === "string") {
|
||||
const tmp = path.join(os.tmpdir(), `p2c-css-snap-${process.pid}.json`);
|
||||
take(tmp);
|
||||
const diffs = compare(JSON.parse(fs.readFileSync(args.compare, "utf8")), JSON.parse(fs.readFileSync(tmp, "utf8")));
|
||||
fs.rmSync(tmp, { force: true });
|
||||
for (const d of diffs.slice(0, 200)) console.log(d);
|
||||
if (diffs.length > 200) console.log(`... and ${diffs.length - 200} more`);
|
||||
console.log(diffs.length ? `${diffs.length} difference(s)` : "no differences");
|
||||
process.exit(diffs.length ? 1 : 0);
|
||||
} else {
|
||||
const out = path.resolve(typeof args.out === "string" ? args.out : "css-snapshot.json");
|
||||
take(out);
|
||||
console.log(`wrote ${out} (${Math.round(fs.statSync(out).size / 1024)} KB)`);
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Start a real console and open its page in a real browser, for the page tests
|
||||
// (scripts/test-web-console-page-*.mjs).
|
||||
//
|
||||
// One browser per test file (pageSuite), a fresh console session and browser
|
||||
// context per test (openSession). Sessions run against the file's own console
|
||||
// home from web-console-test-helpers.mjs, in a temp project unless a test
|
||||
// names one. Any uncaught error on the page fails the test that opened it, so
|
||||
// a later split that breaks a screen shows as a named error, not a blank page.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { cli, payload, until, HOME, REMEMBERED } from "./web-console-test-helpers.mjs";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
// `test` is node:test's test function (or any context with .after): the
|
||||
// browser is launched the first time a test asks for it and closed once the
|
||||
// file is done.
|
||||
export function pageSuite(test) {
|
||||
let launching = null;
|
||||
test.after(async () => {
|
||||
if (launching) await (await launching).close();
|
||||
});
|
||||
return {
|
||||
browser: () => (launching ??= launchBrowser()),
|
||||
};
|
||||
}
|
||||
|
||||
let projects = 0;
|
||||
let payloads = 0;
|
||||
|
||||
// A fresh project folder under the file's console home, removed with it.
|
||||
export function tempProject(files = {}) {
|
||||
const dir = path.join(HOME, "projects", `p${++projects}`);
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, rel), text);
|
||||
}
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens a console session the way an agent does (`console.mjs open`, then
|
||||
// `post`), and its page in a new browser context. Resolves once the page has
|
||||
// drawn from the session's real state, not the boot pane in the markup.
|
||||
// `t` is the test's context: stop() is registered with t.after, so a failing
|
||||
// test still cleans up, and a page error fails the test. `clock: true` gives
|
||||
// the page Playwright's fake clock before it loads (s.page.clock), so a test
|
||||
// can jump past the page's silence limits instead of sitting through them.
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
|
||||
fs.rmSync(REMEMBERED, { force: true });
|
||||
const cwd = project || tempProject();
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
|
||||
const s = {
|
||||
sid: opened.sid,
|
||||
session: opened.session,
|
||||
url: opened.url,
|
||||
project: cwd,
|
||||
errors: [],
|
||||
context: null,
|
||||
page: null,
|
||||
};
|
||||
|
||||
// The agent's side, run from the project like an agent would.
|
||||
s.post = (patch) => {
|
||||
const r = cli(["post", "--session", s.sid, "--file", payload(`page-post-${++payloads}.json`, patch)], { cwd });
|
||||
if (r.status !== 0) throw new Error(`post failed (${r.status}): ${r.stderr}`);
|
||||
return r.json;
|
||||
};
|
||||
s.wait = (seconds = 10) => {
|
||||
const r = cli(["wait", "--session", s.sid, "--seconds", String(seconds)], { cwd });
|
||||
return { code: r.status, ...(r.json || {}) };
|
||||
};
|
||||
// Whether the session's server still answers on its port.
|
||||
s.answers = async () => {
|
||||
try {
|
||||
await fetch(new URL("/health", s.url), { signal: AbortSignal.timeout(1000) });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let stopped = false;
|
||||
s.stop = async () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cli(["stop", "--session", s.sid], { cwd });
|
||||
if (s.context) await s.context.close().catch(() => {});
|
||||
await until(async () => !(await s.answers()), 5000);
|
||||
};
|
||||
t.after(async () => {
|
||||
await s.stop();
|
||||
if (s.errors.length) throw new Error(`uncaught error on the page: ${s.errors[0]}`);
|
||||
});
|
||||
|
||||
if (first) s.post(first);
|
||||
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
if (clock) await s.context.clock.install();
|
||||
s.page = await s.context.newPage();
|
||||
s.page.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
return s;
|
||||
}
|
||||
|
||||
// The page has adopted a state frame: app.js has replaced the boot pane the
|
||||
// markup ships with.
|
||||
export async function drawn(page) {
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
|
||||
}
|
||||
|
||||
// Presses Send on the page and collects the send the way an agent's `wait`
|
||||
// does: the same JSON an agent receives.
|
||||
export async function sendAndCollect(s) {
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
if (got.code !== 0) throw new Error(`nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The card for one item id.
|
||||
export const itemCard = (page, id) => page.locator(`[data-item="${id}"]`).first();
|
||||
|
||||
// A locator's visible text, trimmed.
|
||||
export const textOf = async (locator) => (await locator.innerText()).trim();
|
||||
|
||||
// The scroll offset of the first element matching `selector`.
|
||||
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
|
||||
@@ -17,3 +17,20 @@ and dark WebP images in `docs/screenshots/`.
|
||||
|
||||
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
|
||||
`--only <shot>`.
|
||||
|
||||
## Comparison-only shots
|
||||
|
||||
`--compare` adds the screens the docs never show, so a change to the console
|
||||
can be checked by eye against a "before" set. They are never published: the
|
||||
script refuses `--compare` with an `--out` inside `docs/screenshots/`.
|
||||
|
||||
| File | Stages |
|
||||
| --- | --- |
|
||||
| `stop.json` | A build with a question open, behind the Stop dialog and its handoff choice |
|
||||
| `delete.json` | The dashboard, behind the first step of a spec chip's Delete |
|
||||
| `help.json` | A Plan question, behind Help on its first tab |
|
||||
| `prefs.json` | A Plan question, behind User Preferences |
|
||||
| `cleanup.json` | A Plan question, behind User Preferences scrolled to Cleanup after a scan |
|
||||
| `workspace.json` | A Plan question, behind the Workspace panel with a second folder added (shot last: the console remembers the folder) |
|
||||
|
||||
`node scripts/capture-screenshots.mjs --compare --out <folder outside the repo>`
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"menu": {
|
||||
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
|
||||
"recommend": "plan2code-3-implement",
|
||||
"details": {
|
||||
"plan2code-3-implement": "Phase 3 of 4 is next"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
{
|
||||
"workflow": "implement",
|
||||
"title": "task-api: Phase 3",
|
||||
"specDir": "specs/task-api",
|
||||
"headline": {
|
||||
"stage": "Phase 3: API endpoints",
|
||||
"cleared": 2,
|
||||
"total": 4
|
||||
},
|
||||
"docs": [
|
||||
{
|
||||
"id": "phase",
|
||||
"title": "Phase 3 tasks",
|
||||
"blocks": [
|
||||
{
|
||||
"id": "tasks",
|
||||
"state": "settled",
|
||||
"md": "- [x] **Task 3.1:** Add GET /tasks with cursor paging\n- [x] **Task 3.2:** Add POST /tasks\n- [ ] **Task 3.3:** Add PATCH /tasks/:id\n- [ ] **Task 3.4:** Add DELETE /tasks/:id"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"items": [
|
||||
{
|
||||
"id": "keep",
|
||||
"kind": "confirm",
|
||||
"title": "Tests are failing",
|
||||
"body": "Two paging tests fail after Task 3.2. Fix them before going on?",
|
||||
"yesLabel": "Fix them now",
|
||||
"noLabel": "Note them and go on"
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Tests for the shared browser helper (scripts/browser.mjs) and the two dev
|
||||
// scripts that launch a browser through it. Run with:
|
||||
// node --test scripts/test-browser-helper.mjs
|
||||
//
|
||||
// The unit cases hand findBrowser() a fake `exists`, so they run anywhere. The
|
||||
// live cases launch a real Chrome or Edge and skip when none is installed.
|
||||
|
||||
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 { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
test("playwright-core is pinned exactly in the root devDependencies", () => {
|
||||
const pkg = JSON.parse(fs.readFileSync(path.join(ROOT, "package.json"), "utf8"));
|
||||
assert.equal(pkg.devDependencies["playwright-core"], "1.64.1");
|
||||
});
|
||||
|
||||
// A fake file system holding only `present`.
|
||||
const only = (...present) => (p) => present.includes(p);
|
||||
|
||||
test("findBrowser picks Chrome, then Edge, and honours PLAN2CODE_TEST_BROWSER", async () => {
|
||||
const { findBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const chrome = BROWSER_PATHS.chrome[0];
|
||||
const edge = BROWSER_PATHS.msedge[0];
|
||||
|
||||
assert.deepEqual(findBrowser({ env: {}, exists: only(edge) }), { channel: "msedge", path: edge });
|
||||
assert.deepEqual(findBrowser({ env: {}, exists: only(chrome, edge) }), { channel: "chrome", path: chrome });
|
||||
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "msedge" }, exists: only(chrome, edge) }), { channel: "msedge", path: edge });
|
||||
assert.deepEqual(findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: only(edge) }), null);
|
||||
assert.deepEqual(findBrowser.checked, BROWSER_PATHS.chrome);
|
||||
assert.throws(() => findBrowser({ env: { PLAN2CODE_TEST_BROWSER: "firefox" }, exists: only(chrome) }), (e) => /chrome/.test(e.message) && /msedge/.test(e.message));
|
||||
|
||||
assert.equal(findBrowser({ env: {}, exists: only() }), null);
|
||||
assert.deepEqual(findBrowser.checked, [...BROWSER_PATHS.chrome, ...BROWSER_PATHS.msedge]);
|
||||
});
|
||||
|
||||
test("browserProblem says what is missing in one line of our own words", async () => {
|
||||
const { browserProblem } = await import("./browser.mjs");
|
||||
const found = { channel: "chrome", path: "C:\chrome.exe" };
|
||||
|
||||
const oldNode = browserProblem({ nodeVersion: "18.19.0", found });
|
||||
assert.equal(oldNode, "Page tests need Node 20 or newer (this is 18.19.0). Users of Plan2Code still only need Node 18.");
|
||||
|
||||
const checked = ["C:\a\chrome.exe", "/usr/bin/microsoft-edge"];
|
||||
const none = browserProblem({ nodeVersion: "24.12.0", found: null, checked });
|
||||
assert.match(none, /^Page tests need Chrome or Edge\. Looked in: /);
|
||||
for (const p of checked) assert.ok(none.includes(p), `names ${p}`);
|
||||
assert.ok(none.endsWith("Install either one, or set PLAN2CODE_TEST_BROWSER."));
|
||||
|
||||
assert.equal(browserProblem({ nodeVersion: "24.12.0", found }), null);
|
||||
for (const line of [oldNode, none]) {
|
||||
assert.ok(!line.includes("\n"));
|
||||
assert.ok(!line.includes("playwright install"));
|
||||
}
|
||||
});
|
||||
|
||||
test("launchBrowser fails with our one line when the forced browser is missing", async () => {
|
||||
const { launchBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const edgeOnly = only(BROWSER_PATHS.msedge[0]);
|
||||
await assert.rejects(launchBrowser({}, { env: { PLAN2CODE_TEST_BROWSER: "chrome" }, exists: edgeOnly }), (e) => {
|
||||
assert.equal(e.browserProblem, true);
|
||||
assert.match(e.message, /^Page tests need Chrome or Edge\. Looked in: /);
|
||||
assert.ok(!e.message.includes("\n"));
|
||||
return true;
|
||||
});
|
||||
});
|
||||
|
||||
test("launchBrowser opens a page in the installed browser", async (t) => {
|
||||
const { launchBrowser, findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.goto("data:text/html,<p>ok</p>");
|
||||
assert.equal(await page.textContent("p"), "ok");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
// Width and height from a WebP file's first chunk (lossy VP8, lossless VP8L,
|
||||
// or the extended VP8X header).
|
||||
function webpSize(buf) {
|
||||
assert.equal(buf.toString("ascii", 0, 4), "RIFF");
|
||||
assert.equal(buf.toString("ascii", 8, 12), "WEBP");
|
||||
const chunk = buf.toString("ascii", 12, 16);
|
||||
if (chunk === "VP8 ") return { width: buf.readUInt16LE(26) & 0x3fff, height: buf.readUInt16LE(28) & 0x3fff };
|
||||
if (chunk === "VP8L") {
|
||||
const bits = buf.readUInt32LE(21);
|
||||
return { width: (bits & 0x3fff) + 1, height: ((bits >> 14) & 0x3fff) + 1 };
|
||||
}
|
||||
if (chunk === "VP8X") return { width: buf.readUIntLE(24, 3) + 1, height: buf.readUIntLE(27, 3) + 1 };
|
||||
throw new Error(`unknown WebP chunk ${chunk}`);
|
||||
}
|
||||
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
test("capture-screenshots writes both themes as 2560x1600 WebP (slow)", { timeout: 120000 }, async (t) => {
|
||||
const { findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shots-test-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--only", "question", "--out", out], { encoding: "utf8", timeout: 110000 });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
for (const theme of ["light", "dark"]) {
|
||||
const buf = fs.readFileSync(path.join(out, `question-${theme}.webp`));
|
||||
assert.deepEqual(webpSize(buf), { width: 2560, height: 1600 });
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("capture-screenshots --compare refuses to write into docs/screenshots", () => {
|
||||
// A shot that does not exist: were the guard ever to break, the run would
|
||||
// stop at "Unknown shot" (which never names docs/screenshots) rather than
|
||||
// shoot every screen into the published folder.
|
||||
const argv = [CAPTURE, "--compare", "--only", "__no-such-shot__", "--out", path.join(ROOT, "docs", "screenshots")];
|
||||
const r = spawnSync(process.execPath, argv, { encoding: "utf8", timeout: 30000 });
|
||||
assert.notEqual(r.status, 0);
|
||||
const lines = r.stderr.trim().split("\n");
|
||||
assert.equal(lines.length, 1, r.stderr);
|
||||
assert.match(lines[0], /docs[\\/]screenshots/);
|
||||
});
|
||||
|
||||
test("capture-screenshots --compare shoots the comparison-only screens (slow)", { timeout: 120000 }, async (t) => {
|
||||
const { findBrowser } = await import("./browser.mjs");
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-compare-test-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--only", "help", "--out", out], { encoding: "utf8", timeout: 110000 });
|
||||
assert.equal(r.status, 0, r.stderr || r.stdout);
|
||||
for (const theme of ["light", "dark"]) assert.ok(fs.statSync(path.join(out, `help-${theme}.webp`)).size > 0);
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -29,7 +29,7 @@ import {
|
||||
unreadDot,
|
||||
} from "../src/web-console/public/chat.js";
|
||||
import { WEIGHTS } from "../src/web-console/public/meter.js";
|
||||
import { readChat } from "../src/web-console/lib.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -9,7 +9,8 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { readChat, terminalLine } from "../src/web-console/lib.mjs";
|
||||
import { terminalLine } from "../src/web-console/sessions.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -12,7 +12,10 @@ import path from "node:path";
|
||||
import { execFileSync, spawn } from "node:child_process";
|
||||
import http from "node:http";
|
||||
import { meterView } from "../src/web-console/public/meter.js";
|
||||
import { cwdHash, readLedger, repoRoots, STATE_LOCK_FILE, validate, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
|
||||
import { STATE_LOCK_FILE } from "../src/web-console/files.mjs";
|
||||
import { cwdHash, readLedger, repoRoots } from "../src/web-console/sessions.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -47,7 +50,11 @@ test("helpers: a dashboard hop clears them, a same-workflow or paused resume kee
|
||||
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "implement"]);
|
||||
assert.equal(readState(s.session).helpers.length, 2, "a resume into the same workflow keeps them");
|
||||
|
||||
assert.equal(postPatch(s, { finish: { headline: "Paused at Task 2" } }).status, 0);
|
||||
// A finish is refused while a helper still shows as running, so the pause settles them.
|
||||
assert.equal(
|
||||
postPatch(s, { helpers: [reportedHelper("h1", { state: "done" }), reportedHelper("h2", { state: "failed" })], finish: { headline: "Paused at Task 2" } }).status,
|
||||
0
|
||||
);
|
||||
cli(["open", "--resume", s.sid, "--no-open"]);
|
||||
const resumed = readState(s.session);
|
||||
assert.equal("finish" in resumed, false, "the pause came down");
|
||||
@@ -240,7 +247,7 @@ test("stop never kills a live process that does not answer /health as ours", ()
|
||||
const bystander = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "ignore" });
|
||||
const sidForged = "20000101-000000-beef01";
|
||||
// Under the test home, as the CLI sees it: this process has no override of
|
||||
// its own, and lib.mjs would name the real runtime dir.
|
||||
// its own, and files.mjs would name the real runtime dir.
|
||||
const dir = path.join(HOME, "runtime", cwdHash(repoRoots(ROOT).project));
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const forged = path.join(dir, `${sidForged}.json`);
|
||||
|
||||
@@ -495,30 +495,24 @@ test("git board view: a .gitignore-only pick commits just .gitignore, and never
|
||||
assert.equal(gitReply("commit", { files: ["a.js"], ignore: ["dist/"] }), "Commit this file: a.js. Add dist/ to .gitignore.");
|
||||
});
|
||||
|
||||
test("git board host: app.js draws the board only through drawGitBoard, and the server serves the view", () => {
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
test("git board host: the host draws the board only through drawGitBoard, and the server serves the view", () => {
|
||||
const host = fs.readFileSync(new URL("../src/web-console/public/screens/git-host.js", import.meta.url), "utf8");
|
||||
for (const gone of ["gitActionBar", "gitBranches", "smallButton", "gitHeader", "gitCommitPanel"]) {
|
||||
assert.ok(!app.includes(`function ${gone}(`), `app.js no longer defines ${gone}()`);
|
||||
assert.ok(!host.includes(`function ${gone}(`), `git-host.js no longer defines ${gone}()`);
|
||||
}
|
||||
const drawCalls = [...app.matchAll(/\bdrawGitBoard\(/g)].length;
|
||||
const drawCalls = [...host.matchAll(/\bdrawGitBoard\(/g)].length;
|
||||
assert.equal(drawCalls, 1, "one call to drawGitBoard");
|
||||
const host = app.slice(app.indexOf("function renderGitBoard("), app.indexOf("function rememberGitTabScroll("));
|
||||
assert.ok(host.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
|
||||
const server = fs.readFileSync(new URL("../src/web-console/server.mjs", import.meta.url), "utf8");
|
||||
const body = host.slice(host.indexOf("function renderGitBoard("), host.indexOf("function rememberGitTabScroll("));
|
||||
assert.ok(body.includes("drawGitBoard("), "renderGitBoard is the one that calls it");
|
||||
const server = fs.readFileSync(new URL("../src/web-console/static.mjs", import.meta.url), "utf8");
|
||||
const servable = server.slice(server.indexOf("const SERVABLE = new Set(["), server.indexOf("]);", server.indexOf("const SERVABLE = new Set([")));
|
||||
assert.ok(servable.includes('"git-board-view.js"'), "SERVABLE includes git-board-view.js");
|
||||
assert.ok(servable.includes('"screens/git-host.js"'), "SERVABLE includes screens/git-host.js");
|
||||
});
|
||||
|
||||
test("git board host: the always-on commit table keeps the person's ticks, and a click re-seeds them", () => {
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("const gitOn = {"));
|
||||
assert.match(send, /board\.ticks = null;\s*board\.ignore = new Set\(\);/, "a click drops the old picks");
|
||||
const commit = app.slice(app.indexOf("function openCommit("), app.indexOf("function openCleanup("));
|
||||
assert.ok(!commit.includes("commitTicks("), "opening the panel never re-seeds over their ticks");
|
||||
assert.ok(commit.includes("tablePicks(git)"), "a detached commit carries the table's picks");
|
||||
const panel = app.slice(app.indexOf("function openPanel("), app.indexOf("const closePanel ="));
|
||||
assert.match(panel, /opts\.commit && !opts\.files\) return openCreate\(git, \{ \.\.\.opts, \.\.\.tablePicks\(git\) \}\)/, "Start a branch takes what is ticked");
|
||||
});
|
||||
// The commit table's ticks and the click that re-seeds them are page tests now
|
||||
// ("the commit table keeps the person's ticks across an agent post, and a click
|
||||
// re-seeds them" and its neighbours in test-web-console-page-git.mjs).
|
||||
|
||||
test("git board docs: the agent prose, Help topic and readme describe the tabbed board", () => {
|
||||
const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8");
|
||||
|
||||
@@ -14,12 +14,11 @@ import { spawnSync } from "node:child_process";
|
||||
// is exactly why this lives in its own file.
|
||||
import {
|
||||
cardAvailability,
|
||||
CONSOLE_WORKFLOWS,
|
||||
GIT_INIT_NOTE,
|
||||
resumeCommand,
|
||||
SKILL_CATALOG,
|
||||
START_POSES,
|
||||
} from "../src/web-console/public/answers.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { breakdownFrom, pointsFrom } from "../src/web-console/public/meter.js";
|
||||
import {
|
||||
BRANCH_TYPES,
|
||||
@@ -38,7 +37,7 @@ import {
|
||||
refreshedLine,
|
||||
} from "../src/web-console/public/git-board.js";
|
||||
import { prUrl } from "../src/web-console/public/pr-url.js";
|
||||
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/lib.mjs";
|
||||
import { PROTECTED_CONSOLE_FILES, readLedger } from "../src/web-console/sessions.mjs";
|
||||
import {
|
||||
CONSOLE_CLI,
|
||||
HOME,
|
||||
@@ -290,8 +289,6 @@ test("git: the Git card is never greyed, and its resume command is /plan2code-gi
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null), { on: true });
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: true, pending: null }, null), { on: true });
|
||||
assert.equal(resumeCommand({ workflow: "git" }), "/plan2code-git");
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes("/plan2code-git"));
|
||||
assert.ok(START_POSES.includes("git"));
|
||||
});
|
||||
|
||||
test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)", async () => {
|
||||
@@ -303,8 +300,11 @@ test("git: the Git card's copy, place and availability are pinned (FR-58, FR-59)
|
||||
);
|
||||
assert.equal(entry.group, "extra");
|
||||
assert.equal(entry.chip, "Utility");
|
||||
assert.equal(SKILL_CATALOG.at(-2), entry, "the Git card comes right before Handoff");
|
||||
assert.equal(SKILL_CATALOG.at(-1).skill, "plan2code-handoff", "the Handoff card is last");
|
||||
// The card order is skills.js's order.
|
||||
const order = SKILLS.filter((s) => s.card).map((s) => s.skill);
|
||||
assert.equal(order.indexOf("plan2code-git") + 1, order.indexOf("plan2code-handoff"), "the Git card comes right before Handoff");
|
||||
assert.equal(order.at(-1), "plan2code-handoff", "the Handoff card is last");
|
||||
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), order, "the catalog draws in that order");
|
||||
for (const isGit of [true, false, undefined]) {
|
||||
for (const pending of [0, 3, null]) {
|
||||
const scan = { hasAgents: true, pending, ...(isGit === undefined ? {} : { isGit }) };
|
||||
@@ -327,12 +327,10 @@ test("git: the board stays locked from a click until the agent's next post, not
|
||||
assert.equal(boardAwaiting({ sentAt, updatedAt: "2026-10-10T05:15:51.000Z", cardsAwaiting: 2 }), true);
|
||||
assert.equal(boardAwaiting({ sentAt, cardsAwaiting: 1, adrift: true }), false, "an agent gone quiet releases the lock");
|
||||
|
||||
const app = fs.readFileSync(new URL("../src/web-console/public/app.js", import.meta.url), "utf8");
|
||||
assert.match(app, /const gitMode = \(\) =>[^;]*gitAwaiting\(\)/, "the busy mode includes gitAwaiting()");
|
||||
assert.match(app, /const gitLocked = \(\) => gitMode\(\) !== "idle";/, "gitLocked is anything but idle");
|
||||
const send = app.slice(app.indexOf("async function sendGit("), app.indexOf("function renderGitBoard("));
|
||||
assert.match(send, /local\.gitSentAt = Date\.now\(\);\s*save\(\);/, "a board click records when it was sent, and saves it");
|
||||
assert.match(app, /sentAt: local\.gitSentAt[\s\S]{0,80}updatedAt: S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
|
||||
// gitMode, gitLocked and the click's gitSentAt are page tests now (the board
|
||||
// stays locked in test-web-console-page-git.mjs); what feeds them is here.
|
||||
const selectors = fs.readFileSync(new URL("../src/web-console/public/selectors.js", import.meta.url), "utf8");
|
||||
assert.match(selectors, /sentAt: page\.local\.gitSentAt[\s\S]{0,80}updatedAt: page\.S\.updatedAt[\s\S]{0,80}cardsAwaiting: awaitingReply\(\)\.length/);
|
||||
});
|
||||
|
||||
/* ------------------------------------------- the git board's pure helpers */
|
||||
@@ -563,19 +561,12 @@ test("git board: boardPrLink builds the link for a pushed feature branch only",
|
||||
|
||||
test("git board: the page draws it from git-board.js, with no inline styles", () => {
|
||||
const dir = path.join(path.dirname(CONSOLE_CLI), "public");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const view = fs.readFileSync(path.join(dir, "git-board-view.js"), "utf8");
|
||||
assert.match(app, /^import [^;]+ from "\.\/git-board\.js";/m, "app.js imports git-board.js");
|
||||
assert.match(app, /^import [^;]+ from "\.\/git-board-view\.js";/m, "app.js imports git-board-view.js");
|
||||
for (const m of ["git-board.js", "git-board-view.js", "pr-url.js"]) assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.match(app, /const isGitBoard = \(\) => S && S\.workflow === "git" && S\.git;/);
|
||||
assert.match(app, /i: "__git", type: "git", op/, "a click is one __git action");
|
||||
const selectors = fs.readFileSync(path.join(dir, "selectors.js"), "utf8");
|
||||
assert.match(selectors, /const isGitBoard = \(\) => page\.S && page\.S\.workflow === "git" && page\.S\.git;/);
|
||||
assert.match(view, /a\.rel = "noopener"/, "the PR link opens with rel=noopener");
|
||||
const start = app.indexOf("/* ------------------------------------------------------------ git board */");
|
||||
const end = app.indexOf("/* ------------------------------------------------------------- welcome */");
|
||||
assert.ok(start > 0 && end > start);
|
||||
assert.doesNotMatch(app.slice(start, end), /setAttribute\(\s*["']style["']|\.style\./, "the board sets no inline styles");
|
||||
assert.doesNotMatch(view, /setAttribute\(\s*["']style["']|\.style\./, "nor does its view");
|
||||
});
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { parseArgs } from "../src/web-console/lib.mjs";
|
||||
import { parseArgs } from "../src/web-console/files.mjs";
|
||||
import { BASE, cli, consoleSession, cookieFor, ENV, HOME, payload, ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const SERVER_JS = path.join(ROOT, "src", "web-console", "server.mjs");
|
||||
|
||||
@@ -783,6 +783,19 @@ test("a finish is refused while its command still has a placeholder", () => {
|
||||
assert.match(res.stderr, /placeholder/);
|
||||
});
|
||||
|
||||
// The Subagents tab would otherwise spin on a helper long after the session ended.
|
||||
test("a finish is refused while a reported helper still shows as running", () => {
|
||||
const helper = (state, result) => ({ id: "h1", title: "Check the tests", ask: "Run them.", state, ...(result ? { result } : {}) });
|
||||
const running = cli(["post", "--session", sid, "--file", payload("fin-h-run.json", { helpers: [helper("running")], finish: { headline: "Done", command: "/x" } })], {
|
||||
expectFail: true,
|
||||
});
|
||||
assert.equal(running.status, 3);
|
||||
assert.match(running.stderr, /still shows as running/);
|
||||
assert.match(running.stderr, /"h1"/);
|
||||
const settled = cli(["post", "--session", sid, "--file", payload("fin-h-done.json", { helpers: [helper("done", "All pass.")], finish: { headline: "Done", command: "/x" } })]);
|
||||
assert.equal(settled.status, 0);
|
||||
});
|
||||
|
||||
test("a finish faces the same jargon and completion-marker scan as everything else", () => {
|
||||
const jargon = cli(
|
||||
["post", "--session", sid, "--file", payload("fin-j.json", { finish: { headline: "The grilling is over", command: "/x" } })],
|
||||
|
||||
@@ -147,30 +147,33 @@ import {
|
||||
import {
|
||||
appendLedger,
|
||||
attachmentName,
|
||||
chatReplyLines,
|
||||
checkDocument,
|
||||
initialWorkspace,
|
||||
insideGitRepo,
|
||||
pendingFiles,
|
||||
latestOpenCaps,
|
||||
pendingWorkspaceChanges,
|
||||
PROTECTED_CONSOLE_FILES,
|
||||
readLedger,
|
||||
repoRoots,
|
||||
} from "../src/web-console/sessions.mjs";
|
||||
import { scanProject, removeSpec, SPEC_STATES } from "../src/web-console/scan.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
initialWorkspace,
|
||||
pendingWorkspaceChanges,
|
||||
readWorkspaceCursor,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
} from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
latestOpenCaps,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspaceCursor,
|
||||
resetSubagentCursor,
|
||||
writeSubagentCursor,
|
||||
writeSubagentSetting,
|
||||
repoRoots,
|
||||
scanProject,
|
||||
removeSpec,
|
||||
SPEC_STATES,
|
||||
validate,
|
||||
WORKSPACE_FILE,
|
||||
writeWorkspaceCursor,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
} from "../src/web-console/settings.mjs";
|
||||
import { ROOT, HOME, cli, PDF, postPatch, ask } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
// Someone who worked the whole session in the browser should land back in it.
|
||||
// Every Plan2Code skill ships a console, so the sentence goes on all of
|
||||
@@ -223,34 +226,17 @@ test("every console workflow the page names ships the console", () => {
|
||||
assert.ok(fs.existsSync(path.join(dir, "console.mjs")), `${skill} must bundle the console`);
|
||||
assert.ok(fs.existsSync(path.join(dir, "building.md")), `${skill} must bundle building.md`);
|
||||
}
|
||||
// And the other way round: a skill that ships the console but is missing
|
||||
// from the list would hand off a bare command, and its next session would
|
||||
// ask the interface question of someone who was already in the browser.
|
||||
for (const skill of fs.readdirSync(path.join(ROOT, "skills"))) {
|
||||
if (!fs.existsSync(path.join(ROOT, "skills", skill, "references", "web-console"))) continue;
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes("/" + skill), `${skill} ships the console but is not in CONSOLE_WORKFLOWS`);
|
||||
}
|
||||
});
|
||||
|
||||
// The dashboard draws its cards from the page's own catalog, so the catalog
|
||||
// is the contract: every card has to be a skill that really installs, every
|
||||
// installed skill has to be a card (a skill that is missing launches nothing),
|
||||
// and every card's workflow has to be one the console names.
|
||||
test("the dashboard catalog is exactly the set of installable skills", () => {
|
||||
// The dashboard draws its cards from the page's own catalog, so every card
|
||||
// has to be filled in and launch into a real SKILL.md. Which skills have a
|
||||
// card is held against install.js in test-web-console-skills.mjs.
|
||||
test("every dashboard card is filled in and launches a real skill", () => {
|
||||
const skillsDir = path.join(ROOT, "skills");
|
||||
const installed = fs.readdirSync(skillsDir).filter((d) => fs.statSync(path.join(skillsDir, d)).isDirectory());
|
||||
const cataloged = SKILL_CATALOG.map((e) => e.skill);
|
||||
|
||||
// The dashboard itself is the hub, not a card.
|
||||
assert.ok(!cataloged.includes("plan2code"), "the dashboard does not launch itself");
|
||||
assert.ok(!SKILL_CATALOG.some((e) => e.skill === "plan2code"), "the dashboard does not launch itself");
|
||||
|
||||
for (const skill of installed) {
|
||||
if (skill === "plan2code") continue;
|
||||
assert.ok(cataloged.includes(skill), `${skill} installs but has no card on the dashboard`);
|
||||
}
|
||||
for (const e of SKILL_CATALOG) {
|
||||
assert.ok(installed.includes(e.skill), `${e.skill} is a card but does not install`);
|
||||
assert.ok(CONSOLE_WORKFLOWS.includes(e.command), `${e.command} must be a console workflow`);
|
||||
assert.ok(CATALOG_GROUPS.some((g) => g.id === e.group), `${e.skill}: unknown group ${e.group}`);
|
||||
for (const field of ["workflow", "chip", "title", "blurb"]) {
|
||||
assert.ok(e[field] && String(e[field]).trim(), `${e.skill}.${field} must be filled in`);
|
||||
@@ -1773,7 +1759,6 @@ test("skip: the last open card goes to Send, a middle one to the next unstaged,
|
||||
test("page: the Workspace dialog, meter pill and new modules are in the page, with no inline styles or scripts", () => {
|
||||
const dir = path.join(ROOT, "src", "web-console", "public");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
for (const id of [
|
||||
"workspace-modal",
|
||||
"workspace-title",
|
||||
@@ -1800,7 +1785,6 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.ok(pill[0].includes('class="meter-track"') && pill[0].includes('class="meter-fill"'));
|
||||
for (const m of ["workspace.js", "meter.js", "mentions.js", "favicon.js"]) {
|
||||
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
|
||||
assert.match(app, new RegExp(`^import [^;]+ from "\\./${m.replace(".", "\\.")}";`, "m"), `app.js imports ${m}`);
|
||||
}
|
||||
// The CSP refuses style attributes and inline script: the new markup has neither.
|
||||
const added = [
|
||||
@@ -1812,23 +1796,18 @@ test("page: the Workspace dialog, meter pill and new modules are in the page, wi
|
||||
assert.doesNotMatch(block, /<script/i);
|
||||
assert.doesNotMatch(block, /\son[a-z]+=/i, "no inline event handlers");
|
||||
}
|
||||
assert.doesNotMatch(app, /setAttribute\(\s*["']style["']/, "no style attributes set from script");
|
||||
});
|
||||
|
||||
test("page: the footer label opens the workspace instead of copying", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.ok(app.includes('$("footer-where").addEventListener("click", openWorkspace)'));
|
||||
assert.doesNotMatch(app, /\$\("footer-where"\)\.addEventListener\("blur"/, "the copied-state blur handler is gone");
|
||||
assert.ok(app.includes('"Open workspace: " + label'));
|
||||
assert.ok(app.includes("footerLabel(") && app.includes("FOOTER_TIERS"));
|
||||
// The dashboard keeps the footer for the workspace label, minus the summary and Send.
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
assert.ok(app.includes('foot.classList.toggle("is-dash", Boolean(isDashboard() && !finish()))'));
|
||||
assert.doesNotMatch(app, /foot\.hidden = Boolean\(isDashboard\(\)/, "the dashboard no longer hides the whole footer");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.footer\.is-dash \.footer-summary,\s*\.footer\.is-dash \.footer-actions \{ display: none; \}/);
|
||||
assert.match(css, /\.footer\.is-dash \.footer-where:not\(\[hidden\]\) \{ display: block;/, "narrow screens keep the label on the dashboard");
|
||||
// Every typing place offers @name suggestions.
|
||||
assert.equal((app.match(/attachMentions\((ta|input)\);/g) || []).length, 4, "Ask, card note, notes panel, text answer");
|
||||
// Every typing place offers @name suggestions: the Ask pane and the notes panel
|
||||
// (screens/ask.js) and the card note and text answer (screens/cards.js).
|
||||
const read = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", f), "utf8");
|
||||
const count = (text) => (text.match(/attachMentions\((ta|input)\);/g) || []).length;
|
||||
assert.equal(count(read("ask.js")) + count(read("cards.js")), 4, "Ask, card note, notes panel, text answer");
|
||||
});
|
||||
|
||||
// The quoted flags between -NoProfile and -EncodedCommand, whichever quote style.
|
||||
@@ -2086,7 +2065,7 @@ test("subagents: the store round-trips per project and workflow under the consol
|
||||
try {
|
||||
const project = path.join(home, "My Repo");
|
||||
const script = `
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/lib.mjs", import.meta.url).href)});
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/settings.mjs", import.meta.url).href)});
|
||||
const project = ${JSON.stringify(project)};
|
||||
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5 });
|
||||
const flipped = project.replace(/My Repo$/, "MY REPO");
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
// Page tests for the Ask tab: a Quick question and the agent's reply, the
|
||||
// starters, a retry after a failed send, a new conversation, a picture attached
|
||||
// to a note, and the Subagents tab. Run with:
|
||||
// node --test scripts/test-web-console-page-ask.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 test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
|
||||
import { reportedHelper } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question, the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// A real 1x1 PNG. The page decodes and re-encodes every picture before it
|
||||
// uploads, so the fake JPEG the server tests use would be refused here.
|
||||
const PNG = Buffer.from(
|
||||
"iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==",
|
||||
"base64"
|
||||
);
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The questions in a send's chat entries (the first send also carries the
|
||||
// conversation's start, which is not a question).
|
||||
const messages = (got) => got.chat.filter((e) => e.kind === "message");
|
||||
|
||||
// Opens the Ask tab and returns its question box.
|
||||
async function openAsk(s) {
|
||||
await s.page.locator("nav").getByRole("button", { name: "Ask", exact: true }).click();
|
||||
const box = s.page.locator("#ask-input");
|
||||
await box.waitFor();
|
||||
return box;
|
||||
}
|
||||
|
||||
// Types a question and presses Send in the Ask pane.
|
||||
async function askQuestion(s, text) {
|
||||
const box = s.page.locator("#ask-input");
|
||||
await box.fill(text);
|
||||
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
|
||||
}
|
||||
|
||||
// What a person sees break: a question typed in Ask that never reaches the
|
||||
// agent, or an answer that never shows.
|
||||
test("a Quick question typed in Ask reaches the agent under chat, and the agent's reply shows in the pane", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "Where does the export live?");
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "chat");
|
||||
const [asked, ...more] = messages(got);
|
||||
assert.equal(more.length, 0, "one question, one message");
|
||||
assert.equal(asked.text, "Where does the export live?");
|
||||
assert.match(got.reply, /^Quick question: Where does the export live\?$/m);
|
||||
// The question is in the pane, and the box is empty for the next one.
|
||||
await s.page.locator(".ask-row.person").getByText("Where does the export live?").waitFor();
|
||||
assert.equal(await s.page.locator("#ask-input").inputValue(), "");
|
||||
|
||||
s.post({ chat: { replies: [{ id: "r1", re: asked.seq, conversation: 1, md: "It lives in `exports/`." }] } });
|
||||
const reply = s.page.locator(".ask-row.agent");
|
||||
await reply.getByText("It lives in").waitFor();
|
||||
assert.match(await textOf(reply), /exports\//);
|
||||
assert.match(await textOf(s.page.locator(".ask-counter")), /1/);
|
||||
});
|
||||
|
||||
// What a person sees break: starters that send for them, or that are missing
|
||||
// from an empty conversation.
|
||||
test("an empty Ask offers starters, a click only fills the box, and nothing is sent until Send", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const box = await openAsk(s);
|
||||
const starters = s.page.locator(".ask-starters .ask-starter");
|
||||
await starters.first().waitFor();
|
||||
assert.ok((await starters.count()) >= 1, "no starter questions are offered");
|
||||
const first = (await textOf(starters.first())).trim();
|
||||
await starters.first().click();
|
||||
assert.equal(await box.inputValue(), first, "the starter fills the box");
|
||||
assert.equal(s.wait(1).code === 0, false, "a starter click sent something");
|
||||
|
||||
await s.page.locator(".ask-composer").getByRole("button", { name: "Send", exact: true }).click();
|
||||
assert.deepEqual(messages(collect(s)).map((e) => e.text), [first]);
|
||||
// With a question in the list the starters are gone.
|
||||
await s.page.locator(".ask-starters").waitFor({ state: "detached" });
|
||||
});
|
||||
|
||||
// What a person sees break: a question lost when the network hiccups, or
|
||||
// sent twice when they press Retry.
|
||||
test("a failed send shows Not sent with Retry, and Retry delivers the question once", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
// The page's own request fails as a dropped connection would.
|
||||
await s.page.route("**/chat", (route) => route.abort());
|
||||
await askQuestion(s, "Is the header row kept?");
|
||||
const row = s.page.locator(".ask-row.person.pending");
|
||||
await row.getByText("Not sent").waitFor();
|
||||
assert.equal(s.wait(1).code === 0, false, "a failed send reached the agent");
|
||||
|
||||
await s.page.unroute("**/chat");
|
||||
await row.getByRole("button", { name: "Retry" }).click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(messages(got).map((e) => e.text), ["Is the header row kept?"]);
|
||||
await s.page.locator(".ask-row.person:not(.pending)").getByText("Is the header row kept?").waitFor();
|
||||
assert.equal(s.wait(1).code === 0, false, "the question was sent twice");
|
||||
});
|
||||
|
||||
// What a person sees break: New conversation that leaves the old rows, or
|
||||
// that does not start the next question in a fresh conversation.
|
||||
test("New conversation clears the pane back to the starters, and the next question belongs to the new conversation", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openAsk(s);
|
||||
await askQuestion(s, "First question");
|
||||
const first = collect(s);
|
||||
assert.equal(messages(first)[0].conversation, 1);
|
||||
await s.page.locator(".ask-row.person:not(.pending)").waitFor();
|
||||
|
||||
await s.page.getByRole("button", { name: "New conversation" }).click();
|
||||
await s.page.locator(".ask-row").waitFor({ state: "detached" });
|
||||
await s.page.locator(".ask-starters").waitFor();
|
||||
|
||||
await askQuestion(s, "Second question");
|
||||
const second = collect(s);
|
||||
assert.deepEqual(messages(second).map((e) => e.text), ["Second question"]);
|
||||
assert.equal(messages(second)[0].conversation, 2);
|
||||
});
|
||||
|
||||
// What a person sees break: a picture that shows in the tray but never goes
|
||||
// to the agent, or goes without the note it belongs to.
|
||||
test("a picture attached to a note uploads, and the send carries it in the note's images entry", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").waitFor();
|
||||
const aside = s.page.locator("#aside");
|
||||
await aside.locator('input[type="file"]').setInputFiles({ name: "shot.png", mimeType: "image/png", buffer: PNG });
|
||||
await aside.locator(".attach-thumb.is-ready").waitFor();
|
||||
await aside.locator("#thread-q1").fill("See the screenshot.");
|
||||
|
||||
await s.page.click("#btn-send");
|
||||
const got = collect(s);
|
||||
const note = got.actions.find((a) => a.i === "q1" && a.type === "comment");
|
||||
assert.ok(note, `a note action for q1: ${JSON.stringify(got.actions)}`);
|
||||
assert.equal(note.text, "See the screenshot.");
|
||||
assert.equal(note.images.length, 1);
|
||||
assert.equal(note.images[0].name, "shot.png");
|
||||
assert.ok(note.images[0].path, "the image names the file the console saved");
|
||||
});
|
||||
|
||||
// What a person sees break: the Subagents tab missing once helpers are
|
||||
// reported, or showing the wrong state.
|
||||
test("posting helpers adds a Subagents tab that lists each with its state and result", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 2" }, items: PLAN_QUESTION.items },
|
||||
});
|
||||
const tab = s.page.locator("nav").getByRole("button", { name: /^Subagents/ });
|
||||
assert.equal(await tab.count(), 0, "no tab before any helper is reported");
|
||||
|
||||
s.post({
|
||||
helpers: [
|
||||
reportedHelper("h1", { title: "Read the store helpers", state: "running" }),
|
||||
reportedHelper("h2", { title: "Check the tests", state: "done", result: "All 9 pass." }),
|
||||
],
|
||||
});
|
||||
await tab.waitFor();
|
||||
await tab.click();
|
||||
const card = s.page.locator("#main .sa-card");
|
||||
await card.getByRole("heading", { name: "Subagents" }).waitFor();
|
||||
const rows = card.locator(".sa-row");
|
||||
assert.equal(await rows.count(), 2);
|
||||
const running = rows.filter({ hasText: "Read the store helpers" });
|
||||
const done = rows.filter({ hasText: "Check the tests" });
|
||||
assert.match(await textOf(running.locator(".sa-pill")), /running/i);
|
||||
assert.match(await textOf(done.locator(".sa-pill")), /done/i);
|
||||
assert.match(await textOf(done), /All 9 pass\./);
|
||||
assert.match(await textOf(running), /Find the callers of applyPatch/);
|
||||
});
|
||||
@@ -0,0 +1,689 @@
|
||||
// Page tests for question cards: every kind answered on the page and sent, the
|
||||
// sign-off card, and a redraw keeping your place. Run with:
|
||||
// node --test scripts/test-web-console-page-cards.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 test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf } from "./page-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
test("a session with nothing posted yet shows its starting screen, and stop ends its server", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
assert.match(await s.page.innerText("#main"), /Starting Plan/);
|
||||
assert.equal(await s.page.locator("#main .pose-stage").count(), 1);
|
||||
await s.stop();
|
||||
assert.equal(await s.answers(), false, "the server still answers after stop()");
|
||||
});
|
||||
|
||||
test("a text answer typed on the page reaches the agent as it was typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type, text }) => ({ i, type, text })),
|
||||
[{ i: "q1", type: "answer", text: "audit-export" }]
|
||||
);
|
||||
assert.match(got.reply, /audit-export/);
|
||||
});
|
||||
|
||||
// The agent's side of one question: settle what came before, post `item`
|
||||
// alone, and wait for its card.
|
||||
async function ask(s, item) {
|
||||
s.post({ settle: true, items: [item] });
|
||||
const card = itemCard(s.page, item.id);
|
||||
await card.waitFor();
|
||||
return card;
|
||||
}
|
||||
|
||||
// The answer an agent reads for item `id`, without the routing fields.
|
||||
function answerTo(got, id) {
|
||||
const action = got.actions.find((a) => a.i === id);
|
||||
assert.ok(action, `the send carries an answer to ${id}: ${JSON.stringify(got.actions)}`);
|
||||
const { i, type, kind, ...answer } = action;
|
||||
assert.equal(type, "answer");
|
||||
return answer;
|
||||
}
|
||||
|
||||
const opt = (k, text) => ({ k, text, detail: `The ${text.toLowerCase()} option.` });
|
||||
|
||||
test("every kind of question card sends the answer shape the agent reads", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
|
||||
let card = await ask(s, { id: "c1", kind: "choice", title: "Export format", body: "Which format?", options: [opt("A", "CSV"), opt("B", "JSON")] });
|
||||
await card.getByLabel("JSON").check();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c1"), { k: "B" });
|
||||
assert.equal(got.reply, "Export format: B");
|
||||
|
||||
card = await ask(s, { id: "c2", kind: "choice", title: "Where it goes", body: "Where?", allowOther: true, options: [opt("A", "Email"), opt("B", "Slack")] });
|
||||
await card.getByRole("radio", { name: "Something else, in your own words" }).check();
|
||||
await card.locator("textarea").fill("A shared drive");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c2"), { text: "A shared drive" });
|
||||
assert.equal(got.reply, "Where it goes: A shared drive");
|
||||
|
||||
card = await ask(s, { id: "m1", kind: "multi", title: "Columns", body: "Which?", options: [opt("1", "Date"), opt("2", "User"), opt("3", "Action")], presets: [{ label: "Date and user", ks: ["1", "2"] }] });
|
||||
await card.getByRole("button", { name: "Date and user" }).click();
|
||||
await card.getByLabel("Action").check();
|
||||
await card.locator("textarea").fill("and the IP");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "m1"), { ks: ["1", "2", "3"], text: "and the IP" });
|
||||
assert.equal(got.reply, "Columns: 1, 2, 3; and the IP");
|
||||
|
||||
card = await ask(s, { id: "t1", kind: "text", title: "What to call it", body: "A name.", pattern: "^[a-z][a-z0-9-]*$", patternHint: "Lowercase letters, digits and hyphens.", placeholder: "For example: audit-export" });
|
||||
const field = card.locator("input[type=text]");
|
||||
// The suggestion is the placeholder without its "For example:" lead-in.
|
||||
await card.getByRole("button", { name: "Autofill suggestion" }).click();
|
||||
assert.equal(await field.inputValue(), "audit-export");
|
||||
await field.fill("Audit Export");
|
||||
await card.getByText("Lowercase letters, digits and hyphens.").waitFor();
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a value that breaks the pattern is not sendable");
|
||||
await field.fill("audit-export");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "t1"), { text: "audit-export" });
|
||||
assert.equal(got.reply, "What to call it: audit-export");
|
||||
|
||||
card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
await card.getByRole("button", { name: "Yes" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y1"), { yes: true });
|
||||
assert.equal(got.reply, "Keep going: yes");
|
||||
|
||||
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Is this right?", summary: "- CSV\n- Mondays" });
|
||||
await card.getByRole("button", { name: "Yes, that is right" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "r1"), { ok: true });
|
||||
assert.equal(got.reply, "What we decided: confirmed");
|
||||
|
||||
card = await ask(s, { id: "k1", kind: "checklist", title: "Set up access", body: "Only you can do these.", steps: ["Create the app", "Paste its key"] });
|
||||
await card.locator("input[type=checkbox]").first().check();
|
||||
await card.getByRole("button", { name: "All done" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "k1"), { done: [0], state: "done" });
|
||||
assert.equal(got.reply, "Set up access: all done; did steps 1");
|
||||
|
||||
card = await ask(s, { id: "n1", kind: "menu", title: "What next", body: "Pick one.", options: [opt("1", "Keep planning"), opt("2", "Stop here")] });
|
||||
await card.getByLabel("Stop here").check();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "n1"), { k: "2" });
|
||||
assert.equal(got.reply, "What next: 2");
|
||||
|
||||
const rows = [
|
||||
{ id: "a", title: "Read the data", body: "x" },
|
||||
{ id: "b", title: "Write the file", body: "y" },
|
||||
];
|
||||
card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Reorder or rename.", rows });
|
||||
await card.getByRole("button", { name: "No changes" }).click();
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "l1"), { text: "no changes" });
|
||||
assert.equal(got.reply, "The steps: no changes");
|
||||
|
||||
card = await ask(s, { id: "l2", kind: "list", title: "The steps again", body: "Reorder or rename.", rows });
|
||||
await card.locator("input[type=text]").first().fill("Read the audit log");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(
|
||||
answerTo(got, "l2").rows.map((r) => [r.id, r.title]),
|
||||
[["a", "Read the audit log"], ["b", "Write the file"]]
|
||||
);
|
||||
assert.equal(got.reply, "The steps again: the list: Read the audit log, then Write the file; renamed Read the data to Read the audit log");
|
||||
|
||||
s.post({ settle: true, items: [{ id: "x1", kind: "notice", title: "Heads up", body: "The export runs **nightly**." }] });
|
||||
await s.page.getByText("The export runs").waitFor();
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "a notice alone gives nothing to send");
|
||||
});
|
||||
|
||||
test("a sign-off card opens its document, and each verdict reaches the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: {
|
||||
docs: [{ id: "report", title: "Completion report", blocks: [{ id: "b1", state: "settled", md: "## Summary\n\nPhase 3 adds the /tasks endpoints." }] }],
|
||||
},
|
||||
});
|
||||
const signoff = (id, extra = {}) => ({
|
||||
id,
|
||||
kind: "review",
|
||||
title: "Approve this phase",
|
||||
doc: "report",
|
||||
body: "Read the report, then approve it or say what to change.",
|
||||
verdicts: [
|
||||
{ id: "approve", label: "Approve this phase" },
|
||||
{ id: "changes", label: "I want changes" },
|
||||
{ id: "discard", label: "Throw it away", danger: true },
|
||||
],
|
||||
...extra,
|
||||
});
|
||||
|
||||
let card = await ask(s, signoff("so1"));
|
||||
await card.getByRole("button", { name: /Read .*Completion report.* in full/ }).click();
|
||||
await s.page.getByText("Phase 3 adds the /tasks endpoints.").waitFor();
|
||||
assert.ok(await s.page.getByText("Phase 3 adds the /tasks endpoints.").isVisible(), "the report is on screen");
|
||||
// The danger verdict is marked as such: here the class is the behaviour.
|
||||
await s.page.locator("#views").getByRole("button", { name: /^Questions/ }).click();
|
||||
card = itemCard(s.page, "so1");
|
||||
assert.match(await card.getByRole("button", { name: "Throw it away" }).getAttribute("class"), /danger/);
|
||||
assert.doesNotMatch(await card.getByRole("button", { name: "Approve this phase" }).getAttribute("class"), /danger/);
|
||||
|
||||
await card.getByRole("button", { name: "Approve this phase" }).click();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "so1"), { verdict: "approve" });
|
||||
|
||||
card = await ask(s, signoff("so2"));
|
||||
await card.getByRole("button", { name: "I want changes" }).click();
|
||||
await card.locator("textarea").fill("Keep the header row.");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "so2"), { verdict: "changes", text: "Keep the header row." });
|
||||
});
|
||||
|
||||
const longText = (n) => Array.from({ length: n }, (_, i) => `Paragraph ${i + 1}. The export runs every night and keeps a year of rows.`).join("\n\n");
|
||||
|
||||
// The agent posts something unrelated, and the page redraws: wait until the
|
||||
// new title is drawn.
|
||||
async function unrelatedPost(s, title) {
|
||||
s.post({ title });
|
||||
await s.page.waitForFunction((want) => document.getElementById("title").textContent.includes(want), title);
|
||||
}
|
||||
|
||||
test("a redraw keeps your place: the scroll and the focused field survive an agent post", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }],
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: longText(80) }] }],
|
||||
},
|
||||
});
|
||||
|
||||
// Reading a question part-way down: the card scrolls itself.
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.evaluate((el) => (el.scrollTop = 400));
|
||||
assert.equal(await card.evaluate((el) => el.scrollTop), 400, "the question card scrolls");
|
||||
await unrelatedPost(s, "Audit export, take two");
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), 400);
|
||||
|
||||
// Typing in its answer box: the box keeps the focus and the caret, and the
|
||||
// card stays where it was.
|
||||
const field = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
await field.click();
|
||||
await field.pressSequentially("audit-ex");
|
||||
await field.evaluate((el) => el.setSelectionRange(3, 3));
|
||||
const typingAt = await itemCard(s.page, "q1").evaluate((el) => el.scrollTop);
|
||||
await unrelatedPost(s, "Audit export, take three");
|
||||
const after = itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
assert.deepEqual(await after.evaluate((el) => [el === document.activeElement, el.value, el.selectionStart]), [true, "audit-ex", 3]);
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), typingAt);
|
||||
|
||||
// On a doc: the column scrolls.
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
await s.page.getByText("Paragraph 80.").waitFor();
|
||||
await s.page.locator("#main").evaluate((el) => (el.scrollTop = 900));
|
||||
const docBefore = await scrollTopOf(s.page, "#main");
|
||||
assert.ok(docBefore > 0, "the doc column scrolls");
|
||||
await unrelatedPost(s, "Audit export, take four");
|
||||
assert.equal(await scrollTopOf(s.page, "#main"), docBefore);
|
||||
});
|
||||
|
||||
// The progress line under the title, once the page has drawn `want`.
|
||||
async function progressSays(s, want) {
|
||||
await s.page.waitForFunction((w) => document.getElementById("progress-text").textContent === w, want, { timeout: 5000 }).catch(() => {});
|
||||
return (await s.page.innerText("#progress-text")).trim();
|
||||
}
|
||||
|
||||
// One answered question, so a question workflow has something to count.
|
||||
const answered = { id: "a1", kind: "text", title: "What to call it", body: "A name.", status: "answered", answer: { text: "audit-export" } };
|
||||
const open = { id: "o1", kind: "text", title: "Who uses it", body: "Who?" };
|
||||
|
||||
test("a build's header counts its tasks, 0 done included, and a question workflow counts its answers", async (t) => {
|
||||
for (const workflow of ["implement", "implement-review", "quick-task"]) {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow,
|
||||
payload: { headline: { stage: "Phase 3", cleared: 3, total: 9 }, items: [answered] },
|
||||
});
|
||||
assert.equal(await progressSays(s, "3 of 9 done"), "3 of 9 done", `${workflow} counts its tasks`);
|
||||
s.post({ headline: { cleared: 0 } });
|
||||
assert.equal(await progressSays(s, "0 of 9 done"), "0 of 9 done", `${workflow}: 0 done is 0 done, not the answered card`);
|
||||
// A build between counts (a review starting at total 0) shows its stage.
|
||||
s.post({ headline: { stage: "Reviewing the phase", cleared: 0, total: 0 }, items: [open] });
|
||||
assert.equal(await progressSays(s, "Reviewing the phase"), "Reviewing the phase", `${workflow} shows its stage at total 0`);
|
||||
assert.equal(await s.page.locator("#progress-bar").isHidden(), true, `${workflow}: no track for a stage`);
|
||||
await s.stop();
|
||||
}
|
||||
|
||||
// A question workflow that set a total and never moved `cleared` fills as
|
||||
// cards are answered, and at total 0 counts its cards instead of the stage.
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { headline: { stage: "Charting", cleared: 0, total: 4 }, items: [answered] },
|
||||
});
|
||||
assert.equal(await progressSays(s, "1 of 4 answered"), "1 of 4 answered");
|
||||
s.post({ headline: { total: 0 }, items: [open] });
|
||||
assert.equal(await progressSays(s, "1 of 2 answered"), "1 of 2 answered");
|
||||
});
|
||||
|
||||
test("an answer typed over several lines reaches the agent under its title, never as reply lines of its own", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").locator("textarea").fill("audit-export\nIdea name: not a heading");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.equal(answerTo(got, "q1").text, "audit-export\nIdea name: not a heading");
|
||||
assert.ok(got.reply.includes("What to call it: audit-export\n Idea name: not a heading"), `the second line is not indented under its title: ${JSON.stringify(got.reply)}`);
|
||||
});
|
||||
|
||||
test("a redraw keeps the place of the dashboard, the waiting screen and the finished screen, and a new question starts at its top", async (t) => {
|
||||
// The dashboard's menu scrolls itself.
|
||||
let s = await openSession(await suite.browser(), { t, workflow: "dashboard" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
await s.page.getByRole("button", { name: "Skip the intro" }).click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
await s.page.locator("#main > .dash").evaluate((el) => (el.scrollTop = 150));
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard scrolls");
|
||||
await unrelatedPost(s, "Dashboard, take two");
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard lost its place");
|
||||
await s.stop();
|
||||
|
||||
// A build with nothing to ask yet: the waiting screen, and then its finish.
|
||||
s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
|
||||
});
|
||||
await s.page.setViewportSize({ width: 1280, height: 300 });
|
||||
const pane = "#main > .waiting-pane";
|
||||
await s.page.locator(pane).waitFor();
|
||||
await s.page.locator(pane).evaluate((el) => (el.scrollTop = 60));
|
||||
const waitingAt = await scrollTopOf(s.page, pane);
|
||||
assert.ok(waitingAt > 0, "the waiting screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take two");
|
||||
assert.equal(await scrollTopOf(s.page, pane), waitingAt, "the waiting screen lost its place");
|
||||
|
||||
s.post({ finish: { headline: "Phase 1 is done", body: longText(30), command: "/plan2code-3-implement specs/audit-export/overview.md" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
const end = "#main > .card";
|
||||
await s.page.locator(end).evaluate((el) => (el.scrollTop = 300));
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take three");
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen lost its place");
|
||||
await s.stop();
|
||||
|
||||
// Part-way down one question, a new one arrives: it starts at its top.
|
||||
s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").evaluate((el) => (el.scrollTop = 400));
|
||||
s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: longText(40) }] });
|
||||
await itemCard(s.page, "q2").waitFor();
|
||||
assert.equal(await itemCard(s.page, "q2").evaluate((el) => el.scrollTop), 0, "the new question opened part-way down");
|
||||
});
|
||||
|
||||
// The accent colour as the browser resolves it, and a button's outline colour,
|
||||
// so "wears the accent" is read off the screen, not off a class name.
|
||||
const accentOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--accent)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
});
|
||||
const outlineOf = (button) => button.evaluate((b) => getComputedStyle(b).borderTopColor);
|
||||
const warnOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--warn)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
});
|
||||
|
||||
// What a person sees break: the way forward on a sign-off card looks like any
|
||||
// other choice.
|
||||
test("on a sign-off card, approve and yes are outlined in the accent until picked, and the others are not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement" });
|
||||
const accent = await accentOf(s.page);
|
||||
const review = (id, verdicts) => ({ id, kind: "review", title: "Sign off " + id, body: "Read it.", verdicts });
|
||||
|
||||
let card = await ask(s, review("so1", [{ id: "approve", label: "Approve this phase" }, { id: "changes", label: "I want changes" }]));
|
||||
const approve = card.getByRole("button", { name: "Approve this phase" });
|
||||
assert.equal(await outlineOf(approve), accent, "an unpicked approve is outlined in the accent");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "I want changes" })), accent, "the other verdict is not");
|
||||
await approve.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await approve.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, approve fills with the accent");
|
||||
|
||||
card = await ask(s, review("so2", [{ id: "yes", label: "Build it" }, { id: "no", label: "Not yet" }]));
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Build it" })), accent, "an unpicked yes is outlined too");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "Not yet" })), accent);
|
||||
});
|
||||
|
||||
// What a person sees break: Skip this one turns into a full-size button, or
|
||||
// the quick answer under a note box does.
|
||||
test("Skip this one and a comment box's quick answer are the same small accent button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }];
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", required: false, rows });
|
||||
const skip = card.getByRole("button", { name: "Skip this one" });
|
||||
const quick = card.getByRole("button", { name: "No changes" });
|
||||
const look = (b) => b.evaluate((x) => { const c = getComputedStyle(x); return [c.fontSize, c.paddingTop, c.paddingLeft, c.color]; });
|
||||
assert.deepEqual(await look(skip), await look(quick), "the two chips look alike");
|
||||
const [size, , , colour] = await look(skip);
|
||||
assert.equal(size, "12px", "small, not a full-size button");
|
||||
assert.equal(colour, await accentOf(s.page), "in the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: a safe yes looks like any button, or a risky yes
|
||||
// stops warning.
|
||||
test("a confirm's safe yes and a recap's yes are outlined in the accent, and a dangerous yes stays red", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const accent = await accentOf(s.page);
|
||||
const warn = await warnOf(s.page);
|
||||
|
||||
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
const yes = card.getByRole("button", { name: "Yes" });
|
||||
assert.equal(await outlineOf(yes), accent, "a safe, unpicked yes wears the accent");
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "No" })), accent, "the no does not");
|
||||
await yes.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await yes.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, it fills");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "Delete it", body: "Really?", danger: true });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes" })), warn, "a dangerous yes stays red");
|
||||
|
||||
card = await ask(s, { id: "r1", kind: "recap", title: "What we decided", body: "Right?", summary: "- CSV" });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes, that is right" })), accent, "the recap's yes wears the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: a long question runs off the window with nothing
|
||||
// to say there is more, or the fade stays on at the very end.
|
||||
test("a card cut by the window fades at its bottom edge while there is more below", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: longText(40) });
|
||||
const fades = () => card.evaluate((el) => { const c = getComputedStyle(el); return (c.maskImage || c.webkitMaskImage || "none") !== "none"; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); return c && c.scrollHeight > c.clientHeight + 4; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") !== "none"; });
|
||||
assert.equal(await fades(), true, "a cut card fades at the bottom");
|
||||
await card.evaluate((el) => (el.scrollTop = el.scrollHeight));
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") === "none"; });
|
||||
assert.equal(await fades(), false, "at the end, the fade is gone");
|
||||
});
|
||||
|
||||
// What a person sees break: a rename typed in a list is lost when the agent
|
||||
// posts or Ctrl+Enter sends before the field was left.
|
||||
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }, { id: "b", title: "Write the file", body: "y" }];
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", rows });
|
||||
const first = card.locator("input.row-title").first();
|
||||
await first.click();
|
||||
await first.fill("Read the audit log");
|
||||
// The field is still focused: it has not changed or blurred.
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
await unrelatedPost(s, "Steps, take two");
|
||||
assert.equal(await itemCard(s.page, "l1").locator("input.row-title").first().inputValue(), "Read the audit log", "the agent post kept the typed name");
|
||||
await itemCard(s.page, "l1").locator("input.row-title").first().focus();
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "Ctrl+Enter sent");
|
||||
assert.deepEqual(answerTo(got, "l1").rows.map((r) => [r.id, r.title]), [["a", "Read the audit log"], ["b", "Write the file"]]);
|
||||
});
|
||||
|
||||
// What a person sees break: a send the agent already collected still shows as
|
||||
// being with the agent, locking a question it left open.
|
||||
test("a send made before the last collection is never shown as still with the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: "A name." });
|
||||
// Sent from another tab: this page never learns of it except from the session.
|
||||
await s.page.evaluate(() =>
|
||||
fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [{ i: "q1", type: "answer", kind: "text", text: "audit-export" }], reply: "What to call it: audit-export" }),
|
||||
})
|
||||
);
|
||||
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
|
||||
await lock.waitFor();
|
||||
assert.equal(await card.locator("textarea").count(), 0, "before the agent collects it, the card is locked");
|
||||
// The agent collects it, leaves the question open and waits again.
|
||||
assert.equal(s.wait(10).code, 0);
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await card.locator("textarea").waitFor();
|
||||
assert.equal(await lock.count(), 0, "after the collection, it is not shown as sent");
|
||||
});
|
||||
|
||||
// What a person sees break: a note box on a card above the git board grows and
|
||||
// squeezes the board, or the card is cut short under it.
|
||||
test("a note box over the git board grows no box, and the card flows at its own height", async (t) => {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
const confirm = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
|
||||
const git = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "git",
|
||||
project: dir,
|
||||
payload: { reread: true, board: { describe: "export-more" }, items: [confirm] },
|
||||
});
|
||||
await git.page.getByRole("tablist").waitFor();
|
||||
const gitCard = itemCard(git.page, "y1");
|
||||
await gitCard.waitFor();
|
||||
const note = gitCard.locator("textarea").first();
|
||||
const gitBox = await note.evaluate((el) => ({ min: el.style.minHeight, height: el.offsetHeight }));
|
||||
assert.equal(gitBox.min, "", "no height was filled in for the note box");
|
||||
assert.ok(gitBox.height < 120, `the note box keeps its ordinary height over the board: ${gitBox.height}`);
|
||||
assert.ok(await gitCard.evaluate((el) => el.scrollHeight <= el.clientHeight + 1), "the card is not shrunk under the board");
|
||||
|
||||
// The same card away from the board does fill the free height of the card.
|
||||
const plan = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [confirm] } });
|
||||
const planBox = plan.page.locator('[data-item="y1"] textarea').first();
|
||||
await planBox.waitFor();
|
||||
await plan.page.waitForFunction(() => document.querySelector('[data-item="y1"] textarea').offsetHeight >= 160);
|
||||
assert.ok((await planBox.evaluate((el) => el.offsetHeight)) > gitBox.height, "away from the board, the note box grows");
|
||||
});
|
||||
|
||||
const three = ["First", "Second", "Third"].map((name, n) => ({ id: `q${n + 1}`, kind: "text", title: `${name} question`, body: `Body ${n + 1}.` }));
|
||||
|
||||
// What a person sees break: Previous and Next stop walking the open questions.
|
||||
test("Previous and Next walk the questions still waiting, and the ends have no button", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: three } });
|
||||
const pager = s.page.getByRole("navigation", { name: "Move between the questions waiting" });
|
||||
const shown = () => s.page.locator("#main [data-item]").first().getAttribute("data-item");
|
||||
await pager.getByText("1 of 3 waiting").waitFor();
|
||||
assert.equal(await pager.getByRole("button", { name: /Previous/ }).count(), 0, "nothing before the first");
|
||||
await pager.getByRole("button", { name: /Next.*Second question/ }).click();
|
||||
await pager.getByText("2 of 3 waiting").waitFor();
|
||||
assert.equal(await shown(), "q2");
|
||||
await pager.getByRole("button", { name: /Next.*Third question/ }).click();
|
||||
await pager.getByText("3 of 3 waiting").waitFor();
|
||||
assert.equal(await pager.getByRole("button", { name: /Next/ }).count(), 0, "nothing after the last");
|
||||
await pager.getByRole("button", { name: /Previous.*Second question/ }).click();
|
||||
await pager.getByText("2 of 3 waiting").waitFor();
|
||||
assert.equal(await shown(), "q2");
|
||||
});
|
||||
|
||||
// What a person sees break: Skip this one does nothing, or leaves you on the
|
||||
// card you skipped.
|
||||
test("Skip this one on an optional card moves on, and the skip reaches the agent", async (t) => {
|
||||
const items = three.map((q, n) => ({ ...q, required: n !== 2 ? false : true }));
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items } });
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.getByRole("button", { name: "Skip this one" }).click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#main [data-item]")?.dataset.item === "q2");
|
||||
assert.equal(await itemCard(s.page, "q3").getByRole("button", { name: "Skip this one" }).count(), 0, "a required card cannot be skipped");
|
||||
await itemCard(s.page, "q2").locator("textarea").fill("Ana");
|
||||
await s.page.getByRole("navigation", { name: "Move between the questions waiting" }).getByRole("button", { name: /Next/ }).click();
|
||||
await itemCard(s.page, "q3").locator("textarea").fill("Bo");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type, text }) => ({ i, type, text })),
|
||||
[{ i: "q1", type: "skip", text: undefined }, { i: "q2", type: "answer", text: "Ana" }, { i: "q3", type: "answer", text: "Bo" }]
|
||||
);
|
||||
});
|
||||
|
||||
// What a person sees break: an answered question can be edited again, or says
|
||||
// nothing about what was answered.
|
||||
test("a settled card is a record: your answer in words, the options as marks, and no form", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
s.post({
|
||||
settle: true,
|
||||
items: [
|
||||
{ id: "c1", kind: "choice", title: "Export format", body: "Which?", options: [opt("A", "CSV"), opt("B", "JSON")], status: "answered", answer: { k: "B" } },
|
||||
{ id: "q9", kind: "text", title: "Still open", body: "Next." },
|
||||
],
|
||||
});
|
||||
await s.page.locator("#sidebar").getByRole("button", { name: /Export format/ }).click();
|
||||
const card = itemCard(s.page, "c1");
|
||||
await card.waitFor();
|
||||
const record = card.locator(".answered");
|
||||
assert.match(await record.innerText(), /Your answer[\s\S]*JSON/i);
|
||||
assert.match(await record.innerText(), /Locked\./);
|
||||
assert.equal(await card.locator("input, textarea").count(), 0, "a record has no inputs");
|
||||
});
|
||||
|
||||
// What a person sees break: a card still takes edits after Send, or never
|
||||
// opens again when the agent hands it back.
|
||||
test("a sent card locks, and the agent's next post on it unlocks it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: { items: [three[0]] } });
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.locator("textarea").fill("Ana");
|
||||
await s.page.click("#btn-send");
|
||||
const lock = card.getByText(/Plan2Code is working on it|Waiting for Plan2Code to pick this up/);
|
||||
await lock.waitFor();
|
||||
assert.match(await card.locator(".answered").innerText(), /Sent[\s\S]*Ana/i);
|
||||
assert.equal(await card.locator("textarea").count(), 0, "no form while the agent has it");
|
||||
s.wait(10);
|
||||
s.post({ items: [{ id: "q1", status: "reopened", thread: [{ who: "agent", text: "Which Ana?" }] }], agent: { status: "waiting" } });
|
||||
await card.locator("textarea").waitFor();
|
||||
assert.equal(await lock.count(), 0, "the next post gives the card back");
|
||||
});
|
||||
|
||||
// What a person sees break: the "something else" box takes the words but the
|
||||
// pick sent is still the listed option, or the pick is lost on a switch back.
|
||||
test("Something else in your own words replaces the pick, and picking an option again drops the words", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
const card = await ask(s, { id: "c1", kind: "choice", title: "Where", body: "Where?", options: [opt("A", "Email"), opt("B", "Slack")] });
|
||||
await card.getByLabel("Email").check();
|
||||
const other = card.getByRole("radio", { name: "Something else, in your own words" });
|
||||
await other.check();
|
||||
await card.locator("textarea.other-text").fill("A shared drive");
|
||||
assert.equal(await card.getByLabel("Email").isChecked(), false, "the options and the other share one group");
|
||||
await card.getByLabel("Slack").check();
|
||||
await other.check();
|
||||
assert.equal(await card.locator("textarea.other-text").inputValue(), "A shared drive", "the words survive a switch");
|
||||
const got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "c1"), { text: "A shared drive" });
|
||||
});
|
||||
|
||||
// What a person sees break: a note typed on a card is dropped by the verdict,
|
||||
// or is lost when the verdict comes first.
|
||||
test("a note's comment field rides along with the answer, typed before or after the pick", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
let card = await ask(s, { id: "y1", kind: "confirm", title: "Keep going", body: "Carry on?" });
|
||||
await card.getByLabel("Anything to add?").fill("Only on weekdays.");
|
||||
await card.getByRole("button", { name: "Yes" }).click();
|
||||
let got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y1"), { yes: true, text: "Only on weekdays." });
|
||||
assert.equal(got.reply, "Keep going: yes; Only on weekdays.");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "And this", body: "Also?" });
|
||||
await card.getByRole("button", { name: "No" }).click();
|
||||
await card.getByLabel("Anything to add?").fill("Not this quarter.");
|
||||
got = await sendAndCollect(s);
|
||||
assert.deepEqual(answerTo(got, "y2"), { yes: false, text: "Not this quarter." });
|
||||
});
|
||||
|
||||
/* ----------------------------------------------------------------- docs */
|
||||
|
||||
// What a person sees break: a guess reads like a decision, or a draft does.
|
||||
test("a doc tags an assumed block and a draft block, and shows a file block's text", async (t) => {
|
||||
const project = tempProject({ "notes/facts.md": "The export keeps **a year** of rows.\n" });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
project,
|
||||
payload: {
|
||||
docs: [
|
||||
{
|
||||
id: "map",
|
||||
title: "What we've agreed",
|
||||
blocks: [
|
||||
{ id: "b1", state: "settled", md: "Runs nightly." },
|
||||
{ id: "b2", state: "assumed", md: "Output is CSV." },
|
||||
{ id: "b3", state: "draft", md: "Maybe a weekly digest." },
|
||||
{ id: "b4", file: "notes/facts.md" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const block = (id) => s.page.locator(`#main [data-block="${id}"]`);
|
||||
await block("b4").waitFor();
|
||||
assert.equal(await block("b1").innerText(), "Runs nightly.", "a settled block has no tag");
|
||||
assert.match(await block("b2").innerText(), /^assumed for now, still open\s+Output is CSV\.$/i);
|
||||
assert.match(await block("b3").innerText(), /^draft\s+Maybe a weekly digest\.$/i);
|
||||
assert.match(await block("b4").innerText(), /The export keeps a year of rows\./, "the file's text is on the page");
|
||||
});
|
||||
|
||||
// What a person sees break: Download hands over something other than the
|
||||
// document, or loses which parts are still guesses.
|
||||
test("Download offers a Markdown file with the doc's title, blocks and marks", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: {
|
||||
docs: [{ id: "map", title: "What we've agreed", blocks: [{ id: "b1", state: "settled", md: "Runs nightly." }, { id: "b2", state: "assumed", md: "Output is CSV." }] }],
|
||||
},
|
||||
});
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
const [download] = await Promise.all([s.page.waitForEvent("download"), s.page.getByRole("button", { name: "Download" }).click()]);
|
||||
assert.equal(download.suggestedFilename(), "what-we-ve-agreed.md");
|
||||
const chunks = [];
|
||||
for await (const c of await download.createReadStream()) chunks.push(c);
|
||||
assert.equal(Buffer.concat(chunks).toString("utf8"), "# What we've agreed\n\nRuns nightly.\n\n> **Assumed for now, still open.**\n\nOutput is CSV.");
|
||||
});
|
||||
|
||||
// What a person sees break: the brief button turns up where no playbook
|
||||
// answers it, or sends a different range than the one picked.
|
||||
test("a pathfinder session offers Write a brief, and the picked range reaches the agent", async (t) => {
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
assert.equal(await plain.page.locator("#btn-brief").isHidden(), true, "no brief button outside pathfinder");
|
||||
await plain.stop();
|
||||
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: { agent: { status: "waiting" } } });
|
||||
await s.page.getByRole("button", { name: "Write a brief" }).first().click();
|
||||
const dialog = s.page.locator("#brief-modal");
|
||||
await dialog.getByLabel("This week").check();
|
||||
await dialog.getByRole("button", { name: "Write the brief" }).click();
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "a brief request was sent");
|
||||
assert.deepEqual(got.actions.map(({ i, type, range }) => ({ i, type, range })), [{ i: "__brief", type: "brief", range: "this week" }]);
|
||||
assert.equal(got.reply, "Write a brief for this week.");
|
||||
});
|
||||
@@ -0,0 +1,447 @@
|
||||
// Page tests for the dashboard: a spec in the picker, a card picked and
|
||||
// started, the launch send the agent collects, and its `resume` turning the
|
||||
// page into the launched skill's starting screen. Run with:
|
||||
// node --test scripts/test-web-console-page-dashboard.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, textOf } from "./page-test-helpers.mjs";
|
||||
import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A project that is set up (AGENTS.md) with one spec holding a Plan draft.
|
||||
// A PLAN-DRAFT whose Status line says only "Draft" (no "Resume at Phase N")
|
||||
// scans as `planned`, which the picker labels "Ready to document". Plan is
|
||||
// still lit for it (only exploring, fixed and documented-or-later grey Plan
|
||||
// out); Document is the state's own next step.
|
||||
const DRAFT_PROJECT = {
|
||||
"AGENTS.md": "# AGENTS.md\n\nA small demo project.\n",
|
||||
"specs/demo/PLAN-DRAFT-20261017.md": "# Plan draft: demo\n\n**Status:** Draft\n\nA lunch vote for the team.\n",
|
||||
};
|
||||
|
||||
// What a real agent posts on the dashboard (plan2code.md, "The menu"): its
|
||||
// judgment on top of the scan, then it waits.
|
||||
const MENU = {
|
||||
menu: {
|
||||
note: "One spec on disk, with a plan drafted.",
|
||||
recommend: "plan2code-2-document",
|
||||
details: { "plan2code-2-document": "Plan drafted" },
|
||||
},
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
test("a Plan launch from the dashboard carries the picked spec, and its resume turns the page to Starting Plan", async (t) => {
|
||||
const project = tempProject(DRAFT_PROJECT);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
|
||||
// The picker shows the spec with its state, and opens on it.
|
||||
const chip = main.getByRole("button").filter({ hasText: /^demo/ });
|
||||
await chip.waitFor();
|
||||
// The state is drawn in capitals, so the match ignores case.
|
||||
const chipText = await textOf(chip);
|
||||
assert.match(chipText, /Ready to document/i, "the spec chip names its state");
|
||||
assert.match(chipText, /plan drafted/, "the spec chip says how far it got");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "true", "the picker opens on the only spec");
|
||||
|
||||
// The Plan card is lit for this spec; picking it asks to confirm.
|
||||
const planCard = main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) });
|
||||
assert.equal(await planCard.isEnabled(), true, "the Plan card is greyed for a drafted plan");
|
||||
await planCard.click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const launch = got.actions.find((a) => a.i === "__launch");
|
||||
assert.ok(launch, `the send carries a launch: ${JSON.stringify(got.actions)}`);
|
||||
assert.deepEqual(
|
||||
{ i: launch.i, skill: launch.skill, workflow: launch.workflow, spec: launch.spec },
|
||||
{ i: "__launch", skill: "plan2code-1-plan", workflow: "plan", spec: "specs/demo" }
|
||||
);
|
||||
|
||||
// `resume` is the one command to run, naming the session, workflow and spec.
|
||||
const head = `node "${CONSOLE_CLI}" `;
|
||||
assert.ok(got.resume.startsWith(head), `resume runs this console: ${got.resume}`);
|
||||
const args = got.resume.slice(head.length).split(" ");
|
||||
assert.deepEqual(args, ["open", "--resume", s.sid, "--no-open", "--workflow", "plan", "--spec", "specs/demo"]);
|
||||
|
||||
// `skillFile` is offered only when the skill's SKILL.md sits beside the
|
||||
// console's own folder, as in an install. Run from this repo's source tree
|
||||
// (src/web-console/), that is a plan2code-1-plan/ folder next to the repo,
|
||||
// which does not exist, so the send leaves it out (console-launches.md:
|
||||
// "absent outside an install").
|
||||
assert.equal("skillFile" in got, false, `a source-tree launch names no skillFile: ${got.skillFile}`);
|
||||
|
||||
// The agent runs `resume` first: the page leaves the menu for Plan's
|
||||
// starting screen while the skill is read.
|
||||
const r = cli(args, { cwd: s.project });
|
||||
assert.equal(r.status, 0, `resume failed: ${r.stderr}`);
|
||||
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
|
||||
});
|
||||
|
||||
// A project holding one fixed bug (a diagnosis Quick Task marked Fixed) and
|
||||
// one drafted plan. The fixed bug is touched last, so it is the newest spec on
|
||||
// disk: the picker must still open on the plan, since a finished spec is never
|
||||
// the default.
|
||||
function fixedProject() {
|
||||
const project = tempProject({
|
||||
...DRAFT_PROJECT,
|
||||
"specs/old-bug/DIAGNOSIS-20261017.md": "# Diagnosis: old bug\n\n**Status:** Fixed\n\nThe save button lost its handler.\n",
|
||||
});
|
||||
const later = new Date(Date.now() + 60_000);
|
||||
fs.utimesSync(path.join(project, "specs/old-bug/DIAGNOSIS-20261017.md"), later, later);
|
||||
return project;
|
||||
}
|
||||
|
||||
// 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");
|
||||
const heading = main.getByRole("heading", { name: "What are we doing today?" });
|
||||
await heading.waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) {
|
||||
await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
}
|
||||
return main;
|
||||
}
|
||||
|
||||
// Sets the picker's "Hide unavailable workflows" switch. Looks are kept per
|
||||
// console home, so each test sets the one it needs rather than trusting the
|
||||
// default.
|
||||
async function hideUnavailable(main, on) {
|
||||
const box = main.getByRole("switch", { name: "Hide unavailable workflows" });
|
||||
if ((await box.isChecked()) !== on) await main.getByText("Hide unavailable workflows").click();
|
||||
assert.equal(await box.isChecked(), on);
|
||||
}
|
||||
|
||||
const chipFor = (main, name) => main.getByRole("button").filter({ hasText: new RegExp(`^${name}`) });
|
||||
|
||||
test("a fixed bug is hidden while unavailable workflows are, dimmed when they show, and never the picker's default", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
|
||||
const main = await toTheMenu(s);
|
||||
|
||||
// Hidden while the switch is on.
|
||||
await hideUnavailable(main, true);
|
||||
const demo = chipFor(main, "demo");
|
||||
await demo.waitFor();
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the picker opens on the plan, not the newer fixed bug");
|
||||
assert.equal(await chipFor(main, "old-bug").count(), 0, "the fixed bug's chip is hidden while unavailable workflows are");
|
||||
|
||||
// Switched off: the chip shows, labelled and dimmed, and still not picked.
|
||||
await hideUnavailable(main, false);
|
||||
const bug = chipFor(main, "old-bug");
|
||||
await bug.waitFor();
|
||||
assert.match(await textOf(bug), /Bug fixed/i, "the chip names its state");
|
||||
assert.doesNotMatch(await textOf(bug), /bug fixed\s+bug fixed/i, "the scan's detail does not repeat the label");
|
||||
assert.equal(await bug.getAttribute("aria-current"), "false", "the fixed bug is not picked");
|
||||
const opacity = await bug.evaluate((b) => Number(getComputedStyle(b).opacity));
|
||||
assert.ok(opacity < 1, `the fixed bug's chip is dimmed (opacity ${opacity})`);
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the plan stays picked");
|
||||
});
|
||||
|
||||
test("a fixed bug's Delete asks once with no name to type, while any other spec asks for its name", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: fixedProject() });
|
||||
const main = await toTheMenu(s);
|
||||
await hideUnavailable(main, false);
|
||||
await chipFor(main, "old-bug").waitFor();
|
||||
|
||||
const dialog = s.page.locator("#delete-modal");
|
||||
const go = s.page.locator("#delete-go");
|
||||
const nameStep = s.page.locator("#delete-confirm");
|
||||
|
||||
// Any other spec: the first press only reveals the name step.
|
||||
await main.getByRole("button", { name: "Delete the spec demo" }).click({ force: true });
|
||||
await dialog.waitFor();
|
||||
assert.equal(await textOf(go), "Delete this spec…");
|
||||
await go.click();
|
||||
await nameStep.waitFor();
|
||||
assert.equal(await go.isDisabled(), true, "the final button waits for the name");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await dialog.waitFor({ state: "hidden" });
|
||||
|
||||
// The fixed bug: a visible Delete, its own warning, and one press sends it.
|
||||
const del = main.getByRole("button", { name: "Delete the spec old-bug" });
|
||||
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labelled button");
|
||||
await del.click();
|
||||
await dialog.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#delete-warn")), /The bug is fixed, so this only clears the write-up/);
|
||||
assert.equal(await textOf(go), "Delete it");
|
||||
assert.equal(await nameStep.isHidden(), true, "no name step for a fixed bug");
|
||||
await go.click();
|
||||
|
||||
const got = collect(s);
|
||||
assert.equal(await nameStep.isHidden(), true, "the name step never showed");
|
||||
const action = got.actions.find((a) => a.i === "__delete");
|
||||
assert.deepEqual({ type: action?.type, spec: action?.spec }, { type: "delete", spec: "specs/old-bug" });
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The picker's switching, the first-open wake-up, handoffs, the update banner,
|
||||
// the workspace scope, and the pose that carries a launch into the work.
|
||||
|
||||
const lightOf = (main, command) => main.getByRole("button").filter({ has: main.page().locator("code", { hasText: new RegExp(`^${command}$`) }) });
|
||||
const pickedChip = (main, name) => main.locator('button[aria-current="true"]', { hasText: new RegExp(`^${name}`) });
|
||||
|
||||
// What a person would see break: picking another target leaves the launch
|
||||
// aimed at the old spec, or the cards lit for it.
|
||||
test("picking Start from scratch instead of a spec greys Document, and a launch then carries no spec", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(s);
|
||||
const document = lightOf(main, "/plan2code-2-document");
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
assert.equal(await document.isEnabled(), true, "Document is lit for the drafted spec");
|
||||
|
||||
// From scratch there is no draft to document: the card greys.
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
assert.equal(await document.isDisabled(), true, "Document is greyed with no spec picked");
|
||||
assert.equal(await chipFor(main, "demo").getAttribute("aria-current"), "false");
|
||||
|
||||
// Back on the spec it is lit again; then from scratch once more to launch.
|
||||
await chipFor(main, "demo").click();
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
assert.equal(await document.isEnabled(), true, "Document is lit again for the spec");
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
await lightOf(main, "/plan2code-1-plan").click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
const launch = collect(s).actions.find((a) => a.i === "__launch");
|
||||
assert.equal(launch.skill, "plan2code-1-plan");
|
||||
assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`);
|
||||
});
|
||||
|
||||
// What a person would see break: the intro cannot be skipped, or it replays
|
||||
// on every reload of the same tab.
|
||||
test("Skip the intro ends the first-open wake-up at once, and a reload of the tab does not play it again", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.waitFor();
|
||||
await toTheMenu(s);
|
||||
assert.equal(await skip.isVisible(), false);
|
||||
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
assert.equal(await skip.isVisible(), false, "the intro does not play again in this tab");
|
||||
});
|
||||
|
||||
// A project with no spec, only a handoff written for it (the Handoff skill's
|
||||
// file pair under the test's own handoffs folder), removed with the test.
|
||||
const HANDOFF_DOC = "# Handoff: Lunch vote\n\n## Next task\n\nWire the vote button to the tally.\n\n## Notes\n\nA long body line.\n";
|
||||
function handoffProject(t) {
|
||||
const project = tempProject({ "AGENTS.md": "# AGENTS.md\n\nA small demo project.\n" });
|
||||
const made = cli(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--title", "Lunch vote"], { cwd: project }).json;
|
||||
fs.writeFileSync(made.path, HANDOFF_DOC);
|
||||
t.after(() => {
|
||||
fs.rmSync(made.path, { force: true });
|
||||
fs.rmSync(made.path.replace(/\.md$/, ".json"), { force: true });
|
||||
});
|
||||
return { project, made };
|
||||
}
|
||||
|
||||
async function openHandoffMenu(t) {
|
||||
const { project, made } = handoffProject(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
const chip = chipFor(main, "Lunch vote");
|
||||
await chip.waitFor();
|
||||
return { s, main, chip, made };
|
||||
}
|
||||
|
||||
// What a person would see break: a handoff is not offered when it is all the
|
||||
// project has, or picking it still shows the skill cards beside the preview.
|
||||
test("a handoff shows as a dashed Handoff chip even with no spec, and picking it swaps the cards for a preview of four buttons", async (t) => {
|
||||
const { main, chip } = await openHandoffMenu(t);
|
||||
assert.match(await textOf(chip), /Handoff/i, "the chip is labelled Handoff");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "false", "a handoff is offered, not picked for you");
|
||||
assert.equal(await chip.evaluate((b) => getComputedStyle(b).borderTopStyle), "dashed", "the chip's border is dashed");
|
||||
assert.ok(await lightOf(main, "/plan2code-1-plan").isVisible(), "the cards show before a handoff is picked");
|
||||
|
||||
await chip.click();
|
||||
assert.equal(await chip.getAttribute("aria-current"), "true");
|
||||
await main.getByRole("heading", { name: "Lunch vote" }).waitFor();
|
||||
assert.match(await textOf(main), /Wire the vote button to the tally\./, "the preview quotes the Next task");
|
||||
for (const name of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
|
||||
assert.equal(await main.getByRole("button", { name, exact: true }).count(), 1, `the preview has ${name}`);
|
||||
}
|
||||
assert.equal(await lightOf(main, "/plan2code-1-plan").count(), 0, "the skill cards give way to the preview");
|
||||
assert.equal(await main.getByRole("switch", { name: "Hide unavailable workflows" }).count(), 0, "and so does their toggle");
|
||||
});
|
||||
|
||||
// What a person would see break: Pick it up here sends nothing, or sends more
|
||||
// than the handoff's id.
|
||||
test("Pick it up here sends a pickup naming the handoff, and the page turns to its launch screen", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await chip.click();
|
||||
await main.getByRole("button", { name: "Pick it up here" }).click();
|
||||
const got = collect(s);
|
||||
const pick = got.actions.find((a) => a.i === "__pickup");
|
||||
assert.deepEqual({ type: pick?.type, handoff: pick?.handoff }, { type: "pickup", handoff: made.id });
|
||||
assert.match(got.resume, /--workflow quick-task$/, "the CLI read the handoff's own workflow");
|
||||
await main.getByRole("heading", { name: "Waking up Lunch vote" }).waitFor();
|
||||
});
|
||||
|
||||
// What a person would see break: Read it all opens nothing, or Copy puts the
|
||||
// wrong words on the clipboard.
|
||||
test("Read it all opens the handoff's text, and Copy puts a prompt naming its file on the clipboard", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
await chip.click();
|
||||
|
||||
await main.getByRole("button", { name: "Read it all" }).click();
|
||||
const reader = s.page.locator("#handoff-modal");
|
||||
await reader.getByText("A long body line.").waitFor();
|
||||
await s.page.keyboard.press("Escape");
|
||||
await reader.waitFor({ state: "hidden" });
|
||||
|
||||
const copy = main.getByRole("button", { name: "Copy for a new conversation" });
|
||||
await copy.click();
|
||||
await main.getByRole("button", { name: "Copied" }).waitFor();
|
||||
const text = await s.page.evaluate(() => navigator.clipboard.readText());
|
||||
assert.match(text, /^Read the handoff at .*\.md and carry on with its Next task\.$/);
|
||||
assert.ok(text.includes(made.id), `the prompt names the handoff's file: ${text}`);
|
||||
});
|
||||
|
||||
// What a person would see break: Delete asks for a name, or sends a spec
|
||||
// delete instead of the handoff's.
|
||||
test("a handoff's Delete asks once in its own dialog and sends a delete naming the handoff", async (t) => {
|
||||
const { s, main, chip, made } = await openHandoffMenu(t);
|
||||
await chip.click();
|
||||
await main.getByRole("button", { name: "Delete", exact: true }).click();
|
||||
const dialog = s.page.locator("#delete-modal");
|
||||
await dialog.waitFor();
|
||||
assert.equal(await textOf(s.page.locator("#delete-title")), "Delete this handoff?");
|
||||
assert.equal(await s.page.locator("#delete-warn-handoff").isVisible(), true, "the warning says where handoffs live");
|
||||
assert.equal(await s.page.locator("#delete-confirm").isHidden(), true, "no name to type");
|
||||
await s.page.locator("#delete-go").click();
|
||||
const action = collect(s).actions.find((a) => a.i === "__delete");
|
||||
assert.deepEqual({ type: action?.type, handoff: action?.handoff, spec: action?.spec }, { type: "delete", handoff: made.id, spec: undefined });
|
||||
});
|
||||
|
||||
// A newer release on record, so a console that boots now has an update to
|
||||
// announce (the check reads this file for an hour instead of asking the
|
||||
// network). The file is put back as the suite had it.
|
||||
function aNewerReleaseExists(t) {
|
||||
const file = path.join(HOME, "update-check.json");
|
||||
const before = fs.readFileSync(file, "utf8");
|
||||
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
|
||||
t.after(() => fs.writeFileSync(file, before));
|
||||
}
|
||||
|
||||
// What a person would see break: the banner shows on a build's page, or the
|
||||
// dashboard never offers it.
|
||||
test("the update banner shows on the dashboard only, and its dismiss hides it", async (t) => {
|
||||
aNewerReleaseExists(t);
|
||||
const browser = await suite.browser();
|
||||
const build = await openSession(browser, { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const dash = await openSession(browser, { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(dash);
|
||||
const banner = main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ });
|
||||
await banner.waitFor();
|
||||
// The build's server booted under the same record; a later frame has landed
|
||||
// on its page by the time this text shows, and it still has no banner.
|
||||
build.post({ agent: { status: "working", activity: "Task 1 of 1, one more look" } });
|
||||
await build.page.getByText("Task 1 of 1, one more look").first().waitFor();
|
||||
assert.equal(await build.page.getByText("UPDATE AVAILABLE").count(), 0, "a build's page has no banner");
|
||||
|
||||
await main.getByRole("button", { name: "Dismiss until next time" }).click();
|
||||
await banner.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
// What a person would see break: two dashboard tabs of one session, on
|
||||
// different picks, keep taking the workspace's folders back from each other.
|
||||
test("two dashboard tabs on different picks leave the workspace scope with the last pick and ask for it no more", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const mainA = await toTheMenu(s);
|
||||
const second = await s.context.newPage();
|
||||
second.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await second.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
const mainB = await toTheMenu({ page: second });
|
||||
const asks = { a: 0, b: 0 };
|
||||
s.page.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.a++);
|
||||
second.on("request", (r) => r.method() === "POST" && r.url().endsWith("/workspace/scope") && asks.b++);
|
||||
const scopeOf = () => s.page.evaluate(async () => (await (await fetch("/workspace?check=1", { cache: "no-store" })).json()).scope || "");
|
||||
assert.equal(await scopeOf(), "specs/demo", "both tabs opened on the spec");
|
||||
|
||||
// The second tab moves to Start from scratch: its folders become the project's own.
|
||||
await chipFor(mainB, "Start from scratch").click();
|
||||
await pickedChip(mainB, "Start from scratch").waitFor();
|
||||
assert.ok(await until(async () => (await scopeOf()) === ""), "the scope followed the second tab");
|
||||
|
||||
// The first tab keeps its pick and takes a frame from the agent after the change.
|
||||
s.post({ menu: { ...MENU.menu, note: "A second look from the agent." } });
|
||||
await mainA.getByText("A second look from the agent.").waitFor();
|
||||
assert.equal(await pickedChip(mainA, "demo").count(), 1, "the first tab still has its own pick");
|
||||
assert.equal(asks.a, 0, "the tab that did not move never asked for its own scope back");
|
||||
assert.equal(asks.b, 1, "the tab that moved asked once");
|
||||
assert.equal(await scopeOf(), "", "the scope stays with the last pick");
|
||||
});
|
||||
|
||||
// What a person would see break: Planny is rebuilt on every screen change, so
|
||||
// his animation restarts as the launch becomes the work.
|
||||
test("the pose pane a launch shows is the very element the starting and waiting screens keep, and the waiting pane shows the agent's activity", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(s);
|
||||
await lightOf(main, "/plan2code-1-plan").click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
// The launching screen, with its pose; mark that exact element.
|
||||
const pane = s.page.locator("#main > [data-pose]");
|
||||
await pane.waitFor();
|
||||
const pose = await pane.getAttribute("data-pose");
|
||||
await pane.evaluate((el) => (el.__sameElement = true));
|
||||
|
||||
// The agent resumes the session as Plan: the starting screen reuses the pane.
|
||||
const got = collect(s);
|
||||
const args = got.resume.slice(`node "${CONSOLE_CLI}" `.length).split(" ");
|
||||
assert.equal(cli(args, { cwd: s.project }).status, 0);
|
||||
await main.getByRole("heading", { name: "Starting Plan" }).waitFor();
|
||||
assert.equal(await pane.getAttribute("data-pose"), pose, "the same pose carries into the starting screen");
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane was kept, not rebuilt");
|
||||
|
||||
// The agent starts work and says what it is doing: the waiting screen shows it,
|
||||
// still in the same pane.
|
||||
s.post({ agent: { status: "working", activity: "Reading the plan draft" } });
|
||||
await main.getByText("Reading the plan draft").waitFor();
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "the pane survives into the waiting screen");
|
||||
s.post({ agent: { status: "working", activity: "Writing the first questions" } });
|
||||
await main.getByText("Writing the first questions").waitFor();
|
||||
assert.equal(await pane.evaluate((el) => el.__sameElement === true && el.isConnected), true, "and survives each state frame after it");
|
||||
});
|
||||
|
||||
// What a person would see break: a quick-task build points at a Plan tab that
|
||||
// does not open, or another skill's page gains a pointer it has no list for.
|
||||
test("a quick-task build's waiting pane points at its Plan tab, and a plan session with the same tab gets no pointer", async (t) => {
|
||||
const plan = { id: "plan", title: "Plan", blocks: [{ id: "steps", state: "settled", md: "## Steps\n\n- [ ] **1.** Wire the vote button" }] };
|
||||
const working = { agent: { status: "working", activity: "Step 1 of 1" } };
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { docs: [plan], ...working } });
|
||||
const pane = s.page.locator("#main > .waiting-pane");
|
||||
await pane.waitFor();
|
||||
const jump = pane.getByRole("button", { name: "Plan", exact: true });
|
||||
await jump.waitFor();
|
||||
await jump.click();
|
||||
await s.page.locator("#main").getByText("Wire the vote button").waitFor();
|
||||
|
||||
const other = await openSession(await suite.browser(), { t, workflow: "plan", payload: { docs: [plan], ...working } });
|
||||
const otherPane = other.page.locator("#main > .waiting-pane");
|
||||
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");
|
||||
});
|
||||
@@ -0,0 +1,314 @@
|
||||
// Page tests for the git board: the Changes, Branches and Sync tabs drawn
|
||||
// from a real repository, each tab's content on show when it is picked. Run
|
||||
// with:
|
||||
// node --test scripts/test-web-console-page-git.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. The fixture repo is built under the scrubbed git config
|
||||
// that skill-script-helpers.mjs sets for the whole process, so the console's
|
||||
// own snapshot reads it the way the fixture wrote it.
|
||||
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, tempProject, textOf, itemCard } from "./page-test-helpers.mjs";
|
||||
import { until } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A repo with one commit on main, a second branch, and one file changed on
|
||||
// the tree since that commit.
|
||||
function gitProject() {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
g("branch", "feature/export-csv");
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
// What a real Git skill posts once the board is up (notes/git.md): a reread,
|
||||
// so the console snapshots the repo, and the description of what changed.
|
||||
const BOARD = { reread: true, board: { describe: "export-more" } };
|
||||
|
||||
test("the git board shows Changes, Branches and Sync, and each tab shows its own content", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
|
||||
const { page } = s;
|
||||
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const panel = page.getByRole("tabpanel");
|
||||
|
||||
await page.getByRole("tablist").waitFor();
|
||||
assert.deepEqual(
|
||||
(await page.getByRole("tab").allInnerTexts()).map((x) => x.trim().split(/\s/)[0]),
|
||||
["Changes", "Branches", "Sync"]
|
||||
);
|
||||
|
||||
await tab("Changes").click();
|
||||
await page.waitForFunction(() => document.querySelector('[role="tab"][aria-selected="true"]')?.textContent.startsWith("Changes"));
|
||||
await panel.getByText("src/app.js", { exact: true }).waitFor();
|
||||
assert.match(await textOf(panel), /src\/app\.js/);
|
||||
|
||||
await tab("Branches").click();
|
||||
await panel.getByText("feature/export-csv").first().waitFor();
|
||||
const branches = await textOf(panel);
|
||||
assert.match(branches, /feature\/export-csv/);
|
||||
assert.doesNotMatch(branches, /src\/app\.js/, "the Branches tab still shows the changed files");
|
||||
|
||||
await tab("Sync").click();
|
||||
await panel.getByText(/nothing to sync/).waitFor();
|
||||
const sync = await textOf(panel);
|
||||
assert.match(sync, /No remote yet, so nothing to sync/);
|
||||
assert.doesNotMatch(sync, /feature\/export-csv/, "the Sync tab still lists the branches");
|
||||
});
|
||||
|
||||
test("each git tab keeps its own scroll place, across a tab switch and an agent post", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: BOARD });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await page.setViewportSize({ width: 1280, height: 260 });
|
||||
const tab = (label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const column = () => page.locator("#main").evaluate((el) => el.scrollTop);
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
await page.locator("#main").evaluate((el) => (el.scrollTop = 120));
|
||||
const changesAt = await column();
|
||||
assert.ok(changesAt > 0, "the board's column scrolls");
|
||||
// Another tab opens at its own place, not where Changes was left.
|
||||
await tab("Branches").click();
|
||||
await page.getByRole("tabpanel").getByText("feature/export-csv").first().waitFor();
|
||||
assert.equal(await column(), 0, "Branches opened at the place Changes was left");
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
assert.equal(await column(), changesAt, "Changes lost its place across the switch");
|
||||
// An agent post redraws the board: still the same place.
|
||||
s.post({ title: "Git, take two" });
|
||||
await page.waitForFunction(() => document.getElementById("title").textContent.includes("Git, take two"));
|
||||
assert.equal(await column(), changesAt, "Changes lost its place across a redraw");
|
||||
});
|
||||
|
||||
// The agent is sitting in `wait`, so the board is the person's to use. A fresh
|
||||
// session has the agent working, which locks every button but the tabs.
|
||||
const READY = { ...BOARD, agent: { status: "waiting" } };
|
||||
|
||||
// A repo with one commit, then two changes on the tree: src/app.js edited and
|
||||
// notes.md new. `branch` checks out a branch of its own (or "detached" a bare
|
||||
// commit), so the commit panel is the next step; on main the next step is to
|
||||
// start a branch. `remotes` names the remotes to add.
|
||||
function changesProject({ branch = null, remotes = [] } = {}) {
|
||||
const dir = tempProject({ "README.md": "# Sample\n", "src/app.js": "export const app = 1;\n" });
|
||||
const g = gitInit(dir);
|
||||
g("add", "-A");
|
||||
g("commit", "-q", "-m", "First commit");
|
||||
g("branch", "feature/export-csv");
|
||||
for (const name of remotes) {
|
||||
const bare = tempProject();
|
||||
g("init", "-q", "--bare", bare);
|
||||
g("remote", "add", name, bare);
|
||||
}
|
||||
if (branch === "detached") g("checkout", "-q", "--detach");
|
||||
else if (branch) g("checkout", "-q", "-b", branch);
|
||||
fs.appendFileSync(path.join(dir, "src", "app.js"), "export const more = 2;\n");
|
||||
fs.writeFileSync(path.join(dir, "notes.md"), "Notes.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
const confirmCard = { id: "y1", kind: "confirm", title: "Save these changes", body: "Commit them?" };
|
||||
const tabButton = (page, label) => page.getByRole("tab", { name: new RegExp(`^${label}\\b`) });
|
||||
const tickBox = (page, file) => page.getByLabel(`Commit ${file}`);
|
||||
// The Branches tab's Switch button, for the one other branch.
|
||||
const switchButton = (page) => page.getByRole("tabpanel").getByRole("button", { name: "Switch" });
|
||||
// The board's step button, in the strip above the tab's content.
|
||||
const stepButton = (page, name) => page.locator(".git-step-actions").getByRole("button", { name });
|
||||
|
||||
// Whether the board's own controls (not its tabs or the pointer to another
|
||||
// tab) are all off, or at least one is on. Whatever tab the board has moved to,
|
||||
// a locked board has every one of them disabled.
|
||||
const boardControls = (page) => page.locator(".git-panel-tab").locator("button, input[type=checkbox], select");
|
||||
const usable = async (page) => {
|
||||
const off = await boardControls(page).evaluateAll((all) => all.filter((x) => !x.classList.contains("git-hint")).map((x) => x.disabled));
|
||||
return off.some((x) => !x);
|
||||
};
|
||||
// The board redraws a moment after its cause, so each check gets time to settle.
|
||||
const settles = (control, enabled) => until(async () => (await control.isEnabled()) === enabled, 8000);
|
||||
const settlesUsable = (page, want) => until(async () => (await usable(page)) === want, 8000);
|
||||
const titled = (page, text) => page.waitForFunction((x) => document.getElementById("title").textContent.includes(x), text);
|
||||
|
||||
test("the commit dialog sends the ticked files as one __git action, with its reply sentence", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "feature/x" }), payload: READY });
|
||||
const { page } = s;
|
||||
await page.getByRole("tablist").waitFor();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("button", { name: "Close" }).waitFor();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await panel.getByRole("button", { name: "Commit 1 file" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "the agent collected the click");
|
||||
assert.deepEqual(got.actions, [{ i: "__git", type: "git", op: "commit", files: ["src/app.js"], ignore: [] }]);
|
||||
assert.equal(got.reply, "Commit this file: src/app.js.");
|
||||
});
|
||||
|
||||
test("a board click is exactly one __git action", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Branches").click();
|
||||
await switchButton(page).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions.length, 1, "one click, one action");
|
||||
assert.equal(got.actions[0].i, "__git");
|
||||
assert.equal(got.actions[0].type, "git");
|
||||
assert.equal(got.reply, "Switch to feature/export-csv.");
|
||||
assert.notEqual(s.wait(1).code, 0, "nothing else was sent beside it");
|
||||
});
|
||||
|
||||
test("the board stays locked from a click until the agent's next post, not just until it is collected", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Branches").click();
|
||||
assert.ok(await settlesUsable(page, true), "the board is the person's before any click");
|
||||
await switchButton(page).click();
|
||||
assert.ok(await settlesUsable(page, false), "locked from the click");
|
||||
// The agent has the click now (it is running git), and the board still waits.
|
||||
assert.equal(s.wait(10).code, 0);
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
assert.equal(await usable(page), false, "collected is not yet answered");
|
||||
// The agent's next post lets the board go.
|
||||
s.post({ title: "Switched", agent: { status: "waiting" } });
|
||||
await titled(page, "Switched");
|
||||
assert.ok(await settlesUsable(page, true), "the agent's post gave the board back");
|
||||
});
|
||||
|
||||
test("an open card of the agent's holds the board, and a notice does not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
const { page } = s;
|
||||
assert.ok(await settlesUsable(page, true));
|
||||
s.post({ items: [{ id: "n1", kind: "notice", title: "Heads up", body: "Nothing to act on." }], agent: { status: "waiting" } });
|
||||
await page.getByText("Heads up", { exact: true }).waitFor();
|
||||
assert.equal(await usable(page), true, "a notice leaves the board alone");
|
||||
s.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
await itemCard(page, "y1").waitFor();
|
||||
assert.ok(await settlesUsable(page, false), "a question card holds the board");
|
||||
});
|
||||
|
||||
test("the git board lets go of a working agent that went adrift", async (t) => {
|
||||
const working = { agent: { status: "working", activity: "Looking at the repo" } };
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), clock: true, payload: { ...BOARD, ...working } });
|
||||
const { page } = s;
|
||||
assert.equal(await usable(page), false, "a working agent holds the board");
|
||||
// Nobody has listened for longer than the adrift limit. The board only
|
||||
// redraws on a post, and the agent is still "working" in it: the lock must
|
||||
// not outlive the agent.
|
||||
await page.clock.fastForward(200_000);
|
||||
s.post({ title: "Still on it", ...working });
|
||||
await titled(page, "Still on it");
|
||||
assert.ok(await settlesUsable(page, true), "an agent gone quiet gave the board back");
|
||||
});
|
||||
|
||||
test("the commit table keeps the person's ticks across an agent post, and a click re-seeds them", async (t) => {
|
||||
const dir = changesProject({ branch: "feature/x" });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: dir, payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// An agent post redraws the board: the person's tick stays off.
|
||||
s.post({ title: "Still looking", agent: { status: "waiting" } });
|
||||
await titled(page, "Still looking");
|
||||
assert.equal(await tickBox(page, "notes.md").isChecked(), false, "an agent post put the tick back");
|
||||
assert.equal(await tickBox(page, "src/app.js").isChecked(), true);
|
||||
// Their click goes out with the one file. Then the agent commits it and a new file turns up.
|
||||
await page.locator(".git-panel-actions").getByRole("button", { name: "Commit 1 file" }).click();
|
||||
assert.deepEqual(s.wait(10).actions[0].files, ["src/app.js"]);
|
||||
const g = gitInit(dir, "feature/x");
|
||||
g("add", "src/app.js");
|
||||
g("commit", "-q", "-m", "Edit app");
|
||||
fs.writeFileSync(path.join(dir, "later.md"), "Later.\n");
|
||||
s.post({ reread: true, title: "Committed", agent: { status: "waiting" } });
|
||||
await titled(page, "Committed");
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "later.md").waitFor();
|
||||
assert.equal(await tickBox(page, "notes.md").isChecked(), true, "the click dropped the old picks, so the table was seeded afresh");
|
||||
});
|
||||
|
||||
test("starting a branch for the changes carries the files ticked in the commit table", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject(), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
await stepButton(page, /^Start a branch for/).click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
assert.ok(await settles(create, true), "a free name is composed from the description");
|
||||
await create.click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions.length, 1);
|
||||
assert.equal(got.actions[0].op, "create");
|
||||
assert.equal(got.actions[0].then, "commit");
|
||||
assert.deepEqual(got.actions[0].files, ["src/app.js"], "the unticked file stayed out");
|
||||
assert.match(got.reply, /^Create \S+ from main\. Then commit this file: src\/app\.js\.$/);
|
||||
});
|
||||
|
||||
test("a commit with no branch to land on carries the ticked files into the new branch", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: changesProject({ branch: "detached" }), payload: READY });
|
||||
const { page } = s;
|
||||
await tabButton(page, "Changes").click();
|
||||
await tickBox(page, "notes.md").uncheck();
|
||||
// The step is on the Branches tab, and its Commit button finds no branch to commit on.
|
||||
await tabButton(page, "Branches").click();
|
||||
await stepButton(page, "Commit 2 files").click();
|
||||
const panel = page.locator(".git-panel");
|
||||
await panel.getByRole("heading", { name: "New branch for this commit" }).waitFor();
|
||||
const create = panel.getByRole("button", { name: "Create", exact: true });
|
||||
assert.ok(await settles(create, true));
|
||||
await create.click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
assert.equal(got.actions[0].op, "create");
|
||||
assert.deepEqual(got.actions[0].files, ["src/app.js"]);
|
||||
assert.match(got.reply, /Then commit this file: src\/app\.js\.$/);
|
||||
});
|
||||
|
||||
test("Publish names a remote only when there is exactly one", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const published = async (remotes) => {
|
||||
const s = await openSession(browser, { t, workflow: "git", project: changesProject({ branch: "feature/x", remotes }), payload: READY });
|
||||
await tabButton(s.page, "Sync").click();
|
||||
await s.page.locator(".git-sync-actions").getByRole("button", { name: "Publish" }).click();
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0);
|
||||
await s.stop();
|
||||
return got;
|
||||
};
|
||||
const one = await published(["origin"]);
|
||||
assert.equal(one.actions[0].remote, "origin");
|
||||
assert.equal(one.reply, "Publish to origin.");
|
||||
const two = await published(["origin", "backup"]);
|
||||
assert.equal(Object.hasOwn(two.actions[0], "remote"), false, "with two remotes the agent is the one to ask which");
|
||||
assert.equal(two.reply, "Publish.");
|
||||
});
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "git", project: gitProject(), payload: READY });
|
||||
s.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
const note = itemCard(s.page, "y1").locator("textarea").first();
|
||||
await note.waitFor();
|
||||
const before = await note.evaluate((el) => el.offsetHeight);
|
||||
await note.fill(Array.from({ length: 8 }, (_, n) => `Line ${n + 1} of a longer note.`).join("\n"));
|
||||
const after = await note.evaluate((el) => el.offsetHeight);
|
||||
assert.ok(after > before + 40, `the note box grew with its text: ${before} to ${after}`);
|
||||
|
||||
// A folder that is no repository: the note points up only once there is a card up there.
|
||||
const bare = await openSession(await suite.browser(), { t, workflow: "git", payload: { reread: true, agent: { status: "waiting" } } });
|
||||
const aside = bare.page.locator(".git-note");
|
||||
await aside.waitFor();
|
||||
assert.match(await textOf(aside), /will ask what to do here in a moment/);
|
||||
bare.post({ items: [confirmCard], agent: { status: "waiting" } });
|
||||
await itemCard(bare.page, "y1").waitFor();
|
||||
assert.match(await textOf(aside), /asks above what to do/);
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
// Page tests for Help, the first-run Welcome and the update notice's modal. Run
|
||||
// with:
|
||||
// node --test scripts/test-web-console-page-help.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. Help's prose stays untested; these cover how the dialog
|
||||
// behaves.
|
||||
|
||||
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, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME } from "./web-console-test-helpers.mjs";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// The console home's saved looks, shared by every session of this file. Each
|
||||
// test that cares sets it first and the file is removed once the test is done.
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
function savedLooks(t, looks) {
|
||||
if (looks) fs.writeFileSync(LOOKS_FILE, JSON.stringify({ looks }));
|
||||
else fs.rmSync(LOOKS_FILE, { force: true });
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
|
||||
// A plan session on the person's turn: one text question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The dashboard, past Planny's wake-up. The Welcome may be on top of it. The
|
||||
// wake-up plays once per tab, so a reloaded page has no intro to skip.
|
||||
async function toTheDashboard(s) {
|
||||
const heading = s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" });
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.or(heading).first().waitFor();
|
||||
if (await skip.isVisible()) await skip.click();
|
||||
await heading.waitFor();
|
||||
}
|
||||
|
||||
const helpModal = (s) => s.page.locator("#help-modal");
|
||||
const tabButton = (s, id) => s.page.locator("#help-tab-" + id);
|
||||
const selectedTab = (s) => s.page.locator('#help-tabs [role="tab"][aria-selected="true"]');
|
||||
const focusedId = (s) => s.page.evaluate(() => document.activeElement && document.activeElement.id);
|
||||
|
||||
async function openHelp(s) {
|
||||
await s.page.click("#btn-about");
|
||||
await helpModal(s).waitFor();
|
||||
}
|
||||
|
||||
test("Help opens on a tab, moves between tabs with the arrow, Home and End keys, and closes with Escape", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Built on first open: the tab buttons are not in the page before it.
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), 0, "Help is built before it is opened");
|
||||
await openHelp(s);
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length, "one tab button per Help topic");
|
||||
|
||||
// A plain workflow page opens on the first topic, with focus on its tab.
|
||||
const ids = HELP_TABS.map((x) => x.id);
|
||||
assert.equal(await selectedTab(s).count(), 1, "exactly one tab is selected");
|
||||
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + ids[0]);
|
||||
assert.equal(await focusedId(s), "help-tab-" + ids[0], "focus starts on the selected tab");
|
||||
|
||||
// Roving focus: only the selected tab is in the tab order, and its panel is the one shown.
|
||||
const onlySelected = async (id) => {
|
||||
assert.equal(await selectedTab(s).getAttribute("id"), "help-tab-" + id);
|
||||
assert.equal(await focusedId(s), "help-tab-" + id, `focus is on ${id}`);
|
||||
assert.equal(await tabButton(s, id).getAttribute("tabindex"), "0");
|
||||
assert.equal(await s.page.locator('#help-tabs [role=tab][tabindex="0"]').count(), 1, "one tab stop");
|
||||
assert.equal(await s.page.locator("#help-panel-" + id).isVisible(), true, `${id}'s panel is shown`);
|
||||
assert.equal(await s.page.locator('#help-panels [role=tabpanel]:not([hidden])').count(), 1, "one panel is shown");
|
||||
};
|
||||
await onlySelected(ids[0]);
|
||||
await s.page.keyboard.press("ArrowDown");
|
||||
await onlySelected(ids[1]);
|
||||
await s.page.keyboard.press("ArrowRight");
|
||||
await onlySelected(ids[2]);
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await onlySelected(ids[1]);
|
||||
await s.page.keyboard.press("End");
|
||||
await onlySelected(ids[ids.length - 1]);
|
||||
await s.page.keyboard.press("ArrowDown");
|
||||
await onlySelected(ids[0]);
|
||||
await s.page.keyboard.press("ArrowUp");
|
||||
await onlySelected(ids[ids.length - 1]);
|
||||
await s.page.keyboard.press("Home");
|
||||
await onlySelected(ids[0]);
|
||||
// A click picks a tab too.
|
||||
await tabButton(s, ids[3]).click();
|
||||
await onlySelected(ids[3]);
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
assert.equal(await focusedId(s), "btn-about", "focus goes back to the Help button");
|
||||
// Reopened, the built dialog is reused: no second set of tabs.
|
||||
await openHelp(s);
|
||||
assert.equal(await s.page.locator("#help-tabs [role=tab]").count(), HELP_TABS.length);
|
||||
});
|
||||
|
||||
test("Help shows the live connection line and the version as a safe link to the Releases page", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openHelp(s);
|
||||
const live = s.page.locator("#about-live");
|
||||
assert.match(await textOf(live), /^Right now: both halves are talking to each other\./);
|
||||
assert.equal(await live.evaluate((n) => n.classList.contains("is-good")), true);
|
||||
|
||||
const link = s.page.locator("#help-version a");
|
||||
await link.waitFor();
|
||||
assert.match(await textOf(link), /^Plan2Code v\d+\.\d+\.\d+/, "the link names the installed version");
|
||||
assert.equal(await link.getAttribute("href"), RELEASES_URL);
|
||||
assert.equal(await link.getAttribute("rel"), "noopener noreferrer");
|
||||
assert.equal(await link.getAttribute("target"), "_blank");
|
||||
|
||||
// The line is written on open: a finished session says so the next time.
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
await openHelp(s);
|
||||
assert.match(await textOf(live), /^Right now: the session is finished/);
|
||||
});
|
||||
|
||||
test("a click on Help's backdrop closes it, and a click inside it does not", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openHelp(s);
|
||||
await s.page.locator("#help-title").click();
|
||||
assert.equal(await helpModal(s).isVisible(), true, "a click inside closed Help");
|
||||
// The top-left corner of the page is the backdrop, well outside the dialog.
|
||||
await s.page.mouse.click(4, 4);
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("Ctrl+Enter does not send while Help is open, and sends once it is closed", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.locator('[data-item="q1"]').first().locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await openHelp(s);
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
await s.page.keyboard.press("Meta+Enter");
|
||||
assert.equal(s.wait(1).code === 0, false, "something was sent from behind Help");
|
||||
assert.equal(await helpModal(s).isVisible(), true, "the key closed Help");
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
await s.page.keyboard.press("Control+Enter");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, "Ctrl+Enter sends nothing with Help closed");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type }) => ({ i, type })),
|
||||
[{ i: "q1", type: "answer" }]
|
||||
);
|
||||
});
|
||||
|
||||
test("the Welcome shows on a first dashboard, saves that it was seen, and Help's Show the welcome again brings it back", async (t) => {
|
||||
savedLooks(t, null);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
const welcome = s.page.locator("#welcome-modal");
|
||||
await welcome.waitFor();
|
||||
assert.equal(await s.page.locator("#welcome-title").isVisible(), true);
|
||||
await s.page.getByRole("button", { name: "Start building" }).click();
|
||||
await welcome.waitFor({ state: "hidden" });
|
||||
// Saved with the other looks, so it holds for the next page too.
|
||||
await s.page.waitForFunction(async () => ((await (await fetch("/looks")).json()).looks || {}).welcomeSeen === true);
|
||||
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await toTheDashboard(s);
|
||||
await s.page.waitForTimeout(800);
|
||||
assert.equal(await welcome.isVisible(), false, "the Welcome came back on a later page");
|
||||
|
||||
// Help's first topic offers it again, and Help steps aside for it.
|
||||
// (On the dashboard Help opens on the dashboard topic, so go to the first.)
|
||||
await openHelp(s);
|
||||
await tabButton(s, HELP_TABS[0].id).click();
|
||||
await s.page.getByRole("button", { name: "Show the welcome again" }).click();
|
||||
await welcome.waitFor();
|
||||
assert.equal(await helpModal(s).isVisible(), false, "Help stayed open under the Welcome");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await welcome.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("the Welcome stays away when the person has seen it, and off the dashboard", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const seen = await openSession(browser, { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(seen);
|
||||
await seen.page.waitForTimeout(800);
|
||||
assert.equal(await seen.page.locator("#welcome-modal").isVisible(), false, "a seen Welcome showed again");
|
||||
|
||||
// Unseen, but a workflow page is not a first dashboard.
|
||||
savedLooks(t, null);
|
||||
const plan = await openSession(browser, { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await plan.page.waitForTimeout(800);
|
||||
assert.equal(await plan.page.locator("#welcome-modal").isVisible(), false, "the Welcome showed on a workflow page");
|
||||
});
|
||||
|
||||
// A newer release on record, so a console that boots now has an update to
|
||||
// announce (the check reads this file for an hour instead of asking the
|
||||
// network). The file is put back as the suite had it.
|
||||
function aNewerReleaseExists(t) {
|
||||
const file = path.join(HOME, "update-check.json");
|
||||
const before = fs.readFileSync(file, "utf8");
|
||||
fs.writeFileSync(file, JSON.stringify({ checkedAt: Date.now(), latest: "99.0.0" }));
|
||||
t.after(() => fs.writeFileSync(file, before));
|
||||
}
|
||||
|
||||
test("the update banner opens a modal with the exact update commands, and its dismissal is remembered for the session", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
aNewerReleaseExists(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("button", { name: /UPDATE AVAILABLE · v99\.0\.0/ }).click();
|
||||
|
||||
const modal = s.page.locator("#update-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#update-versions")), /^Version v99\.0\.0 is out/);
|
||||
const releases = s.page.locator("#update-versions a");
|
||||
assert.equal(await releases.getAttribute("href"), RELEASES_URL);
|
||||
assert.equal(await releases.getAttribute("rel"), "noopener noreferrer");
|
||||
assert.equal(await textOf(s.page.locator("#update-command code")), "plan2code update");
|
||||
assert.equal(
|
||||
await textOf(s.page.locator("#update-fallback code")),
|
||||
"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"
|
||||
);
|
||||
await s.page.locator("#update-done").click();
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
|
||||
// The ×: gone now, remembered under this session's key, and still gone after a reload.
|
||||
await main.getByRole("button", { name: "Dismiss until next time" }).click();
|
||||
await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).waitFor({ state: "hidden" });
|
||||
assert.equal(await s.page.evaluate((k) => sessionStorage.getItem(k), "p2c-update-dismissed:" + s.sid), "99.0.0");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await toTheDashboard(s);
|
||||
assert.equal(await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).count(), 0, "the banner came back after a reload");
|
||||
});
|
||||
@@ -0,0 +1,156 @@
|
||||
// Page tests for User Preferences: the saved looks (highlight and theme), the
|
||||
// launcher's model menus and the Cleanup tab. Run with:
|
||||
// node --test scripts/test-web-console-page-prefs.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, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME, MODELS_DIR, backdate } from "./web-console-test-helpers.mjs";
|
||||
import { formatBytes } from "../src/web-console/public/answers.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The console home's saved looks are shared by every session of this file, so
|
||||
// each test starts with none and leaves none.
|
||||
const LOOKS_FILE = path.join(HOME, "looks.json");
|
||||
function noSavedLooks(t) {
|
||||
fs.rmSync(LOOKS_FILE, { force: true });
|
||||
t.after(() => fs.rmSync(LOOKS_FILE, { force: true }));
|
||||
}
|
||||
|
||||
const root = (s, attr) => s.page.evaluate((a) => document.documentElement.getAttribute(a), attr);
|
||||
// The highlight the page paints with: an inline override while it is not the default.
|
||||
const accentVar = (s) => s.page.evaluate(() => document.documentElement.style.getPropertyValue("--accent"));
|
||||
const swatch = (s, id) => s.page.locator(`#looks-swatches [data-accent="${id}"]`);
|
||||
|
||||
// The page as the server first sends it, before any script has run: the saved
|
||||
// theme and highlight are in the markup so a reload never flashes the defaults.
|
||||
async function firstPaintAttrs(s) {
|
||||
const html = await (await s.context.request.get(s.url)).text();
|
||||
const tag = html.match(/<html\b[^>]*>/i)[0];
|
||||
return { theme: tag.match(/data-theme="([^"]*)"/)?.[1] ?? null, accent: tag.match(/data-looks-accent="([^"]*)"/)?.[1] ?? null };
|
||||
}
|
||||
|
||||
test("the violet highlight and dark theme chosen in preferences stick across a reload, and Back to default clears them", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
assert.equal(await root(s, "data-theme"), null, "the theme starts on the system's");
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#looks-modal[open]").waitFor();
|
||||
await swatch(s, "violet").click();
|
||||
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true");
|
||||
assert.equal(await accentVar(s), "#a785e2", "the dark violet is painted");
|
||||
// Saved on the server (looks.json), not only in this tab.
|
||||
await s.page.waitForFunction(async () => {
|
||||
const saved = (await (await fetch("/looks")).json()).looks || {};
|
||||
return saved.accent === "violet" && saved.theme === "dark";
|
||||
});
|
||||
await s.page.click("#looks-done");
|
||||
|
||||
// What the server sends first, and what the page settles on, both keep the choice.
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: "dark", accent: "violet" }, "the first paint carries the saved looks");
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
assert.equal(await root(s, "data-theme"), "dark", "the theme did not stick");
|
||||
await s.page.waitForFunction(() => document.documentElement.style.getPropertyValue("--accent") === "#a785e2");
|
||||
await s.page.click("#btn-looks");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "true", "the violet swatch is not the chosen one after a reload");
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="dark"]').isChecked(), true);
|
||||
|
||||
// Back to default returns both, here and for the next page.
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await accentVar(s), "", "the chosen highlight is still painted");
|
||||
assert.equal(await swatch(s, "violet").getAttribute("aria-pressed"), "false");
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true);
|
||||
await s.page.waitForFunction(async () => {
|
||||
const saved = (await (await fetch("/looks")).json()).looks || {};
|
||||
return saved.theme === "system" && saved.accent !== "violet";
|
||||
});
|
||||
assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks");
|
||||
});
|
||||
|
||||
test("the launcher's model menus have Claude, Devin and Codex tabs, and a model id typed on the Codex tab is saved", async (t) => {
|
||||
noSavedLooks(t);
|
||||
// The file the launcher reads: put back as the suite had it (no file).
|
||||
t.after(() => fs.rmSync(path.join(MODELS_DIR, "models.json"), { force: true }));
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-looks");
|
||||
const tabs = s.page.getByRole("group", { name: "Which agent" });
|
||||
for (const name of ["Claude", "Devin", "Codex"]) assert.equal(await tabs.getByRole("button", { name, exact: true }).count(), 1, `a ${name} tab`);
|
||||
const pressed = async () => (await tabs.locator('button[aria-pressed="true"]').allInnerTexts()).map((x) => x.trim());
|
||||
assert.deepEqual(await pressed(), ["Claude"], "the menus open on Claude");
|
||||
|
||||
await tabs.getByRole("button", { name: "Codex", exact: true }).click();
|
||||
assert.deepEqual(await pressed(), ["Codex"]);
|
||||
await s.page.click("#models-add");
|
||||
const id = s.page.locator("#models-user").getByRole("textbox", { name: "Model id" });
|
||||
await id.fill("gpt-test-codex-1");
|
||||
await id.press("Tab");
|
||||
await s.page.locator("#models-status").filter({ hasText: /^Saved\./ }).waitFor();
|
||||
const saved = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user);
|
||||
assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-1"], "the id was not saved under Codex");
|
||||
assert.deepEqual([saved.claude, saved.devin], [[], []], "the id leaked into another agent's menu");
|
||||
|
||||
// Back on Claude the typed id is not listed; on Codex it is, after a reload.
|
||||
await tabs.getByRole("button", { name: "Claude", exact: true }).click();
|
||||
assert.equal(await s.page.locator("#models-user .models-row").count(), 0);
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator("#models-tab-codex").click();
|
||||
await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).waitFor();
|
||||
assert.equal(await s.page.locator("#models-user").getByRole("textbox", { name: "Model id" }).inputValue(), "gpt-test-codex-1");
|
||||
});
|
||||
|
||||
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
|
||||
noSavedLooks(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// Made after the session opens: opening sweeps old sessions away. A session
|
||||
// is old when nothing in it has been touched for 30 days.
|
||||
const sid = "20250801-101010-aaaaaa";
|
||||
const dir = path.join(HOME, "sessions", sid);
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
const state = path.join(dir, "state.json");
|
||||
fs.writeFileSync(state, "x".repeat(3000));
|
||||
backdate(state);
|
||||
backdate(dir);
|
||||
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
|
||||
|
||||
await s.page.click("#btn-looks");
|
||||
const list = s.page.locator("#cleanup-list");
|
||||
assert.equal(await list.locator(".cleanup-row").count(), 0, "Cleanup lists things before a scan");
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true, "Delete is offered before a scan");
|
||||
await s.page.click("#cleanup-scan");
|
||||
const row = list.locator(".cleanup-row").filter({ hasText: sid });
|
||||
await row.waitFor();
|
||||
assert.match(await textOf(row), new RegExp(`^Session ${sid}`));
|
||||
const size = await textOf(row.locator(".cleanup-size"));
|
||||
assert.match(size, /^\d/, "the row names a size");
|
||||
assert.ok(size === formatBytes(3000) || /^[\d.,]+\s*(kB|KB|MB|B)\b/.test(size), `the size reads as a size: ${size}`);
|
||||
assert.match(await textOf(list.locator(".cleanup-summary")), /1 old session/);
|
||||
assert.match(await textOf(s.page.locator("#cleanup-status")), /^Found \d+ items?\./);
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isVisible(), true, "Delete these is offered once something is found");
|
||||
// The scan only looks.
|
||||
assert.equal(fs.existsSync(dir), true, "a scan deleted the folder");
|
||||
|
||||
// Closing preferences forgets the scan: a reopened dialog starts clean.
|
||||
await s.page.click("#looks-done");
|
||||
await s.page.click("#btn-looks");
|
||||
assert.equal(await list.locator(".cleanup-row").count(), 0, "the old scan is still listed");
|
||||
assert.equal(await s.page.locator("#cleanup-delete").isHidden(), true);
|
||||
});
|
||||
@@ -0,0 +1,497 @@
|
||||
// Page tests for how a session ends and comes back: the finished screen and
|
||||
// its buttons, Stop and Stop with a handoff, and a page that loses its server
|
||||
// and finds it again after a resume. Run with:
|
||||
// node --test scripts/test-web-console-page-session.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 test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, drawn, textOf, tempProject } from "./page-test-helpers.mjs";
|
||||
import { cli, until } from "./web-console-test-helpers.mjs";
|
||||
import { STOP_HANDOFF_REPLY, HOME_REPLY } from "../src/web-console/public/answers.js";
|
||||
// How long the page waits without contact before it calls itself offline:
|
||||
// the page's own constant, so this file never drifts from it.
|
||||
import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
|
||||
// The banner the page raises when it loses its server mid-session.
|
||||
const LOST_CONTACT = /Lost contact with Plan2Code\. Nothing you have typed is lost\./;
|
||||
|
||||
// A plan session on the person's turn, the way an agent opens one: one text
|
||||
// question and the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// The agent's side of `stop`, leaving the browser context open (s.stop()
|
||||
// closes it, which would hide what the page does next).
|
||||
async function stopServer(s) {
|
||||
cli(["stop", "--session", s.sid], { cwd: s.project });
|
||||
assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop");
|
||||
}
|
||||
|
||||
// The one send `wait` hands the agent; fails the test when nothing arrived.
|
||||
function collect(s) {
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// Local helper: checks `fn` keeps returning true for `ms`. A sleep would
|
||||
// prove nothing; this fails the moment the page shows what it must not.
|
||||
async function holds(fn, ms) {
|
||||
const end = Date.now() + ms;
|
||||
while (Date.now() < end) {
|
||||
if (!(await fn())) return false;
|
||||
await new Promise((r) => setTimeout(r, 100));
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
test("the finished screen shows the next command with --web, copies it, turns Send off, and Back to the dashboard reaches the agent", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
s.post({
|
||||
settle: true,
|
||||
finish: {
|
||||
headline: "The plan is written",
|
||||
body: "Everything is under `specs/audit-export/`. Read `PLAN.md` first.",
|
||||
command: "/plan2code-2-document",
|
||||
dashboard: true,
|
||||
},
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
|
||||
const shown = main.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
|
||||
assert.equal(await shown.count(), 1, "the command is shown once, with --web appended");
|
||||
// The Copy that belongs to this command: the innermost block holding both,
|
||||
// whatever wraps them.
|
||||
// (`has` is matched inside each candidate, so these start from the page.)
|
||||
const code = s.page.locator("code").filter({ hasText: /^\/plan2code-2-document --web$/ });
|
||||
const copy = s.page.getByRole("button", { name: "Copy", exact: true });
|
||||
await main.locator("*", { has: code }).filter({ has: copy }).last().getByRole("button", { name: "Copy", exact: true }).click();
|
||||
await s.page.waitForFunction(async () => (await navigator.clipboard.readText()) === "/plan2code-2-document --web");
|
||||
assert.equal(await s.page.evaluate(() => navigator.clipboard.readText()), "/plan2code-2-document --web");
|
||||
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is still on after the finish");
|
||||
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
assert.deepEqual(
|
||||
got.actions.map(({ i, type }) => ({ i, type })),
|
||||
[{ i: "__dashboard", type: "dashboard" }]
|
||||
);
|
||||
});
|
||||
|
||||
test("Stop session, confirmed, sends __stop with no handoff", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
await s.page.locator("#stop-go").click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const stop = got.actions.find((a) => a.i === "__stop");
|
||||
assert.deepEqual(stop, { i: "__stop", type: "stop" });
|
||||
});
|
||||
|
||||
test("Stop with a handoff sends __stop with handoff, and the paused finish and stop that follow end on the paused screen, not an error", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
const handoff = s.page.locator("#stop-handoff");
|
||||
assert.equal(await handoff.isVisible(), true, "the handoff choice is offered off the dashboard");
|
||||
await handoff.click();
|
||||
const got = collect(s);
|
||||
assert.equal(got.type, "submit");
|
||||
const stop = got.actions.find((a) => a.i === "__stop");
|
||||
assert.deepEqual(stop, { i: "__stop", type: "stop", handoff: true });
|
||||
|
||||
// What the agent does next (console-stop.md): a paused finish without
|
||||
// --wait and no dashboard, then `stop`.
|
||||
s.post({
|
||||
settle: true,
|
||||
finish: {
|
||||
headline: "Paused at the naming question",
|
||||
body: "Your place is saved, and a handoff is waiting on the dashboard. The naming question is still open.",
|
||||
command: "/plan2code-1-plan",
|
||||
},
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("heading", { name: "Paused at the naming question" }).waitFor();
|
||||
await stopServer(s);
|
||||
|
||||
// The page needs GONE_AFTER_MS without contact before it would call the
|
||||
// server lost. Through that window and past it, the paused screen stays.
|
||||
const settled = async () =>
|
||||
!LOST_CONTACT.test(await s.page.locator("#banner").innerText()) &&
|
||||
!(await s.page.locator("#planny").getAttribute("class")).includes("is-gone");
|
||||
assert.ok(await holds(settled, GONE_AFTER_MS + 3000), "the page raised a lost-contact state after a paused finish");
|
||||
assert.match(await main.innerText(), /Session paused/i);
|
||||
assert.match(await textOf(s.page.locator("#agent-text")), /^Paused\./);
|
||||
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code-1-plan --web$/ }).count(), "the resume command is gone");
|
||||
});
|
||||
|
||||
test("a page that loses its server goes offline, and after a resume it shows the session again with the unsent answer still typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const field = () => itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
await field().fill("audit-export");
|
||||
// Typed, not sent: the page mirrors it to the server's draft.json, which
|
||||
// is what a page on a new port reads back (localStorage is per origin).
|
||||
const draftFile = path.join(s.session, "draft.json");
|
||||
assert.ok(
|
||||
await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes("audit-export"), 5000),
|
||||
"the typed answer never reached the server's draft"
|
||||
);
|
||||
|
||||
await stopServer(s);
|
||||
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, {
|
||||
timeout: GONE_AFTER_MS + 10000,
|
||||
});
|
||||
assert.match(await textOf(s.page.locator("#agent-text")), /^Not connected\. Your answers are saved\./);
|
||||
assert.match(await s.page.locator("#banner").innerText(), LOST_CONTACT);
|
||||
assert.equal(await s.page.locator("#btn-send").isDisabled(), true, "Send is on with no server");
|
||||
|
||||
const resumed = cli(["open", "--resume", s.sid, "--workflow", "plan", "--no-open"], { cwd: s.project }).json;
|
||||
assert.ok(resumed && resumed.url, "the resume printed no url");
|
||||
await s.page.goto(resumed.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await itemCard(s.page, "q1").getByText("What to call it").first().waitFor();
|
||||
assert.equal(await field().inputValue(), "audit-export", "the unsent answer was lost across the resume");
|
||||
assert.equal(await s.page.locator("#planny").evaluate((n) => n.classList.contains("is-gone")), false);
|
||||
});
|
||||
|
||||
// The status line beside Planny, and its "What to check" button when it has
|
||||
// one. The button opens Help on the stuck tab.
|
||||
const statusLine = (s) => s.page.locator("#agent-text");
|
||||
const whatToCheck = (s) => statusLine(s).getByRole("button", { name: "What to check" });
|
||||
async function lineSays(s, re) {
|
||||
await s.page.waitForFunction((src) => new RegExp(src).test(document.getElementById("agent-text").textContent), re.source, { timeout: 10000 });
|
||||
return textOf(statusLine(s));
|
||||
}
|
||||
|
||||
test("the quiet, not running and not connected lines offer What to check, opening Help on the stuck tab, and the plain lines do not", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
clock: true,
|
||||
payload: { headline: { stage: "Phase 1", cleared: 0, total: 3 }, agent: { status: "working", activity: "Task 1 of 3: the reader" } },
|
||||
});
|
||||
// Working, and heard from just now: the plain working line.
|
||||
await lineSays(s, /Task 1 of 3: the reader/);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the working line is plain");
|
||||
// Quiet for 30 s: the approval hint, with the button.
|
||||
await s.page.clock.fastForward(40_000);
|
||||
await lineSays(s, /waiting on an approval in your terminal/);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the approval hint carries What to check");
|
||||
// Quiet for two minutes: still working, and the button stays.
|
||||
await s.page.clock.fastForward(100_000);
|
||||
await lineSays(s, /^Still working on it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the quiet working line carries What to check");
|
||||
|
||||
// Back to real time, and the agent asks something: the person's turn is plain.
|
||||
await s.page.clock.setSystemTime(Date.now());
|
||||
s.post({ items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } });
|
||||
await lineSays(s, /^Your turn: 1 question waiting\./);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the your-turn line is plain");
|
||||
// Nobody listening for three minutes: not running, with the button.
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running right now\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not running line carries What to check");
|
||||
await whatToCheck(s).click();
|
||||
await s.page.locator("#help-modal[open]").waitFor();
|
||||
assert.equal(await s.page.locator("#help-tab-stuck").getAttribute("aria-selected"), "true", "Help opened on the stuck tab");
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.locator("#help-modal[open]").waitFor({ state: "detached" });
|
||||
|
||||
// Answered and sent, never collected, and nobody listening: the saved line.
|
||||
await s.page.clock.setSystemTime(Date.now());
|
||||
s.post({ agent: { status: "waiting" } });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
|
||||
assert.equal(await whatToCheck(s).count(), 0, "the sent line is plain");
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the saved-and-waiting line carries What to check");
|
||||
|
||||
// No server at all: not connected, with the button.
|
||||
await stopServer(s);
|
||||
for (let i = 0; i < 20 && !(await s.page.locator("#planny.is-gone").count()); i++) {
|
||||
await s.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await lineSays(s, /^Not connected\. Your answers are saved\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
|
||||
});
|
||||
|
||||
test("an answered finish offer comes back unanswered on a later finish, once the first finish has gone", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const finishWith = (headline) => s.post({ finish: { headline, command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
|
||||
const main = s.page.locator("#main");
|
||||
finishWith("Phase 1 is done");
|
||||
await main.getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).click();
|
||||
assert.deepEqual(collect(s).actions.map(({ i }) => i), ["__dashboard"]);
|
||||
await lineSays(s, /^Opening the dashboard…/);
|
||||
// The agent takes the press somewhere that clears the finish, and a later
|
||||
// phase ends: that finish starts with its own offer unanswered.
|
||||
s.post({ finish: null, agent: { status: "working", activity: "Task 1 of 1" } });
|
||||
await lineSays(s, /Task 1 of 1/);
|
||||
finishWith("Phase 2 is done");
|
||||
await main.getByRole("heading", { name: "Phase 2 is done" }).waitFor();
|
||||
await lineSays(s, /^Done\. Head back to the dashboard, or close this tab\./);
|
||||
assert.equal(await main.getByRole("button", { name: "Back to the dashboard" }).count(), 1, "the later finish offers the way back again");
|
||||
});
|
||||
|
||||
test("a finished session never puts a sent answer back on its form", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea").fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
collect(s);
|
||||
// Collected and left open, then the session ends: nothing more can be sent,
|
||||
// so the answer stays sent rather than coming back to edit. It would show
|
||||
// once the finish goes away (a review taken up), as an answer ready to send.
|
||||
s.post({ finish: { headline: "The plan is written", command: "/plan2code-2-document" }, agent: { status: "waiting" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor();
|
||||
s.post({ finish: null, agent: { status: "waiting" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "The plan is written" }).waitFor({ state: "detached" });
|
||||
const q1 = s.page.locator("#sidebar").getByRole("button", { name: /What to call it/ });
|
||||
await q1.click();
|
||||
await itemCard(s.page, "q1").waitFor();
|
||||
const mark = q1.locator(".rail-mark");
|
||||
assert.notEqual(await mark.getAttribute("title"), "ready to send", "the sent answer came back on the form");
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
assert.notEqual((await box.count()) ? await box.inputValue() : "", "audit-export", "the sent answer is back in its box");
|
||||
});
|
||||
|
||||
test("the footer keeps its workspace label on the dashboard, and the label opens the Workspace dialog", async (t) => {
|
||||
const project = tempProject();
|
||||
const name = path.basename(project);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", project });
|
||||
// Past Planny's wake-up and, on this console home's first run, the Welcome.
|
||||
await s.page.getByRole("button", { name: "Skip the intro" }).click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
const foot = s.page.locator("footer.footer");
|
||||
const where = s.page.locator("#footer-where");
|
||||
await where.waitFor();
|
||||
// The dashboard drops the summary and Send, never the label.
|
||||
assert.equal(await foot.evaluate((f) => f.classList.contains("is-dash")), true, "the dashboard's footer is marked is-dash");
|
||||
assert.equal(await s.page.locator("#footer-summary").isVisible(), false, "the summary shows on the dashboard");
|
||||
assert.equal(await s.page.locator("#btn-send").isVisible(), false, "Send shows on the dashboard");
|
||||
assert.match(await textOf(where), new RegExp(`^${name}`), "the label names the project");
|
||||
assert.equal(await where.getAttribute("title"), "Open workspace");
|
||||
assert.match(await where.getAttribute("aria-label"), new RegExp(`^Open workspace: ${name}`));
|
||||
// A click opens the Workspace dialog on the session's folders; leaving the
|
||||
// label leaves it as it was (no copied state to undo).
|
||||
await where.click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor();
|
||||
assert.match(await textOf(s.page.locator("#workspace-list")), new RegExp(name));
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
await s.page.locator("body").click({ position: { x: 5, y: 5 } });
|
||||
assert.match(await textOf(where), new RegExp(`^${name}`), "the label changed after a click away");
|
||||
});
|
||||
|
||||
test("a workflow page uses its modules: the full footer, the session meter, @ suggestions and the tab icon", async (t) => {
|
||||
const project = tempProject();
|
||||
const name = path.basename(project);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", project, payload: PLAN_QUESTION });
|
||||
// Off the dashboard the footer is whole (workspace.js names the label).
|
||||
assert.equal(await s.page.locator("footer.footer").evaluate((f) => f.classList.contains("is-dash")), false);
|
||||
assert.equal(await s.page.locator("#btn-send").isVisible(), true);
|
||||
// meter.js: the pill shows once a frame carries the meter.
|
||||
await s.page.locator("#meter-pill").waitFor();
|
||||
assert.ok((await textOf(s.page.locator("#meter-words"))).length, "the meter pill has no words");
|
||||
// mentions.js: an @ in a text box offers the workspace's folders.
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
await box.click();
|
||||
await box.pressSequentially("See @");
|
||||
await s.page.locator("#mention-pop").waitFor();
|
||||
assert.match(await textOf(s.page.locator("#mention-pop")), new RegExp(name));
|
||||
// favicon.js: the person's move puts a bar on the tab icon.
|
||||
await s.page.waitForFunction(() => document.querySelector('link[rel="icon"][type="image/svg+xml"]').href.startsWith("data:image/svg+xml"));
|
||||
});
|
||||
|
||||
// The dashboard, past Planny's wake-up and the first-run Welcome.
|
||||
async function pastTheIntro(s) {
|
||||
const skip = s.page.getByRole("button", { name: "Skip the intro" });
|
||||
await skip.click();
|
||||
await s.page.locator("#main").getByRole("heading", { name: "What are we doing today?" }).waitFor();
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
}
|
||||
|
||||
// What a person sees break: a handoff offered where there is nothing to hand off.
|
||||
test("the stop dialog offers a handoff in a workflow and one plain Stop on the dashboard", async (t) => {
|
||||
const plan = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await plan.page.click("#btn-stop");
|
||||
const modal = plan.page.locator("#stop-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(modal), /Stop with a handoff/);
|
||||
assert.match(await textOf(modal.locator("#stop-go")), /Just stop and save/);
|
||||
|
||||
const dash = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } } });
|
||||
await pastTheIntro(dash);
|
||||
await dash.page.click("#btn-stop");
|
||||
await dash.page.locator("#stop-modal").waitFor();
|
||||
assert.equal(await dash.page.locator("#stop-handoff").isVisible(), false, "the dashboard offers a handoff");
|
||||
assert.match(await textOf(dash.page.locator("#stop-go")), /Stop\s+Ends the console session\./);
|
||||
assert.doesNotMatch(await textOf(dash.page.locator("#stop-modal")), /Stop with a handoff/);
|
||||
});
|
||||
|
||||
// What the agent would misread: a handoff stop that carries the plain stop's words.
|
||||
test("Stop with a handoff sends its own reply line beside the stop, and a plain stop sends another", async (t) => {
|
||||
const handoff = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await handoff.page.click("#btn-stop");
|
||||
await handoff.page.locator("#stop-handoff").click();
|
||||
const got = collect(handoff);
|
||||
assert.deepEqual(got.actions.find((a) => a.i === "__stop"), { i: "__stop", type: "stop", handoff: true });
|
||||
assert.ok(got.reply.includes(STOP_HANDOFF_REPLY), `the handoff stop's words: ${got.reply}`);
|
||||
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "waiting" }, items: PLAN_QUESTION.items } });
|
||||
await plain.page.click("#btn-stop");
|
||||
await plain.page.locator("#stop-go").click();
|
||||
const sent = collect(plain);
|
||||
assert.equal(sent.actions.find((a) => a.i === "__stop").handoff, undefined);
|
||||
assert.ok(!sent.reply.includes(STOP_HANDOFF_REPLY), "a plain stop asked for a handoff");
|
||||
});
|
||||
|
||||
// A finish that offers a review, a commit and the dashboard, on a build.
|
||||
const OFFERS = { headline: "Quick task done", command: "/plan2code-5-git", review: true, commit: true, dashboard: true };
|
||||
const closeGuide = (s) => s.page.getByRole("region", { name: "Before you close this" });
|
||||
|
||||
// What a person sees break: "Safe to close" printed under "Review requested", or the review offer coming back after a reload.
|
||||
test("Before you close this shows while a review is on offer, goes while it is asked, and the asked offer stays locked after a reload", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "quick-task", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: OFFERS });
|
||||
const main = s.page.locator("#main");
|
||||
const reviewNow = main.getByRole("button", { name: "Review it now" });
|
||||
await reviewNow.waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 1, "a review only on offer must not hide the guide");
|
||||
assert.match(await textOf(main), /The review is optional\./);
|
||||
|
||||
await reviewNow.click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "__review", type: "review" }]);
|
||||
await main.getByRole("button", { name: "Review requested…" }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 0, "the guide shows while a review is starting");
|
||||
assert.equal(await main.getByRole("button", { name: "No thanks, I am done" }).count(), 0);
|
||||
|
||||
// The press is remembered: the buttons do not come back on a reload.
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await main.getByRole("button", { name: "Review requested…" }).waitFor();
|
||||
assert.equal(await main.getByRole("button", { name: "Review it now" }).count(), 0);
|
||||
assert.equal(await closeGuide(s).count(), 0, "the guide came back on a reload");
|
||||
});
|
||||
|
||||
// What a person sees break: the guide missing while a commit or the dashboard
|
||||
// is starting (it would say "start a new one" under "Opening Git"), or missing
|
||||
// once they said they are done or the server is gone.
|
||||
test("Before you close this goes while a commit or the dashboard is starting, and stays once they are done or the server is gone", async (t) => {
|
||||
const browser = await suite.browser();
|
||||
const finishPage = async (opts) => {
|
||||
const s = await openSession(browser, { t, workflow: "quick-task", ...opts, payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
s.post({ finish: OFFERS });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Quick task done" }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), 1, "a plain finish shows the guide");
|
||||
return s;
|
||||
};
|
||||
const cases = [
|
||||
["Commit it now", "__commit", "Opening Git…", 0],
|
||||
["Back to the dashboard", "__dashboard", "Opening the dashboard…", 0],
|
||||
["No thanks, I am done", "__done", null, 1],
|
||||
];
|
||||
for (const [button, id, asked, guides] of cases) {
|
||||
const s = await finishPage({});
|
||||
await s.page.locator("#main").getByRole("button", { name: button }).click();
|
||||
assert.deepEqual(collect(s).actions.map((a) => a.i), [id]);
|
||||
if (asked) await s.page.locator("#main").getByRole("button", { name: asked }).waitFor();
|
||||
assert.equal(await closeGuide(s).count(), guides, `the guide after ${button}`);
|
||||
}
|
||||
// A review asked, then the server gone: nothing is starting any more.
|
||||
const gone = await finishPage({ clock: true });
|
||||
await gone.page.locator("#main").getByRole("button", { name: "Review it now" }).click();
|
||||
collect(gone);
|
||||
assert.equal(await closeGuide(gone).count(), 0);
|
||||
await stopServer(gone);
|
||||
for (let i = 0; i < 20 && !(await gone.page.locator("#planny.is-gone").count()); i++) {
|
||||
await gone.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await closeGuide(gone).waitFor();
|
||||
});
|
||||
|
||||
// What a person sees break: a finished screen with no Before you close this,
|
||||
// a pause that promises the wrong thing, or the guide's own text going wrong.
|
||||
test("every finished shape shows Before you close this with its three rows, and a pause names the resume command", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const main = s.page.locator("#main");
|
||||
const shapes = [
|
||||
["A skill next", { command: "/plan2code-4-finalize" }, /A new session starts from clean context/, /Paste the command above in the new session, or start from the dashboard with \/plan2code\./],
|
||||
["A terminal command next", { command: "git status" }, /A new session starts from clean context/, /Run the command above in your terminal, then start the next step/],
|
||||
["Nothing left", {}, /A new session starts from clean context/, /In the new session, start from the dashboard with \/plan2code\./],
|
||||
["Paused here", { command: "/plan2code-3-implement specs/x/overview.md" }, /Your saved place is picked up by the resume command above\./, /Paste the command above/],
|
||||
];
|
||||
for (const [headline, rest, fresh, carry] of shapes) {
|
||||
s.post({ finish: { headline, ...rest } });
|
||||
await main.getByRole("heading", { name: headline }).waitFor();
|
||||
const guide = closeGuide(s);
|
||||
assert.equal(await guide.count(), 1, `${headline}: one guide`);
|
||||
assert.equal(await guide.locator("li").count(), 3, `${headline}: three rows`);
|
||||
const text = await textOf(guide);
|
||||
for (const label of ["Before you close this", "Safe to close", "Start fresh", "Carry on"]) assert.ok(text.includes(label), `${headline}: says "${label}"`);
|
||||
assert.match(text, fresh, `${headline}: the Start fresh sentence`);
|
||||
assert.match(text, carry, `${headline}: the Carry on sentence`);
|
||||
assert.ok(!text.includes("—"), `${headline}: the guide carries an em dash`);
|
||||
}
|
||||
// With a stop warning up, a pause's command starts the work again.
|
||||
s.post({ stopWarning: "Answers since the last save will not be kept." });
|
||||
await closeGuide(s).getByText(/The command above starts it again\./).waitFor();
|
||||
assert.equal(await s.page.locator("#btn-home").isVisible(), false, "a finished screen carries its own way back");
|
||||
});
|
||||
|
||||
// What a person sees break: the triangle leaving answers behind, or sending a
|
||||
// finish-style stop instead of the way home.
|
||||
test("the top bar's back triangle asks first, then sends __dashboard with the typed answers and the home reply", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-home");
|
||||
const modal = s.page.locator("#home-modal");
|
||||
await modal.waitFor();
|
||||
assert.match(await textOf(modal), /Leave this workflow\?/);
|
||||
assert.match(await textOf(modal.locator("#home-blurb")), /The answer you have ready goes with it\./);
|
||||
await modal.locator("#home-cancel").click();
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
assert.equal(s.wait(1).code === 0, false, "Cancel sent something");
|
||||
|
||||
await s.page.click("#btn-home");
|
||||
await modal.locator("#home-go").click();
|
||||
const got = collect(s);
|
||||
assert.deepEqual(got.actions.map(({ i, type }) => ({ i, type })), [{ i: "q1", type: "answer" }, { i: "__dashboard", type: "dashboard" }]);
|
||||
assert.ok(got.reply.includes("audit-export") && got.reply.endsWith(HOME_REPLY), `the reply carries the answer, then the home line: ${got.reply}`);
|
||||
await s.page.waitForFunction(() => document.getElementById("btn-home").disabled);
|
||||
});
|
||||
|
||||
// What a person sees break: Back to default in Preferences does nothing.
|
||||
test("Back to default in Preferences returns the theme to follow the system and clears the chosen look", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.locator('input[name="looks-theme"][value="dark"]').check();
|
||||
await s.page.waitForFunction(() => document.documentElement.getAttribute("data-theme") === "dark");
|
||||
await s.page.click("#looks-reset");
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true, "the system choice is ticked again");
|
||||
});
|
||||
@@ -0,0 +1,94 @@
|
||||
// Page tests for the Workspace dialog and @mentions: adding a folder from the
|
||||
// footer label, what the next send tells the agent, and picking a folder from
|
||||
// the list an @ opens in a note. Run with:
|
||||
// node --test scripts/test-web-console-page-workspace.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 test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, itemCard, textOf } from "./page-test-helpers.mjs";
|
||||
import { tempFolder } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn: one text question, the agent listening.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
// A folder named `datasets` in its own temp parent, so its @name is known.
|
||||
function datasetsFolder() {
|
||||
const dir = path.join(tempFolder(), "datasets");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens Workspace from the footer label and adds `dir` by typing its path.
|
||||
async function addFolderFromDialog(s, dir) {
|
||||
await s.page.locator("#footer-where").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor();
|
||||
await s.page.locator("#workspace-path").fill(dir);
|
||||
await s.page.locator("#workspace-add").click();
|
||||
await s.page.locator("#workspace-add-msg.is-good").waitFor();
|
||||
}
|
||||
|
||||
// What a person sees break: a folder that does not show in the dialog, or
|
||||
// that the agent is never told about.
|
||||
test("a folder added in Workspace is listed with its @name, and the next send tells the agent in its reply", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const dir = datasetsFolder();
|
||||
await addFolderFromDialog(s, dir);
|
||||
|
||||
assert.equal(await textOf(s.page.locator("#workspace-add-msg")), "Added as @datasets.");
|
||||
const rows = s.page.locator("#workspace-list .ws-entry");
|
||||
assert.equal(await rows.count(), 2, "the project's own folder and the new one");
|
||||
const added = rows.filter({ hasText: "@datasets" });
|
||||
assert.equal(await added.count(), 1);
|
||||
assert.equal(await textOf(added.locator(".ws-path")), dir);
|
||||
assert.equal(await added.locator(".ws-original").count(), 0, "only the first folder is the original");
|
||||
assert.equal(await rows.first().locator(".ws-original").count(), 1);
|
||||
assert.equal(await s.page.locator("#workspace-path").inputValue(), "", "the path box empties after an add");
|
||||
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
assert.equal(got.code, 0, `nothing was sent (wait exit ${got.code})`);
|
||||
assert.ok(got.reply.includes("audit-export"), `the answer is in the reply: ${got.reply}`);
|
||||
assert.ok(got.reply.includes("Workspace: added @datasets"), `the Workspace line: ${got.reply}`);
|
||||
assert.ok(got.reply.includes(dir), `the Workspace line names the path: ${got.reply}`);
|
||||
});
|
||||
|
||||
// What a person sees break: an @ that offers nothing, or a pick that leaves
|
||||
// the box as it was.
|
||||
test("an @ in a note offers the workspace's folders, and picking one writes its @name into the note", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await addFolderFromDialog(s, datasetsFolder());
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
|
||||
const note = s.page.locator("#aside #thread-q1");
|
||||
await note.click();
|
||||
await note.pressSequentially("Look in @da");
|
||||
const pop = s.page.locator("#mention-pop");
|
||||
await pop.waitFor();
|
||||
const options = pop.locator(".mention-opt");
|
||||
assert.deepEqual(await options.allTextContents(), ["@datasets"], "only the folder that matches what was typed");
|
||||
await options.first().click();
|
||||
await pop.waitFor({ state: "detached" });
|
||||
assert.equal(await note.inputValue(), "Look in @datasets ");
|
||||
|
||||
// A bare @ lists every folder, the project's own first.
|
||||
await note.pressSequentially("and @");
|
||||
await pop.waitFor();
|
||||
assert.equal(await pop.locator(".mention-opt").count(), 2);
|
||||
await s.page.keyboard.press("Escape");
|
||||
await pop.waitFor({ state: "detached" });
|
||||
});
|
||||
@@ -13,11 +13,12 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { applyPatch, validate, blankState } from "../src/web-console/lib.mjs";
|
||||
import { applyPatch, validate, blankState } from "../src/web-console/patches.mjs";
|
||||
import { rebasingBranch } from "../src/web-console/git-repo.mjs";
|
||||
import { indentReply, noteReplyLines, agentRepliedAfterSend } from "../src/web-console/public/answers.js";
|
||||
import { chatView } from "../src/web-console/public/chat.js";
|
||||
import { ROOT, CONSOLE_CLI, ENV, cli, payload, readState, postPatch, EXPORT_A, openSession } from "./web-console-test-helpers.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
|
||||
const choice = (id, extra = {}) => ({
|
||||
id,
|
||||
@@ -32,8 +33,7 @@ const choice = (id, extra = {}) => ({
|
||||
});
|
||||
const waitFor = (s, seconds = 10) => cli(["wait", "--session", s.sid, "--seconds", String(seconds)]);
|
||||
const runCli = (args, opts = {}) => spawnSync(process.execPath, [CONSOLE_CLI, ...args], { env: ENV, encoding: "utf8", ...opts });
|
||||
const app = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const css = () => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = () => joinedCss();
|
||||
|
||||
/* ------------------------------------------------------------ settling */
|
||||
|
||||
@@ -195,7 +195,6 @@ test("a rebase in progress names the branch it is rewriting", () => {
|
||||
test("a typed line never starts a reply line of its own", () => {
|
||||
assert.equal(indentReply("a\nIdea name: foo\r\n Image: C:\\x"), "a\n Idea name: foo\n Image: C:\\x");
|
||||
assert.deepEqual(noteReplyLines("Q", "one\ntwo", []), ["Note on Q: one\n two"]);
|
||||
assert.match(app(), /replyLines\.push\(`\$\{item\.title\}: \$\{indentReply\(tok\)\}`\)/);
|
||||
});
|
||||
|
||||
test("an approved edit stops saying 'please wait' once the agent has answered it", () => {
|
||||
@@ -211,32 +210,17 @@ test("an approved edit stops saying 'please wait' once the agent has answered it
|
||||
assert.equal(chatView(frame).rows[1].done, true);
|
||||
});
|
||||
|
||||
test("a build's own count wins, 0 done included; a question workflow still fills as cards are answered", () => {
|
||||
const chrome = app().slice(app().indexOf("function renderChrome("), app().indexOf("// Planny and the line beside him"));
|
||||
assert.match(chrome, /if \(Number\(h\.total\) > 0\)/);
|
||||
assert.match(chrome, /building \? Math\.max\(0, Number\(h\.cleared\) \|\| 0\) : Number\(h\.cleared\) \|\| answeredCount\(\)/);
|
||||
assert.match(chrome, /else if \(building && h\.stage\)/, "a review starting at total 0 shows its stage");
|
||||
});
|
||||
|
||||
test("the git board: Publish names a remote only when there is one, and an open card holds the board", () => {
|
||||
const js = app();
|
||||
test("the git board: Publish names a remote only when there is one, and Continue is always offered", () => {
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const action = view.slice(view.indexOf("function runStep("), view.indexOf("function stepButton("));
|
||||
assert.match(action, /remotes\.length === 1/);
|
||||
const at = js.indexOf("const gitMode = ");
|
||||
assert.match(js.slice(at, js.indexOf(";", at)), /myTurn\(\)\.some\(\(i\) => i\.kind !== "notice"\)/);
|
||||
const banner = view.slice(view.indexOf("function opBlock("), view.indexOf("function prBlock("));
|
||||
assert.ok(!/if \(conflicted\.every/.test(banner), "Continue is always offered; plan continue checks the files itself");
|
||||
});
|
||||
|
||||
test("a card cut by the window fades at its bottom edge while there is more below", () => {
|
||||
assert.match(app(), /function markMore\(\)[\s\S]*?classList\.toggle\("has-more"/);
|
||||
assert.match(css(), /\.main > \.card\.has-more \{[\s\S]*?mask-image/);
|
||||
});
|
||||
|
||||
test("kept attachments are served read-only from the session's spec, by their exact name shape", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const route = server.slice(server.indexOf('pathname.startsWith("/attachments/")'), server.indexOf('pathname.startsWith("/uploads/")'));
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
const route = server.slice(server.indexOf("function attachment("), server.indexOf("function shot("));
|
||||
assert.match(route, /req\.method !== "GET"/);
|
||||
assert.match(server, /const KEPT_ROUTE = new RegExp\(`\^\/attachments\/\(\[a-z0-9-\]\{1,40\}-\[0-9a-f-\]\{8\}/);
|
||||
const kept = server.slice(server.indexOf("function keptPath("), server.indexOf("function uploadPath("));
|
||||
@@ -274,12 +258,6 @@ test("a plain reopen (status and a thread reply only) moves the sent note into t
|
||||
assert.ok(card.thread.some((m) => m.who === "user" && m.text === "Add a dry-run flag."));
|
||||
});
|
||||
|
||||
test("a list rename is staged as it is typed, so Ctrl+Enter or an agent post never drops it", () => {
|
||||
const js = app();
|
||||
const list = js.slice(js.indexOf("function buildList("), js.indexOf("function buildList(") + 6000);
|
||||
assert.match(list, /title\.addEventListener\("input", \(\) => \{[\s\S]*?stageQuiet\(item\.id/);
|
||||
});
|
||||
|
||||
test("the git board's Publish reply names no remote when it sent none, and key chips show only for short keys", async () => {
|
||||
const { gitReply } = await import("../src/web-console/public/git-board.js");
|
||||
assert.equal(gitReply("publish", {}), "Publish.");
|
||||
@@ -292,25 +270,17 @@ test("the git board's Publish reply names no remote when it sent none, and key c
|
||||
});
|
||||
|
||||
test("a skip is recorded as one, collected with the send, and settles as skipped", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
assert.match(server, /\.\.\.\(type === "skip" \? \{ skipped: true \} : \{\}\)/);
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
|
||||
assert.match(cli, /a\.type === "answer" \|\| a\.type === "skip"/);
|
||||
});
|
||||
|
||||
test("a send made before the last collection is never shown as still with the agent", () => {
|
||||
const js = app();
|
||||
const fn = js.slice(js.indexOf("const sendCollected = "), js.indexOf("const submittedInFlight = "));
|
||||
assert.match(fn, /String\(sub\.at\) <= String\(c\.at\)/);
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const cli = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-post-wait.mjs"), "utf8");
|
||||
assert.match(cli, /collected: \{ at: result\.consumedAt \|\| nowIso\(\), ids \}/, "the collection time, which every earlier send precedes");
|
||||
});
|
||||
|
||||
test("two dashboards on different specs never trade the workspace back and forth", () => {
|
||||
const js = app();
|
||||
assert.match(js, /wantScope !== scopeMine\) syncWorkspaceScope\(\)/);
|
||||
});
|
||||
|
||||
/* -------------------------------------------------------------- round 3 */
|
||||
|
||||
test("a branch whose remote copy was deleted offers Publish again, not Pull or Push", async () => {
|
||||
@@ -331,13 +301,8 @@ test("a branch whose remote copy was deleted offers Publish again, not Pull or P
|
||||
assert.equal(acts.publish.enabled, true);
|
||||
});
|
||||
|
||||
test("a finished session never puts a sent answer back on its form", () => {
|
||||
const js = app();
|
||||
assert.match(js, /if \(effort && !finish\(\) && isOpen\(item\)/);
|
||||
});
|
||||
|
||||
test("keep names a copy from the upload's real path, so an 8.3 spelling reuses the same copy", () => {
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "console.mjs"), "utf8");
|
||||
const src = fs.readFileSync(path.join(ROOT, "src", "web-console", "cmd-small.mjs"), "utf8");
|
||||
assert.match(src, /attachmentName\(\{ upload: real\(upload\), name: args\.name \}\)/);
|
||||
});
|
||||
|
||||
|
||||
@@ -34,8 +34,9 @@ import {
|
||||
STRAY_GRACE_MS,
|
||||
staleSessions,
|
||||
terminalLine,
|
||||
validate,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
} from "../src/web-console/sessions.mjs";
|
||||
import { validate } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HANDOFFS_DIR,
|
||||
@@ -528,7 +529,7 @@ test("cleanup lists the project's completed specs untouched for 30 days, and rem
|
||||
|
||||
test("User Preferences: wider, its body scrolls and the button bar stays put, without touching dialogs that borrow .looks", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const dialog = html.match(/<dialog class="modal looks prefs" id="looks-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "the Preferences dialog carries the prefs class");
|
||||
const body = dialog[1].indexOf('<div class="prefs-body">');
|
||||
@@ -722,12 +723,6 @@ test("notes/quick-task.md has a quick-task build tick the Plan tab's steps live"
|
||||
assert.ok(section.includes("- [x] **1.** Step one"));
|
||||
});
|
||||
|
||||
test("the waiting pane points a quick-task build at its Plan tab", () => {
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function renderWaiting("), js.indexOf("function renderNotice("));
|
||||
assert.ok(fn.includes('S.workflow === "quick-task" && docs().find((d) => d.id === "plan")'));
|
||||
});
|
||||
|
||||
test("notes/quick-task.md has the finished quick task offer Back to the dashboard as well as the review", () => {
|
||||
const md = fs.readFileSync(path.join(ROOT, "src", "web-console", "notes", "quick-task.md"), "utf8");
|
||||
const section = md.slice(md.indexOf("## Quick task (`quick-task`)"));
|
||||
@@ -791,3 +786,61 @@ test("an image block under the session's shots folder round-trips, and /shots/ s
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// /app.css is the files under public/styles/ joined in CSS_ORDER (one newline
|
||||
// after each), then the accent rules. The files themselves are never served.
|
||||
test("/app.css is the style files joined in CSS_ORDER with the accent rules last", async () => {
|
||||
const { CSS_ORDER, asset, etagOf } = await import("../src/web-console/static.mjs");
|
||||
const dir = path.join(ROOT, "src", "web-console", "public", "styles");
|
||||
const res = cli(["open", "--workflow", "review", "--no-open"]);
|
||||
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
const cookie = cookieFor(m[1], m[2]);
|
||||
try {
|
||||
const r = await fetch(m[1] + "/app.css", { headers: { cookie } });
|
||||
assert.equal(r.status, 200);
|
||||
assert.match(r.headers.get("content-type"), /^text\/css/);
|
||||
const body = await r.text();
|
||||
// One newline between files: each file's own last newline is that one.
|
||||
const joined = CSS_ORDER.map((f) => fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "")).join("\n") + "\n";
|
||||
assert.ok(body.startsWith(joined), "the body opens with the files, in CSS_ORDER, one newline between");
|
||||
const accents = body.slice(joined.length);
|
||||
assert.match(accents, /^\n*\/\* Generated by server\.mjs from palette\.js/, "the accent rules come last");
|
||||
assert.ok(accents.includes(`:root[data-looks-accent="violet"]`));
|
||||
// The tests' helper joins through the server's own function, so the two agree.
|
||||
assert.equal(body, joinedCss() + accents, "joinedCss() plus the accent rules is the body the server returns");
|
||||
// The ETag is a hash of the whole body, so a change to any one file moves it.
|
||||
assert.equal(r.headers.get("etag"), etagOf(Buffer.from(body)));
|
||||
assert.equal(asset("app.css").etag, etagOf(Buffer.from(body)));
|
||||
for (const f of CSS_ORDER) {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8").replace(/\n$/, "");
|
||||
assert.notEqual(etagOf(Buffer.from(body.replace(text, text + "\n/* changed */"))), r.headers.get("etag"), `a change to ${f} moves the ETag`);
|
||||
}
|
||||
for (const f of CSS_ORDER) {
|
||||
const own = await fetch(m[1] + "/styles/" + f, { headers: { cookie } });
|
||||
assert.equal(own.status, 404, `/styles/${f} is not served on its own`);
|
||||
await own.arrayBuffer();
|
||||
}
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// The skills the build writes carry public/styles/ with every file in CSS_ORDER,
|
||||
// and a console started from that tree serves the same /app.css as this one.
|
||||
test("the built skills tree serves the same /app.css as the source console", async (t) => {
|
||||
const { CSS_ORDER, asset } = await import("../src/web-console/static.mjs");
|
||||
const built = path.join(ROOT, "skills", "plan2code", "references", "web-console");
|
||||
// npm test builds first; a bare run of this file may not have.
|
||||
if (!fs.existsSync(path.join(built, "console.mjs"))) return t.skip("skills/ is not built: run npm run build:skills");
|
||||
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(built, "public", "styles", f)), `the build is missing public/styles/${f}`);
|
||||
const out = execFileSync(process.execPath, [path.join(built, "console.mjs"), "open", "--workflow", "review", "--no-open"], { env: ENV, encoding: "utf8", cwd: ROOT });
|
||||
const json = JSON.parse(out.trim().split("\n").pop());
|
||||
const m = json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
try {
|
||||
const res = await fetch(m[1] + "/app.css", { headers: { cookie: cookieFor(m[1], m[2]) } });
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(await res.text(), asset("app.css").body.toString("utf8"));
|
||||
} finally {
|
||||
execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid], { env: ENV, cwd: ROOT });
|
||||
}
|
||||
});
|
||||
@@ -24,9 +24,6 @@ import {
|
||||
noteReplyLines,
|
||||
staleLaunchFeedback,
|
||||
REVIEW_REPLY,
|
||||
SKILL_CATALOG,
|
||||
START_POSES,
|
||||
startPose,
|
||||
STOP_REPLY,
|
||||
STOP_HANDOFF_REPLY,
|
||||
threadText,
|
||||
@@ -38,13 +35,9 @@ import { ACCENTS, CARD_WIDTHS, SOUND_EVENTS, soundKey, soundPrefs } from "../src
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../src/web-console/public/help.js";
|
||||
import { RED_AT, YELLOW_AT } from "../src/web-console/public/meter.js";
|
||||
import { REMOTE_FOLD } from "../src/web-console/public/git-board.js";
|
||||
import {
|
||||
applyPatch,
|
||||
readLedger,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sweepUploads,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
} from "../src/web-console/lib.mjs";
|
||||
import { readLedger, SESSION_MAX_AGE_MS, sweepUploads, UPLOAD_MAX_AGE_MS } from "../src/web-console/sessions.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
@@ -475,8 +468,7 @@ test("the way home follows Stop's turn rules and hides where it has no job", ()
|
||||
test("the page carries the way home: the triangle, its confirm, and the wiring", () => {
|
||||
const dir = path.join(ROOT, "src", "web-console", "public");
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(dir, "app.js"), "utf8");
|
||||
const css = fs.readFileSync(path.join(dir, "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
assert.ok(html.indexOf('id="btn-home"') < html.indexOf('id="btn-stop"'), "the triangle sits left of Stop session");
|
||||
assert.match(html, /id="btn-home"[\s\S]{0,200}aria-label="Back to the dashboard"/, "the icon button has a name");
|
||||
for (const id of ["home-modal", "home-blurb", "home-warn", "home-cancel", "home-go"]) {
|
||||
@@ -484,8 +476,6 @@ test("the page carries the way home: the triangle, its confirm, and the wiring",
|
||||
}
|
||||
assert.ok(html.includes("Leave this workflow?"));
|
||||
assert.match(css, /\.home-btn path\s*\{\s*fill:\s*var\(--accent\)/, "the triangle is filled with the highlight color");
|
||||
assert.ok(app.includes('{ i: "__dashboard", type: "dashboard" }'), "the confirm sends __dashboard");
|
||||
assert.ok(app.includes("stagedPayload()") && app.includes("HOME_REPLY"), "the staged answers ride along with the reply line");
|
||||
});
|
||||
|
||||
test("the way home cannot be mistaken for a brief request", () => {
|
||||
@@ -523,9 +513,12 @@ test("console-launches.md and the dashboard prompt teach the handoff pick-up and
|
||||
test("every module the page imports is actually served", async () => {
|
||||
const dir = path.join(ROOT, "src", "web-console", "public");
|
||||
const wanted = new Set(["app.js"]);
|
||||
for (const f of fs.readdirSync(dir).filter((f) => f.endsWith(".js"))) {
|
||||
// The modules beside app.js and the screens under screens/, each import
|
||||
// resolved from the file that makes it (a screen's "../state.js" is state.js).
|
||||
const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...fs.readdirSync(path.join(dir, "screens")).map((f) => `screens/${f}`)];
|
||||
for (const f of files) {
|
||||
const src = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
for (const m of src.matchAll(/^\s*import\b[^"']*["']\.\/([^"']+)["']/gm)) wanted.add(m[1]);
|
||||
for (const m of src.matchAll(/^\s*import\b[^"']*["'](\.\.?\/[^"']+)["']/gm)) wanted.add(path.posix.join(path.posix.dirname(f), m[1]));
|
||||
}
|
||||
const html = fs.readFileSync(path.join(dir, "index.html"), "utf8");
|
||||
for (const m of html.matchAll(/<link rel="modulepreload" href="\/([^"]+)"/g)) wanted.add(m[1]);
|
||||
@@ -613,28 +606,6 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
|
||||
assert.doesNotMatch(html, /rel="icon"[^>]*href="data:/);
|
||||
});
|
||||
|
||||
// Each skill's starting and waiting screens clone its pose from index.html.
|
||||
// A pose with no drawing silently falls back to the flight, and a style
|
||||
// attribute in one would be refused by the CSP, so hold the markup to the list.
|
||||
test("every skill has a pose drawn in the page, with no inline styles", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
|
||||
assert.ok(tpl, "index.html has the start-poses template");
|
||||
const drawn = [...tpl[1].matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
|
||||
assert.deepEqual(drawn.sort(), [...START_POSES].sort());
|
||||
assert.doesNotMatch(tpl[1], /\sstyle=/);
|
||||
for (const pose of START_POSES) {
|
||||
assert.ok(SKILL_CATALOG.some((e) => e.workflow === pose), `${pose} is a real workflow`);
|
||||
assert.equal(startPose(pose), pose);
|
||||
}
|
||||
assert.equal(startPose("implement-review"), "implement");
|
||||
assert.equal(startPose("revise-plan"), "plan");
|
||||
assert.equal(startPose("init-update"), "init");
|
||||
for (const e of SKILL_CATALOG) assert.ok(startPose(e.workflow), `${e.workflow} has a pose`);
|
||||
assert.equal(startPose("dashboard"), null);
|
||||
assert.equal(startPose(undefined), null);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------- help */
|
||||
|
||||
|
||||
@@ -798,9 +769,9 @@ const helpFacts = () => ({
|
||||
maxDocMb: MAX_DOC_BYTES / 1024 / 1024,
|
||||
imageEdge: IMAGE_LONG_EDGE,
|
||||
cleanupDays: SESSION_MAX_AGE_MS / 86400000,
|
||||
goneSeconds: sourceConst("public/app.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
|
||||
adriftMinutes: sourceConst("public/app.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
|
||||
maxUploadMb: sourceConst("public/app.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
|
||||
goneSeconds: sourceConst("public/screens/core.js", /const GONE_AFTER_MS = ([^;]+);/, "GONE_AFTER_MS") / 1000,
|
||||
adriftMinutes: sourceConst("public/selectors.js", /const ADRIFT_MS = ([^;]+);/, "ADRIFT_MS") / 60000,
|
||||
maxUploadMb: sourceConst("public/uploads.js", /const MAX_UPLOAD_BYTES = ([^;]+);/, "MAX_UPLOAD_BYTES") / 1024 / 1024,
|
||||
idleMinutes: sourceConst("server.mjs", /const IDLE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "IDLE_MS") / 60000,
|
||||
maxLifeHours: sourceConst("server.mjs", /const MAX_LIFE_MS = Number\(args\[[^\]]+\] \|\| ([^)]+)\)/, "MAX_LIFE_MS") / 3600000,
|
||||
closedTabMinutes: sourceConst("server.mjs", /\(IDLE_MS - ([^)]+)\)/, "the closed-tab shutdown") / 60000,
|
||||
|
||||
@@ -0,0 +1,325 @@
|
||||
// Web console tests, the shape of the source: no console file grows past
|
||||
// 3,000 lines, and the files lib.mjs split into stand on their own.
|
||||
// Run with: node --test scripts/test-web-console-shape.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { ROOT } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const CONSOLE_DIR = path.join(ROOT, "src", "web-console");
|
||||
const MAX_LINES = 3000;
|
||||
|
||||
// Every .mjs, .js and .css file under `dir` (vendored code aside), as paths
|
||||
// relative to it with forward slashes.
|
||||
function sourceFiles(dir, rel = "") {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
||||
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "public/vendor") out.push(...sourceFiles(dir, p));
|
||||
} else if (/\.(mjs|js|css)$/.test(e.name)) out.push(p);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// A file's line count, as `wc -l` gives it for a file ending in a newline.
|
||||
function lineCount(text) {
|
||||
return text.split("\n").length - (text.endsWith("\n") ? 1 : 0);
|
||||
}
|
||||
|
||||
// The lines that name each file over the limit.
|
||||
function oversized(dir) {
|
||||
return sourceFiles(dir)
|
||||
.map((p) => [p, lineCount(fs.readFileSync(path.join(dir, p), "utf8"))])
|
||||
.filter(([p, n]) => n > MAX_LINES)
|
||||
.map(([p, n]) => `${p} is ${n} lines, over the ${MAX_LINES}-line limit: split it by job`);
|
||||
}
|
||||
|
||||
test("shape: no console file is over 3,000 lines", () => {
|
||||
assert.deepEqual(oversized(CONSOLE_DIR), []);
|
||||
});
|
||||
|
||||
test("shape: the size check names the file that is too big", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "public", "vendor"), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "big.mjs"), "x\n".repeat(MAX_LINES + 1));
|
||||
fs.writeFileSync(path.join(dir, "edge.css"), "x\n".repeat(MAX_LINES));
|
||||
fs.writeFileSync(path.join(dir, "small.js"), "x\n");
|
||||
fs.writeFileSync(path.join(dir, "public", "vendor", "huge.js"), "x\n".repeat(MAX_LINES * 2));
|
||||
assert.deepEqual(oversized(dir), [`big.mjs is ${MAX_LINES + 1} lines, over the ${MAX_LINES}-line limit: split it by job`]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("shape: files.mjs still finds the console's own folder", async () => {
|
||||
const { HERE, PUBLIC_DIR } = await import("../src/web-console/files.mjs");
|
||||
assert.equal(path.basename(HERE), "web-console");
|
||||
assert.equal(PUBLIC_DIR, path.join(HERE, "public"));
|
||||
});
|
||||
|
||||
test("shape: lib.mjs is gone, and every file it split into is there", () => {
|
||||
assert.equal(fs.existsSync(path.join(CONSOLE_DIR, "lib.mjs")), false, "src/web-console/lib.mjs still exists");
|
||||
for (const f of SPLIT_FILES) {
|
||||
const text = fs.readFileSync(path.join(CONSOLE_DIR, f), "utf8");
|
||||
assert.match(text, /^\/\/ Plan2Code Web Console - \S.*\.\n/, `${f} opens with a one-line job comment`);
|
||||
}
|
||||
});
|
||||
|
||||
// Every page file but the entry (app.js) only defines things, so each one
|
||||
// loads under plain Node with no page around it. Imported alone in a fresh
|
||||
// process: one that reaches for `document` or `window` at load, or runs
|
||||
// anything else that throws, is named with its first error line. One that
|
||||
// starts a timer or a listener throws nothing but never exits: it is named too.
|
||||
const LOAD_TIMEOUT_MS = 5000;
|
||||
function pageLoadFailures(pub) {
|
||||
return sourceFiles(pub)
|
||||
.filter((p) => p.endsWith(".js") && p !== "app.js" && (!p.includes("/") || p.startsWith("screens/")))
|
||||
.flatMap((p) => {
|
||||
const url = pathToFileURL(path.join(pub, p)).href;
|
||||
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], {
|
||||
encoding: "utf8",
|
||||
timeout: LOAD_TIMEOUT_MS,
|
||||
});
|
||||
if (r.error && r.error.code === "ETIMEDOUT") return [`${p} does not load on its own: still running after load (a timer or listener started at module scope)`];
|
||||
if (r.status === 0) return [];
|
||||
const line = r.stderr.split("\n").find((l) => /Error/.test(l)) || r.stderr.trim().split("\n")[0];
|
||||
return [`${p} does not load on its own: ${line.trim()}`];
|
||||
});
|
||||
}
|
||||
|
||||
test("shape: every page file but app.js only defines things, and loads under plain Node", () => {
|
||||
assert.deepEqual(pageLoadFailures(path.join(CONSOLE_DIR, "public")), []);
|
||||
});
|
||||
|
||||
test("shape: the define-only check names a page file that touches the page at load", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-define-only-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "screens"));
|
||||
fs.mkdirSync(path.join(dir, "vendor"));
|
||||
fs.writeFileSync(path.join(dir, "package.json"), '{ "type": "module" }\n');
|
||||
fs.writeFileSync(path.join(dir, "app.js"), "document.title = 'the entry may';\n");
|
||||
fs.writeFileSync(path.join(dir, "fine.js"), "export const title = () => document.title;\n");
|
||||
fs.writeFileSync(path.join(dir, "screens", "eager.js"), "export const title = document.title;\n");
|
||||
fs.writeFileSync(path.join(dir, "screens", "ticks.js"), "setInterval(() => {}, 1000);\n");
|
||||
fs.writeFileSync(path.join(dir, "vendor", "lib.js"), "window.x = 1;\n");
|
||||
const failures = pageLoadFailures(dir);
|
||||
assert.equal(failures.length, 2, failures.join("\n"));
|
||||
assert.match(failures.find((f) => f.startsWith("screens/eager.js")), /does not load on its own: ReferenceError: document is not defined/);
|
||||
assert.match(failures.find((f) => f.startsWith("screens/ticks.js")), /does not load on its own: still running after load/);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// A screen reaches the rest of the page through ../state.js and the pure
|
||||
// modules beside it, never through another screen: only core.js (the render
|
||||
// loop, which draws every screen) imports screens, and only app.js (the
|
||||
// entry) imports core.js. Each import that breaks that is named.
|
||||
function pageImportProblems(pub) {
|
||||
const problems = [];
|
||||
for (const p of sourceFiles(pub).filter((f) => f.endsWith(".js") && (!f.includes("/") || f.startsWith("screens/")))) {
|
||||
const text = fs.readFileSync(path.join(pub, p), "utf8");
|
||||
for (const m of text.matchAll(/^\s*(?:import|export)\b[^;]*?\bfrom\s*["']([^"']+)["']|\bimport\(\s*["']([^"']+)["']\s*\)|^\s*import\s*["']([^"']+)["']/gm)) {
|
||||
const spec = m[1] || m[2] || m[3];
|
||||
if (!spec.startsWith(".")) continue;
|
||||
const target = path.posix.join(path.posix.dirname(p), spec);
|
||||
if (target === "screens/core.js" && p !== "app.js") problems.push(`${p} imports ${spec}: only app.js imports core.js`);
|
||||
else if (p.startsWith("screens/") && p !== "screens/core.js" && target.startsWith("screens/"))
|
||||
problems.push(`${p} imports ${spec}: a screen imports ../state.js and the modules beside it, never another screen`);
|
||||
}
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
test("shape: a screen never imports another screen, and only app.js imports core.js", () => {
|
||||
assert.deepEqual(pageImportProblems(path.join(CONSOLE_DIR, "public")), []);
|
||||
});
|
||||
|
||||
test("shape: the import check names a screen that imports another, and any file but app.js importing core.js", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-imports-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "screens"));
|
||||
const put = (rel, text) => fs.writeFileSync(path.join(dir, rel), text);
|
||||
put("app.js", 'import { render } from "./screens/core.js";\n');
|
||||
put("state.js", "export const page = {};\n");
|
||||
put("render.js", "export const el = () => null;\n");
|
||||
put("screens/core.js", 'import { a } from "./a.js";\nimport { page } from "../state.js";\n');
|
||||
put("screens/a.js", 'import { b } from "./b.js";\nimport { page } from "../state.js";\nimport { el } from "../render.js";\n');
|
||||
put("screens/b.js", 'import { page } from "../state.js";\n');
|
||||
put("screens/c.js", 'import { render } from "./core.js";\n');
|
||||
put("helper.js", 'import { render } from "./screens/core.js";\n');
|
||||
put("screens/d.js", 'import "./b.js";\n');
|
||||
assert.deepEqual(pageImportProblems(dir).sort(), [
|
||||
"helper.js imports ./screens/core.js: only app.js imports core.js",
|
||||
"screens/a.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
|
||||
"screens/c.js imports ./core.js: only app.js imports core.js",
|
||||
"screens/d.js imports ./b.js: a screen imports ../state.js and the modules beside it, never another screen",
|
||||
]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The page's CSP refuses style attributes, so one set from script is dropped
|
||||
// on the floor in the browser. Every page module, wherever a split moves the
|
||||
// code that draws.
|
||||
test("shape: no page module sets a style attribute from script", () => {
|
||||
const pub = path.join(CONSOLE_DIR, "public");
|
||||
const offenders = sourceFiles(pub)
|
||||
.filter((p) => p.endsWith(".js"))
|
||||
.filter((p) => /setAttribute\(\s*["']style["']/.test(fs.readFileSync(path.join(pub, p), "utf8")));
|
||||
assert.deepEqual(offenders, []);
|
||||
});
|
||||
|
||||
// Every URL the server's old `if` chain matched, in its order, so a route lost
|
||||
// or moved in routes.mjs fails here by name: several match by prefix, and the
|
||||
// token gate sits after the first two. SERVABLE stands for the page's own files
|
||||
// and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has
|
||||
// no routes of its own: its buttons are sends (`__git`), through /submit.
|
||||
const ROUTE_ORDER = [
|
||||
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
|
||||
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
|
||||
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
|
||||
];
|
||||
|
||||
test("shape: routes.mjs lists every URL the server answers, in order", () => {
|
||||
const routes = fs.readFileSync(path.join(CONSOLE_DIR, "routes.mjs"), "utf8");
|
||||
const start = routes.indexOf("const ROUTES = [");
|
||||
const list = routes.slice(start, routes.indexOf("\n];", start));
|
||||
const entries = list
|
||||
.split("\n")
|
||||
.filter((line) => /^\s*\{/.test(line))
|
||||
.map((line) => (line.match(/path: "([^"]*)"|startsWith\("([^"]*)"\)|\b(SERVABLE|WORKSPACE_EDITS)\b/) || []).slice(1).find(Boolean));
|
||||
assert.deepEqual(entries, ROUTE_ORDER);
|
||||
const edits = routes.match(/const WORKSPACE_EDITS = \{([^}]*)\}/)[1];
|
||||
for (const p of ["/workspace/add", "/workspace/edit", "/workspace/remove"]) assert.ok(edits.includes(`"${p}"`), `${p} is a workspace edit`);
|
||||
});
|
||||
|
||||
// Each file split out of lib.mjs, imported first and alone in a fresh
|
||||
// process: a module-scope read of a value from a file still loading (an
|
||||
// import cycle) throws here, naming the file, before it reaches a real run.
|
||||
const SPLIT_FILES = ["files.mjs", "sessions.mjs", "scan.mjs", "patches.mjs", "inbox.mjs", "workspace.mjs", "settings.mjs"];
|
||||
|
||||
test("shape: every file split out of lib.mjs loads first and alone", () => {
|
||||
for (const f of SPLIT_FILES) {
|
||||
const url = pathToFileURL(path.join(CONSOLE_DIR, f)).href;
|
||||
const r = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(url)});`], { encoding: "utf8" });
|
||||
assert.equal(r.status, 0, `${f} does not load on its own: ${r.stderr.trim().split("\n").find((l) => /Error/.test(l)) || r.stderr}`);
|
||||
}
|
||||
});
|
||||
|
||||
// app.js is the entry and nothing else, so no test may read it as text: what a
|
||||
// screen does is tested by driving the page, and what a screen file holds is
|
||||
// read from that screen. A statement that both reads a file and names app.js
|
||||
// is a read (a fetch of /app.js, or a fixture file called app.js, is not).
|
||||
const SCRIPTS_DIR = path.join(ROOT, "scripts");
|
||||
|
||||
// parse-check.mjs only parses the entry, so it may name it.
|
||||
const MAY_NAME_APP_JS = new Set(["parse-check.mjs"]);
|
||||
|
||||
// One statement that reads and names app.js, or a read helper handed it
|
||||
// (`web("app.js")`, `publicSource("public/app.js")`), or a path to it
|
||||
// under public/, in any file that also reads files.
|
||||
function appJsReaders(dir) {
|
||||
return fs
|
||||
.readdirSync(dir)
|
||||
.filter((f) => f.endsWith(".mjs") && f !== "test-web-console-shape.mjs" && !MAY_NAME_APP_JS.has(f))
|
||||
.filter((f) => {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
const oneStatement = text
|
||||
.split(";")
|
||||
.some((statement) => /\b(readFileSync|readFile|publicSource)\s*\(/.test(statement) && /["'/]app\.js["']/.test(statement));
|
||||
const handedToAHelper = /\w\(\s*["'](?:(?:src\/web-console\/)?public\/)?app\.js["']\s*\)/.test(text);
|
||||
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
|
||||
return oneStatement || handedToAHelper || publicPath;
|
||||
})
|
||||
.map((f) => `${f} reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it`);
|
||||
}
|
||||
|
||||
test("shape: no test in scripts/ reads public/app.js as text", () => {
|
||||
assert.deepEqual(appJsReaders(SCRIPTS_DIR), []);
|
||||
});
|
||||
|
||||
test("shape: the app.js check names the test file that reads it", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shape-"));
|
||||
try {
|
||||
fs.writeFileSync(path.join(dir, "test-fine.mjs"), 'const r = await fetch(base + "/app.js");\nfs.appendFileSync(path.join(d, "src", "app.js"), "x");\n');
|
||||
assert.deepEqual(appJsReaders(dir), []);
|
||||
fs.writeFileSync(path.join(dir, "test-reads-it.mjs"), 'const app = fs.readFileSync(path.join(ROOT, "public", "app.js"), "utf8");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-reads-it.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
fs.rmSync(path.join(dir, "test-reads-it.mjs"));
|
||||
fs.writeFileSync(path.join(dir, "test-alias.mjs"), 'const web = (f) => fs.readFileSync(path.join(ROOT, "public", f), "utf8");\nconst app = web("app.js");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-alias.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The stylesheet is many files under public/styles/, joined by the server into
|
||||
// the one /app.css the page asks for. CSS_ORDER is the one place the cascade
|
||||
// order is stated: every file in it exists, each once, and no file in the folder
|
||||
// is left out of it or served on its own.
|
||||
test("shape: CSS_ORDER names every file in public/styles/ once, and none is served on its own", async () => {
|
||||
const { CSS_ORDER, SERVABLE } = await import("../src/web-console/static.mjs");
|
||||
const dir = path.join(CONSOLE_DIR, "public", "styles");
|
||||
assert.ok(CSS_ORDER.length > 0, "CSS_ORDER lists files");
|
||||
assert.equal(new Set(CSS_ORDER).size, CSS_ORDER.length, "no file is listed twice");
|
||||
for (const f of CSS_ORDER) assert.ok(fs.existsSync(path.join(dir, f)), `CSS_ORDER lists ${f}, which is not in public/styles/`);
|
||||
const onDisk = fs.readdirSync(dir).filter((f) => f.endsWith(".css")).sort();
|
||||
assert.deepEqual([...CSS_ORDER].sort(), onDisk, "public/styles/ holds exactly the files CSS_ORDER lists");
|
||||
for (const rel of SERVABLE) assert.ok(!rel.startsWith("styles/") && !CSS_ORDER.includes(rel), `${rel} must not be served on its own`);
|
||||
});
|
||||
|
||||
// The files table in AGENTS-architecture.md gives every console file a row,
|
||||
// so a contributor finds where a job lives without searching. A row's first
|
||||
// cell names the file by its path under src/web-console/ (backticked; one cell
|
||||
// may name several files, joined by "·").
|
||||
const ARCHITECTURE_DOC = path.join(ROOT, ".agents-docs", "AGENTS-architecture.md");
|
||||
|
||||
// The paths the files table names, from the first cell of each table row.
|
||||
function tableFiles(markdown) {
|
||||
const named = new Set();
|
||||
for (const line of markdown.split("\n")) {
|
||||
if (!line.startsWith("|")) continue;
|
||||
const cell = line.split("|")[1] || "";
|
||||
for (const m of cell.matchAll(/`([^`]+)`/g)) named.add(m[1]);
|
||||
}
|
||||
return named;
|
||||
}
|
||||
|
||||
// One line per console file with no row in the table.
|
||||
function undocumented(dir, markdown) {
|
||||
const named = tableFiles(markdown);
|
||||
return sourceFiles(dir)
|
||||
.filter((p) => !named.has(p))
|
||||
.map((p) => `${p} has no row in the files table of AGENTS-architecture.md: add one with its one-line job`);
|
||||
}
|
||||
|
||||
test("shape: every console file has a row in the files table of AGENTS-architecture.md", () => {
|
||||
const problems = undocumented(CONSOLE_DIR, fs.readFileSync(ARCHITECTURE_DOC, "utf8"));
|
||||
assert.deepEqual(problems, []);
|
||||
});
|
||||
|
||||
test("shape: the docs-table check names a file with no row, and passes one that has it", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-docs-table-"));
|
||||
try {
|
||||
fs.mkdirSync(path.join(dir, "public"));
|
||||
fs.writeFileSync(path.join(dir, "a.mjs"), "");
|
||||
fs.writeFileSync(path.join(dir, "public", "b.js"), "");
|
||||
const table = "| File | Role |\n|---|---|\n| `a.mjs` | the first |\n";
|
||||
assert.deepEqual(undocumented(dir, table), [
|
||||
"public/b.js has no row in the files table of AGENTS-architecture.md: add one with its one-line job",
|
||||
]);
|
||||
assert.deepEqual(undocumented(dir, `${table}| \`public/b.js\` · \`x.js\` | the second |\n`), []);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,247 @@
|
||||
// Web console tests, the skill list: public/skills.js holds every per-skill
|
||||
// fact the console uses, and the older tables are lookups on it.
|
||||
// Run with: node --test scripts/test-web-console-skills.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import {
|
||||
SKILLS,
|
||||
skillFor,
|
||||
skillByName,
|
||||
isBuild,
|
||||
isPhased,
|
||||
isMetered,
|
||||
subagentsFor,
|
||||
takesTemplates,
|
||||
labelFor,
|
||||
} from "../src/web-console/public/skills.js";
|
||||
import { CONSOLE_WORKFLOWS, SKILL_CATALOG, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
|
||||
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
|
||||
import { BUILD_WORKFLOWS } from "../src/web-console/public/labels.js";
|
||||
import { helpTabFor } from "../src/web-console/public/help.js";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { ROOT, cli, poseTemplate } from "./web-console-test-helpers.mjs";
|
||||
import { SUBAGENT_WORKFLOWS } from "../src/web-console/public/subagents.js";
|
||||
import { TEMPLATE_WORKFLOWS } from "../src/web-console/public/starters.js";
|
||||
|
||||
// meter.js keeps its answers-row names private: what they were when the list
|
||||
// moved, written out. A skill added since has no row here, and only has to
|
||||
// have a name.
|
||||
const NAMES_AT_THE_MOVE = {
|
||||
dashboard: "the dashboard",
|
||||
pathfinder: "Pathfinder",
|
||||
plan: "Plan",
|
||||
"revise-plan": "Revise plan",
|
||||
document: "Document",
|
||||
implement: "Implement",
|
||||
"implement-review": "Implement + Review",
|
||||
review: "Review",
|
||||
"quick-task": "Quick task",
|
||||
init: "Init",
|
||||
"init-update": "Init update",
|
||||
finalize: "Finalize",
|
||||
handoff: "Handoff",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
xray: "X-ray",
|
||||
diagnose: "Diagnose",
|
||||
};
|
||||
|
||||
const CARD_FIELDS = ["group", "chip", "title", "blurb", "about", "spec"];
|
||||
|
||||
test("every skill the console knows has one entry, the dashboard included", () => {
|
||||
const workflows = SKILLS.map((s) => s.workflow);
|
||||
assert.deepEqual([...workflows].sort(), Object.keys(WORKFLOW_LABEL).sort());
|
||||
assert.equal(new Set(workflows).size, workflows.length, "one entry per workflow");
|
||||
assert.deepEqual(SKILLS.map((s) => s.command).sort(), [...CONSOLE_WORKFLOWS].sort());
|
||||
// The cards come first, in the dashboard's order.
|
||||
const carded = SKILLS.filter((s) => s.card);
|
||||
assert.deepEqual(carded.map((s) => s.skill), SKILL_CATALOG.map((e) => e.skill));
|
||||
assert.equal(skillFor("dashboard").skill, "plan2code");
|
||||
assert.equal(skillFor("dashboard").card, null, "the dashboard is the hub, not a card");
|
||||
});
|
||||
|
||||
// The older exports (WORKFLOW_LABEL, SKILL_CATALOG, LAUNCH_COUNTED and the
|
||||
// rest) are now built from SKILLS, so this checks the wiring: each one still
|
||||
// says what its entry says. It proved the move when the tables were still
|
||||
// written by hand; the meter names and the build flags, which have no
|
||||
// importable twin, are held to their values at the move.
|
||||
test("the derived exports agree with each entry", () => {
|
||||
for (const s of SKILLS) {
|
||||
const w = s.workflow;
|
||||
for (const f of ["skill", "workflow", "label", "name"]) assert.ok(typeof s[f] === "string" && s[f].trim(), `${w}: ${f} must be filled in`);
|
||||
assert.equal(s.command, "/" + s.skill, `${w}: command`);
|
||||
assert.equal(s.label, WORKFLOW_LABEL[w], `${w}: label`);
|
||||
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) assert.equal(s.name, NAMES_AT_THE_MOVE[w], `${w}: name`);
|
||||
assert.equal(s.pose, startPose(w), `${w}: pose`);
|
||||
assert.equal(s.metered, LAUNCH_COUNTED.has(w), `${w}: metered`);
|
||||
assert.equal(s.subagents, SUBAGENT_WORKFLOWS[w] ? SUBAGENT_WORKFLOWS[w].instruction : null, `${w}: subagents`);
|
||||
assert.equal(s.templates, TEMPLATE_WORKFLOWS.includes(w), `${w}: templates`);
|
||||
if (Object.hasOwn(NAMES_AT_THE_MOVE, w)) {
|
||||
assert.equal(s.builds, ["implement", "implement-review", "quick-task"].includes(w), `${w}: builds`);
|
||||
assert.equal(s.phased, ["implement", "implement-review"].includes(w), `${w}: phased`);
|
||||
}
|
||||
const entry = SKILL_CATALOG.find((e) => e.workflow === w);
|
||||
if (!entry) {
|
||||
assert.equal(s.card, null, `${w}: no card`);
|
||||
continue;
|
||||
}
|
||||
assert.equal(entry.skill, s.skill, `${w}: skill`);
|
||||
assert.equal(entry.command, s.command, `${w}: card command`);
|
||||
for (const f of CARD_FIELDS) assert.equal(s.card[f], entry[f], `${w}: card.${f}`);
|
||||
}
|
||||
// Every pose in the page's list belongs to an entry.
|
||||
for (const pose of START_POSES) assert.ok(SKILLS.some((s) => s.pose === pose), `${pose} belongs to a skill`);
|
||||
for (const w of PROGRESS_WORKFLOWS) assert.ok(isPhased(w), `${w} counts its tasks`);
|
||||
});
|
||||
|
||||
test("the entries are frozen data", () => {
|
||||
assert.ok(Object.isFrozen(SKILLS));
|
||||
for (const s of SKILLS) {
|
||||
assert.ok(Object.isFrozen(s), `${s.workflow} is frozen`);
|
||||
if (s.card) assert.ok(Object.isFrozen(s.card), `${s.workflow}.card is frozen`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the lookups answer by workflow or skill name, and say nothing for an unknown one", () => {
|
||||
assert.equal(skillFor("implement-review").skill, "plan2code-3-implement-review");
|
||||
assert.equal(skillByName("plan2code-git").workflow, "git");
|
||||
assert.equal(skillByName("plan2code").workflow, "dashboard");
|
||||
assert.equal(labelFor("xray"), "X-ray");
|
||||
assert.equal(subagentsFor("review"), SUBAGENT_WORKFLOWS.review.instruction);
|
||||
for (const unknown of ["nope", undefined, null, "", "constructor", "__proto__"]) {
|
||||
assert.equal(skillFor(unknown), null);
|
||||
assert.equal(skillByName(unknown), null);
|
||||
assert.equal(labelFor(unknown), null);
|
||||
assert.equal(subagentsFor(unknown), null);
|
||||
for (const is of [isBuild, isPhased, isMetered, takesTemplates]) assert.equal(is(unknown), false);
|
||||
}
|
||||
});
|
||||
|
||||
// Which workflows labels.js and help.js count as builds, as they stood when the
|
||||
// sets moved onto skills.js: labels.js leaves Quick Task out, help.js keeps it.
|
||||
test("the two build sets hold what they held before", () => {
|
||||
assert.deepEqual([...BUILD_WORKFLOWS].sort(), ["implement", "implement-review"]);
|
||||
assert.deepEqual(SKILLS.filter((s) => isBuild(s.workflow)).map((s) => s.workflow).sort(), ["implement", "implement-review", "quick-task"]);
|
||||
// help.js keeps its set private: Help opens on its Building tab for exactly these.
|
||||
const onBuild = SKILLS.map((s) => s.workflow).filter((workflow) => helpTabFor({ workflow }) === "build");
|
||||
assert.deepEqual(onBuild.sort(), ["implement", "implement-review", "quick-task"]);
|
||||
assert.equal(helpTabFor({ workflow: "nope" }), "about");
|
||||
});
|
||||
|
||||
/* ------------------------------------------- tests that name what was missed */
|
||||
|
||||
// Each check below is a pure function of a skill list, so a test can hand it a
|
||||
// copy with one thing wrong and see the message name the skill.
|
||||
|
||||
// Each skill's starting screen clones its pose from index.html. A pose with no
|
||||
// drawing silently falls back to the flight, and a drawing no skill uses is
|
||||
// dead markup.
|
||||
function poseProblems(skills, drawn) {
|
||||
const problems = [];
|
||||
for (const s of skills) {
|
||||
if (s.card && !s.pose) problems.push(`${s.skill} has a card but no pose`);
|
||||
if (s.pose && !drawn.includes(s.pose)) problems.push(`${s.skill} names pose "${s.pose}", which index.html does not draw`);
|
||||
}
|
||||
for (const pose of drawn) {
|
||||
if (!skills.some((s) => s.pose === pose)) problems.push(`index.html draws pose "${pose}", which belongs to no skill`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// Every workflow the console can open has its notes behind `console.mjs help`.
|
||||
function helpProblems(skills, topics) {
|
||||
return skills.filter((s) => !Object.hasOwn(topics, s.workflow)).map((s) => `${s.skill} (${s.workflow}) has no help topic in console.mjs`);
|
||||
}
|
||||
|
||||
// The skills with a card, plus the dashboard, are exactly what install.js builds.
|
||||
function installProblems(skills, installed) {
|
||||
const named = skills.filter((s) => s.card || s.workflow === "dashboard").map((s) => s.skill);
|
||||
return [
|
||||
...named.filter((n) => !installed.includes(n)).map((n) => `${n} is in skills.js but not in install.js SOURCE_PROMPTS`),
|
||||
...installed.filter((n) => !named.includes(n)).map((n) => `${n} is in install.js SOURCE_PROMPTS but has no card in skills.js`),
|
||||
];
|
||||
}
|
||||
|
||||
const drawnPoses = () => [...poseTemplate().matchAll(/data-pose="([^"]+)"/g)].map((m) => m[1]);
|
||||
const helpTopics = () => cli(["help", "topics"]).json.topics;
|
||||
|
||||
// install.js reads the home directory at load: point it at a temp one, as the
|
||||
// install tests do. Requiring it never runs its CLI (that waits on require.main).
|
||||
function installedSkills() {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-skills-"));
|
||||
const saved = { HOME: process.env.HOME, USERPROFILE: process.env.USERPROFILE };
|
||||
process.env.HOME = home;
|
||||
process.env.USERPROFILE = home;
|
||||
try {
|
||||
const { SOURCE_PROMPTS, generateSkillName } = createRequire(import.meta.url)(path.join(ROOT, "install.js"));
|
||||
return SOURCE_PROMPTS.map(generateSkillName);
|
||||
} finally {
|
||||
for (const [k, v] of Object.entries(saved)) v === undefined ? delete process.env[k] : (process.env[k] = v);
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("every skill's pose is drawn in the page, and every drawn pose belongs to a skill", () => {
|
||||
const drawn = drawnPoses();
|
||||
assert.deepEqual(poseProblems(SKILLS, drawn), []);
|
||||
assert.doesNotMatch(poseTemplate(), /\sstyle=/, "a style attribute would be refused by the CSP");
|
||||
// Variants borrow their pose; the dashboard keeps the flight.
|
||||
assert.equal(startPose("implement-review"), "implement");
|
||||
assert.equal(startPose("revise-plan"), "plan");
|
||||
assert.equal(startPose("init-update"), "init");
|
||||
assert.equal(startPose("dashboard"), null);
|
||||
assert.equal(startPose(undefined), null);
|
||||
|
||||
const broken = SKILLS.map((s) => (s.workflow === "xray" ? { ...s, pose: "x-ray-glasses" } : s));
|
||||
assert.deepEqual(poseProblems(broken, drawn), [
|
||||
'plan2code-xray names pose "x-ray-glasses", which index.html does not draw',
|
||||
'index.html draws pose "xray", which belongs to no skill',
|
||||
]);
|
||||
const poseless = SKILLS.map((s) => (s.workflow === "git" ? { ...s, pose: null } : s));
|
||||
assert.deepEqual(poseProblems(poseless, drawn), ["plan2code-git has a card but no pose", 'index.html draws pose "git", which belongs to no skill']);
|
||||
});
|
||||
|
||||
test("every workflow in the skill list has a help topic", () => {
|
||||
const topics = helpTopics();
|
||||
assert.deepEqual(helpProblems(SKILLS, topics), []);
|
||||
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up" }];
|
||||
assert.deepEqual(helpProblems(extra, topics), ["plan2code-made-up (made-up) has no help topic in console.mjs"]);
|
||||
});
|
||||
|
||||
test("the skill list and install.js agree on which skills exist", () => {
|
||||
const installed = installedSkills();
|
||||
assert.ok(installed.includes("plan2code"), "read SOURCE_PROMPTS");
|
||||
assert.deepEqual(installProblems(SKILLS, installed), []);
|
||||
const extra = [...SKILLS, { skill: "plan2code-made-up", workflow: "made-up", card: {} }];
|
||||
assert.deepEqual(installProblems(extra, installed), ["plan2code-made-up is in skills.js but not in install.js SOURCE_PROMPTS"]);
|
||||
assert.deepEqual(installProblems(SKILLS, [...installed, "plan2code-orphan"]), ["plan2code-orphan is in install.js SOURCE_PROMPTS but has no card in skills.js"]);
|
||||
});
|
||||
|
||||
test("dashboard note: the agent's note shows only on the spec the picker opened on", () => {
|
||||
const a = { dir: "specs/a" };
|
||||
const b = { dir: "specs/b" };
|
||||
assert.equal(onInitialPick(a, a), true);
|
||||
assert.equal(onInitialPick(a, b), false);
|
||||
assert.equal(onInitialPick(a, null), false);
|
||||
assert.equal(onInitialPick(null, null), true, "no spec at all: scratch is the opening pick");
|
||||
assert.equal(onInitialPick(null, a), false);
|
||||
});
|
||||
|
||||
test("dashboard note: the agent's note, the looking-over line and the neutral line", () => {
|
||||
const menu = { note: "Phase 2 is next." };
|
||||
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: true, working: false }), "agent");
|
||||
assert.equal(dashNoteKind({ menu, hasMenu: true, onInitial: false, working: false }), "neutral", "another pick, another line");
|
||||
assert.equal(dashNoteKind({ menu: { note: " " }, hasMenu: true, onInitial: true, working: true }), "neutral", "a blank note is no note");
|
||||
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: true }), "looking");
|
||||
assert.equal(dashNoteKind({ menu: {}, hasMenu: false, onInitial: true, working: false }), "neutral");
|
||||
});
|
||||
|
||||
test("starting screen: the hint stays calm for ninety seconds, then points at the terminal", () => {
|
||||
assert.match(startingHint(0), /fills in by itself/);
|
||||
assert.match(startingHint(90000), /fills in by itself/, "ninety seconds is still calm");
|
||||
assert.match(startingHint(90001), /terminal has the play-by-play/);
|
||||
});
|
||||
@@ -13,6 +13,7 @@ import path from "node:path";
|
||||
// (it touches `document` at module scope and starts a session on import), which
|
||||
// is exactly why this lives in its own file.
|
||||
import { cardAvailability, SKILL_CATALOG } from "../src/web-console/public/answers.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
import { FAVICON_BODY, FAVICON_COLORS, faviconState, faviconSvg } from "../src/web-console/public/favicon.js";
|
||||
import {
|
||||
@@ -24,8 +25,9 @@ import {
|
||||
latestTag,
|
||||
} from "../src/web-console/update-check.mjs";
|
||||
import { runHint } from "../src/web-console/public/render.js";
|
||||
import { applyPatch } from "../src/web-console/lib.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { ROOT, cli, helpTemplate, sessionUrl } from "./web-console-test-helpers.mjs";
|
||||
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.
|
||||
@@ -82,7 +84,7 @@ test("runHint: command words (git included) get the hint, the rest nothing", ()
|
||||
});
|
||||
|
||||
test("a reused item id does not inherit the previous answer's submitted record", async () => {
|
||||
const { applyPatch } = await import("../src/web-console/lib.mjs");
|
||||
const { applyPatch } = await import("../src/web-console/patches.mjs");
|
||||
const before = { items: [{ id: "q7", kind: "choice", title: "A", body: "old", status: "open", submitted: { at: "t", text: "old answer" } }] };
|
||||
const reworded = applyPatch(before, { items: [{ id: "q7", kind: "choice", title: "B", body: "new", status: "open" }] });
|
||||
assert.equal(reworded.items[0].submitted, undefined);
|
||||
@@ -100,7 +102,7 @@ test("a reused item id does not inherit the previous answer's submitted record",
|
||||
});
|
||||
|
||||
test("unansweredChat lists delivered Quick questions that still have no reply", async () => {
|
||||
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/lib.mjs");
|
||||
const { unansweredChat, appendChat, writeCursor } = await import("../src/web-console/inbox.mjs");
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-chat-"));
|
||||
appendChat(dir, { kind: "reset", conversation: 1, workflow: "dashboard", reason: "start" });
|
||||
appendChat(dir, { kind: "message", conversation: 1, text: "run it" });
|
||||
@@ -251,8 +253,7 @@ test("update check: the frame carries update only when a newer release is cached
|
||||
test("stop modal: handoff choice first, plain stop second, Keep going last, styled and wired", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const html = web("index.html");
|
||||
const app = web("app.js");
|
||||
const css = web("app.css");
|
||||
const css = joinedCss();
|
||||
const dialog = html.match(/<dialog class="modal" id="stop-modal"[^>]*>([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "index.html has the stop modal");
|
||||
const body = dialog[1];
|
||||
@@ -262,39 +263,17 @@ test("stop modal: handoff choice first, plain stop second, Keep going last, styl
|
||||
assert.doesNotMatch(body, /\sstyle=|<script/i);
|
||||
assert.match(css, /\.stop-choice/, "app.css styles the choices");
|
||||
assert.match(css, /\.stop-choice:focus-visible/, "and gives them a focus outline");
|
||||
const open = app.slice(app.indexOf("function openStopConfirm()"), app.indexOf("async function stopSession("));
|
||||
assert.ok(open.includes("stop-handoff") && open.includes("isDashboard()"), "openStopConfirm hides the handoff on the dashboard");
|
||||
assert.ok(app.includes("stopSession(true)") && app.includes("STOP_HANDOFF_REPLY") && app.includes("stopAction"), "app.js wires the handoff stop");
|
||||
const help = helpTemplate().match(/<section class="help-panel" data-tab="finishing">([\s\S]*?)<\/section>/);
|
||||
assert.ok(help && help[1].includes("Stop with a handoff") && help[1].includes("Just stop and save") && help[1].includes("~/.plan2code/handoffs/"), "Help names both choices and where handoffs land");
|
||||
});
|
||||
|
||||
// The dashboard's handoff chips, preview and their four actions.
|
||||
test("dashboard handoffs: dashed chips, a preview with four buttons, and the cards give way", () => {
|
||||
// The dashboard's handoff chips, preview and their four actions. What they
|
||||
// do on the page is held by the page tests in test-web-console-page-dashboard.mjs;
|
||||
// this keeps the style, the modal markup and the Help.
|
||||
test("dashboard handoffs: the style, the read dialog and the delete warning ship, and Help explains the chips", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const app = web("app.js");
|
||||
const css = web("app.css");
|
||||
const css = joinedCss();
|
||||
const html = web("index.html");
|
||||
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
|
||||
|
||||
const picker = fn("renderSpecPicker", "\nfunction ");
|
||||
assert.ok(picker.includes("is-handoff") && picker.includes('"Handoff"'), "renderSpecPicker builds handoff chips");
|
||||
assert.ok(picker.includes('"handoff:"'), "a handoff is picked as handoff:<id>");
|
||||
const dash = fn("renderDashboard", "\n/* -----");
|
||||
assert.ok(dash.includes("handoffList()"), "renderDashboard shows the picker for handoffs alone");
|
||||
const early = dash.indexOf("renderHandoffPreview(");
|
||||
assert.ok(early > 0 && early < dash.indexOf("hideUnavailableToggle()"), "the preview returns before the toggle and the card groups");
|
||||
assert.match(app, /const selHandoff = \(\) =>/);
|
||||
assert.match(app, /startsWith\("handoff:"\)/);
|
||||
|
||||
const preview = fn("renderHandoffPreview", "\nasync function ");
|
||||
for (const label of ["Pick it up here", "Read it all", "Copy for a new conversation", "Delete"]) {
|
||||
assert.ok(preview.includes(`"${label}"`), `the preview names ${label}`);
|
||||
}
|
||||
assert.ok(app.includes("pickupAction(") && app.includes('"/submit"'), "Pick it up here posts a __pickup to /submit");
|
||||
assert.ok(app.includes('"/handoff?id="'), "Read it all fetches /handoff?id=");
|
||||
assert.ok(app.includes("handoffCopyText("), "Copy puts the ready prompt on the clipboard");
|
||||
assert.ok(app.includes("deleteHandoffAction(") && app.includes("function openHandoffDelete("), "Delete reuses the confirm dialog");
|
||||
|
||||
assert.match(css, /\.spec-chip\.is-handoff/, "app.css styles handoff chips");
|
||||
assert.match(css, /\.handoff-preview\b/, "and the preview panel");
|
||||
@@ -318,41 +297,25 @@ test("sign-off: approve leads show, and the approve button wears the accent", ()
|
||||
const show = text.indexOf('{ "id": "show", "label": "Show me it working" }');
|
||||
assert.ok(approve > 0 && show > approve, `${f} lists Approve this phase before Show me it working`);
|
||||
}
|
||||
const app = doc("public/app.js");
|
||||
assert.match(app, /const forward = v\.id === "approve" \|\| v\.id === "yes";/, "approve and yes are the forward verdicts");
|
||||
assert.match(app, /forward \? " is-approve"/, "an unpicked forward verdict gets is-approve");
|
||||
assert.match(doc("public/app.css"), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
|
||||
assert.match(joinedCss(), /\.btn\.is-approve\s*\{[^}]*border-color:\s*var\(--accent\)/, "is-approve borders in the accent");
|
||||
});
|
||||
|
||||
// A fixed bug's chip: a visible Delete, one confirm, and "bug fixed" said once.
|
||||
test("bug fixed delete: a promoted Delete on the chip and a one-step confirm", () => {
|
||||
// What the fixed bug's chip and Delete do on the page is held by the page tests
|
||||
// in test-web-console-page-dashboard.mjs; this keeps the style and the Help.
|
||||
test("bug fixed delete: the Delete button is styled and Help explains the one confirm", () => {
|
||||
const web = (f) => fs.readFileSync(path.join(ROOT, "src", "web-console", "public", f), "utf8");
|
||||
const app = web("app.js");
|
||||
const fn = (name, next) => app.slice(app.indexOf(`function ${name}(`), app.indexOf(next, app.indexOf(`function ${name}(`)));
|
||||
|
||||
const picker = fn("renderSpecPicker", "\nfunction ");
|
||||
assert.ok(picker.includes('"spec-chip-del-label"') && picker.includes('"Delete"'), "renderSpecPicker builds a Delete button for a fixed bug");
|
||||
assert.ok(picker.includes("chipDetail("), "the chip's detail line comes from chipDetail");
|
||||
assert.doesNotMatch(picker, /spec\.detail\b/, "never the scan's detail directly");
|
||||
|
||||
const css = web("app.css");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.spec-chip-del-label\s*\{/, "app.css styles the Delete button");
|
||||
assert.match(css, /\.spec-chip-del-label:focus-visible/, "and gives it a focus outline");
|
||||
|
||||
const step = fn("deleteStep", "\nasync function ");
|
||||
const fixedAt = step.indexOf('state === "fixed"');
|
||||
const revealAt = step.indexOf('$("delete-confirm").hidden = false');
|
||||
assert.ok(fixedAt > 0 && revealAt > 0 && fixedAt < revealAt, "deleteStep sends a fixed bug's delete before it would reveal the name step");
|
||||
const open = fn("openDeleteConfirm", "\nfunction ");
|
||||
assert.ok(open.includes('state === "fixed"') && open.includes("so this only clears the write-up"), "openDeleteConfirm sets up one step and the fixed warning");
|
||||
|
||||
const panel = helpTemplate().match(/<section class="help-panel" data-tab="dashboard">([\s\S]*?)<\/section>/);
|
||||
assert.ok(panel && /fixed\s+bug[\s\S]*?Delete[\s\S]*?one\s+confirm/i.test(panel[1]), "Help says a fixed bug has its own Delete and needs one confirm");
|
||||
});
|
||||
|
||||
test("update banner: the modal is in the page, with the exact command and no inline styles or scripts", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
|
||||
const dialog = html.match(/<dialog class="modal" id="update-modal" aria-labelledby="update-title">([\s\S]*?)<\/dialog>/);
|
||||
assert.ok(dialog, "index.html has the update modal");
|
||||
assert.doesNotMatch(dialog[1], /\sstyle=/);
|
||||
@@ -362,33 +325,26 @@ test("update banner: the modal is in the page, with the exact command and no inl
|
||||
assert.match(panel[1], /UPDATE AVAILABLE/, "the dashboard topic explains the banner");
|
||||
assert.doesNotMatch(panel[1], /\sstyle=/);
|
||||
assert.doesNotMatch(panel[1], /<script/i);
|
||||
assert.ok(app.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "app.js copies the exact command");
|
||||
assert.ok(dash.includes('"npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git"'), "the dashboard copies the exact command");
|
||||
});
|
||||
|
||||
test("update banner: built only on the dashboard, dismissed per session, and Help's version links to Releases", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const start = app.indexOf("function renderDashboard(main) {");
|
||||
assert.ok(start >= 0, "app.js has renderDashboard");
|
||||
const end = app.indexOf("\n}\n", start);
|
||||
const body = app.slice(start, end);
|
||||
assert.match(body, /"dash-nudge update-banner"/, "renderDashboard builds the banner");
|
||||
const outside = app.slice(0, start) + app.slice(end);
|
||||
assert.doesNotMatch(outside, /update-banner/, "no other code builds it");
|
||||
assert.match(app, /"p2c-update-dismissed:" \+ S\.sid/, "the dismissal is keyed by the session id");
|
||||
assert.match(app, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
|
||||
assert.match(app, /\.rel = "noopener noreferrer";/);
|
||||
const help = app.match(/async function renderHelpVersion\(\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(help, "app.js has renderHelpVersion");
|
||||
assert.match(help[1], /releasesLink\(/, "the help version is a Releases link");
|
||||
const dash = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "screens", "dashboard.js"), "utf8");
|
||||
const render = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "render.js"), "utf8");
|
||||
assert.match(dash, /"p2c-update-dismissed:" \+ page\.S\.sid/, "the dismissal is keyed by the session id");
|
||||
assert.match(render, /const RELEASES_URL = "https:\/\/github\.com\/jparkerweb\/plan2code\/releases\/";/);
|
||||
assert.match(render, /\.rel = "noopener noreferrer";/);
|
||||
});
|
||||
|
||||
// The Changelog card sits left of Git, which sits left of Handoff, the last
|
||||
// card. It is always clickable, and a launch from it resumes the session under
|
||||
// its own workflow.
|
||||
test("the Changelog card comes just before Git, Handoff is last, and Changelog is always on", () => {
|
||||
const skills = SKILL_CATALOG.map((e) => e.skill);
|
||||
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"));
|
||||
assert.deepEqual(skills.slice(-3), ["plan2code-changelog", "plan2code-git", "plan2code-handoff"]);
|
||||
// The card order is skills.js's order.
|
||||
const skills = SKILLS.filter((s) => s.card).map((s) => s.skill);
|
||||
assert.equal(skills.indexOf("plan2code-changelog") + 1, skills.indexOf("plan2code-git"), "Changelog sits just before Git");
|
||||
assert.equal(skills.indexOf("plan2code-git") + 1, skills.indexOf("plan2code-handoff"), "Git sits just before Handoff");
|
||||
assert.equal(skills.at(-1), "plan2code-handoff", "Handoff is last");
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-changelog");
|
||||
assert.equal(entry.workflow, "changelog");
|
||||
assert.equal(entry.command, "/plan2code-changelog");
|
||||
@@ -434,93 +390,17 @@ test("help: privacy names the handoffs folder and preferences says Cleanup never
|
||||
assert.match(cleanup, /never\s+offered/, "the Cleanup text says the handoffs folder is never offered for removal");
|
||||
});
|
||||
|
||||
// Every say(...) call in a source slice, as its top-level arguments (raw
|
||||
// source text). String-aware, so commas and brackets inside a line are text.
|
||||
function sayCalls(source) {
|
||||
const calls = [];
|
||||
let at = 0;
|
||||
while ((at = source.indexOf("say(", at)) !== -1) {
|
||||
if (/[\w.]/.test(source[at - 1] || "")) {
|
||||
at += 4;
|
||||
continue;
|
||||
}
|
||||
const args = [];
|
||||
let depth = 0;
|
||||
let quote = null;
|
||||
let start = at + 4;
|
||||
let i = start;
|
||||
for (; i < source.length; i++) {
|
||||
const ch = source[i];
|
||||
if (quote) {
|
||||
if (ch === "\\") i++;
|
||||
else if (ch === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (ch === '"' || ch === "'" || ch === "`") quote = ch;
|
||||
else if ("([{".includes(ch)) depth++;
|
||||
else if (")]}".includes(ch)) {
|
||||
if (depth === 0) break;
|
||||
depth--;
|
||||
} else if (ch === "," && depth === 0) {
|
||||
args.push(source.slice(start, i).trim());
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
const last = source.slice(start, i).trim();
|
||||
if (last) args.push(last);
|
||||
calls.push(args);
|
||||
at = i;
|
||||
}
|
||||
return calls;
|
||||
}
|
||||
|
||||
test("status line: the quiet, Not running and Not connected lines offer What to check, opening Help on the stuck tab", () => {
|
||||
const app = publicSource("app.js");
|
||||
test("help: the stuck tab is second, and openHelpOn only opens a tab that exists", () => {
|
||||
const app = publicSource("screens/help-dialog.js");
|
||||
assert.equal(HELP_TABS.findIndex((t) => t.id === "stuck"), 1, "the stuck tab is second");
|
||||
const opener = app.match(/function openHelpOn\(id\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(opener, "app.js has openHelpOn");
|
||||
assert.ok(opener, "help-dialog.js has openHelpOn");
|
||||
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
|
||||
const render = app.slice(app.indexOf("function renderStatus()"), app.indexOf("/* ---------------------------------------------------------------- brief */"));
|
||||
const sayDef = render.slice(render.indexOf("const say = ("), render.indexOf("text.replaceChildren("));
|
||||
assert.match(sayDef, /help\.textContent = "What to check"/);
|
||||
assert.match(sayDef, /help\.addEventListener\("click", \(\) => openHelpOn\("stuck"\)\)/, "the button opens Help on the stuck tab");
|
||||
const calls = sayCalls(render.slice(render.indexOf("text.replaceChildren(")));
|
||||
const checked = calls.filter((args) => args[4] && args[4] !== "false");
|
||||
for (const needle of ["Not connected. Your answers are saved.", "Still working on it.", "is not running. Your answers are saved", "is not running right now."]) {
|
||||
assert.ok(checked.some((args) => args.join(",").includes(needle)), `"${needle}" carries What to check`);
|
||||
}
|
||||
assert.ok(checked.some((args) => args[4] === "Boolean(hint)"), "the approval hint carries What to check");
|
||||
// Nothing else does: the finished, working and adrift lines stay plain.
|
||||
assert.equal(checked.length, 4, `four calls pass check, got: ${checked.map((a) => a[1]).join(" | ")}`);
|
||||
});
|
||||
|
||||
test("finished screen: Before you close this waits while a hand-off they asked for is starting", () => {
|
||||
const app = publicSource("app.js");
|
||||
const handoff = app.slice(app.indexOf("function renderHandoff("));
|
||||
const body = handoff.slice(0, handoff.indexOf("\n}\n"));
|
||||
assert.match(body, /if \(!closeGuideHeld\(\)\) card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
|
||||
const held = app.match(/function closeGuideHeld\(\) \{([\s\S]*?)\n\}/);
|
||||
assert.ok(held, "app.js has closeGuideHeld");
|
||||
const run = (gone, afterBuild, pending) =>
|
||||
new Function("gone", "local", "reviewPending", held[1])(gone, { afterBuild }, () => pending);
|
||||
for (const kind of ["review", "commit", "dashboard"]) {
|
||||
assert.equal(run(false, kind, null), true, `held while ${kind} is starting`);
|
||||
}
|
||||
assert.equal(run(false, null, "asked"), true, "held while a review is asked");
|
||||
assert.equal(run(false, null, "open"), false, "shown while the review is only on offer");
|
||||
assert.equal(run(false, null, null), false, "shown on a plain finish");
|
||||
assert.equal(run(false, "done", null), false, "shown once they said they are done");
|
||||
assert.equal(run(true, "review", null), false, "shown once the server is gone: nothing is starting");
|
||||
// The press re-renders the page, and so does the finish going away, so the
|
||||
// panel follows the state.
|
||||
const send = app.slice(app.indexOf("async function sendAfterBuild("), app.indexOf("/* ------------------------------------------------------------- dashboard */"));
|
||||
assert.match(send, /local\.afterBuild = kind;[\s\S]*finally \{\s*render\(\);/);
|
||||
assert.match(app, /if \(!finish\(\) && local\.afterBuild\) \{\s*local\.afterBuild = null;/);
|
||||
});
|
||||
|
||||
test("models: Codex is a model CLI on the server and the page, with its own tab", () => {
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "server.mjs"), "utf8");
|
||||
const app = publicSource("app.js");
|
||||
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
|
||||
const app = publicSource("screens/looks.js");
|
||||
const html = publicSource("index.html");
|
||||
const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]);
|
||||
assert.deepEqual(list(server), ["claude", "devin", "codex"]);
|
||||
@@ -534,52 +414,9 @@ test("models: Codex is a model CLI on the server and the page, with its own tab"
|
||||
for (const cli of list(server)) assert.ok(Array.isArray(shipped[cli]), `the launcher's models.json has ${cli}`);
|
||||
});
|
||||
|
||||
test("finished screen: every shape shows Before you close this, with three rows", () => {
|
||||
const app = publicSource("app.js");
|
||||
const handoff = app.slice(app.indexOf("function renderHandoff("));
|
||||
assert.match(handoff.slice(0, handoff.indexOf("\n}\n")), /card\.appendChild\(renderCloseGuide\(shape, fin\)\)/);
|
||||
const guide = app.slice(app.indexOf("function renderCloseGuide("), app.indexOf("function renderHandoff("));
|
||||
for (const label of ["Safe to close", "Start fresh", "Carry on", "Before you close this"]) {
|
||||
assert.ok(guide.includes(label), `the guide says "${label}"`);
|
||||
}
|
||||
assert.match(guide, /shape === "paused"/, "a pause changes the Start fresh sentence");
|
||||
assert.match(guide, /resume command/);
|
||||
});
|
||||
|
||||
test("getting started: the new help, status and finished-screen strings carry no em dash", () => {
|
||||
const app = publicSource("app.js");
|
||||
const guide = app.slice(app.indexOf("const GUIDE_ICONS"), app.indexOf("function renderHandoff("));
|
||||
assert.ok(!guide.includes(EM), "the close guide has no em dash");
|
||||
const tpl = helpTemplate();
|
||||
const stuck = tpl.match(/<section class="help-panel" data-tab="stuck">([\s\S]*?)<\/section>/)[1];
|
||||
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");
|
||||
});
|
||||
|
||||
test("a redraw keeps the place of whatever scrolls: question card, finished screen, doc column", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = app.slice(app.indexOf("function withFocus("), app.indexOf("// Scroll memory across tab switches."));
|
||||
assert.ok(fn.includes("const place = mainPlace();") && fn.includes("restoreMainPlace(place);"), "withFocus saves and restores the main column's place");
|
||||
assert.ok(!fn.includes('querySelector(".card.question")'), "not only a question card");
|
||||
const scrollers = app.match(/const MAIN_SCROLLERS = "([^"]+)"/);
|
||||
assert.ok(scrollers, "MAIN_SCROLLERS lists the column's scrolling children");
|
||||
for (const s of [".card", ".dash", ".waiting-pane"]) assert.ok(scrollers[1].includes(":scope > " + s), `${s} keeps its place`);
|
||||
const place = app.slice(app.indexOf("function mainPlace("), app.indexOf("function withFocus("));
|
||||
assert.match(place, /if \(drawnView === place\.key\) main\.scrollTop = place\.top;/, "the doc column comes back only on the same tab");
|
||||
assert.match(place, /scrollerKey\(inner\) === place\.key/, "a card comes back only while it shows the same thing");
|
||||
assert.match(place, /:scope > \.git-board/, "the git board keeps its own per-tab place");
|
||||
});
|
||||
|
||||
test("Skip this one is a small accent button, like a comment box's quick answer", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.match(app, /const skip = el\("button", "btn tiny", skipped \? "Do not skip" : "Skip this one"\);/, "the skip button is btn tiny");
|
||||
assert.match(app, /quick = el\("button", "btn tiny"/, "the quick answer it matches is btn tiny");
|
||||
});
|
||||
|
||||
test("a confirm's yes and a recap's yes are outlined in the accent, a dangerous yes stays red", () => {
|
||||
const app = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const confirm = app.slice(app.indexOf("function buildConfirm("), app.indexOf("row.appendChild(mk(noLabel"));
|
||||
assert.match(confirm, /\(yes && !danger && !on \? " is-approve" : ""\)/, "an unpicked, safe yes gets is-approve");
|
||||
assert.match(confirm, /\(danger && !on \? " danger" : ""\)/, "a dangerous yes stays red");
|
||||
assert.match(app, /const ok = el\("button", "btn" \+ \(okOn \? " primary" : " is-approve"\)/, "the recap's yes gets is-approve");
|
||||
});
|
||||
@@ -0,0 +1,408 @@
|
||||
// Web console tests, the spec states: public/spec-states.js defines every
|
||||
// state the dashboard scan can report, and the labels, next steps and card
|
||||
// rules are lookups on it.
|
||||
// Run with: node --test scripts/test-web-console-spec-states.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { SPEC_STATES as TABLE, stateFor } from "../src/web-console/public/spec-states.js";
|
||||
import { SKILLS } from "../src/web-console/public/skills.js";
|
||||
import { SKILL_CATALOG, cardAvailability, defaultSpec } from "../src/web-console/public/answers.js";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
|
||||
// What the picker labels each state and which card each state lights, as
|
||||
// answers.js's SPEC_STATE_LABELS and NEXT_FOR_STATE said before the table.
|
||||
const LABELS = {
|
||||
diagnosed: "Bug diagnosed",
|
||||
fixed: "Bug fixed",
|
||||
exploring: "Exploring",
|
||||
mapped: "Ready to plan",
|
||||
planned: "Ready to document",
|
||||
documented: "Ready to build",
|
||||
building: "Building",
|
||||
built: "Ready to finalize",
|
||||
unrecognized: "Files on disk",
|
||||
};
|
||||
const NEXT = {
|
||||
diagnosed: "plan2code-quick-task",
|
||||
fixed: null,
|
||||
exploring: "plan2code-0-pathfinder",
|
||||
mapped: "plan2code-1-plan",
|
||||
planned: "plan2code-2-document",
|
||||
documented: "plan2code-3-implement",
|
||||
building: "plan2code-3-implement",
|
||||
built: "plan2code-4-finalize",
|
||||
unrecognized: null,
|
||||
};
|
||||
|
||||
test("spec states: each state keeps its label and next step, and only fixed is finished", () => {
|
||||
assert.deepEqual(Object.keys(TABLE), Object.keys(LABELS), "the states, in the scan's order");
|
||||
for (const [name, label] of Object.entries(LABELS)) {
|
||||
const s = stateFor(name);
|
||||
assert.ok(s, `${name} is in the table`);
|
||||
assert.equal(s.label, label, `${name}'s label`);
|
||||
assert.equal(s.next, NEXT[name], `${name}'s next step`);
|
||||
assert.equal(s.finished, name === "fixed", `${name}'s finished flag`);
|
||||
}
|
||||
assert.equal(stateFor("made-up"), null, "an unknown state is null");
|
||||
assert.ok(Object.isFrozen(TABLE) && Object.values(TABLE).every(Object.isFrozen), "the table is frozen");
|
||||
});
|
||||
|
||||
// Every card's answer for every picker selection, as cardAvailability() gave
|
||||
// them before the card rules moved onto skills.js: generated once from that
|
||||
// code and written out here, so the move is proven to change nothing. "none"
|
||||
// is "start from scratch" (no spec picked). The scan is a set-up git project
|
||||
// with nothing to commit; SCAN_CASES covers the three cards that read it.
|
||||
const SCAN = { hasAgents: true, isGit: true, pending: 0 };
|
||||
const CARDS = {
|
||||
"plan2code-init": {
|
||||
"none": { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
diagnosed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
fixed: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
exploring: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
mapped: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
planned: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
documented: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
building: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
built: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
unrecognized: { on: false, reason: "AGENTS.md is already written. Refresh it instead." },
|
||||
},
|
||||
"plan2code-init-update": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-0-pathfinder": {
|
||||
"none": { on: true, next: true },
|
||||
diagnosed: { on: false, reason: "The cause is found. Fix it in a quick task, or plan it." },
|
||||
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
|
||||
exploring: { on: true, next: true },
|
||||
mapped: { on: false, reason: "This spec is already past the questions" },
|
||||
planned: { on: false, reason: "This spec is already past the questions" },
|
||||
documented: { on: false, reason: "This spec is already past the questions" },
|
||||
building: { on: false, reason: "This spec is already past the questions" },
|
||||
built: { on: false, reason: "This spec is already past the questions" },
|
||||
unrecognized: { on: true, next: false },
|
||||
},
|
||||
"plan2code-1-plan": {
|
||||
"none": { on: true, next: false },
|
||||
diagnosed: { on: true, next: false },
|
||||
fixed: { on: false, reason: "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/." },
|
||||
exploring: { on: false, reason: "Pathfinder is not finished with this spec yet" },
|
||||
mapped: { on: true, next: true },
|
||||
planned: { on: true, next: false },
|
||||
documented: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
building: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
built: { on: false, reason: "The plan is written. Revise it instead if it moved." },
|
||||
unrecognized: { on: true, next: false },
|
||||
},
|
||||
"plan2code-1b-revise-plan": {
|
||||
"none": { on: false, reason: "Needs a spec that is already written up" },
|
||||
diagnosed: { on: false, reason: "Needs a spec that is already written up" },
|
||||
fixed: { on: false, reason: "Needs a spec that is already written up" },
|
||||
exploring: { on: false, reason: "Needs a spec that is already written up" },
|
||||
mapped: { on: false, reason: "Needs a spec that is already written up" },
|
||||
planned: { on: false, reason: "Needs a spec that is already written up" },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: false, reason: "The spec is fully built" },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is already written up" },
|
||||
},
|
||||
"plan2code-2-document": {
|
||||
"none": { on: false, reason: "Needs a drafted plan first" },
|
||||
diagnosed: { on: false, reason: "Needs a drafted plan first" },
|
||||
fixed: { on: false, reason: "Needs a drafted plan first" },
|
||||
exploring: { on: false, reason: "Needs a drafted plan first" },
|
||||
mapped: { on: false, reason: "Needs a drafted plan first" },
|
||||
planned: { on: true, next: true },
|
||||
documented: { on: false, reason: "The phases are already written up" },
|
||||
building: { on: false, reason: "The phases are already written up" },
|
||||
built: { on: false, reason: "The phases are already written up" },
|
||||
unrecognized: { on: false, reason: "Needs a drafted plan first" },
|
||||
},
|
||||
"plan2code-3-implement": {
|
||||
"none": { on: false, reason: "Needs the phase checklists written up first" },
|
||||
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
fixed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
exploring: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
mapped: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
planned: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
documented: { on: true, next: true },
|
||||
building: { on: true, next: true },
|
||||
built: { on: false, reason: "All tasks are already done" },
|
||||
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
},
|
||||
"plan2code-3-implement-review": {
|
||||
"none": { on: false, reason: "Needs the phase checklists written up first" },
|
||||
diagnosed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
fixed: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
exploring: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
mapped: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
planned: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
documented: { on: true, next: false },
|
||||
building: { on: true, next: false },
|
||||
built: { on: false, reason: "All tasks are already done" },
|
||||
unrecognized: { on: false, reason: "Needs the phase checklists written up first" },
|
||||
},
|
||||
"plan2code-4-finalize": {
|
||||
"none": { on: false, reason: "Needs a spec that is fully built" },
|
||||
diagnosed: { on: false, reason: "Needs a spec that is fully built" },
|
||||
fixed: { on: false, reason: "Needs a spec that is fully built" },
|
||||
exploring: { on: false, reason: "Needs a spec that is fully built" },
|
||||
mapped: { on: false, reason: "Needs a spec that is fully built" },
|
||||
planned: { on: false, reason: "Needs a spec that is fully built" },
|
||||
documented: { on: false, reason: "Needs a spec that is fully built" },
|
||||
building: { on: false, reason: "Needs a spec that is fully built" },
|
||||
built: { on: true, next: true },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is fully built" },
|
||||
},
|
||||
"plan2code-quick-task": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true, next: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-review": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-xray": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-diagnose": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-changelog": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-git": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
"plan2code-handoff": {
|
||||
"none": { on: true },
|
||||
diagnosed: { on: true },
|
||||
fixed: { on: true },
|
||||
exploring: { on: true },
|
||||
mapped: { on: true },
|
||||
planned: { on: true },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: true },
|
||||
unrecognized: { on: true },
|
||||
},
|
||||
};
|
||||
|
||||
const SCAN_CASES = [
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init", { on: true }],
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-init-update", { on: false, reason: "Needs an AGENTS.md. Set the project up first." }],
|
||||
[{ hasAgents: false, isGit: false, pending: null }, "plan2code-git", { on: true, note: "Not a git repository yet: it offers to start one" }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-init-update", { on: true }],
|
||||
[{ hasAgents: true, isGit: true, pending: 3 }, "plan2code-git", { on: true, note: "3 files to commit" }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init", { on: false, reason: "AGENTS.md is already written. Refresh it instead." }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-init-update", { on: true }],
|
||||
[{ hasAgents: true, isGit: true, pending: 1 }, "plan2code-git", { on: true, note: "1 file to commit" }],
|
||||
];
|
||||
|
||||
test("card rules: every card gives the same answer for every spec state as before", () => {
|
||||
assert.deepEqual(SKILL_CATALOG.map((e) => e.skill), Object.keys(CARDS), "one row per card, in card order");
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
for (const [sel, want] of Object.entries(CARDS[entry.skill])) {
|
||||
const spec = sel === "none" ? null : { dir: "specs/x", name: "x", state: sel };
|
||||
assert.deepEqual(cardAvailability(entry, SCAN, spec), want, `${entry.skill} with ${sel}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("card rules: a state the table does not know is treated like files on disk", () => {
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
const weird = cardAvailability(entry, SCAN, { dir: "specs/x", name: "x", state: "made-up" });
|
||||
assert.deepEqual(weird, CARDS[entry.skill].unrecognized, `${entry.skill} with an unknown state`);
|
||||
}
|
||||
});
|
||||
|
||||
test("card rules: Init, Init update and Git read the scan, not the spec", () => {
|
||||
for (const [scan, skill, want] of SCAN_CASES) {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
assert.deepEqual(cardAvailability(entry, scan, null), want, `${skill} with ${JSON.stringify(scan)}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("finished: any finished state is never the picker's default, not only fixed", () => {
|
||||
// The test's own copy of the table, with a made-up second finished state.
|
||||
const table = { ...TABLE, archived: { label: "Archived", next: null, finished: true } };
|
||||
const lookup = (name) => (Object.hasOwn(table, name) ? table[name] : null);
|
||||
const specs = [
|
||||
{ dir: "specs/a", name: "a", state: "archived" },
|
||||
{ dir: "specs/b", name: "b", state: "fixed" },
|
||||
{ dir: "specs/c", name: "c", state: "planned" },
|
||||
];
|
||||
assert.equal(defaultSpec(specs, lookup)?.dir, "specs/c", "the newest spec still in play");
|
||||
assert.equal(defaultSpec(specs.slice(0, 2), lookup), null, "only finished specs: start from scratch");
|
||||
assert.equal(defaultSpec(specs)?.dir, "specs/a", "the real table does not know archived, so it is in play");
|
||||
|
||||
// The cards greyed for a fixed bug give a made-up finished state the same reason.
|
||||
const archived = { dir: "specs/a", name: "a", state: "archived" };
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
const fixed = cardAvailability(entry, SCAN, { dir: "specs/b", name: "b", state: "fixed" });
|
||||
assert.deepEqual(cardAvailability(entry, SCAN, archived, lookup), fixed, `${entry.skill} treats archived as it treats fixed`);
|
||||
}
|
||||
});
|
||||
|
||||
// One spec folder per state, in the shapes classifySpec() reads.
|
||||
const PHASE = (ticks) => "# Phase 1\n\n" + ticks.map((x, i) => `- [${x ? "x" : " "}] **Task 1.${i + 1}:** Step ${i + 1}\n`).join("");
|
||||
const FIXTURES = {
|
||||
diagnosed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Diagnosed\n" },
|
||||
fixed: { "DIAGNOSIS-20261017.md": "# Diagnosis\n\n**Status:** Fixed\n" },
|
||||
exploring: { "pathfinder/map.md": "# Map\n\nStatus: Working\n" },
|
||||
mapped: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Phase 3 Complete - Resume at Phase 4\n" },
|
||||
planned: { "PLAN-DRAFT-20261017.md": "# Plan draft\n\n**Status:** Draft\n" },
|
||||
documented: { "overview.md": "# Overview\n", "phase-1.md": PHASE([false, false]) },
|
||||
building: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, false]) },
|
||||
built: { "overview.md": "# Overview\n", "phase-1.md": PHASE([true, true]) },
|
||||
unrecognized: { "notes.md": "Some loose notes.\n" },
|
||||
};
|
||||
|
||||
// The states a scan of these fixtures reports, against the table's: the
|
||||
// lines that name what does not match, empty when they agree.
|
||||
function scanProblems(fixtures, table) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-states-"));
|
||||
try {
|
||||
for (const [name, files] of Object.entries(fixtures))
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
const file = path.join(root, "specs", name, rel);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, text);
|
||||
}
|
||||
const scan = scanProject(root);
|
||||
const problems = scan.specs.filter((sp) => sp.state !== sp.name).map((sp) => `the ${sp.name} fixture scans as ${sp.state}`);
|
||||
const seen = new Set(scan.specs.map((sp) => sp.state));
|
||||
for (const state of seen) if (!Object.hasOwn(table, state)) problems.push(`the scan returns ${state}, which spec-states.js lacks`);
|
||||
for (const state of Object.keys(table)) if (!seen.has(state)) problems.push(`no fixture reaches ${state}: add one, or drop it from spec-states.js`);
|
||||
return problems;
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
test("the scan: every state it can return is in the table, and a fixture reaches every state in it", () => {
|
||||
assert.deepEqual(scanProblems(FIXTURES, TABLE), []);
|
||||
// The check names what is missing.
|
||||
const { built, ...short } = FIXTURES;
|
||||
assert.deepEqual(scanProblems(short, TABLE), ["no fixture reaches built: add one, or drop it from spec-states.js"]);
|
||||
const { unrecognized, ...known } = TABLE;
|
||||
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
|
||||
});
|
||||
|
||||
// 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.
|
||||
function untakenStates(skills, table) {
|
||||
const taken = new Set(skills.flatMap((sk) => (Array.isArray(sk.states) ? sk.states : [])));
|
||||
return Object.entries(table)
|
||||
.filter(([name, s]) => !s.finished && !taken.has(name))
|
||||
.map(([name]) => `no card's states take ${name}: add it to the skills.js entries whose card it lights`);
|
||||
}
|
||||
|
||||
test("card rules: every state still in play is taken by at least one card", () => {
|
||||
assert.deepEqual(untakenStates(SKILLS, TABLE), []);
|
||||
// The check names the state: Document and Plan are the cards that take planned.
|
||||
const without = SKILLS.map((sk) =>
|
||||
Array.isArray(sk.states) && (sk.skill === "plan2code-2-document" || sk.skill === "plan2code-1-plan")
|
||||
? { ...sk, states: sk.states.filter((st) => st !== "planned") }
|
||||
: sk
|
||||
);
|
||||
assert.deepEqual(untakenStates(without, TABLE), ["no card's states take planned: add it to the skills.js entries whose card it lights"]);
|
||||
});
|
||||
|
||||
test("card rules: a card's states and greyed reasons name only real states", () => {
|
||||
const known = new Set([...Object.keys(TABLE), "none"]);
|
||||
for (const sk of SKILLS) {
|
||||
if (Array.isArray(sk.states)) for (const st of sk.states) assert.ok(known.has(st), `${sk.skill} takes ${st}, which is no state`);
|
||||
for (const key of Object.keys(sk.greyed || {})) assert.ok(key === "default" || key === "finished" || known.has(key), `${sk.skill}'s greyed names ${key}, which is no state`);
|
||||
if (Array.isArray(sk.states) && sk.card) assert.ok(sk.greyed && sk.greyed.default, `${sk.skill} has a default greyed reason`);
|
||||
}
|
||||
});
|
||||
|
||||
// The states the dashboard skill's prose (src/plan2code.md) never mentions,
|
||||
// by name in backticks (`planned`) or by label in quotes ("Ready to
|
||||
// document"). The agent reads that prose to choose its recommendation, so
|
||||
// every state needs a word there; a bare word ("reading or exploring", a file
|
||||
// named building-habits.md) is not one.
|
||||
function unmentionedStates(prose, table) {
|
||||
const lower = prose.toLowerCase();
|
||||
return Object.entries(table)
|
||||
.filter(([name, s]) => !prose.includes("`" + name + "`") && !lower.includes(`"${s.label.toLowerCase()}"`))
|
||||
.map(([name, s]) => `src/plan2code.md mentions neither \`${name}\` nor "${s.label}"`);
|
||||
}
|
||||
|
||||
test("the dashboard skill: its prose names every spec state", () => {
|
||||
const prose = fs.readFileSync(path.join(import.meta.dirname, "..", "src", "plan2code.md"), "utf8");
|
||||
assert.deepEqual(unmentionedStates(prose, TABLE), []);
|
||||
const sample = 'Only `planned` and "Ready to build", while building and exploring are bare words.';
|
||||
const some = { planned: TABLE.planned, documented: TABLE.documented, building: TABLE.building, exploring: TABLE.exploring };
|
||||
assert.deepEqual(unmentionedStates(sample, some), [
|
||||
'src/plan2code.md mentions neither `building` nor "Building"',
|
||||
'src/plan2code.md mentions neither `exploring` nor "Exploring"',
|
||||
]);
|
||||
});
|
||||
@@ -15,7 +15,9 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { applyPatch, scanProject } from "../src/web-console/lib.mjs";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
import { applyPatch } from "../src/web-console/patches.mjs";
|
||||
import { joinedCss } from "./css-helpers.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
@@ -615,13 +617,6 @@ test("a wait with nothing open leaves a working agent working", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the git board lets go of a working agent that went adrift", () => {
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const at = js.indexOf("const gitMode = ");
|
||||
const line = js.slice(at, js.indexOf(";", at));
|
||||
assert.ok(line.includes("(agentWorking() && !agentAdrift())"), line);
|
||||
});
|
||||
|
||||
test("post --file - reads the patch from stdin, UTF-8 and a BOM included", () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
@@ -715,16 +710,13 @@ test("a finish ends the working stretch, and resuming a pause starts a fresh one
|
||||
});
|
||||
|
||||
test("a card with a note box over the git board flows at its own height, never shrunk under the board", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const rule = css.slice(css.indexOf(".git-cards > .card,"), css.indexOf("{", css.indexOf(".git-cards > .card,")));
|
||||
assert.ok(rule.includes(".git-cards > .card.is-primary.has-grow"), "the board's natural-height rule outranks .has-grow");
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
const fn = js.slice(js.indexOf("function markGrowBox("), js.indexOf("function naturalHeight("));
|
||||
assert.ok(fn.includes("isGitBoard()"), "no box grows over the board");
|
||||
});
|
||||
|
||||
test("a card and its pager in the git board's card slot fill the board's width, never shrink to their content", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
// .card and .pager centre with auto inline margins; in the slot's grid those
|
||||
// would shrink a short confirm, and the pager under it, to fit their content.
|
||||
assert.match(css, /\.card\s*\{[^}]*margin:\s*0 auto/, "the base card still centres outside the board");
|
||||
@@ -733,7 +725,7 @@ test("a card and its pager in the git board's card slot fill the board's width,
|
||||
});
|
||||
|
||||
test("long task lines, long words, a narrow board and a narrow Ask pane never widen the page", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
const rule = (sel) => {
|
||||
const at = css.indexOf("\n" + sel + " {");
|
||||
assert.ok(at > -1, `${sel} has a rule`);
|
||||
@@ -750,12 +742,10 @@ test("long task lines, long words, a narrow board and a narrow Ask pane never wi
|
||||
});
|
||||
|
||||
test("over the git board a note box grows with its text, and the no-repo note only points above when a card is there", () => {
|
||||
const css = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.css"), "utf8");
|
||||
const css = joinedCss();
|
||||
assert.match(css, /\.git-cards > \.card textarea \{ field-sizing: content; max-height: 50vh; \}/);
|
||||
const view = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "git-board-view.js"), "utf8");
|
||||
const fn = view.slice(view.indexOf("export function drawGitBoard("), view.indexOf("function header("));
|
||||
assert.ok(fn.includes("ctx.hasCard"), "the note checks for a card first");
|
||||
assert.ok(fn.includes("will ask what to do here in a moment"));
|
||||
const js = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "app.js"), "utf8");
|
||||
assert.match(js, /hasCard: Boolean\(card\)/, "the host says whether a card is in the slot");
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
// Web console tests, the page's shared state: public/state.js holds what
|
||||
// every screen reads (`page`) and the hooks a screen calls instead of the
|
||||
// render loop and the draft's save. It only defines, so it imports here under
|
||||
// plain Node, page or no page.
|
||||
// Run with: node --test scripts/test-web-console-state.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { page, redraw, onRedraw, saveNow, onSave, fresh, freshChat, hooks, useHooks, stage, setDraft, bootData } from "../src/web-console/public/state.js";
|
||||
|
||||
test("state: page starts as app.js always started it", () => {
|
||||
assert.equal(page.S, null, "no server state before the first frame");
|
||||
assert.equal(page.selected, null, "no question picked");
|
||||
assert.equal(page.view, "questions", "the questions tab");
|
||||
assert.deepEqual(page.local, {
|
||||
staged: {},
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
launching: null,
|
||||
deleting: null,
|
||||
retract: {},
|
||||
chat: { draft: "", history: [], about: null, pending: [], lastSeenReplyId: null, images: [], conversation: null },
|
||||
});
|
||||
});
|
||||
|
||||
test("state: the rest of the shared state starts as app.js always started it", () => {
|
||||
const { S, local, selected, view, ...rest } = page;
|
||||
assert.deepEqual(rest, {
|
||||
agentLastSeen: null,
|
||||
pendingResult: false,
|
||||
pendingStop: false,
|
||||
pendingBannerUp: false,
|
||||
gone: false,
|
||||
chatFrame: null,
|
||||
chatDot: false,
|
||||
chatError: "",
|
||||
askRowCount: 0,
|
||||
docInView: null,
|
||||
wsFrame: null,
|
||||
meterFrame: null,
|
||||
updateFrame: null,
|
||||
subagentsFrame: null,
|
||||
overview: { key: null, text: null },
|
||||
wake: null,
|
||||
dashPick: null,
|
||||
mentionPop: null,
|
||||
heldPose: null,
|
||||
scopeMine: null,
|
||||
launchScoping: false,
|
||||
});
|
||||
});
|
||||
|
||||
test("state: fresh() and freshChat() hand out a new empty draft each time", () => {
|
||||
assert.deepEqual(fresh(), page.local);
|
||||
assert.notEqual(fresh(), fresh(), "two calls share one object");
|
||||
assert.notEqual(fresh().chat, fresh().chat, "two drafts share one chat");
|
||||
assert.deepEqual(freshChat(), page.local.chat);
|
||||
});
|
||||
|
||||
for (const [name, call, on] of [
|
||||
["redraw", redraw, onRedraw],
|
||||
["saveNow", saveNow, onSave],
|
||||
]) {
|
||||
test(`state: ${name}() does nothing until a hook is set, then calls the latest one once per call`, () => {
|
||||
assert.doesNotThrow(() => call(), `${name}() throws with no hook`);
|
||||
let first = 0;
|
||||
let second = 0;
|
||||
on(() => first++);
|
||||
call();
|
||||
call();
|
||||
assert.equal(first, 2, "each call runs the hook once");
|
||||
on(() => second++);
|
||||
call();
|
||||
assert.deepEqual([first, second], [2, 1], "a second hook replaces the first");
|
||||
});
|
||||
}
|
||||
|
||||
test("state: a hook a screen calls throws by name until start-up sets it, then runs the one set", () => {
|
||||
assert.throws(() => hooks.banner("x"), /hooks\.banner was called before start-up set it/);
|
||||
const seen = [];
|
||||
useHooks({ banner: (text) => seen.push(text) });
|
||||
hooks.banner("hello");
|
||||
assert.deepEqual(seen, ["hello"]);
|
||||
useHooks({ banner: (text) => seen.push(text + "!") });
|
||||
hooks.banner("again");
|
||||
assert.deepEqual(seen, ["hello", "again!"], "a second set replaces the first");
|
||||
assert.throws(() => hooks.unknown(), /hooks\.unknown was called/);
|
||||
});
|
||||
|
||||
test("state: stage() stages or takes back an answer, then saves and redraws; setDraft() only saves", () => {
|
||||
let saved = 0;
|
||||
let drawn = 0;
|
||||
onSave(() => saved++);
|
||||
onRedraw(() => drawn++);
|
||||
stage("q1", { k: "A" });
|
||||
assert.deepEqual(page.local.staged, { q1: { k: "A" } });
|
||||
assert.deepEqual([saved, drawn], [1, 1]);
|
||||
stage("q1", null);
|
||||
assert.deepEqual(page.local.staged, {}, "null takes the answer back");
|
||||
assert.deepEqual([saved, drawn], [2, 2]);
|
||||
setDraft("note-q1", "typed");
|
||||
assert.equal(page.local.drafts["note-q1"], "typed");
|
||||
assert.deepEqual([saved, drawn], [3, 2], "a draft is kept without a redraw");
|
||||
delete page.local.drafts["note-q1"];
|
||||
});
|
||||
|
||||
test("state: bootData() is null without a page, and asked again it says the same", () => {
|
||||
assert.equal(bootData(), null);
|
||||
assert.equal(bootData(), null);
|
||||
});
|
||||
@@ -9,7 +9,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultInstruction, offered } from "../src/web-console/public/subagents.js";
|
||||
import { readSubagentCursor } from "../src/web-console/lib.mjs";
|
||||
import { readSubagentCursor } from "../src/web-console/settings.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
HOME,
|
||||
|
||||
@@ -12,7 +12,8 @@ import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { defaultName } from "../src/web-console/public/workspace.js";
|
||||
import { meterView } from "../src/web-console/public/meter.js";
|
||||
import { readLedger, readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/lib.mjs";
|
||||
import { readLedger } from "../src/web-console/sessions.mjs";
|
||||
import { readWorkspaceCursor, WORKSPACE_FILE } from "../src/web-console/workspace.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
CONSOLE_CLI,
|
||||
|
||||
@@ -21,7 +21,7 @@ import path from "node:path";
|
||||
import { execFileSync, spawnSync } from "node:child_process";
|
||||
import http from "node:http";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { readChat } from "../src/web-console/lib.mjs";
|
||||
import { readChat } from "../src/web-console/inbox.mjs";
|
||||
|
||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -179,6 +179,14 @@ export const helpTemplate = () => {
|
||||
return tpl[1];
|
||||
};
|
||||
|
||||
// The Planny poses each skill's starting screen clones, from index.html.
|
||||
export const poseTemplate = () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const tpl = html.match(/<template id="start-poses">([\s\S]*?)<\/template>/);
|
||||
assert.ok(tpl, "index.html has the start-poses template");
|
||||
return tpl[1];
|
||||
};
|
||||
|
||||
// The server checks magic bytes only, so a JPEG header and some padding will do.
|
||||
export const JPEG = Buffer.concat([Buffer.from([0xff, 0xd8, 0xff, 0xe0]), Buffer.alloc(400, 7), Buffer.from([0xff, 0xd9])]);
|
||||
|
||||
|
||||
@@ -51,7 +51,7 @@ const UPDATE_COMMAND = 'update';
|
||||
// nothing but Node built-ins (and update-check.mjs is ESM), so it keeps its own copy.
|
||||
const REPO_URL = 'https://github.com/jparkerweb/plan2code.git';
|
||||
// The web console's cached release check, and how long it counts as fresh (update-check.mjs
|
||||
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in lib.mjs.
|
||||
// CACHE_MS). PLAN2CODE_CONSOLE_HOME moves the console's files, as in files.mjs.
|
||||
const CONSOLE_HOME = process.env.PLAN2CODE_CONSOLE_HOME || path.join(os.homedir(), '.plan2code', 'console');
|
||||
const UPDATE_CACHE_FILE = path.join(CONSOLE_HOME, 'update-check.json');
|
||||
const UPDATE_CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
@@ -15,7 +15,7 @@ import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { EXIT, consoleLib, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
|
||||
import { EXIT, consoleModule, fail, gitRepo, out, parseArgs, readText, run } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
git.mjs: read-only facts and exact commands for the Git skill. JSON on stdout.
|
||||
@@ -182,7 +182,7 @@ const remoteNames = (root) => g(["remote"], root).out.split(/\r?\n/).filter(Bool
|
||||
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
||||
|
||||
async function prHosts() {
|
||||
return (await consoleLib()).readPrHosts();
|
||||
return (await consoleModule("settings.mjs")).readPrHosts();
|
||||
}
|
||||
|
||||
function readStatus(root) {
|
||||
|
||||
@@ -33,6 +33,12 @@ The page draws the cards itself — you never send the list. It also knows the r
|
||||
|
||||
- No AGENTS.md → `recommend: "plan2code-init"`; the note says why.
|
||||
- A spec mid-pipeline → recommend its next step; that card's `details` names where it stands ("Plan drafted", "Phase 2 of 4 is next"). The picker pre-selects the most recently touched spec that is not `fixed` — recommend for THAT one.
|
||||
- `exploring` ("Exploring"): Pathfinder is next.
|
||||
- `mapped` ("Ready to plan"): Plan is next.
|
||||
- `planned` ("Ready to document"): Document is next.
|
||||
- `documented` ("Ready to build"): Implement is next.
|
||||
- `building` ("Building"): Implement is next.
|
||||
- `built` ("Ready to finalize"): Finalize is next.
|
||||
- A spec that scans `unrecognized` ("files on disk") is input, not progress: its folder rides along on a Pathfinder or Plan launch as reference, and those are the only pipeline cards it lights. Read the files and recommend the fit — a settled design doc the person wrote is Plan's brief, loose notes are Pathfinder's. No skill generates such a doc; see the table below for what each one does write. Never flag Document or anything downstream of it for such a spec.
|
||||
- A `diagnosed` spec ("Bug diagnosed") is a bug Diagnose wrote up: recommend Quick Task, or Plan when its `DIAGNOSIS-<date>.md` sizes the fix as big; its folder rides along on either launch.
|
||||
- A `fixed` spec ("Bug fixed") is a diagnosed bug Quick Task fixed but did not archive: finished, so never recommend for it or name it in the note; the picker never pre-selects one and hides it while unavailable workflows are hidden. The person archives it (Quick Task offers that once the bug is fixed) or deletes it with the picker's ✕.
|
||||
|
||||
@@ -240,30 +240,38 @@ export function scrapeHits(text) {
|
||||
|
||||
// The web console ships beside these scripts in every installed skill
|
||||
// (references/web-console/), and in this repo it sits at src/web-console/. Its
|
||||
// lib.mjs is the one home of the spec-state classifier and the loop-marker /
|
||||
// metrics-bait scan, so the scripts import it rather than keep a second copy.
|
||||
const CONSOLE_LIB_CANDIDATES = [
|
||||
path.join(HERE, "..", "references", "web-console", "lib.mjs"), // installed skill
|
||||
path.join(HERE, "..", "web-console", "lib.mjs"), // src/skill-scripts in the repo
|
||||
// scan.mjs is the one home of the spec-state classifier, and its settings.mjs
|
||||
// of the pull-request host store, so the scripts import them rather than keep
|
||||
// a second copy.
|
||||
const CONSOLE_DIR_CANDIDATES = [
|
||||
path.join(HERE, "..", "references", "web-console"), // installed skill
|
||||
path.join(HERE, "..", "web-console"), // src/skill-scripts in the repo
|
||||
];
|
||||
|
||||
let consoleLibPromise;
|
||||
export function consoleLib() {
|
||||
consoleLibPromise ||= (async () => {
|
||||
for (const candidate of CONSOLE_LIB_CANDIDATES) {
|
||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
||||
}
|
||||
fail(
|
||||
EXIT.NOT_FOUND,
|
||||
"console-lib-missing",
|
||||
`The web console's lib.mjs is not beside this script (looked in ${CONSOLE_LIB_CANDIDATES.join(", ")}).`,
|
||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
||||
const consoleModules = new Map();
|
||||
/** One of the web console's modules by file name ("scan.mjs"), imported once. */
|
||||
export function consoleModule(file) {
|
||||
if (!consoleModules.has(file)) {
|
||||
consoleModules.set(
|
||||
file,
|
||||
(async () => {
|
||||
const candidates = CONSOLE_DIR_CANDIDATES.map((dir) => path.join(dir, file));
|
||||
for (const candidate of candidates) {
|
||||
if (fs.existsSync(candidate)) return import(pathToFileURL(candidate).href);
|
||||
}
|
||||
fail(
|
||||
EXIT.NOT_FOUND,
|
||||
"console-module-missing",
|
||||
`The web console's ${file} is not beside this script (looked in ${candidates.join(", ")}).`,
|
||||
"The skill install is incomplete; reinstall the Plan2Code skills (node install.js)."
|
||||
);
|
||||
})()
|
||||
);
|
||||
})();
|
||||
return consoleLibPromise;
|
||||
}
|
||||
return consoleModules.get(file);
|
||||
}
|
||||
|
||||
// The one read-only git reader (git-repo.mjs) ships beside lib.mjs, so the git
|
||||
// The one read-only git reader (git-repo.mjs) ships beside scan.mjs, so the git
|
||||
// skill's scripts read the repository with exactly the code the console uses.
|
||||
const GIT_REPO_CANDIDATES = [
|
||||
path.join(HERE, "..", "references", "web-console", "git-repo.mjs"), // installed skill
|
||||
|
||||
@@ -14,7 +14,7 @@
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleLib, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
|
||||
import { EXIT, fail, out, parseArgs, run, readText, isDir, rel, eol, consoleModule, isoDate, phaseFiles, LOOP_TOKENS, scrapeHits } from "./common.mjs";
|
||||
|
||||
const USAGE = `
|
||||
specs.mjs: spec state for the Plan2Code pipeline skills. JSON on stdout.
|
||||
@@ -500,7 +500,7 @@ function nextPhase(phases, groups, haveChecklist, leftovers = []) {
|
||||
|
||||
async function cmdList(args) {
|
||||
const root = path.resolve(args.root || ".");
|
||||
const { scanProject } = await consoleLib();
|
||||
const { scanProject } = await consoleModule("scan.mjs");
|
||||
const scan = scanProject(root);
|
||||
const specs = scan.specs.map((s) => {
|
||||
const dir = path.join(root, s.dir);
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
// Plan2Code Web Console - the `chat` command: hand over Quick questions now, never waiting.
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import { readJson } from "./files.mjs";
|
||||
import { healthOk, listHandles, pidAlive, terminalLine } from "./sessions.mjs";
|
||||
import { chatReplyLines, collectChat, deliverableChat } from "./inbox.mjs";
|
||||
import { pendingWorkspaceChanges } from "./workspace.mjs";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
import { withSubagents, advanceSubagents, serverGone, advanceCursor, advanceWorkspace } from "./cmd-post-wait.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
let print, mustSession, sessionProject;
|
||||
export function useCli(cli) {
|
||||
({ print, mustSession, sessionProject } = cli);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- chat */
|
||||
|
||||
// The instant check a build makes between tasks. Never sleeps, and never
|
||||
// touches result.json: card sends stay with `wait`.
|
||||
export async function cmdChat() {
|
||||
const dir = mustSession();
|
||||
const sid = path.basename(dir);
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === sid);
|
||||
if (!handle || !pidAlive(handle.pid) || !(await healthOk(handle))) {
|
||||
print(serverGone(sid));
|
||||
process.exitCode = 20;
|
||||
return;
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
// Plan2Code Web Console - the `help` command: the CLI's usage and the contract's topic files.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { HERE } from "./files.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
let args, print, die;
|
||||
export function useCli(cli) {
|
||||
({ args, print, die } = cli);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
export function cmdHelp() {
|
||||
const topic = args._[0];
|
||||
if (topic !== undefined) return helpTopic(String(topic));
|
||||
process.stdout.write(`console.mjs — the Plan2Code web console. A detached server, a loopback
|
||||
port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
|
||||
open [--file <payload.json>] [--workflow <w>] [--title "<t>"] [--spec <dir>]
|
||||
[--session|--resume <sid>] [--no-open] [--idle-ms <ms>]
|
||||
Start or resume a session and its server. Prints { ok, sid, session,
|
||||
url, terminalLine }, plus swept { sessions, scratch, handoffs } when
|
||||
old sessions, scratch files or handoffs were removed. Run it FIRST, before
|
||||
reading anything: the page shows a starting screen until your
|
||||
first post. --file is optional, and --title defaults to the
|
||||
project's folder name. Also prints workspace: { folders: [{ name,
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json | -> [--wait <N>]
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. --wait <N>
|
||||
then waits up to N seconds in the same command (two JSON lines;
|
||||
the exit code is the wait's). The patch may carry settle: true
|
||||
(or a list of item ids) to mark the latest send's cards answered
|
||||
with what was sent; doc blocks may carry file: "<path>" (and
|
||||
select: "tasks"), read from the project, and a doc refresh: true
|
||||
re-reads them. A doc's version moves up by itself. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(help subagents).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
in the web console"; call again), 20 = server gone (open --resume
|
||||
<sid>), 30 = cancelled. Exits 0 and 10 carry terminalLine.
|
||||
Exit 0 may carry "chat" (Quick questions); with no card send it
|
||||
is type: "chat" and actions is empty. Exit 0 may also carry
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either. A hop
|
||||
(__launch, __dashboard, __commit) carries resume, the exact
|
||||
open --resume command, and skillFile when installed. Collecting
|
||||
a send sets the page to working; a wait with a question open
|
||||
hands the turn back.
|
||||
chat --session <sid>
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
Copy a cited note attachment into specs/<idea>/attachments/. Prints
|
||||
{ ok, path, link, image, reused }; exit 2 = bad usage, 3 = refused or
|
||||
missing. Paste link as it is.
|
||||
forget --spec specs/<idea>
|
||||
Drop the workspace folders remembered for that spec, in this
|
||||
folder (Finalize, after archiving it). Prints { ok, spec, forgot };
|
||||
forgot is false when nothing was saved. Exit 2 = bad usage.
|
||||
delete-spec --spec specs/<name>
|
||||
Delete that spec folder for good (the dashboard's Delete button, a
|
||||
__delete action). Only an existing specs/<name> folder inside this
|
||||
worktree: never a link, never deeper, never specs--completed/.
|
||||
Prints { ok, removed }; exit 2 = bad usage, 3 = refused, with
|
||||
{ ok: false, message } saying why. Nothing is touched on a refusal.
|
||||
handoff new --workflow <w> --skill <s> [--spec specs/<name>] [--title "<t>"] [--from-stop]
|
||||
Claim a handoff for this checkout in ~/.plan2code/handoffs/ (Stop
|
||||
with a handoff, the Handoff skill). Writes only <id>.json; you write
|
||||
the document at path. Prints { ok, id, path, meta }; exit 2 = bad
|
||||
usage, 3 = a bad value, with { ok: false, message } saying why.
|
||||
delete-handoff --handoff <id>
|
||||
Delete that handoff for good (a Handoff chip's Delete, a __delete
|
||||
action): <id>.md and <id>.json, only in ~/.plan2code/handoffs/,
|
||||
never a link. Prints { ok, removed }; exit 2 = bad usage, 3 =
|
||||
refused, with { ok: false, message } saying why. Nothing is touched
|
||||
on a refusal.
|
||||
status [--session <sid>] [--all]
|
||||
One session, or (--all) every session on this machine, every project.
|
||||
stop --session <sid> | --all
|
||||
Shut a session's server down. Always post finish first.
|
||||
|
||||
workflows: dashboard · init · init-update · pathfinder · quick-task · plan ·
|
||||
revise-plan · document · implement · implement-review · review ·
|
||||
finalize · handoff · git · changelog · xray · diagnose
|
||||
|
||||
A session handed to you by the dashboard (a --session id): resume it with
|
||||
"open --resume <sid> --no-open --workflow <yours>" (the resume it carries) -- never a
|
||||
fresh "open", which would strand the page the person is watching.
|
||||
|
||||
The contract is console.md beside this file, read once; the rest is
|
||||
read when its moment comes. help <topic> prints one; help topics lists
|
||||
them. Build sessions (implement, implement-review, quick-task) also read
|
||||
building.md.
|
||||
`);
|
||||
}
|
||||
|
||||
// The contract's topic files, by the name console.md's index gives them.
|
||||
// Printing one saves an agent the path hunt: it already runs this CLI.
|
||||
export const HELP_TOPICS = {
|
||||
console: "console.md",
|
||||
building: "building.md",
|
||||
"building-review": "building-review.md",
|
||||
finish: "console-finish.md",
|
||||
stop: "console-stop.md",
|
||||
attachments: "console-attachments.md",
|
||||
chat: "console-chat.md",
|
||||
workspace: "console-workspace.md",
|
||||
subagents: "console-subagents.md",
|
||||
launches: "console-launches.md",
|
||||
dashboard: "console-launches.md",
|
||||
meter: "console-meter.md",
|
||||
trouble: "console-trouble.md",
|
||||
};
|
||||
for (const f of fs.existsSync(path.join(HERE, "notes")) ? fs.readdirSync(path.join(HERE, "notes")) : []) {
|
||||
if (f.endsWith(".md")) HELP_TOPICS[f.slice(0, -3)] ??= `notes/${f}`;
|
||||
}
|
||||
HELP_TOPICS["init-update"] ??= HELP_TOPICS.init;
|
||||
HELP_TOPICS["implement-review"] ??= HELP_TOPICS.implement;
|
||||
|
||||
function helpTopic(topic) {
|
||||
const names = Object.keys(HELP_TOPICS).sort();
|
||||
if (topic === "topics") {
|
||||
print({ topics: Object.fromEntries(names.map((n) => [n, HELP_TOPICS[n]])) });
|
||||
return;
|
||||
}
|
||||
const file = Object.hasOwn(HELP_TOPICS, topic) ? HELP_TOPICS[topic] : null;
|
||||
if (!file) die(`no help topic "${topic}". Topics: ${names.join(", ")}`, 2);
|
||||
process.stdout.write(fs.readFileSync(path.join(HERE, file), "utf8"));
|
||||
}
|
||||
@@ -0,0 +1,650 @@
|
||||
// Plan2Code Web Console - the `open` command: start or resume a session, its server and the browser.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
import { HERE, HOME_DIR, SESSIONS_DIR, appendEvent, ensureDir, nowIso, readJson, updateState } from "./files.mjs";
|
||||
import {
|
||||
appendLedger,
|
||||
bindLoopback,
|
||||
handOff,
|
||||
handleFile,
|
||||
healthOk,
|
||||
listHandles,
|
||||
newSessionId,
|
||||
newToken,
|
||||
nextLaunchId,
|
||||
pidAlive,
|
||||
readLedger,
|
||||
reapHandles,
|
||||
remoteWarning,
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
staleScratch,
|
||||
staleSessions,
|
||||
sweepUploads,
|
||||
terminalLine,
|
||||
UPLOAD_MAX_AGE_MS,
|
||||
} from "./sessions.mjs";
|
||||
import { scanProject } from "./scan.mjs";
|
||||
import {
|
||||
applyPatch,
|
||||
blankState,
|
||||
isOpen,
|
||||
switchWorkflow,
|
||||
resolveDocFiles,
|
||||
resolveDocImages,
|
||||
validate,
|
||||
} from "./patches.mjs";
|
||||
import {
|
||||
initialWorkspace,
|
||||
readWorkspace,
|
||||
rememberedWorkspace,
|
||||
workspaceForAgent,
|
||||
writeWorkspaceCursor,
|
||||
} from "./workspace.mjs";
|
||||
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
|
||||
import {
|
||||
readPatch,
|
||||
failValidation,
|
||||
liftReread,
|
||||
gitBlock,
|
||||
ledgerFromPost,
|
||||
awaitSubagentSync,
|
||||
withSubagents,
|
||||
advanceSubagents,
|
||||
} from "./cmd-post-wait.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
let args, print, die;
|
||||
export function useCli(cli) {
|
||||
({ args, print, die } = cli);
|
||||
}
|
||||
|
||||
// PLAN2CODE_CONSOLE_TRACE=1 prints where the time goes, to stderr: the
|
||||
// start path is what stands between someone and their first look at the page,
|
||||
// and it is only worth optimising with numbers in hand.
|
||||
const TRACE = Boolean(process.env.PLAN2CODE_CONSOLE_TRACE);
|
||||
function trace(what) {
|
||||
if (TRACE) process.stderr.write(`trace ${Math.round(performance.now())}ms ${what}\n`);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- open */
|
||||
|
||||
// Cache this console's directory where a later agent session can find it.
|
||||
// HOME_DIR is fixed (~/.plan2code/console, or $PLAN2CODE_CONSOLE_HOME), so
|
||||
// console-dir there is a stable place to look: the next skill that offers the
|
||||
// console points its agent at the file rather than making it search the skill
|
||||
// install dirs again. Written by `open` alone, which starts every session: a
|
||||
// `wait` or a `post` every few seconds need not rewrite it each time.
|
||||
function leavePointer() {
|
||||
try {
|
||||
ensureDir(HOME_DIR);
|
||||
fs.writeFileSync(path.join(HOME_DIR, "console-dir"), HERE + "\n");
|
||||
} catch {
|
||||
/* a pointer we cannot leave costs nothing */
|
||||
}
|
||||
}
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
leavePointer();
|
||||
const { project, worktree, branch } = repoRoots();
|
||||
reapHandles(project);
|
||||
trace("open: project found");
|
||||
|
||||
let sid = args.resume || args.session;
|
||||
let dir;
|
||||
let state;
|
||||
// A new skill run for the meter: a fresh open, or a resume into another workflow.
|
||||
let launched = true;
|
||||
// Everything `open` does to a stored state, as a step it can take twice:
|
||||
// once now, on the read below, so a bad payload is refused before anything
|
||||
// starts, and again on a fresh read under the state lock when it writes, so
|
||||
// a send the person made in between is kept rather than written over.
|
||||
let reshape = (s) => s;
|
||||
|
||||
if (sid) {
|
||||
sid = path.basename(sid);
|
||||
dir = sessionDir(sid);
|
||||
if (!fs.existsSync(dir)) die(`no session "${sid}" to resume`, 1);
|
||||
state = readJson(path.join(dir, "state.json"));
|
||||
if (!state) die(`session "${sid}" has no state`, 1);
|
||||
// A resume can also be a hand-off: the dashboard launches another skill
|
||||
// into its own session, and the first thing that skill needs is for the
|
||||
// page to stop being a dashboard. Letting the flags restate these fields
|
||||
// on resume means one command both reuses the server and turns the page,
|
||||
// rather than a resume plus a whole extra post.
|
||||
const switching = args.workflow && args.workflow !== state.workflow;
|
||||
launched = Boolean(switching);
|
||||
// Going through the dashboard is a fresh start: a skill launched from
|
||||
// the menu gets a clean page, not the last skill's questions and tabs
|
||||
// under its own name. The staged draft goes too, since its item ids
|
||||
// belonged to the old questions. Git counts as a launch from anywhere:
|
||||
// Commit it now on a finished screen and Changelog's "Commit this now?"
|
||||
// both stand in for its dashboard card, and a finish left
|
||||
// behind would keep the page on the old ending above the new questions
|
||||
// (or the new board). A hop also drops the last run's state.git, since
|
||||
// switchWorkflow() starts from a blank state.
|
||||
// A skill run inline from another (a quick task's review) never switches
|
||||
// through here, so it keeps the page.
|
||||
const hop =
|
||||
switching &&
|
||||
(args.workflow === "dashboard" ||
|
||||
state.workflow === "dashboard" ||
|
||||
args.workflow === "git");
|
||||
if (hop) fs.rmSync(path.join(dir, "draft.json"), { force: true });
|
||||
reshape = (s) => {
|
||||
// Resuming takes a pause back down. A paused finish is a bookmark --
|
||||
// "saved here, pick it up later" -- and picking it up is exactly what
|
||||
// this is. Left in place, the page keeps saying PAUSED over every
|
||||
// question the resumed session asks, because `finish` is a scalar and
|
||||
// only an explicit `finish: null` patch clears it. A real ending is
|
||||
// different: re-sharing a finished session's link should still show its
|
||||
// card, so only a headline that says "paused" comes down. Done before
|
||||
// --file applies, so a patch can still post a finish of its own.
|
||||
if (s.finish && /^\s*paused\b/i.test(String(s.finish.headline || ""))) {
|
||||
delete s.finish;
|
||||
// A new agent picking the session up: its own working turn, timed
|
||||
// from now, not the paused run's last status.
|
||||
s.agent = { status: "working", since: nowIso() };
|
||||
// The old run's warning about what a stop would lose is about its
|
||||
// unsaved work; the new run posts its own when it has some.
|
||||
delete s.stopWarning;
|
||||
// So is its count: the open questions it counted are dropped below,
|
||||
// and the page falls back to its own tally until the new run posts.
|
||||
s.headline = { stage: "", cleared: 0, total: 0, confidence: "", note: "" };
|
||||
// The questions still open at the pause were the old session's asks,
|
||||
// already narrated in the finish body so the next session can name
|
||||
// them. Whatever the resumed session still needs it asks again, in its
|
||||
// own words -- kept, the leftovers sit beside the new asks as
|
||||
// duplicates nobody owns. Settled items stay: they are the record.
|
||||
s.items = (s.items || []).filter((i) => !isOpen(i));
|
||||
// And the topics that only the dropped items lived under, so a new
|
||||
// item reusing an old topic id does not inherit a stale title.
|
||||
const liveTopics = new Set(s.items.map((i) => i.topic));
|
||||
s.topics = (s.topics || []).filter((t) => liveTopics.has(t.id));
|
||||
}
|
||||
if (hop) {
|
||||
s = switchWorkflow(s, {
|
||||
workflow: args.workflow,
|
||||
title: typeof args.title === "string" ? args.title : path.basename(worktree),
|
||||
specDir: args.spec,
|
||||
});
|
||||
} else if (switching) s.workflow = args.workflow;
|
||||
if (args.title) s.title = args.title;
|
||||
if (args.spec) s.specDir = args.spec;
|
||||
// Every resume clears the wake-up flag: a server restart, a launch from
|
||||
// the dashboard, a Back-to-dashboard return. Cleared here rather than by
|
||||
// the page because the page cannot write state, and a replay on a return
|
||||
// is exactly what the decision rules out.
|
||||
delete s.wake;
|
||||
return s;
|
||||
};
|
||||
} else {
|
||||
sid = newSessionId();
|
||||
// Named, not made: the folder is created once --file has passed, so a
|
||||
// rejected first payload leaves no empty session behind for nothing to sweep.
|
||||
dir = sessionDir(sid);
|
||||
state = blankState({
|
||||
sid,
|
||||
project,
|
||||
workflow: args.workflow,
|
||||
// Until the agent knows what the session is about, the folder it runs
|
||||
// in is the honest name, and it lets `open` go before any thinking.
|
||||
title: typeof args.title === "string" ? args.title : path.basename(worktree),
|
||||
specDir: args.spec,
|
||||
});
|
||||
// Only a freshly opened dashboard plays Planny's wake-up.
|
||||
if (args.workflow === "dashboard") state.wake = true;
|
||||
}
|
||||
|
||||
// A first payload's meter and folder reports, as `post` takes them: checked
|
||||
// now, before anything is written, and appended once the launch is.
|
||||
let openRun;
|
||||
let openIssue;
|
||||
let openReread;
|
||||
let patch = null;
|
||||
if (args.file) {
|
||||
patch = readPatch(args.file);
|
||||
if (!patch) die(`could not read --file ${args.file} as one JSON object`, 2);
|
||||
({ run: openRun, folderIssue: openIssue } = patch);
|
||||
delete patch.run;
|
||||
delete patch.folderIssue;
|
||||
openReread = liftReread(patch, args.workflow || state.workflow);
|
||||
}
|
||||
const base = reshape;
|
||||
if (patch) {
|
||||
// Against the page as this open leaves it (a hop starts blank), so a
|
||||
// refresh never re-reads the last skill's files into the new page.
|
||||
try {
|
||||
patch = resolveDocFiles(patch, base(structuredClone(state)), worktree);
|
||||
patch = resolveDocImages(patch, base(structuredClone(state)), dir);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
}
|
||||
const settle = (s) => {
|
||||
s = base(s);
|
||||
// On every open, so a resume from another worktree refreshes both.
|
||||
s.worktree = worktree;
|
||||
s.branch = branch;
|
||||
return s;
|
||||
};
|
||||
reshape = (s) => (patch ? applyPatch(settle(s), patch) : settle(s));
|
||||
state = settle(state);
|
||||
if (patch) {
|
||||
ledgerFromPost(dir, openRun, openIssue, state.workflow);
|
||||
try {
|
||||
state = applyPatch(state, patch);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
const problems = validate(state);
|
||||
if (problems.length) return failValidation(problems);
|
||||
}
|
||||
ensureDir(dir);
|
||||
|
||||
// A fresh session needs a fresh server, and a server is a whole Node boot:
|
||||
// the slowest thing `open` does, bar the browser. Start both now, before
|
||||
// the scan and the state write, so their start-up runs alongside them
|
||||
// instead of after. The server does look at the state as it boots, and on
|
||||
// a fresh session finds none yet: it takes the worktree from its command
|
||||
// line, not from the state, and picks the state up on its first request or
|
||||
// poll tick. No page can reach it before it is listening, and the state is
|
||||
// on disk long before a browser gets there.
|
||||
const existing = sid && (args.resume || args.session) ? listHandles(project).find((h) => h.sid === sid) : null;
|
||||
// A live pid gets a second, longer look before it is given up on, as `stop`
|
||||
// gives one: a server busy right after a post can miss the first, and a
|
||||
// second server for the same session strands the page on the first.
|
||||
const reusable =
|
||||
existing && pidAlive(existing.pid)
|
||||
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
|
||||
: Promise.resolve(false);
|
||||
let boot = null;
|
||||
if (!existing) boot = await startServer(project, worktree, sid, dir);
|
||||
|
||||
// The dashboard's spec picker reads its inventory straight off the session
|
||||
// state, so the scan belongs to `open` rather than to the agent: filesystem
|
||||
// facts, recomputed every time the session becomes (or stays) a dashboard,
|
||||
// never something a model has to remember to fetch. Rooted at the worktree's
|
||||
// own top level: `project` is the common-dir key so linked worktrees share
|
||||
// sessions, but each shows the specs on its own disk.
|
||||
const scan = state.workflow === "dashboard" ? scanProject(worktree) : null;
|
||||
// This checkout's unused handoffs live outside every repo (handoffs.mjs), so
|
||||
// they join the scan here and not in scanProject(), which also serves
|
||||
// `specs.mjs list`. handoffsDir rides along so the page never guesses it.
|
||||
if (scan) {
|
||||
scan.handoffs = listHandoffs(worktree);
|
||||
scan.handoffsDir = handoffsDir();
|
||||
}
|
||||
// The git board's data, the same way: the console's own read-only snapshot
|
||||
// (git-repo.mjs), taken before the lock so no git process runs under it.
|
||||
const gitSnap = state.workflow === "git" ? snapshot(worktree, { prHosts: readPrHosts() }) : null;
|
||||
|
||||
// Under the state lock, which a send on the page takes too: the result and
|
||||
// the state are read fresh here and the state is rebuilt from that read, so
|
||||
// nothing the person sent since the read above is lost or stamped over.
|
||||
let carried = false;
|
||||
let written;
|
||||
try {
|
||||
written = updateState(dir, (fresh) => {
|
||||
const next = fresh ? reshape(fresh) : state;
|
||||
if (scan) next.scan = scan;
|
||||
// A launch or hop starts the board fresh; a plain resume (a server
|
||||
// restart) keeps the last word on whether a Refresh failed.
|
||||
if (gitSnap) next.git = launched ? gitBlock(gitSnap, openReread ?? { refreshFailed: false }) : gitBlock(gitSnap, openReread, fresh?.git);
|
||||
|
||||
// Clear a result the agent already collected, and ONLY that one.
|
||||
//
|
||||
// An unconsumed result is answers a person pressed Send on that nobody has
|
||||
// picked up yet. Deleting it here is exactly the documented crash-recovery
|
||||
// case ("your session died, press Send anyway, the next session picks it
|
||||
// up") and deleting it destroys their work silently.
|
||||
const resultPath = path.join(dir, "result.json");
|
||||
const waiting = readJson(resultPath);
|
||||
if (waiting && waiting.consumedAt) fs.rmSync(resultPath, { force: true });
|
||||
carried = Boolean(waiting && !waiting.consumedAt);
|
||||
|
||||
// Do not stamp over "submitted" either: the phase is how the page knows a
|
||||
// send is still in flight.
|
||||
if (!carried) next.phase = "collecting";
|
||||
return next;
|
||||
});
|
||||
} catch (e) {
|
||||
written = { error: e.message };
|
||||
}
|
||||
if (!written || written.error) {
|
||||
// A server just started for this state would only serve a page that never starts.
|
||||
if (boot) boot.kill();
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
// issues the page shows reset with every skill run. Never fatal: the meter
|
||||
// is advice, and the page must not wait on it.
|
||||
try {
|
||||
if (launched) appendLedger(dir, { kind: "launch", id: nextLaunchId(readLedger(dir)), workflow: state.workflow });
|
||||
for (const line of ledgerFromPost(dir, openRun, openIssue, state.workflow)) appendLedger(dir, line);
|
||||
} catch {}
|
||||
const workspace = workspaceOnOpen(dir, worktree, state.specDir);
|
||||
|
||||
// Month-old sessions and scratch files: listed before the print so the
|
||||
// agent can see what went, removed after it so the page waits for nothing.
|
||||
// Nothing about this reaches the page.
|
||||
const sweptSessions = staleSessions(SESSIONS_DIR, Date.now(), SESSION_MAX_AGE_MS, sid);
|
||||
const sweptScratch = staleScratch(HOME_DIR, Date.now(), SESSION_MAX_AGE_MS);
|
||||
const sweptHandoffs = staleHandoffs(Date.now(), SESSION_MAX_AGE_MS);
|
||||
const swept =
|
||||
sweptSessions.length || sweptScratch.length || sweptHandoffs.length
|
||||
? { swept: { sessions: sweptSessions, scratch: sweptScratch, handoffs: sweptHandoffs } }
|
||||
: {};
|
||||
const sweep = () => {
|
||||
sweepUploads(SESSIONS_DIR, Date.now(), UPLOAD_MAX_AGE_MS, sid).catch(() => {});
|
||||
removeSessions(SESSIONS_DIR, sweptSessions).catch(() => {});
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
removeHandoffs(sweptHandoffs).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
session: dir,
|
||||
url: existing.url,
|
||||
reused: true,
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
|
||||
// A handle whose pid is alive but is not ours (the pid was reused) leaves
|
||||
// this for last: nothing could be started until that was known.
|
||||
let started = boot || (await startServer(project, worktree, sid, dir));
|
||||
let handle = await awaitHandle(started);
|
||||
if (!handle && started.handoff) {
|
||||
// The handover went wrong somewhere (a platform that will not pass the
|
||||
// socket, a server that died taking it). Once more the old way, where
|
||||
// the server binds its own port: slower, and certain.
|
||||
started.kill();
|
||||
started = await startServer(project, worktree, sid, dir, { handoff: false });
|
||||
handle = await awaitHandle(started);
|
||||
}
|
||||
if (!handle) {
|
||||
const log = tail(path.join(dir, "server.log"), 12);
|
||||
die(`the console server did not start within 8s.\n${log}`, 1);
|
||||
}
|
||||
trace("open: server listening");
|
||||
// Unref'd, or the cap itself would hold the process open for its full span.
|
||||
await Promise.race([started.released, new Promise((r) => setTimeout(r, 2000).unref())]);
|
||||
trace("open: socket handed over");
|
||||
|
||||
// The early tab went to the port `open` bound. If the server ended up
|
||||
// anywhere else, that tab is a dead end, so send the browser to the real one.
|
||||
if (!args["no-open"] && handle.url !== started.opened) openBrowser(handle.url);
|
||||
const remote = remoteWarning();
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
session: dir,
|
||||
url: handle.url,
|
||||
port: handle.port,
|
||||
pid: handle.pid,
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||
* match: the agent now has the whole list, so no change up to here is owed.
|
||||
* Read-only on workspace.json, which only the server writes; on a fresh
|
||||
* session the server has not made it yet, so what was remembered for this
|
||||
* folder and spec stands in, the same list the server is about to make.
|
||||
*/
|
||||
function workspaceOnOpen(dir, worktree, specDir) {
|
||||
const ws = readWorkspace(dir) || initialWorkspace(worktree, rememberedWorkspace(worktree, specDir).entry);
|
||||
const missing = ws.folders.filter((f) => !isFolder(f.path)).map((f) => f.id);
|
||||
try {
|
||||
writeWorkspaceCursor(dir, ws.version || 0);
|
||||
} catch {}
|
||||
return workspaceForAgent({ ...ws, missing });
|
||||
}
|
||||
|
||||
function isFolder(p) {
|
||||
try {
|
||||
return fs.statSync(p).isDirectory();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Start a detached server for the session, and the browser with it.
|
||||
*
|
||||
* The browser is the slowest thing in the whole start: from `start <url>` to
|
||||
* its first request is most of a second on Windows, far longer than the
|
||||
* server takes to boot. So the port is bound HERE, the link exists while the
|
||||
* server is still booting, and the browser is sent at once. The bound socket
|
||||
* is then handed to the server over an IPC channel; a request that arrives
|
||||
* before the handover waits in the socket's queue, and one this process
|
||||
* happened to accept is passed across as a socket of its own. Nothing the
|
||||
* browser sends is refused or lost on the way.
|
||||
*
|
||||
* The order is timed. The server is spawned first, because its boot is the
|
||||
* longest step the agent waits on. The bind comes next and overlaps that
|
||||
* boot: a process's first listen() blocks for ~50ms on Windows while the
|
||||
* socket stack loads, which is time the server spends booting anyway.
|
||||
*/
|
||||
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
|
||||
const token = newToken();
|
||||
const handlePath = handleFile(project, sid);
|
||||
ensureDir(path.dirname(handlePath));
|
||||
fs.rmSync(handlePath, { force: true });
|
||||
|
||||
const logFd = fs.openSync(path.join(dir, "server.log"), "a");
|
||||
const child = spawn(
|
||||
process.execPath,
|
||||
[
|
||||
path.join(HERE, "server.mjs"),
|
||||
// Always `--flag=value`, never two words: a base64url token can start
|
||||
// with "--", and parseArgs would read it as the next flag and leave the
|
||||
// server with `token: true`. The paths get the same form for the same reason.
|
||||
`--session=${dir}`,
|
||||
`--token=${token}`,
|
||||
`--project=${project}`,
|
||||
// The checkout the session runs in, which the state does not hold yet
|
||||
// on a fresh open. See WORKTREE in server.mjs.
|
||||
`--worktree=${worktree}`,
|
||||
...(handoff ? ["--handoff"] : []),
|
||||
...(args["idle-ms"] ? [`--idle-ms=${args["idle-ms"]}`] : []),
|
||||
],
|
||||
{
|
||||
// Detached, because harness-managed background tasks get killed at
|
||||
// assorted timeouts and on compaction, which would take the human's
|
||||
// half-finished answers with them. Detached processes are immune.
|
||||
detached: true,
|
||||
// Redirecting stdio to a file is what lets the child outlive us. The
|
||||
// IPC channel is only for the handover, and is closed straight after.
|
||||
stdio: ["ignore", logFd, logFd, ...(handoff ? ["ipc"] : [])],
|
||||
// windowsHide defaults to FALSE, and `detached` on Windows gives the
|
||||
// child its own console window which "once enabled, cannot be disabled".
|
||||
// Omit this and every handoff flashes a black box at the user.
|
||||
windowsHide: true,
|
||||
}
|
||||
);
|
||||
fs.closeSync(logFd);
|
||||
let exited = false;
|
||||
child.on("exit", () => (exited = true));
|
||||
child.on("error", () => (exited = true));
|
||||
trace("open: server spawned");
|
||||
|
||||
let opened = null;
|
||||
let released = Promise.resolve();
|
||||
if (handoff) {
|
||||
const pre = await bindLoopback();
|
||||
trace("open: port bound");
|
||||
// No socket to give (the bind failed): the server binds its own, and the
|
||||
// channel is let go once it has.
|
||||
released = handOff(child, pre);
|
||||
if (pre && !args["no-open"]) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
|
||||
} else child.unref();
|
||||
// Each spawn blocks for a moment (tens of ms for cmd.exe on Windows), so
|
||||
// the browser's comes after the server's: the server's boot is what the
|
||||
// agent waits on, and the browser's lead is most of a second regardless.
|
||||
if (opened) {
|
||||
openBrowser(opened);
|
||||
trace("open: browser sent");
|
||||
}
|
||||
return {
|
||||
handlePath,
|
||||
handoff,
|
||||
opened,
|
||||
released,
|
||||
dead: () => exited,
|
||||
kill: () => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Learn the port by waiting for the handle file, not by parsing stdout:
|
||||
// stdout went to the log file, and the file handshake is race-free and is
|
||||
// the same code path the reap sweep uses. Checked every 10ms: the file is
|
||||
// tiny, and a coarse tick here is dead time added to every first paint.
|
||||
// Null when the server died first, or never showed up.
|
||||
async function awaitHandle(started) {
|
||||
const deadline = Date.now() + 8000;
|
||||
while (Date.now() < deadline) {
|
||||
const handle = readJson(started.handlePath);
|
||||
if (handle && handle.url) return handle;
|
||||
if (started.dead()) return null;
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function tail(file, lines) {
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8").split("\n").slice(-lines).join("\n");
|
||||
} catch {
|
||||
return "(no server log)";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Best-effort, never fatal. If we cannot open a browser we still printed the URL,
|
||||
* and the URL is the primary channel.
|
||||
*/
|
||||
function openBrowser(url) {
|
||||
try {
|
||||
if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return;
|
||||
// Do not try from a place where there is no browser to open.
|
||||
if (process.env.SSH_CONNECTION || process.env.REMOTE_CONTAINERS) return;
|
||||
|
||||
// A browser of their choosing: a command line, run through the shell,
|
||||
// with the link appended. The token is base64url, so the quoted link
|
||||
// carries nothing a shell would read.
|
||||
const custom = process.env.PLAN2CODE_BROWSER;
|
||||
if (custom) {
|
||||
spawn(`${custom} "${url}"`, { shell: true, detached: true, stdio: "ignore", windowsHide: true }).unref();
|
||||
return;
|
||||
}
|
||||
|
||||
const plat = process.platform;
|
||||
if (plat === "win32") {
|
||||
// The empty "" is the mandatory window-title argument: omit it and
|
||||
// `start` treats a quoted URL as the title and opens nothing.
|
||||
spawn(process.env.COMSPEC || "cmd.exe", ["/d", "/s", "/c", "start", '""', `"${url}"`], {
|
||||
windowsVerbatimArguments: true,
|
||||
detached: true,
|
||||
stdio: "ignore",
|
||||
windowsHide: true,
|
||||
}).unref();
|
||||
return;
|
||||
}
|
||||
if (plat === "darwin") {
|
||||
spawn("open", [url], { detached: true, stdio: "ignore" }).unref();
|
||||
return;
|
||||
}
|
||||
// Linux and friends. WSL first: xdg-open there either is absent or opens a
|
||||
// Linux browser that cannot reach the Windows host.
|
||||
if (isWsl()) {
|
||||
const exe = which("wslview") ? "wslview" : "powershell.exe";
|
||||
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
|
||||
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
|
||||
return;
|
||||
}
|
||||
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return; // headless
|
||||
spawn(process.env.BROWSER || "xdg-open", [url], { detached: true, stdio: "ignore" }).unref();
|
||||
} catch {
|
||||
/* never fatal */
|
||||
}
|
||||
}
|
||||
|
||||
function isWsl() {
|
||||
if (process.platform !== "linux") return false;
|
||||
try {
|
||||
return /microsoft/i.test(fs.readFileSync("/proc/version", "utf8"));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function which(bin) {
|
||||
const dirs = (process.env.PATH || "").split(path.delimiter);
|
||||
return dirs.some((d) => {
|
||||
try {
|
||||
fs.accessSync(path.join(d, bin), fs.constants.X_OK);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,676 @@
|
||||
// Plan2Code Web Console - `post` and `wait`: publish a patch, then collect what the person sent.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { HERE, appendEvent, fileStamp, nowIso, readJson, sleepSync, updateState, writeJsonAtomic } from "./files.mjs";
|
||||
import {
|
||||
appendLedger,
|
||||
healthOk,
|
||||
lastLaunchId,
|
||||
listHandles,
|
||||
pidAlive,
|
||||
readLedger,
|
||||
repoRoots,
|
||||
terminalLine,
|
||||
} from "./sessions.mjs";
|
||||
import { applyPatch, isOpen, proseProblems, resolveDocFiles, resolveDocImages, validate } from "./patches.mjs";
|
||||
import {
|
||||
CHAT_FILE,
|
||||
chatReplyLines,
|
||||
collectChat,
|
||||
deliverableChat,
|
||||
unansweredChat,
|
||||
readChat,
|
||||
validateChat,
|
||||
writeCursor,
|
||||
} from "./inbox.mjs";
|
||||
import { pendingWorkspaceChanges, writeWorkspaceCursor } from "./workspace.mjs";
|
||||
import { readPrHosts, readSubagentCursor, readSubagentSetting, writeSubagentCursor } from "./settings.mjs";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { handoffsDir, isHandoffId, markHandoffUsed, readHandoffMeta } from "./handoffs.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_COMMITS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
let args, print, die, mustSession, sessionProject;
|
||||
export function useCli(cli) {
|
||||
({ args, print, die, mustSession, sessionProject } = cli);
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- post */
|
||||
|
||||
// A patch from a file, or from stdin with `--file -`: a heredoc piped into
|
||||
// the command saves the agent writing a file first, one tool call a turn.
|
||||
// A file PowerShell wrote comes with a BOM (Out-File / Set-Content in 5.1) or
|
||||
// in UTF-16 (its `>`), and both are the documented Windows route, so both read.
|
||||
export function readPatch(file) {
|
||||
try {
|
||||
const buf = fs.readFileSync(file === "-" ? 0 : path.resolve(file));
|
||||
let text;
|
||||
if (buf[0] === 0xff && buf[1] === 0xfe) text = buf.subarray(2).toString("utf16le");
|
||||
else if (buf[0] === 0xfe && buf[1] === 0xff) text = Buffer.from(buf.subarray(2)).swap16().toString("utf16le");
|
||||
else text = buf.toString("utf8");
|
||||
// A patch is one JSON object: an array, string or number would merge
|
||||
// into the state as junk keys ("0", "1"...) and still report ok.
|
||||
const patch = JSON.parse(text.replace(/^\uFEFF/, ""));
|
||||
return patch && typeof patch === "object" && !Array.isArray(patch) ? patch : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
export function failValidation(problems) {
|
||||
process.stderr.write("console: the payload was rejected, nothing was written.\n");
|
||||
for (const p of problems) process.stderr.write(" - " + p + "\n");
|
||||
// exitCode, not exit(): the agent has to read these lines to fix the patch,
|
||||
// and process.exit() can truncate a pipe Node has not flushed.
|
||||
process.exitCode = 3;
|
||||
}
|
||||
|
||||
export async function cmdPost() {
|
||||
// `post --wait <seconds>` is a post and then a wait in one command: one tool
|
||||
// call per turn instead of two. A rejected post never waits (exit 3).
|
||||
if (args.wait !== undefined && args.wait !== true && !Number.isFinite(Number.parseFloat(args.wait))) {
|
||||
die("post --wait takes the slice in seconds, as wait --seconds does", 2);
|
||||
}
|
||||
if (!postOnce()) return;
|
||||
if (args.wait === undefined) return;
|
||||
// A bare --wait takes the slice from --seconds, as wait does.
|
||||
args.seconds = args.wait === true ? args.seconds : args.wait;
|
||||
return cmdWait();
|
||||
}
|
||||
|
||||
function postOnce() {
|
||||
const dir = mustSession();
|
||||
const file = args.file;
|
||||
if (!file) die("post needs --file <path to a JSON patch>", 2);
|
||||
let patch = readPatch(file);
|
||||
if (!patch) die(`could not read --file ${file} as one JSON object`, 2);
|
||||
|
||||
const statePath = path.join(dir, "state.json");
|
||||
const before = readJson(statePath);
|
||||
if (!before) die("that session has no state", 1);
|
||||
try {
|
||||
patch = resolveDocFiles(patch, before, before.worktree || repoRoots().worktree);
|
||||
patch = resolveDocImages(patch, before, dir);
|
||||
} catch (e) {
|
||||
die(e.message, 3);
|
||||
}
|
||||
|
||||
// Meter and folder reports go to the ledger, never into state.json. Checked
|
||||
// here, before anything is written: a rejected post appends nothing.
|
||||
const { run, folderIssue } = patch;
|
||||
delete patch.run;
|
||||
delete patch.folderIssue;
|
||||
const reread = liftReread(patch, before.workflow);
|
||||
const ledgerLines = ledgerFromPost(dir, run, folderIssue, before.workflow);
|
||||
// Taken before the lock: git processes must not run while it is held.
|
||||
const snap = reread === undefined ? null : snapshot(before.worktree || repoRoots().worktree, { prHosts: readPrHosts() });
|
||||
|
||||
// The patch is applied to a fresh read under the state lock, never to the
|
||||
// read above: a send the person made in between is in the file, and a write
|
||||
// built on the older read would take it away. Nothing in here may exit, so
|
||||
// the lock is always let go; a refusal is carried out and reported after.
|
||||
let refused = null;
|
||||
let problems = [];
|
||||
let written;
|
||||
try {
|
||||
written = updateState(dir, (fresh) => {
|
||||
if (!fresh) {
|
||||
refused = ["that session has no state", 1];
|
||||
return null;
|
||||
}
|
||||
let next;
|
||||
try {
|
||||
next = applyPatch(fresh, patch);
|
||||
} catch (e) {
|
||||
refused = [e.message, 3];
|
||||
return null;
|
||||
}
|
||||
// The result card and the fresh board land in this one write.
|
||||
if (snap) {
|
||||
next.git = gitBlock(snap, reread, fresh.git);
|
||||
// The footer names the branch too: after a switch or a create it is
|
||||
// the new one, and mid-rebase the one being rebased.
|
||||
const onBranch = snap.head && (snap.head.branch || snap.head.rebasing);
|
||||
if (onBranch) next.branch = onBranch;
|
||||
}
|
||||
problems = validate(next);
|
||||
if (!problems.length && patch.chat) problems = validateChat(next, readChat(dir));
|
||||
return problems.length ? null : next;
|
||||
});
|
||||
} catch (e) {
|
||||
die(e.message, 1);
|
||||
}
|
||||
if (refused) die(...refused);
|
||||
if (problems.length) return failValidation(problems);
|
||||
const next = written.state;
|
||||
|
||||
for (const line of ledgerLines) appendLedger(dir, line);
|
||||
// A build scores its tasks as it clears them (meter.js, PROGRESS_WORKFLOWS),
|
||||
// after any `run` in the same post, so a phase finished here ends its count.
|
||||
if (patch.headline && typeof patch.headline === "object") {
|
||||
const ledger = readLedger(dir);
|
||||
const progress = progressEntry(ledger, lastLaunchId(ledger), next.workflow, patch.headline.cleared);
|
||||
if (progress) appendLedger(dir, progress);
|
||||
}
|
||||
appendEvent(dir, { type: "post", items: (patch.items || []).length });
|
||||
|
||||
const open = next.items.filter((i) => isOpen(i) && i.required !== false && i.kind !== "notice").length;
|
||||
// Only a live server's link: no handle, no line, never a dead link.
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
print({
|
||||
ok: true,
|
||||
items: next.items.length,
|
||||
open,
|
||||
phase: next.phase,
|
||||
...unansweredNote(dir, next),
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
});
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* A patch's `reread`, the agent's "re-read the repo" signal on the git board
|
||||
* (FR-10), lifted out of the patch, or exit 3 when it is malformed or not on a
|
||||
* git session. state.git itself is the console's own: a patch never carries it.
|
||||
*/
|
||||
export function liftReread(patch, workflow) {
|
||||
if (Object.hasOwn(patch, "git")) die("state.git is the console's own: post reread instead", 3);
|
||||
const { reread } = patch;
|
||||
delete patch.reread;
|
||||
if (reread === undefined) return undefined;
|
||||
const flagOnly =
|
||||
reread && typeof reread === "object" && !Array.isArray(reread) && Object.keys(reread).length === 1 && typeof reread.refreshFailed === "boolean";
|
||||
if (reread !== true && !flagOnly) die("reread must be true or { refreshFailed: true|false }", 3);
|
||||
if (workflow !== "git") die("reread only goes with the git workflow", 3);
|
||||
return reread;
|
||||
}
|
||||
|
||||
/**
|
||||
* The new state.git from a snapshot. The agent's refreshFailed wins; without
|
||||
* one, a newer FETCH_HEAD means a refresh worked, and anything else keeps the
|
||||
* last word on it.
|
||||
*/
|
||||
export function gitBlock(snap, reread, previous) {
|
||||
let refreshFailed;
|
||||
if (reread && typeof reread === "object") refreshFailed = reread.refreshFailed;
|
||||
else if (snap.lastFetch && (!previous?.lastFetch || Date.parse(snap.lastFetch) > Date.parse(previous.lastFetch))) refreshFailed = false;
|
||||
else refreshFailed = Boolean(previous?.refreshFailed);
|
||||
// A failed fetch still touches FETCH_HEAD, so its time is not a refresh:
|
||||
// the board keeps saying when the last one that worked was.
|
||||
if (refreshFailed === true && reread && typeof reread === "object") return { ...snap, lastFetch: previous?.lastFetch ?? null, refreshFailed };
|
||||
return { ...snap, refreshFailed };
|
||||
}
|
||||
|
||||
/**
|
||||
* The ledger lines a post's `run` and `folderIssue` stand for, or exit 3 on
|
||||
* the first bad one. Ids are scoped by the skill run in progress, so the same
|
||||
* `run` posted twice counts once, and `phase-2` in one Implement run never
|
||||
* collides with `phase-2` in the next.
|
||||
*/
|
||||
export function ledgerFromPost(dir, run, issue, workflow) {
|
||||
if (run === undefined && issue === undefined) return [];
|
||||
const launch = lastLaunchId(readLedger(dir));
|
||||
const lines = [];
|
||||
if (run !== undefined) {
|
||||
const event = run && typeof run === "object" ? run.event : undefined;
|
||||
if (!RUN_EVENTS.has(event)) die(`run: unknown event "${event}"`, 3);
|
||||
if (typeof run.id !== "string" || !run.id.trim()) die("run: id required", 3);
|
||||
if (run.tasks !== undefined) {
|
||||
if (!TASK_EVENTS.has(event)) die(`run: tasks only goes with ${[...TASK_EVENTS].join(" or ")}`, 3);
|
||||
if (!isTaskCount(run.tasks)) die(`run: tasks must be a whole number from 1 to ${MAX_TASKS}`, 3);
|
||||
}
|
||||
if (run.commits !== undefined) {
|
||||
if (event !== "git-commits") die("run: commits only goes with git-commits", 3);
|
||||
const ok = Number.isInteger(run.commits) && run.commits >= 1 && run.commits <= MAX_COMMITS;
|
||||
if (!ok) die(`run: commits must be a whole number from 1 to ${MAX_COMMITS}`, 3);
|
||||
}
|
||||
lines.push({
|
||||
kind: "run",
|
||||
id: `${launch}:${run.id}`,
|
||||
event,
|
||||
workflow,
|
||||
...(run.tasks !== undefined ? { tasks: run.tasks } : {}),
|
||||
...(run.commits !== undefined ? { commits: run.commits } : {}),
|
||||
});
|
||||
}
|
||||
if (issue !== undefined) {
|
||||
const text = (v) => typeof v === "string" && v.trim() !== "";
|
||||
const ok =
|
||||
issue && typeof issue === "object" && text(issue.name) && text(issue.reason) && (issue.hint === undefined || text(issue.hint));
|
||||
if (!ok) die("folderIssue must be { name, reason, hint? }, each a non-empty string", 3);
|
||||
const problems = proseProblems(JSON.stringify([issue.reason, issue.hint || ""]), "folderIssue");
|
||||
if (problems.length) die(problems.join("\n "), 3);
|
||||
lines.push({
|
||||
kind: "folder-issue",
|
||||
id: `${launch}:${issue.name}`,
|
||||
name: issue.name,
|
||||
reason: issue.reason,
|
||||
...(issue.hint ? { hint: issue.hint } : {}),
|
||||
});
|
||||
}
|
||||
return lines;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- wait */
|
||||
|
||||
export async function cmdWait() {
|
||||
const dir = mustSession();
|
||||
// "240s" reads as 240. A --seconds with no number in it at all would make
|
||||
// the deadline NaN, and the slice would end at once with exit 10: a busy
|
||||
// loop, not a wait. So that is refused rather than guessed at.
|
||||
const given = args.seconds;
|
||||
const asked = typeof given === "string" ? Number.parseFloat(given) : NaN;
|
||||
if (given !== undefined && !Number.isFinite(asked)) {
|
||||
die(`--seconds must be a number, got "${args.seconds}"`, 2);
|
||||
}
|
||||
const seconds = Math.max(5, given === undefined ? 240 : asked);
|
||||
const sid = path.basename(dir);
|
||||
const project = sessionProject(dir);
|
||||
const resultPath = path.join(dir, "result.json");
|
||||
const chatPath = path.join(dir, CHAT_FILE);
|
||||
const deadline = Date.now() + seconds * 1000;
|
||||
const pendingChat = () => deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
|
||||
// A result may already be sitting there: the person can finish the form even
|
||||
// when the agent's session died, and a fresh agent picks it up here.
|
||||
const liveUrl = () => listHandles(project).find((h) => h.sid === sid)?.url || "";
|
||||
const existing = readJson(resultPath);
|
||||
if (existing && !existing.consumedAt) return consume(dir, resultPath, existing, liveUrl(), pendingChat());
|
||||
const earlyChat = pendingChat();
|
||||
if (earlyChat.length) return deliverChat(dir, sid, earlyChat, liveUrl());
|
||||
markWaiting(dir);
|
||||
|
||||
// A stat every 50ms, and a read only when the file has moved. The old tick
|
||||
// was a full read and parse every 400ms, which put up to 0.4s between the
|
||||
// person pressing Send and the agent starting on it, on every single send.
|
||||
let healthAt = 0;
|
||||
// A busy server (right after a post, say) can miss one health check without
|
||||
// being gone. Only a missing handle or dead pid is proof at once; a server
|
||||
// that merely does not answer must fail three checks in a row, each with a
|
||||
// longer look, before the slice ends with exit 20.
|
||||
let healthMisses = 0;
|
||||
// The check in flight, if any. Aborted on every way out, so a fetch left
|
||||
// running never holds the process (and the agent) past the print.
|
||||
let health = null;
|
||||
const healthStop = new AbortController();
|
||||
try {
|
||||
return await pollSlice();
|
||||
} finally {
|
||||
healthStop.abort();
|
||||
}
|
||||
|
||||
async function pollSlice() {
|
||||
// Null, not the current stamp: a result written between the check above and
|
||||
// this line would otherwise read as already seen and wait out the slice.
|
||||
let seen = null;
|
||||
let chatSeen = null;
|
||||
while (Date.now() < deadline) {
|
||||
const stamp = fileStamp(resultPath);
|
||||
if (stamp && stamp !== seen) {
|
||||
const result = readJson(resultPath);
|
||||
if (result && !result.consumedAt) return consume(dir, resultPath, result, liveUrl(), pendingChat());
|
||||
// Unreadable for a moment (a lock, a scanner): look again next tick.
|
||||
seen = result ? stamp : null;
|
||||
}
|
||||
|
||||
// The chat inbox beside it, on the same tick: a Quick question ends the
|
||||
// slice as surely as a card send does.
|
||||
const chatStamp = fileStamp(chatPath);
|
||||
if (chatStamp !== chatSeen) {
|
||||
chatSeen = chatStamp;
|
||||
const entries = pendingChat();
|
||||
if (entries.length) return deliverChat(dir, sid, entries, liveUrl());
|
||||
}
|
||||
|
||||
// The health check runs beside the polling, never in its way: awaited
|
||||
// inline, a slow /health (a busy server, just after a send) held a
|
||||
// finished send back for up to the whole fetch timeout.
|
||||
if (!health && Date.now() - healthAt > 5000) {
|
||||
healthAt = Date.now();
|
||||
const handle = listHandles(project).find((h) => h.sid === sid);
|
||||
if (!handle || !pidAlive(handle.pid)) {
|
||||
print(serverGone(sid));
|
||||
process.exitCode = 20;
|
||||
return;
|
||||
}
|
||||
const check = { done: false, ok: false };
|
||||
health = check;
|
||||
healthOk(handle, 4000, healthStop.signal).then((ok) => Object.assign(check, { done: true, ok }));
|
||||
}
|
||||
if (health && health.done) {
|
||||
const { ok } = health;
|
||||
health = null;
|
||||
if (ok) healthMisses = 0;
|
||||
else if (++healthMisses >= 3) {
|
||||
print(serverGone(sid));
|
||||
process.exitCode = 20;
|
||||
return;
|
||||
} else healthAt = Date.now() - 3000; // look again in about 2s, not 5s
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
|
||||
const state = readJson(path.join(dir, "state.json")) || {};
|
||||
const items = (state.items || []).filter((i) => i.required !== false && i.kind !== "notice");
|
||||
const answered = items.filter((i) => !isOpen(i)).length;
|
||||
const draft = readJson(path.join(dir, "draft.json"), {});
|
||||
const staged = Object.keys(draft.staged || {}).length;
|
||||
const handle = listHandles(project).find((h) => h.sid === sid);
|
||||
|
||||
print({
|
||||
status: "waiting",
|
||||
sid,
|
||||
elapsed: fmtMs(Date.now() - Date.parse(state.created || nowIso())),
|
||||
answered,
|
||||
total: items.length,
|
||||
staged,
|
||||
url: handle ? handle.url : "",
|
||||
message: "Waiting on your answer in the web console",
|
||||
next: "NOT FINISHED, do not end your turn or write a summary: relay the message in one line, then run this same wait command again right now. Repeat until the exit code is not 10.",
|
||||
...unansweredNote(dir, state),
|
||||
// A workspace change alone never ends a slice: it rides on the next send.
|
||||
pendingWorkspace: pendingWorkspaceChanges(dir).length,
|
||||
...(handle && handle.url ? { terminalLine: terminalLine(handle.url) } : {}),
|
||||
});
|
||||
process.exitCode = 10;
|
||||
}
|
||||
}
|
||||
|
||||
// Quick questions already handed over with no reply yet. Always empty when all are answered.
|
||||
function unansweredNote(dir, state) {
|
||||
const seqs = unansweredChat(dir, state);
|
||||
return seqs.length
|
||||
? { unansweredChat: seqs, warning: "Quick questions " + seqs.join(", ") + " have no reply yet and the page still shows them as pending. Reply to each now (chat.replies, re = seq): do what was asked when you can, or say why you will not." }
|
||||
: {};
|
||||
}
|
||||
|
||||
export function serverGone(sid) {
|
||||
return {
|
||||
status: "server-gone",
|
||||
sid,
|
||||
message: "The console server is not running. Start it again with `open --resume <sid> --workflow <yours>` (it gets a new link: give it to the person; without --no-open the browser opens it), then keep waiting: at a finished screen too, since the person's Ask messages and the dashboard button still need you.",
|
||||
};
|
||||
}
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
actions: [],
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
// The workspace changes the agent is owed, added to what it is about to read:
|
||||
// the list as `workspace`, and one line each at the end of `reply`.
|
||||
function withWorkspace(dir, out) {
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!changes.length) return [out, changes];
|
||||
const reply = [out.reply, ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
return [{ ...out, workspace: changes, reply }, changes];
|
||||
}
|
||||
|
||||
// Print first, then this, as with the chat cursor: a kill in between can only
|
||||
// hand the same change over again, never skip one.
|
||||
export function advanceWorkspace(dir, changes) {
|
||||
if (!changes.length) return;
|
||||
try {
|
||||
writeWorkspaceCursor(dir, Math.max(...changes.map((c) => c.version)));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
export function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
export function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
export function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
export function advanceCursor(dir, entries) {
|
||||
if (!entries.length) return;
|
||||
try {
|
||||
writeCursor(dir, Math.max(...entries.map((e) => e.seq)));
|
||||
} catch {}
|
||||
appendEvent(dir, { type: "chat-collect", count: entries.length });
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand a result to the agent, then mark it collected. In that order.
|
||||
*
|
||||
* Both halves of this guard the same thing, and it matters most in agents other
|
||||
* than the one this was built against: plenty of harnesses cap a single shell
|
||||
* call well below a wait slice and kill it at their own timeout.
|
||||
*
|
||||
* Printing before stamping means such a kill can only ever cause the NEXT wait
|
||||
* to hand the same result over twice, which the agent can absorb. The other
|
||||
* order loses answers someone pressed Send on, silently and permanently.
|
||||
*
|
||||
* And exiting by setting `exitCode` rather than calling process.exit(): stdout
|
||||
* to a pipe is asynchronous, and process.exit() truncates whatever Node has not
|
||||
* flushed. That would throw the result away just as thoroughly.
|
||||
*/
|
||||
function consume(dir, resultPath, result, url, chat = []) {
|
||||
const collected = { ...result, consumedAt: nowIso() };
|
||||
// The link, any chat and any workspace change ride on what the agent reads,
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
const hop = hopFor(path.basename(dir), result);
|
||||
markPickedUp(result);
|
||||
print({ ...out, ...hop, ...handoffFor(result), ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
} catch {}
|
||||
markWorking(dir, result);
|
||||
appendEvent(dir, { type: "consume", kind: result.type });
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
// A collected send is the agent's turn: the page says so at once, without the
|
||||
// agent spending a whole post on "working" before it starts. The activity
|
||||
// line belonged to the last stretch of work, so it goes; quietMinutes stays,
|
||||
// since the page only counts it while working. Never fatal.
|
||||
// The send is no longer waiting to be picked up either, so the phase the
|
||||
// server set on it goes back to collecting (status and post report it).
|
||||
function markWorking(dir, result) {
|
||||
if (!result) return;
|
||||
try {
|
||||
updateState(dir, (s) => {
|
||||
if (!s) return null;
|
||||
if (result.type !== "submit") return s.phase === "submitted" ? { ...s, phase: "collecting" } : null;
|
||||
// The cards this send carried, so `settle: true` settles what the agent
|
||||
// was handed and never a later send still waiting to be collected.
|
||||
const ids = [...new Set((result.actions || []).filter((a) => a && (a.type === "answer" || a.type === "skip") && typeof a.i === "string" && !a.i.startsWith("__")).map((a) => a.i))];
|
||||
return applyPatch({ ...s, phase: "collecting", collected: { at: result.consumedAt || nowIso(), ids } }, { agent: { status: "working", activity: null } });
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Waiting on an open question (or a finished screen's buttons) is the
|
||||
// person's turn, whatever the last post said: an agent that replied to a note
|
||||
// and went back to `wait` without restating its status left the page on
|
||||
// "working" with nobody working. With nothing open it stays as it is: an
|
||||
// agent waiting out its research subagents is still working. Only a change
|
||||
// is written.
|
||||
function markWaiting(dir) {
|
||||
try {
|
||||
updateState(dir, (s) => {
|
||||
if (!s || !s.agent || s.agent.status !== "working") return null;
|
||||
// The dashboard's menu and the git board are the page's own, and theirs
|
||||
// to click whenever the agent is waiting.
|
||||
const theirTurn =
|
||||
s.finish || s.workflow === "dashboard" || s.workflow === "git" || (s.items || []).some((i) => isOpen(i) && i.kind !== "notice");
|
||||
return theirTurn ? applyPatch(s, { agent: { status: "waiting" } }) : null;
|
||||
});
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The session hops a send can ask for, each with the one command that makes
|
||||
// it and the skill file to follow after, so the agent copies instead of
|
||||
// assembling `open --resume …` from the action's fields.
|
||||
const HOP_ACTIONS = {
|
||||
launch: (a) => ({ workflow: a.workflow, spec: a.spec, skill: a.skill }),
|
||||
dashboard: () => ({ workflow: "dashboard", skill: "plan2code" }),
|
||||
commit: () => ({ workflow: "git", skill: "plan2code-git" }),
|
||||
pickup: pickupHop,
|
||||
};
|
||||
|
||||
// A pick-up hops into the skill and spec the handoff's `.json` names (the page
|
||||
// sends only the id). When the skill is no longer installed, the spec folder
|
||||
// is gone, or the Handoff skill wrote it, Quick Task picks it up instead,
|
||||
// flagged so the agent says so. In a
|
||||
// source tree no skill sits beside the console, so nothing can be told to be
|
||||
// missing and the stored skill stands.
|
||||
function skillPath(skill) {
|
||||
return path.resolve(HERE, "..", "..", "..", skill, "SKILL.md");
|
||||
}
|
||||
|
||||
function pickupHop(action) {
|
||||
const id = action.handoff;
|
||||
const meta = isHandoffId(id) ? readHandoffMeta(id) : null;
|
||||
const handoffFile = isHandoffId(id) ? path.join(handoffsDir(), id + ".md") : undefined;
|
||||
const quick = { workflow: "quick-task", spec: undefined, skill: "plan2code-quick-task", handoffFile, fallback: true };
|
||||
if (!meta) return quick;
|
||||
if (typeof meta.workflow !== "string" || !/^[a-z-]+$/.test(meta.workflow)) return quick;
|
||||
// The Handoff skill's own handoff: resuming it would only write another one.
|
||||
if (meta.workflow === "handoff") return quick;
|
||||
if (typeof meta.skill !== "string" || !/^[a-z0-9-]+$/.test(meta.skill)) return quick;
|
||||
const specGone =
|
||||
typeof meta.spec === "string" && meta.spec && (!SAFE_SPEC.test(meta.spec) || !fs.existsSync(path.join(meta.worktree || "", meta.spec)));
|
||||
const skillGone = !fs.existsSync(skillPath(meta.skill)) && fs.existsSync(skillPath("plan2code-quick-task"));
|
||||
if (specGone || skillGone) return quick;
|
||||
return { workflow: meta.workflow, spec: meta.spec || undefined, skill: meta.skill, handoffFile };
|
||||
}
|
||||
|
||||
// A stop that asked for a handoff gets the Handoff skill's file beside it, so
|
||||
// the agent opens it instead of locating it. Only a built skill has one.
|
||||
function handoffFor(result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
if (!actions.some((a) => a && a.type === "stop" && a.i === "__stop" && a.handoff === true)) return {};
|
||||
const file = path.resolve(HERE, "..", "..", "..", "plan2code-handoff", "SKILL.md");
|
||||
return fs.existsSync(file) ? { handoffSkill: file } : {};
|
||||
}
|
||||
|
||||
// A pick-up uses its handoff up as its hop is printed, so the next dashboard
|
||||
// scan no longer lists it. Never fatal; a repeat delivery marks it again.
|
||||
function markPickedUp(result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
for (const a of actions) {
|
||||
if (a && a.type === "pickup" && typeof a.i === "string" && a.i.startsWith("__") && isHandoffId(a.handoff)) {
|
||||
try {
|
||||
markHandoffUsed(a.handoff);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A spec name that is safe to put in the `resume` command: `specs/<name>` with
|
||||
// nothing a shell would act on. A handoff's `.json` and a page's send are both
|
||||
// data off disk or the wire, so the name is checked here and not trusted.
|
||||
const SAFE_SPEC = /^specs\/[^/\\"'`$;&|<>(){}*?!#~\r\n]+$/;
|
||||
|
||||
function hopFor(sid, result) {
|
||||
const actions = (result && Array.isArray(result.actions) && result.actions) || [];
|
||||
const action = actions.find((a) => a && Object.hasOwn(HOP_ACTIONS, a.type) && typeof a.i === "string" && a.i.startsWith("__"));
|
||||
if (!action) return {};
|
||||
const { workflow, spec, skill, handoffFile, fallback } = HOP_ACTIONS[action.type](action);
|
||||
if (typeof workflow !== "string" || !/^[a-z-]+$/.test(workflow)) return {};
|
||||
const quote = (v) => (/[\s"]/.test(v) ? `"${v.replace(/"/g, '\\"')}"` : v);
|
||||
const specArg = typeof spec === "string" && SAFE_SPEC.test(spec) ? ` --spec ${quote(spec)}` : "";
|
||||
const out = { resume: `node "${path.join(HERE, "console.mjs")}" open --resume ${sid} --no-open --workflow ${workflow}${specArg}` };
|
||||
if (typeof skill === "string" && /^[a-z0-9-]+$/.test(skill)) {
|
||||
const file = skillPath(skill);
|
||||
if (fs.existsSync(file)) out.skillFile = file;
|
||||
}
|
||||
if (typeof handoffFile === "string") out.handoffFile = handoffFile;
|
||||
if (fallback) out.fallback = true;
|
||||
return out;
|
||||
}
|
||||
|
||||
// One `answer` ledger line per item the person answered in this send, for
|
||||
// the session meter. The id carries the send's stamp, so a send collected
|
||||
// twice (a kill before consumedAt was written) still counts once, while the
|
||||
// same question answered again in a later round counts again: that round was
|
||||
// real back-and-forth. Never fatal: the meter is advice.
|
||||
function ledgerAnswers(dir, result) {
|
||||
if (!result || result.type !== "submit" || !Array.isArray(result.actions)) return;
|
||||
try {
|
||||
const launch = lastLaunchId(readLedger(dir));
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
const items = new Set();
|
||||
for (const a of result.actions) {
|
||||
if (a && a.type === "answer" && typeof a.i === "string" && !a.i.startsWith("__")) items.add(a.i);
|
||||
}
|
||||
for (const i of items) appendLedger(dir, { kind: "answer", id: `${launch}:answer:${result.at}:${i}`, workflow });
|
||||
} catch {}
|
||||
}
|
||||
|
||||
function fmtMs(ms) {
|
||||
if (!Number.isFinite(ms) || ms < 0) return "0s";
|
||||
const s = Math.round(ms / 1000);
|
||||
if (s < 60) return `${s}s`;
|
||||
const m = Math.floor(s / 60);
|
||||
return `${m}m ${s % 60}s`;
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
// Plan2Code Web Console - the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { SESSIONS_DIR, appendEvent, readJson } from "./files.mjs";
|
||||
import { attachmentName, healthOk, listHandles, pidAlive, projectRoot, repoRoots, sessionDir } from "./sessions.mjs";
|
||||
import { removeSpec } from "./scan.mjs";
|
||||
import { isOpen } from "./patches.mjs";
|
||||
import { pendingChatCount } from "./inbox.mjs";
|
||||
import { forgetWorkspace, specKey } from "./workspace.mjs";
|
||||
import { newHandoff, removeHandoff } from "./handoffs.mjs";
|
||||
|
||||
// The CLI's own pieces, handed over by console.mjs through useCli() before
|
||||
// any command runs: console.mjs runs on import, so it cannot be imported back.
|
||||
let args, print, die, mustSession, sessionProject;
|
||||
export function useCli(cli) {
|
||||
({ args, print, die, mustSession, sessionProject } = cli);
|
||||
}
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
// still be one of our servers, so its pid gets no second look.
|
||||
const MAX_SERVER_LIFE_MS = 4 * 60 * 60 * 1000;
|
||||
|
||||
/* ----------------------------------------------------------------- keep */
|
||||
|
||||
// Copy one of the session's note attachments into specs/<idea>/attachments/, so
|
||||
// a spec file can cite it after the session is swept. Run by the agent, never
|
||||
// the server: the server still never writes into a project.
|
||||
export function cmdKeep() {
|
||||
const usage = "keep needs --session <sid> --upload <path> --name <name> --spec specs/<idea>";
|
||||
if ([args.upload, args.name, args.spec].some((v) => typeof v !== "string")) die(usage, 2);
|
||||
const dir = mustSession();
|
||||
const state = readJson(path.join(dir, "state.json"));
|
||||
if (!state) die("that session has no state", 1);
|
||||
const project = state.project;
|
||||
|
||||
const upload = path.resolve(args.upload);
|
||||
// Compared as real paths: Windows hands the same folder out both long
|
||||
// (C:\Users\Justin.Parker) and 8.3 (C:\Users\JUSTIN~1.PAR), and the reply's
|
||||
// path need not be spelled the way this session's directory is.
|
||||
// A path that does not exist (yet) resolves through its nearest real parent,
|
||||
// so a missing upload still reads as missing, not as somewhere else.
|
||||
const real = (p) => {
|
||||
try {
|
||||
return fs.realpathSync.native(p);
|
||||
} catch {
|
||||
const parent = path.dirname(path.resolve(p));
|
||||
return parent === path.resolve(p) ? path.resolve(p) : path.join(real(parent), path.basename(p));
|
||||
}
|
||||
};
|
||||
if (!inside(real(path.join(dir, "uploads")), real(upload))) die("upload is not in this session's uploads folder", 3);
|
||||
const spec = path.resolve(project, args.spec);
|
||||
const attachments = path.join(spec, "attachments");
|
||||
if (!inside(project, spec) || !inside(fs.realpathSync(project), realNearest(attachments))) {
|
||||
die("spec folder is outside the project", 3);
|
||||
}
|
||||
if (!fs.existsSync(upload) || !fs.statSync(upload).isFile()) die("no such upload", 3);
|
||||
|
||||
// The file the link is written for has to be in the project too, or the
|
||||
// relative link would point out of it.
|
||||
if (typeof args.from === "string" && !inside(project, path.resolve(project, args.from))) {
|
||||
die("--from is outside the project", 3);
|
||||
}
|
||||
|
||||
// One upload, one copy: kept again under another name, the copy it already
|
||||
// has (named for the same upload id) is the one reused.
|
||||
// Named from the real path: an 8.3 spelling (7CF881~1.JPG) would name the
|
||||
// copy after the short form and miss the copy this upload already has.
|
||||
const named = attachmentName({ upload: real(upload), name: args.name });
|
||||
const suffix = named.slice(named.lastIndexOf("-"));
|
||||
let existing = null;
|
||||
try {
|
||||
existing = fs.readdirSync(attachments).find((f) => f.endsWith(suffix));
|
||||
} catch {}
|
||||
const file = existing || named;
|
||||
const target = path.join(attachments, file);
|
||||
fs.mkdirSync(attachments, { recursive: true });
|
||||
let reused = false;
|
||||
try {
|
||||
fs.copyFileSync(upload, target, fs.constants.COPYFILE_EXCL);
|
||||
} catch (err) {
|
||||
if (err.code !== "EEXIST") throw err;
|
||||
reused = true;
|
||||
}
|
||||
|
||||
const slashes = (p) => p.split(path.sep).join("/");
|
||||
const linkBase = typeof args.from === "string" ? path.dirname(path.resolve(project, args.from)) : spec;
|
||||
const kept = slashes(path.relative(project, target));
|
||||
print({
|
||||
ok: true,
|
||||
path: kept,
|
||||
link: slashes(path.relative(linkBase, target)),
|
||||
image: path.extname(target) === ".jpg",
|
||||
reused,
|
||||
});
|
||||
appendEvent(dir, { type: "keep", id: path.basename(upload, path.extname(upload)), path: kept });
|
||||
}
|
||||
|
||||
// Whether child sits strictly under parent. path.relative handles drive
|
||||
// letters and POSIX alike; Windows paths fold case, as the server's do.
|
||||
function inside(parent, child) {
|
||||
const fold = (s) => (process.platform === "win32" ? s.toLowerCase() : s);
|
||||
const rel = path.relative(fold(path.resolve(parent)), fold(path.resolve(child)));
|
||||
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
||||
}
|
||||
|
||||
// p with its nearest existing ancestor's symlinks and junctions resolved, so a
|
||||
// linked specs/, spec or attachments/ folder cannot carry a copy out of the project.
|
||||
function realNearest(p) {
|
||||
let existing = p;
|
||||
while (!fs.existsSync(existing)) existing = path.dirname(existing);
|
||||
return path.join(fs.realpathSync(existing), path.relative(existing, p));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- forget */
|
||||
|
||||
// Drop the folder list remembered for one spec (Finalize, once the spec is
|
||||
// archived). The project's own list and every other spec's are untouched.
|
||||
export function cmdForget() {
|
||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("forget needs --spec specs/<idea>", 2);
|
||||
let spec = specKey(args.spec);
|
||||
if (/\.md$/i.test(spec)) spec = spec.slice(0, spec.lastIndexOf("/"));
|
||||
const worktree = repoRoots().worktree;
|
||||
print({ ok: true, spec, forgot: forgetWorkspace(worktree, spec) });
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------- delete-spec */
|
||||
|
||||
// The dashboard's Delete button, carried out by the agent: the page never
|
||||
// writes into a project. removeSpec() does every check; a refusal is exit 3
|
||||
// with the reason, and the remembered workspace for the spec goes with it.
|
||||
export function cmdDeleteSpec() {
|
||||
if (typeof args.spec !== "string" || !args.spec.trim()) die("delete-spec needs --spec specs/<name>", 2);
|
||||
const worktree = repoRoots().worktree;
|
||||
try {
|
||||
const done = removeSpec(worktree, args.spec);
|
||||
forgetWorkspace(worktree, args.spec);
|
||||
print(done);
|
||||
} catch (err) {
|
||||
print({ ok: false, message: err.message });
|
||||
process.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- handoff */
|
||||
|
||||
// A handoff the agent is about to write, claimed in ~/.plan2code/handoffs/
|
||||
// (handoffs.mjs) for this checkout: the Stop flow's "Stop with a handoff" and
|
||||
// the Handoff skill both start here. Only the .json is written; the agent
|
||||
// writes the document at the printed path.
|
||||
export function cmdHandoff() {
|
||||
const usage = "handoff needs: handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]";
|
||||
if (args._[0] !== "new" || args._.length > 1) die(usage, 2);
|
||||
if (typeof args.workflow !== "string" || typeof args.skill !== "string") die(usage, 2);
|
||||
if ("from-stop" in args && args["from-stop"] !== true) die("--from-stop takes no value", 2);
|
||||
const { worktree, project } = repoRoots();
|
||||
try {
|
||||
const { id, path: file, meta } = newHandoff({
|
||||
worktree,
|
||||
project,
|
||||
spec: args.spec,
|
||||
workflow: args.workflow,
|
||||
skill: args.skill,
|
||||
title: args.title,
|
||||
fromStop: args["from-stop"] === true,
|
||||
});
|
||||
print({ ok: true, id, path: file, meta });
|
||||
} catch (err) {
|
||||
print({ ok: false, message: err.message });
|
||||
process.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
// The dashboard's Delete on a Handoff chip, carried out by the agent, the
|
||||
// same shape as delete-spec: removeHandoff() does every check.
|
||||
export function cmdDeleteHandoff() {
|
||||
if (typeof args.handoff !== "string" || !args.handoff.trim()) die("delete-handoff needs --handoff <id>", 2);
|
||||
try {
|
||||
print(removeHandoff(args.handoff));
|
||||
} catch (err) {
|
||||
print({ ok: false, message: err.message });
|
||||
process.exit(3);
|
||||
}
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------------- status */
|
||||
|
||||
export async function cmdStatus() {
|
||||
const project = projectRoot();
|
||||
if (args.session || args.sid) {
|
||||
const dir = mustSession();
|
||||
const state = readJson(path.join(dir, "state.json")) || {};
|
||||
const handle = listHandles(sessionProject(dir)).find((h) => h.sid === path.basename(dir));
|
||||
const result = readJson(path.join(dir, "result.json"));
|
||||
return print({
|
||||
sid: state.sid,
|
||||
session: dir,
|
||||
workflow: state.workflow,
|
||||
title: state.title,
|
||||
phase: state.phase,
|
||||
items: (state.items || []).length,
|
||||
open: (state.items || []).filter(isOpen).length,
|
||||
url: handle ? handle.url : "",
|
||||
live: handle ? pidAlive(handle.pid) : false,
|
||||
pendingResult: Boolean(result && !result.consumedAt),
|
||||
pendingChat: pendingChatCount(dir, state),
|
||||
});
|
||||
}
|
||||
|
||||
let sids = [];
|
||||
try {
|
||||
sids = fs.readdirSync(SESSIONS_DIR).sort().reverse();
|
||||
} catch {
|
||||
return print({ sessions: [] });
|
||||
}
|
||||
const handles = listHandles(project);
|
||||
const rows = [];
|
||||
for (const sid of sids.slice(0, Number(args.limit || 20))) {
|
||||
const dir = sessionDir(sid);
|
||||
const state = readJson(path.join(dir, "state.json"));
|
||||
if (!state) continue;
|
||||
if (!args.all && state.project !== project) continue;
|
||||
const handle = handles.find((h) => h.sid === sid);
|
||||
const result = readJson(path.join(dir, "result.json"));
|
||||
rows.push({
|
||||
sid,
|
||||
workflow: state.workflow,
|
||||
title: state.title,
|
||||
phase: state.phase,
|
||||
created: state.created,
|
||||
live: handle ? pidAlive(handle.pid) : false,
|
||||
url: handle ? handle.url : "",
|
||||
pendingResult: Boolean(result && !result.consumedAt),
|
||||
pendingChat: pendingChatCount(dir, state),
|
||||
});
|
||||
}
|
||||
print({ sessions: rows });
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------------------- stop */
|
||||
|
||||
export async function cmdStop() {
|
||||
// --all is this folder's sessions; one named session is found wherever
|
||||
// the command runs from.
|
||||
const named = !args.all && (args.session || args.sid) ? sessionDir(path.basename(args.session || args.sid)) : null;
|
||||
const project = named && fs.existsSync(named) ? sessionProject(named) : projectRoot();
|
||||
const handles = listHandles(project);
|
||||
const targets = args.all
|
||||
? handles
|
||||
: handles.filter((h) => h.sid === path.basename(args.session || args.sid || ""));
|
||||
if (!targets.length) return print({ ok: true, stopped: 0 });
|
||||
|
||||
let stopped = 0;
|
||||
let skipped = 0;
|
||||
for (const h of targets) {
|
||||
// Identify the process before killing it. A handle file can outlive a
|
||||
// reboot in the system temp directory, and PIDs get reused; without this
|
||||
// check `stop --all` can kill an unrelated program that happens to have
|
||||
// inherited the number. /health returning our own sid is the only proof:
|
||||
// a live pid and a young handle are not, since a server that died a
|
||||
// minute ago leaves exactly that behind for any process to inherit. A
|
||||
// busy server gets a second, longer look, and still has to answer as
|
||||
// ours; one that does not is left alone, and only its handle goes.
|
||||
const young = Date.now() - Date.parse(h.startedAt || 0) < MAX_SERVER_LIFE_MS;
|
||||
const ours = (await healthOk(h)) || (young && pidAlive(h.pid) && (await healthOk(h, 5000)));
|
||||
if (!ours) {
|
||||
skipped++;
|
||||
try {
|
||||
fs.rmSync(h.handlePath, { force: true });
|
||||
} catch {}
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
process.kill(h.pid);
|
||||
stopped++;
|
||||
} catch {}
|
||||
try {
|
||||
fs.rmSync(h.handlePath, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
print({ ok: true, stopped, ...(skipped ? { skippedStaleHandles: skipped } : {}) });
|
||||
}
|
||||
@@ -22,7 +22,9 @@ free to close that terminal and kill them mid-write. While you wait, post
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
never ends on a row still running: post each one's `done` in the same turn its
|
||||
notice arrives, and a `finish` is refused (exit `3`, naming the helper) while
|
||||
any row is still `running`.
|
||||
|
||||
## 1. Post the finish
|
||||
|
||||
|
||||
+32
-1727
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,294 @@
|
||||
// Plan2Code Web Console - where the console's files live, how they are written safely, and the argument parser both command lines share.
|
||||
//
|
||||
// Two directories with deliberately different durability:
|
||||
//
|
||||
// runtime handle os.tmpdir()/plan2code-console/<cwd-hash>/<sid>.json
|
||||
// port, pid, token, url. Losing it on reboot is correct,
|
||||
// because the server is gone too. (Jupyter's jpserver-<pid>.json pattern.)
|
||||
//
|
||||
// session state ~/.plan2code/console/sessions/<sid>/
|
||||
// the request, the human's draft, the result, the event log.
|
||||
// Deliberately NOT under specs/: that keeps the console clear of
|
||||
// the metrics confidence scraper and the loop's completion-marker
|
||||
// parser, and it survives a `git clean`.
|
||||
//
|
||||
// Node built-ins only. No build step.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { pidAlive } from "./sessions.mjs";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
|
||||
export const HOME_DIR =
|
||||
process.env.PLAN2CODE_CONSOLE_HOME ||
|
||||
path.join(os.homedir(), ".plan2code", "console");
|
||||
export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
|
||||
|
||||
// The person's own settings (colors, theme), shared by every session. Lives in
|
||||
// HOME_DIR rather than beside a session precisely because it is NOT session
|
||||
// state: a browser ties localStorage to the origin, and the origin carries the
|
||||
// ephemeral port, so the file under this dir is the only copy of a preference
|
||||
// that survives the next session's new port.
|
||||
// Model menus for the `plan2code` launcher. The shipped list (bin/models.json) is the
|
||||
// authors' and is overwritten by every install; the user's additions (models.json) are
|
||||
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
|
||||
export const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
|
||||
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
|
||||
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
// session someone is actually using.
|
||||
export const RUNTIME_DIR = process.env.PLAN2CODE_CONSOLE_HOME
|
||||
? path.join(process.env.PLAN2CODE_CONSOLE_HOME, "runtime")
|
||||
: path.join(os.tmpdir(), "plan2code-console");
|
||||
|
||||
export const SCHEMA = 1;
|
||||
|
||||
/* ------------------------------------------------------------------ args */
|
||||
|
||||
export function parseArgs(argv) {
|
||||
const out = { _: [] };
|
||||
for (let i = 0; i < argv.length; i++) {
|
||||
const a = argv[i];
|
||||
if (a.startsWith("--")) {
|
||||
const eq = a.indexOf("=");
|
||||
if (eq > -1) out[a.slice(2, eq)] = a.slice(eq + 1);
|
||||
else if (argv[i + 1] && !argv[i + 1].startsWith("--")) out[a.slice(2)] = argv[++i];
|
||||
else out[a.slice(2)] = true;
|
||||
} else out._.push(a);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- fs */
|
||||
|
||||
export function ensureDir(dir) {
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Atomic replace. The waiter polls result.json and WILL land mid-write eventually.
|
||||
//
|
||||
// The retry loop is not paranoia: on Windows, antivirus and the search indexer
|
||||
// hold transient locks that surface as EPERM/EBUSY from rename. It is intermittent,
|
||||
// unreproducible on demand, and looks exactly like a logic bug. Retry from day one.
|
||||
export function writeJsonAtomic(file, data) {
|
||||
const tmp = file + "." + process.pid + ".tmp";
|
||||
const body = JSON.stringify(data, null, 2);
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
const fd = fs.openSync(tmp, "w");
|
||||
try {
|
||||
fs.writeFileSync(fd, body);
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
fs.renameSync(tmp, file);
|
||||
return body;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
|
||||
sleepSync(40 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
throw lastErr;
|
||||
}
|
||||
|
||||
// A cheap "has this file changed?" fingerprint: one stat instead of a read and
|
||||
// a parse. An atomic write replaces the file, so a new write always moves at
|
||||
// least one of these. "" for a file that is not there.
|
||||
export function fileStamp(file) {
|
||||
try {
|
||||
const st = fs.statSync(file, { throwIfNoEntry: false });
|
||||
return st ? `${st.mtimeMs}:${st.size}:${st.ino}` : "";
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function readJson(file, fallback = null) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
export function readText(file) {
|
||||
try {
|
||||
return fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function appendEvent(dir, event) {
|
||||
const line = JSON.stringify({ at: nowIso(), ...event });
|
||||
fs.appendFileSync(path.join(dir, "events.ndjson"), line + "\n");
|
||||
return line;
|
||||
}
|
||||
|
||||
/* ----------------------------------------------------- the state lock */
|
||||
|
||||
// state.json has two writers in two processes: console.mjs (`open` and `post`,
|
||||
// the agent's side) and the server (`/submit` stamps the phase and records
|
||||
// what was sent on each item). Each writer reads the file, changes it and
|
||||
// writes it back, so two of them overlapping lose whichever wrote first. Every
|
||||
// read-modify-write of state.json therefore runs under this lock, a file
|
||||
// created with O_EXCL beside it. The sections it guards are a read, a merge
|
||||
// and a write, milliseconds long, so a lock older than LOCK_STALE_MS, or one
|
||||
// whose holder has died, is a crash left behind and is broken. The wait runs
|
||||
// past the stale age, so a writer always gets in eventually.
|
||||
export const STATE_LOCK_FILE = "state.json.lock";
|
||||
const LOCK_STALE_MS = 5000;
|
||||
const LOCK_WAIT_MS = 7000;
|
||||
|
||||
function lockStale(lock) {
|
||||
try {
|
||||
const st = fs.statSync(lock);
|
||||
if (Date.now() - st.mtimeMs > LOCK_STALE_MS) return true;
|
||||
const pid = Number.parseInt(fs.readFileSync(lock, "utf8"), 10);
|
||||
return Number.isInteger(pid) && pid > 0 && pid !== process.pid && !pidAlive(pid);
|
||||
} catch (err) {
|
||||
// Gone between the failed create and this look: free, so try again.
|
||||
return err.code === "ENOENT";
|
||||
}
|
||||
}
|
||||
|
||||
// Run fn while holding the session's state lock, and release it however fn
|
||||
// ends. fn must not call process.exit(): the release would never run, and the
|
||||
// next writer would wait out the stale age.
|
||||
export function withStateLock(dir, fn, lockName = STATE_LOCK_FILE) {
|
||||
const lock = path.join(dir, lockName);
|
||||
const deadline = Date.now() + LOCK_WAIT_MS;
|
||||
let fd = null;
|
||||
for (let attempt = 0; fd === null; attempt++) {
|
||||
try {
|
||||
fd = fs.openSync(lock, "wx");
|
||||
} catch (err) {
|
||||
// EPERM / EACCES: on Windows, a lock being deleted still blocks a create.
|
||||
if (!["EEXIST", "EPERM", "EACCES", "EBUSY"].includes(err.code)) throw err;
|
||||
if (Date.now() > deadline) throw new Error(`${lockName.replace(/.lock$/, "")} is busy with another writer; try again`);
|
||||
if (err.code === "EEXIST" && lockStale(lock)) {
|
||||
try {
|
||||
fs.rmSync(lock, { force: true });
|
||||
} catch {}
|
||||
continue;
|
||||
}
|
||||
sleepSync(Math.min(5 * (attempt + 1), 50));
|
||||
}
|
||||
}
|
||||
try {
|
||||
try {
|
||||
fs.writeSync(fd, String(process.pid));
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
return fn();
|
||||
} finally {
|
||||
try {
|
||||
fs.rmSync(lock, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
// The one way to change state.json: under the lock, read it fresh, hand it to
|
||||
// fn (null when there is no state yet, with the raw text beside it), and write
|
||||
// back whatever fn returns. A null return writes nothing. Returns the written
|
||||
// state and its text, or null.
|
||||
export function updateState(dir, fn) {
|
||||
const file = path.join(dir, "state.json");
|
||||
return withStateLock(dir, () => {
|
||||
let text = null;
|
||||
try {
|
||||
text = fs.readFileSync(file, "utf8");
|
||||
} catch {}
|
||||
let state = null;
|
||||
try {
|
||||
state = text === null ? null : JSON.parse(text);
|
||||
} catch {}
|
||||
const next = fn(state, text);
|
||||
if (!next) return null;
|
||||
return { state: next, text: writeJsonAtomic(file, next) };
|
||||
});
|
||||
}
|
||||
|
||||
export function sleepSync(ms) {
|
||||
// Node built-ins only, and this runs in short one-shot CLI commands.
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
|
||||
}
|
||||
|
||||
export function nowIso() {
|
||||
return new Date().toISOString();
|
||||
}
|
||||
|
||||
// Every whole, parsable object line of an ndjson file, in order.
|
||||
export function readJsonLines(file) {
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(file, "utf8");
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const lines = text.split("\n");
|
||||
lines.pop(); // "" after a complete last line, or the half-written one
|
||||
const out = [];
|
||||
for (const line of lines) {
|
||||
if (!line.trim()) continue;
|
||||
try {
|
||||
const entry = JSON.parse(line);
|
||||
if (entry && typeof entry === "object") out.push(entry);
|
||||
} catch {}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Append one JSON line to an ndjson file, returning what was stored.
|
||||
export function appendJsonLine(file, stored) {
|
||||
let lead = "";
|
||||
try {
|
||||
const st = fs.statSync(file);
|
||||
// A fragment left by a crash mid-append must not swallow this line too.
|
||||
if (st.size > 0) {
|
||||
const fd = fs.openSync(file, "r");
|
||||
try {
|
||||
const b = Buffer.alloc(1);
|
||||
fs.readSync(fd, b, 0, 1, st.size - 1);
|
||||
if (b[0] !== 0x0a) lead = "\n";
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
}
|
||||
} catch {}
|
||||
const line = lead + JSON.stringify(stored) + "\n";
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
fs.appendFileSync(file, line);
|
||||
return stored;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
|
||||
sleepSync(40 * (attempt + 1));
|
||||
}
|
||||
}
|
||||
throw lastErr;
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
// Plan2Code Web Console - the Quick question chat's inbox beside the card slot.
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { appendJsonLine, nowIso, readJson, readJsonLines, writeJsonAtomic } from "./files.mjs";
|
||||
import { isPlainObject, proseProblems } from "./patches.mjs";
|
||||
|
||||
/* ------------------------------------------------------- the chat inbox */
|
||||
|
||||
// The Quick question chat rides its own channel beside the card slot, so the
|
||||
// two never contend: a chat message never waits on an uncollected card send,
|
||||
// and a card send never waits on chat. Every file has exactly one writer:
|
||||
//
|
||||
// chat.ndjson the server. One JSON line per entry: message / decision / reset.
|
||||
// chat-cursor.json console.mjs. The last seq the agent was handed.
|
||||
// state.json console.mjs `post`. The agent's replies, under chat.replies.
|
||||
// (state.json as a whole has a second writer, the server's
|
||||
// /submit, so every change to it goes through updateState().)
|
||||
//
|
||||
// The Workspace and the session meter follow the same rule, in files that
|
||||
// switchWorkflow() never touches, so they carry across dashboard hops:
|
||||
//
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
|
||||
/**
|
||||
* The inbox's entries with `seq > afterSeq`. A final segment with no newline
|
||||
* is a line still being written: it is left for the next read, never parsed
|
||||
* half-way. A line that will not parse is skipped rather than thrown on.
|
||||
*/
|
||||
export function readChat(dir, afterSeq = 0) {
|
||||
return readJsonLines(path.join(dir, CHAT_FILE)).filter((e) => Number.isInteger(e.seq) && e.seq > afterSeq);
|
||||
}
|
||||
|
||||
// Single-writer rule: only the server may call this (server.mjs and its routes).
|
||||
export function appendChat(dir, entry) {
|
||||
const last = readChat(dir).reduce((max, e) => Math.max(max, e.seq), 0);
|
||||
return appendJsonLine(path.join(dir, CHAT_FILE), { ...entry, seq: last + 1, at: nowIso() });
|
||||
}
|
||||
|
||||
export function readCursor(dir) {
|
||||
const saved = readJson(path.join(dir, CHAT_CURSOR_FILE), { seq: 0 });
|
||||
const n = Number(saved && saved.seq);
|
||||
return Number.isInteger(n) && n > 0 ? n : 0;
|
||||
}
|
||||
|
||||
// Never backwards: a slow collector finishing after a faster one must not
|
||||
// hand the faster one's entries over again.
|
||||
export function writeCursor(dir, seq) {
|
||||
writeJsonAtomic(path.join(dir, CHAT_CURSOR_FILE), { seq: Math.max(readCursor(dir), seq) });
|
||||
}
|
||||
|
||||
// The conversation the inbox is on: the one its last reset opened.
|
||||
export function currentConversation(entries) {
|
||||
for (let i = entries.length - 1; i >= 0; i--) {
|
||||
const e = entries[i];
|
||||
if (e.kind === "reset") return { conversation: e.conversation, workflow: e.workflow || "", sinceSeq: e.seq };
|
||||
}
|
||||
return { conversation: 0, workflow: "", sinceSeq: 0 };
|
||||
}
|
||||
|
||||
// Typed messages only: Approve / Decline and resets never count to the limit.
|
||||
export function typedCount(entries, conversation) {
|
||||
return entries.filter((e) => e.kind === "message" && e.conversation === conversation).length;
|
||||
}
|
||||
|
||||
/**
|
||||
* The chat block of a page frame: the current conversation's person entries
|
||||
* from the inbox and the agent's replies from the state, as one list. A reply
|
||||
* sits straight after the entry it answers; one naming nothing here goes last.
|
||||
*/
|
||||
export function chatForFrame(entries, state) {
|
||||
const { conversation } = currentConversation(entries);
|
||||
const person = entries
|
||||
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
|
||||
.sort((a, b) => a.seq - b.seq);
|
||||
const replies = (state?.chat?.replies || []).filter((r) => r && r.conversation === conversation);
|
||||
const messages = [];
|
||||
const placed = new Set();
|
||||
for (const p of person) {
|
||||
messages.push({ from: "person", ...p });
|
||||
replies.forEach((r, i) => {
|
||||
if (r.re !== p.seq) return;
|
||||
messages.push({ from: "agent", ...r });
|
||||
placed.add(i);
|
||||
});
|
||||
}
|
||||
replies.forEach((r, i) => placed.has(i) || messages.push({ from: "agent", ...r }));
|
||||
return { conversation, messages, typed: typedCount(entries, conversation), limit: CHAT_LIMIT };
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent has not been handed yet: entries past the cursor, minus any
|
||||
* message or decision that already has a reply. The second half is what keeps
|
||||
* a lost cursor from ever causing a second answer. Resets always go through.
|
||||
*/
|
||||
export function collectChat(dir, state) {
|
||||
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
|
||||
return readChat(dir, readCursor(dir)).filter((e) => e.kind === "reset" || !replied.has(e.seq));
|
||||
}
|
||||
|
||||
// What is worth handing over: the collected entries once one of them is
|
||||
// something the person said. A reset alone (every session opens with one)
|
||||
// waits and rides along with the next message, or `wait` would return on the
|
||||
// opening line of every session and every first card reply would carry it.
|
||||
// A run of resets (the session's opening one, then one per skill switch)
|
||||
// says one thing, so only the last of each run is handed over; it carries the
|
||||
// highest seq of the run, so the cursor still moves past all of them.
|
||||
export function deliverableChat(entries) {
|
||||
if (!entries.some((e) => e.kind !== "reset")) return [];
|
||||
return entries.filter((e, i) => !(e.kind === "reset" && entries[i + 1] && entries[i + 1].kind === "reset"));
|
||||
}
|
||||
|
||||
// Things the person said that were handed over but never answered. The page keeps
|
||||
// showing "working on the answer" for each until a reply lands, so the agent is
|
||||
// told on every post and every wait slice until it has replied (a refusal is a reply).
|
||||
export function unansweredChat(dir, state) {
|
||||
const { conversation } = currentConversation(readChat(dir, 0));
|
||||
const replied = new Set((state?.chat?.replies || []).map((r) => r && r.re));
|
||||
const cursor = readCursor(dir);
|
||||
return readChat(dir, 0)
|
||||
.filter((e) => (e.kind === "message" || e.kind === "decision") && e.conversation === conversation)
|
||||
.filter((e) => e.seq <= cursor && !replied.has(e.seq))
|
||||
.map((e) => e.seq);
|
||||
}
|
||||
|
||||
// How many things the person said are still waiting to be collected.
|
||||
export function pendingChatCount(dir, state) {
|
||||
return collectChat(dir, state).filter((e) => e.kind !== "reset").length;
|
||||
}
|
||||
|
||||
// The chat entries as the lines appended to `reply`, in the note's shape.
|
||||
// Whatever the person typed is indented past its first line, so only a real
|
||||
// entry ever starts a line: a typed "Approved: edit p1" must not read as one.
|
||||
export function chatReplyLines(entries) {
|
||||
const indent = (s, pad) => String(s).replace(/\r?\n/g, "\n" + pad);
|
||||
const lines = [];
|
||||
for (const e of entries) {
|
||||
if (e.kind === "message") {
|
||||
lines.push(`Quick question: ${indent(e.text, " ")}`);
|
||||
if (e.about && e.about.label) lines.push(` About: ${indent(e.about.label, " ")}`);
|
||||
for (const img of e.images || []) lines.push(` Image: ${img.path} (${img.name})`);
|
||||
for (const f of e.files || []) lines.push(` File: ${f.path} (${f.name})`);
|
||||
} else if (e.kind === "decision") {
|
||||
lines.push(`${e.decision === "approve" ? "Approved" : "Declined"}: edit ${e.re}`);
|
||||
if (e.text) lines.push(` Note: ${indent(e.text, " ")}`);
|
||||
} else if (e.kind === "reset") {
|
||||
lines.push("New conversation started. Treat earlier chat as closed.");
|
||||
}
|
||||
}
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
// A project-relative path: no root, no drive letter, no step outside.
|
||||
function projectRelative(p) {
|
||||
if (typeof p !== "string" || !p.trim()) return false;
|
||||
if (/^[\\/]/.test(p) || /^[A-Za-z]:/.test(p)) return false;
|
||||
return !p.split(/[\\/]/).includes("..");
|
||||
}
|
||||
|
||||
function underSpec(file, specDir) {
|
||||
const norm = (s) => {
|
||||
const t = s.replace(/\\/g, "/").replace(/^\.\//, "").replace(/\/+$/, "");
|
||||
return process.platform === "win32" ? t.toLowerCase() : t;
|
||||
};
|
||||
const f = norm(file);
|
||||
const spec = norm(specDir);
|
||||
return Boolean(spec) && (f === spec || f.startsWith(spec + "/"));
|
||||
}
|
||||
|
||||
/**
|
||||
* The house rules for the agent's chat replies, checked against the inbox
|
||||
* they answer. Same shape as validate(): problems as sentences, [] when fine.
|
||||
*/
|
||||
export function validateChat(state, entries) {
|
||||
const replies = state?.chat?.replies;
|
||||
if (replies == null) return [];
|
||||
if (!Array.isArray(replies)) return ['"chat.replies" must be an array'];
|
||||
const problems = [];
|
||||
const targets = new Set(
|
||||
entries.filter((e) => e.kind === "message" || e.kind === "decision").map((e) => e.seq)
|
||||
);
|
||||
const ids = new Set();
|
||||
for (const r of replies) {
|
||||
if (!isPlainObject(r)) {
|
||||
problems.push("every chat reply must be an object");
|
||||
continue;
|
||||
}
|
||||
const name = typeof r.id === "string" && r.id.trim() ? r.id : "(no id)";
|
||||
if (name === "(no id)") problems.push('every chat reply needs a non-empty string "id"');
|
||||
else if (ids.has(r.id)) problems.push(`duplicate chat reply id "${r.id}"`);
|
||||
ids.add(r.id);
|
||||
if (!Number.isInteger(r.re) || !targets.has(r.re)) {
|
||||
problems.push(`chat reply "${name}" needs "re": the seq of the message or decision it answers`);
|
||||
}
|
||||
if (!Number.isInteger(r.conversation)) problems.push(`chat reply "${name}" needs an integer "conversation"`);
|
||||
if (typeof r.md !== "string" || !r.md.trim()) problems.push(`chat reply "${name}" needs its answer in "md"`);
|
||||
|
||||
const p = r.proposal;
|
||||
if (p != null) {
|
||||
if (!isPlainObject(p)) problems.push(`chat reply "${name}" "proposal" must be an object`);
|
||||
else {
|
||||
if (typeof p.summary !== "string" || !p.summary.trim()) {
|
||||
problems.push(`chat reply "${name}" proposal needs a plain-English "summary"`);
|
||||
}
|
||||
if (!Array.isArray(p.files) || !p.files.length) {
|
||||
problems.push(`chat reply "${name}" proposal needs "files": the project files it would change`);
|
||||
} else {
|
||||
for (const f of p.files) {
|
||||
if (!projectRelative(f)) {
|
||||
problems.push(`chat reply "${name}" proposal file "${f}" must be a project-relative path`);
|
||||
} else if (state.specDir && underSpec(f, state.specDir)) {
|
||||
problems.push(`a chat edit cannot touch the running skill's own files under ${state.specDir}/`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (r.changed != null) {
|
||||
const count = (n) => Number.isInteger(n) && n >= 0;
|
||||
if (!Array.isArray(r.changed) || !r.changed.every((c) => isPlainObject(c) && typeof c.file === "string" && count(c.added) && count(c.removed))) {
|
||||
problems.push(`chat reply "${name}" "changed" must be a list of { file, added, removed }`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const prose = JSON.stringify(replies.map((r) => [r && r.md, r && r.proposal && r.proposal.summary]));
|
||||
problems.push(...proseProblems(prose, "a chat reply"));
|
||||
return problems;
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,858 @@
|
||||
// Plan2Code Web Console - checking and merging an agent's patch into the session state.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { checkHelpers } from "./public/subagents.js";
|
||||
import { nowIso, SCHEMA } from "./files.mjs";
|
||||
import { TASK_LINE_RE } from "./scan.mjs";
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
export function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
}
|
||||
|
||||
// Reject prototype-pollution attempts before they reach the merge.
|
||||
function guard(obj, where) {
|
||||
if (isPlainObject(obj) && Object.prototype.hasOwnProperty.call(obj, "__proto__")) {
|
||||
throw new Error(`"__proto__" is not a valid key (in ${where})`);
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
function mergeOne(target, patch, where) {
|
||||
const out = { ...(target || {}) };
|
||||
for (const [k, v] of Object.entries(guard(patch, where))) {
|
||||
if (v === null) delete out[k];
|
||||
else if (APPEND_KEYS.has(k) && Array.isArray(v)) out[k] = [...(out[k] || []), ...v];
|
||||
else out[k] = v;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
guard(entry, where);
|
||||
const id = entry[idKey];
|
||||
if (!id) throw new Error(`every ${where} entry needs "${idKey}"`);
|
||||
const i = out.findIndex((x) => x[idKey] === id);
|
||||
if (entry._delete) {
|
||||
if (i !== -1) out.splice(i, 1);
|
||||
} else if (i === -1) out.push(mergeOne({ ...defaults, [idKey]: id }, entry, where));
|
||||
else out[i] = mergeOne(out[i], entry, where);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const ITEM_DEFAULTS = {
|
||||
status: "open",
|
||||
required: true,
|
||||
allowOther: true,
|
||||
options: [],
|
||||
thread: [],
|
||||
};
|
||||
|
||||
// The question a card asks. If a patch rewrites any of these on a known id, it
|
||||
// is a new question wearing an old id.
|
||||
const QUESTION_FIELDS = ["kind", "title", "body", "options", "steps", "rows", "summary", "doc", "verdicts"];
|
||||
|
||||
/**
|
||||
* Merge item patches by id, and keep a reused id from inheriting the person's
|
||||
* old answer. `submitted` is the server's record of what they sent to the
|
||||
* PREVIOUS question. When a patch changes what an item asks and doesn't itself
|
||||
* settle it, that record (and any stale `answer`) is dropped, so the page shows
|
||||
* the new question as open instead of "Sent, waiting for Plan2Code" forever.
|
||||
*/
|
||||
function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
const merged = mergeKeyed(currentItems, patchList, "id", ITEM_DEFAULTS, "items");
|
||||
for (const entry of patchList) {
|
||||
const prev = (before || []).find((x) => x.id === entry.id);
|
||||
if (!prev || (prev.submitted === undefined && prev.answer === undefined)) continue;
|
||||
const rewritten = QUESTION_FIELDS.some(
|
||||
(f) => f in entry && JSON.stringify(entry[f]) !== JSON.stringify(prev[f]),
|
||||
);
|
||||
const settles = entry.status === "answered" || entry.status === "skipped" || "answer" in entry;
|
||||
// A settled question edited in place (a typo in its body) stays settled; only an
|
||||
// explicit reopen turns it into a new question.
|
||||
const wasSettled = prev.status === "answered" || prev.status === "skipped";
|
||||
// A different kind is never a typo fix: a multi turned confirm is another question.
|
||||
const kindChanged = "kind" in entry && entry.kind !== prev.kind;
|
||||
const reopens = entry.status === "open" || entry.status === "reopened" || kindChanged;
|
||||
// An explicit reopen counts as asking again even with the question's
|
||||
// words unchanged (the notes reopen with a status and a thread reply):
|
||||
// the last send stops being in flight, and its note moves to the thread.
|
||||
if ((!rewritten && !reopens) || settles || (wasSettled && !reopens)) continue;
|
||||
const item = merged.find((x) => x.id === entry.id);
|
||||
if (wasSettled && !("status" in entry)) item.status = "open";
|
||||
// What they wrote with that answer ("I want changes: rename tally") is the
|
||||
// context for the question being asked again, so it moves into the thread
|
||||
// rather than leaving with the record.
|
||||
const said = prev.submitted && typeof prev.submitted.text === "string" ? prev.submitted.text.trim() : "";
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
if (said && !thread.some((m) => m && m.who === "user" && String(m.text || "").trim() === said)) {
|
||||
item.thread = [...thread.filter((m) => !(m && m.who === "agent" && m.at === undefined)), { who: "user", text: said, at: prev.submitted.at }, ...thread.filter((m) => m && m.who === "agent" && m.at === undefined)];
|
||||
}
|
||||
if (!("submitted" in entry)) delete item.submitted;
|
||||
delete item.answer;
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
const doc = merged.find((d) => d.id === entry.id);
|
||||
if (!doc) continue;
|
||||
const prev = (current || []).find((d) => d.id === entry.id);
|
||||
doc.blocks = mergeKeyed(prev?.blocks, entry.blocks, "id", {}, "blocks");
|
||||
// A known doc whose content moved, sent with no version, is the next
|
||||
// version: the agent no longer has to track what the page holds, and a
|
||||
// repost of unchanged content is not a new version.
|
||||
if (prev && typeof entry.version !== "number" && typeof prev.version === "number") {
|
||||
const text = (blocks) => JSON.stringify((blocks || []).map((b) => [b.id, b.md, b.state, b.image, b.alt]));
|
||||
if (text(prev.blocks) !== text(doc.blocks)) doc.version = prev.version + 1;
|
||||
}
|
||||
}
|
||||
return merged;
|
||||
}
|
||||
|
||||
/**
|
||||
* `settle` in a patch: the cards the person just answered, marked answered
|
||||
* with what they sent as the answer. `true` takes every open card from the
|
||||
* latest send (one send stamps every card it carries with the same `at`); a
|
||||
* list names the cards. An item the same patch settles itself keeps the
|
||||
* agent's own answer: settle only fills in what the patch left out.
|
||||
*/
|
||||
function settleItems(items, settle, patchItems, collected) {
|
||||
if (settle === undefined || settle === false) return items;
|
||||
if (settle !== true && !(Array.isArray(settle) && settle.every((id) => typeof id === "string"))) {
|
||||
throw new Error('"settle" must be true or a list of item ids');
|
||||
}
|
||||
const sent = (items || []).filter((i) => i && i.submitted && typeof i.submitted === "object");
|
||||
let ids;
|
||||
if (settle === true && collected && Array.isArray(collected.ids)) {
|
||||
// The send `wait` last handed over (state.collected, written as it was
|
||||
// collected): a later send the person made meanwhile is not the agent's yet.
|
||||
ids = sent.filter((i) => isOpen(i) && collected.ids.includes(i.id)).map((i) => i.id);
|
||||
} else if (settle === true) {
|
||||
const latest = sent.filter(isOpen).map((i) => String(i.submitted.at || "")).sort().pop();
|
||||
ids = sent.filter((i) => isOpen(i) && String(i.submitted.at || "") === latest).map((i) => i.id);
|
||||
} else {
|
||||
for (const id of settle) {
|
||||
// The same patch reopening it has already let go of what was sent; the
|
||||
// reopen wins below, so naming it is not an error.
|
||||
const reopening = (patchItems || []).some((e) => e && e.id === id && (e.status === "open" || e.status === "reopened"));
|
||||
if (!reopening && !sent.some((i) => i.id === id)) throw new Error(`settle: "${id}" has nothing sent to settle`);
|
||||
}
|
||||
ids = settle;
|
||||
}
|
||||
const own = new Map((patchItems || []).filter(isPlainObject).map((e) => [e.id, e]));
|
||||
return items.map((item) => {
|
||||
if (!ids.includes(item.id)) return item;
|
||||
const entry = own.get(item.id) || {};
|
||||
// The same patch reopening it (a `changes` verdict answered by a reworked
|
||||
// report) means it is not settled: no answer is recorded over the reopen.
|
||||
if (entry.status === "open" || entry.status === "reopened") return item;
|
||||
const { at, kind, ...answer } = item.submitted;
|
||||
return {
|
||||
...item,
|
||||
// A "Skip this one" send settles as skipped, not as an answer.
|
||||
status: "status" in entry ? item.status : answer.skipped === true ? "skipped" : "answered",
|
||||
...("answer" in entry ? {} : { answer }),
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// A question the patch puts in front of the person: new, or reopened.
|
||||
function asksSomething(patchItems, before) {
|
||||
return (patchItems || []).some((e) => {
|
||||
if (!isPlainObject(e) || e._delete || e.kind === "notice") return false;
|
||||
const prev = (before || []).find((x) => x && x.id === e.id);
|
||||
if (!prev) return e.kind !== undefined && (e.status === undefined || e.status === "open");
|
||||
return e.status === "reopened" || (e.status === "open" && !isOpen(prev));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The agent block after a patch, with the rule kept here rather than in every
|
||||
* prompt: a patch that asks a question and says nothing of the status hands
|
||||
* the turn over (a question stops the work). `quietMinutes` stays put: the
|
||||
* page only counts it while working, and a build that asked a question goes
|
||||
* back to the same long tasks once it is answered.
|
||||
*/
|
||||
function settleAgent(next, patch, before) {
|
||||
const said = isPlainObject(patch.agent) ? patch.agent : null;
|
||||
const saidStatus = said && "status" in said;
|
||||
// A finish ends the working stretch too (nothing may still be running at
|
||||
// one): a pause posted without a wait would otherwise sit at "working".
|
||||
const finishes = isPlainObject(patch.finish);
|
||||
if (!saidStatus && (finishes || asksSomething(patch.items, before.items))) {
|
||||
next.agent = { ...(next.agent || {}), status: "waiting" };
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Doc blocks that name a file get their `md` from disk: a build's phase file
|
||||
* re-posted after every task was the biggest thing an agent typed, and every
|
||||
* word of it was already on disk. `{ "id": "body", "file": "specs/x/phase-3.md" }`
|
||||
* reads the file; `"select": "tasks"` keeps only its task checkbox lines; a doc
|
||||
* with `"refresh": true` re-reads every file block it already has. Paths are
|
||||
* relative to the worktree and must stay inside it. Runs in the CLI before
|
||||
* the merge, so applyPatch itself never touches the disk.
|
||||
*/
|
||||
export const DOC_FILE_MAX = 512 * 1024;
|
||||
|
||||
export function resolveDocFiles(patch, state, worktree) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const root = path.resolve(worktree || state.worktree || process.cwd());
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const read = (file, select, docId) => {
|
||||
if (typeof file !== "string" || !file.trim()) throw new Error(`doc "${docId}": a block's "file" must be a path`);
|
||||
const abs = path.resolve(root, file);
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(abs);
|
||||
} catch {
|
||||
throw new Error(`doc "${docId}": no file at ${file}`);
|
||||
}
|
||||
const rootReal = (() => {
|
||||
try {
|
||||
return fs.realpathSync.native(root);
|
||||
} catch {
|
||||
return root;
|
||||
}
|
||||
})();
|
||||
// path.relative, not a prefix test: a worktree at a drive root ends in a
|
||||
// separator already, and win32's relative() folds case itself.
|
||||
const rel = path.relative(fold(rootReal), fold(real));
|
||||
if (rel.startsWith("..") || path.isAbsolute(rel)) throw new Error(`doc "${docId}": ${file} is outside the project`);
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw new Error(`doc "${docId}": ${file} is not a file`);
|
||||
if (stat.size > DOC_FILE_MAX) throw new Error(`doc "${docId}": ${file} is larger than ${DOC_FILE_MAX / 1024} KB`);
|
||||
const text = fs.readFileSync(real, "utf8").replace(/\r\n/g, "\n");
|
||||
if (select === undefined) return text;
|
||||
if (select !== "tasks") throw new Error(`doc "${docId}": "select" only takes "tasks"`);
|
||||
const tasks = text.split("\n").filter((l) => TASK_LINE_RE.test(l)).map((l) => l.trim());
|
||||
if (!tasks.length) throw new Error(`doc "${docId}": ${file} has no task lines to select`);
|
||||
return tasks.join("\n");
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
if (!isPlainObject(entry)) return entry;
|
||||
const { refresh, ...rest } = entry;
|
||||
let blocks = Array.isArray(rest.blocks) ? rest.blocks : undefined;
|
||||
if (refresh === true) {
|
||||
const prev = (state.docs || []).find((d) => d && d.id === entry.id);
|
||||
const named = new Set((blocks || []).map((b) => b && b.id));
|
||||
const again = ((prev && prev.blocks) || [])
|
||||
.filter((b) => b && typeof b.file === "string" && !named.has(b.id))
|
||||
.map((b) => ({ id: b.id, file: b.file, ...(b.select ? { select: b.select } : {}) }));
|
||||
if (!again.length && !blocks) throw new Error(`doc "${entry.id}": "refresh" found no file blocks to re-read`);
|
||||
blocks = [...(blocks || []), ...again];
|
||||
} else if (refresh !== undefined) throw new Error(`doc "${entry.id}": "refresh" must be true`);
|
||||
if (!blocks) return rest;
|
||||
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
|
||||
return {
|
||||
...rest,
|
||||
blocks: blocks.map((b) => {
|
||||
if (!isPlainObject(b)) return b;
|
||||
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
|
||||
if (b.file === undefined || b.file === null) {
|
||||
// Typed text over a block that was a file: it stops being one, so a
|
||||
// later refresh cannot overwrite it and the prose scan sees it.
|
||||
return "md" in b && prevBlock && typeof prevBlock.file === "string" ? { ...b, file: null, select: null } : b;
|
||||
}
|
||||
// A file named again without `select` is the whole file, now and on
|
||||
// every refresh: an older select must not linger in the merge.
|
||||
const select = "select" in b ? b.select : null;
|
||||
return { state: prevBlock?.state || "settled", ...b, select, md: read(b.file, select ?? undefined, entry.id) };
|
||||
}),
|
||||
};
|
||||
});
|
||||
return { ...patch, docs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Image blocks: `{ "id", "image": "shots/run.png", "alt": "..." }` shows a
|
||||
* screenshot the agent saved under the session's `shots/` folder (Show me it
|
||||
* working). The path resolves against the session folder and must land, after
|
||||
* `realpath`, directly inside `<session>/shots/` under a plain name, so the page
|
||||
* can only ever be pointed at the agent's own pictures. The bytes decide the
|
||||
* type, as checkDocument() does for documents: a text file renamed `.png` is
|
||||
* refused. Stored session-relative; an image block never carries `md` or `file`.
|
||||
* Runs in the CLI beside resolveDocFiles(), so applyPatch never touches the disk.
|
||||
*/
|
||||
export const SHOTS_DIR_NAME = "shots";
|
||||
export const SHOT_MAX = 5 * 1024 * 1024;
|
||||
export const SHOT_NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(png|jpe?g|webp)$/i;
|
||||
|
||||
// What an image's first bytes say it is ("png", "jpeg", "webp"), or null.
|
||||
export function shotType(buf) {
|
||||
if (buf.length >= 8 && buf.subarray(0, 8).equals(Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]))) return "png";
|
||||
if (buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "jpeg";
|
||||
if (buf.length >= 12 && buf.toString("ascii", 0, 4) === "RIFF" && buf.toString("ascii", 8, 12) === "WEBP") return "webp";
|
||||
return null;
|
||||
}
|
||||
|
||||
export function resolveDocImages(patch, state, dir) {
|
||||
if (!isPlainObject(patch) || !Array.isArray(patch.docs)) return patch;
|
||||
const fold = (p) => (process.platform === "win32" || process.platform === "darwin" ? p.toLowerCase() : p);
|
||||
const shotsDir = path.join(path.resolve(dir), SHOTS_DIR_NAME);
|
||||
const check = (image, docId) => {
|
||||
if (typeof image !== "string" || !image.trim()) throw new Error(`doc "${docId}": an image block's "image" must be a path`);
|
||||
const where = `doc "${docId}": image ${image}`;
|
||||
let real;
|
||||
try {
|
||||
real = fs.realpathSync.native(path.resolve(dir, image));
|
||||
} catch {
|
||||
throw new Error(`${where} does not exist. Save it under the session's ${SHOTS_DIR_NAME}/ folder first.`);
|
||||
}
|
||||
let realShots;
|
||||
try {
|
||||
realShots = fs.realpathSync.native(shotsDir);
|
||||
} catch {
|
||||
realShots = shotsDir;
|
||||
}
|
||||
const name = path.basename(real);
|
||||
if (fold(path.dirname(real)) !== fold(realShots)) {
|
||||
throw new Error(`${where} is outside the session's ${SHOTS_DIR_NAME}/ folder (${shotsDir}); only pictures saved there can be shown.`);
|
||||
}
|
||||
if (!SHOT_NAME.test(name)) throw new Error(`${where}: name it with letters, digits, dots, dashes or underscores, ending .png, .jpg, .jpeg or .webp`);
|
||||
const stat = fs.statSync(real);
|
||||
if (!stat.isFile()) throw new Error(`${where} is not a file`);
|
||||
if (stat.size > SHOT_MAX) throw new Error(`${where} is larger than ${SHOT_MAX / 1024 / 1024} MB`);
|
||||
const ext = path.extname(name).slice(1).toLowerCase();
|
||||
const want = ext === "jpg" ? "jpeg" : ext;
|
||||
if (shotType(fs.readFileSync(real)) !== want) throw new Error(`${where} is not a ${want.toUpperCase()} image (its bytes say otherwise)`);
|
||||
return `${SHOTS_DIR_NAME}/${name}`;
|
||||
};
|
||||
const docs = patch.docs.map((entry) => {
|
||||
if (!isPlainObject(entry) || !Array.isArray(entry.blocks)) return entry;
|
||||
const prevBlocks = (state.docs || []).find((d) => d && d.id === entry.id)?.blocks || [];
|
||||
return {
|
||||
...entry,
|
||||
blocks: entry.blocks.map((b) => {
|
||||
if (!isPlainObject(b)) return b;
|
||||
const prevBlock = prevBlocks.find((x) => x && x.id === b.id);
|
||||
if (b.image === undefined || b.image === null) {
|
||||
// Text or a file over what was an image: it stops being one.
|
||||
return ("md" in b || "file" in b) && prevBlock && typeof prevBlock.image === "string" ? { ...b, image: null, alt: null } : b;
|
||||
}
|
||||
if (("md" in b && b.md != null) || ("file" in b && b.file != null)) {
|
||||
throw new Error(`doc "${entry.id}": block "${b.id}" is an image; it cannot also carry "md" or "file"`);
|
||||
}
|
||||
if (b.alt != null && typeof b.alt !== "string") throw new Error(`doc "${entry.id}": block "${b.id}" "alt" must be text`);
|
||||
return { state: prevBlock?.state || "settled", ...b, image: check(b.image, entry.id), md: null, file: null };
|
||||
}),
|
||||
};
|
||||
});
|
||||
return { ...patch, docs };
|
||||
}
|
||||
|
||||
/**
|
||||
* Apply an agent patch to the session state.
|
||||
*
|
||||
* Scalars replace, `null` deletes, `agent`/`headline` merge one level,
|
||||
* `items`/`topics`/`docs` merge by id, and so do a doc's `blocks`. The agent
|
||||
* sends only what changed: a whole-file rewrite would put the entire state
|
||||
* back into the agent's context on every turn, and the state grows with the
|
||||
* session.
|
||||
*/
|
||||
export function applyPatch(state, patch) {
|
||||
guard(patch, "patch");
|
||||
patch = liftActivity(patch);
|
||||
const { settle, ...rest } = patch;
|
||||
patch = rest;
|
||||
const next = { ...state };
|
||||
for (const [k, v] of Object.entries(patch)) {
|
||||
if (v === null) {
|
||||
delete next[k];
|
||||
continue;
|
||||
}
|
||||
switch (k) {
|
||||
case "agent":
|
||||
case "headline":
|
||||
next[k] = mergeOne(next[k], v, k);
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
break;
|
||||
case "chat": {
|
||||
// The agent's side of the Quick question chat. The person's side is
|
||||
// the inbox, which only the server writes; nothing else lives here.
|
||||
if (!isPlainObject(v)) throw new Error('"chat" must be an object');
|
||||
guard(v, "chat");
|
||||
const extra = Object.keys(v).filter((key) => key !== "replies");
|
||||
if (extra.length) throw new Error(`"chat" only takes "replies" (not ${extra.map((key) => `"${key}"`).join(", ")})`);
|
||||
const chat = { ...(next.chat || {}) };
|
||||
if (v.replies != null) {
|
||||
if (!Array.isArray(v.replies)) throw new Error('"chat.replies" must be an array');
|
||||
// A reply with no id is named for the message it answers (`r<seq>`),
|
||||
// so a repeat delivery re-posted the same way replaces, never doubles.
|
||||
const named = v.replies.map((r) =>
|
||||
isPlainObject(r) && (r.id === undefined || r.id === "") && Number.isInteger(r.re) ? { ...r, id: `r${r.re}` } : r,
|
||||
);
|
||||
chat.replies = mergeKeyed(chat.replies, named, "id", {}, "chat.replies");
|
||||
}
|
||||
next.chat = chat;
|
||||
break;
|
||||
}
|
||||
default:
|
||||
next[k] = v;
|
||||
}
|
||||
}
|
||||
if (settle !== undefined) next.items = settleItems(next.items || [], settle, patch.items, state.collected);
|
||||
return stampTimes(state, settleAgent(next, patch, state));
|
||||
}
|
||||
|
||||
// `activity` belongs under `agent`, which is the only place the page reads it.
|
||||
// Sent at the top level it would be stored where nothing looks, and the page
|
||||
// would sit on its starting screen while the skill works.
|
||||
function liftActivity(patch) {
|
||||
if (!Object.prototype.hasOwnProperty.call(patch, "activity")) return patch;
|
||||
const { activity, ...rest } = patch;
|
||||
if (rest.agent === null) return rest;
|
||||
const agent = isPlainObject(rest.agent) ? rest.agent : {};
|
||||
return { ...rest, agent: "activity" in agent ? agent : { ...agent, activity } };
|
||||
}
|
||||
|
||||
// The agent never writes a timestamp. Models do not reliably know the time,
|
||||
// and a wrong `since` makes the page's elapsed counters nonsense.
|
||||
function stampTimes(before, next) {
|
||||
const now = nowIso();
|
||||
if (next.agent) {
|
||||
// A status change starts its own clock: `since` merged along from the
|
||||
// last status would date a fresh working turn to when the session opened.
|
||||
const changed = !before.agent || before.agent.status !== next.agent.status;
|
||||
if (changed) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
for (const d of next.docs) {
|
||||
const prev = (before.docs || []).find((x) => x.id === d.id);
|
||||
if (!prev || prev.version !== d.version) d.at = d.at || now;
|
||||
}
|
||||
}
|
||||
next.updatedAt = now;
|
||||
return next;
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- house rules */
|
||||
|
||||
export const ITEM_KINDS = new Set([
|
||||
"choice",
|
||||
"multi",
|
||||
"text",
|
||||
"confirm",
|
||||
"recap",
|
||||
"review",
|
||||
"checklist",
|
||||
"menu",
|
||||
"list",
|
||||
"notice",
|
||||
]);
|
||||
|
||||
// grilling.md keeps an explicit do-not-say list: this bookkeeping vocabulary is
|
||||
// internal and must never reach the human. In the terminal that is a prompt rule
|
||||
// the model can drift from. Routing through a server makes it mechanical.
|
||||
const JARGON = [
|
||||
/\bgrill(ing|ed)?\b/i,
|
||||
/\bfrontier\b/i,
|
||||
/\bfog\b/i,
|
||||
/\bHITL\b/,
|
||||
/\bAFK\b/,
|
||||
/\bdurable\b/i,
|
||||
/Locked:/,
|
||||
/Blocked by:/,
|
||||
/\bState:\s/,
|
||||
];
|
||||
|
||||
// The loop parses these out of agent output; pathfinder forbids them under specs/.
|
||||
// The other copy is LOOP_TOKENS in src/skill-scripts/common.mjs: the console is
|
||||
// not a skill script and cannot import it, so keep the two in step.
|
||||
const FORBIDDEN_TOKENS =
|
||||
/\b(TASK_COMPLETE|PHASE_COMPLETE|ALL_TASKS_COMPLETE|IMPLEMENTATION_COMPLETE|SPEC_COMPLETE|WORK_COMPLETE)\b/;
|
||||
|
||||
// plan2code-metrics scrapes confidence with patterns that do NOT require a
|
||||
// percent sign, so a bare "Requirements 22" in a rendered doc can poison a run's
|
||||
// metrics. Keep those four words away from bare numbers. The skill scripts'
|
||||
// copy is SCRAPE in src/skill-scripts/common.mjs; keep the two in step.
|
||||
const METRICS_BAIT = /\b(Requirements?|Feasibility|Integration|Risk)[:\s|]+\d{1,2}\b/;
|
||||
|
||||
// The marker and metrics-bait scan on its own, for agent text that never
|
||||
// reaches state.json (a post's `run` / `folderIssue`). Problems as sentences.
|
||||
export function proseProblems(prose, subject = "text") {
|
||||
const problems = [];
|
||||
if (FORBIDDEN_TOKENS.test(prose)) {
|
||||
problems.push(`${subject} contains a loop completion marker (${prose.match(FORBIDDEN_TOKENS)[0]}); the loop scans for these`);
|
||||
}
|
||||
if (METRICS_BAIT.test(prose)) {
|
||||
problems.push(
|
||||
`${subject} contains "${prose.match(METRICS_BAIT)[0]}" — the metrics collector scrapes that pattern. ` +
|
||||
`Hyphenate it (Requirements-clarity 22/25) or reword.`
|
||||
);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
export const MAX_OPEN_REQUIRED = 3;
|
||||
|
||||
/**
|
||||
* Validate a merged state before it is written.
|
||||
*
|
||||
* Returns an array of human-readable problems. An empty array means the patch
|
||||
* is good. These checks turn four prose rules into mechanical ones.
|
||||
*/
|
||||
export function validate(state) {
|
||||
const problems = [];
|
||||
|
||||
if (!Array.isArray(state.items)) return ['"items" must be an array'];
|
||||
|
||||
const ids = new Set();
|
||||
for (const item of state.items) {
|
||||
if (!item.id) problems.push("every item needs an id");
|
||||
if (ids.has(item.id)) problems.push(`duplicate item id "${item.id}"`);
|
||||
ids.add(item.id);
|
||||
|
||||
if (!ITEM_KINDS.has(item.kind)) {
|
||||
problems.push(`item "${item.id}" has unknown kind "${item.kind}" (one of: ${[...ITEM_KINDS].join(", ")})`);
|
||||
}
|
||||
if (typeof item.title !== "string" || !item.title.trim()) {
|
||||
problems.push(`item "${item.id}" needs a plain-English title`);
|
||||
} else {
|
||||
for (const re of JARGON) {
|
||||
if (re.test(item.title)) {
|
||||
problems.push(
|
||||
`item "${item.id}" title contains internal vocabulary (${re.source}). Titles are read by people who have never seen this workflow.`
|
||||
);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((item.kind === "choice" || item.kind === "multi") && !Array.isArray(item.options)) {
|
||||
problems.push(`item "${item.id}" is a ${item.kind} and needs "options"`);
|
||||
}
|
||||
if ((item.kind === "choice" || item.kind === "multi") && Array.isArray(item.options)) {
|
||||
for (const o of item.options) {
|
||||
if (!o || typeof o.k !== "string" || !o.k.trim()) {
|
||||
problems.push(`item "${item.id}" has an option with no "k" (its key, like "A")`);
|
||||
} else if (typeof o.text !== "string" || !o.text.trim()) {
|
||||
problems.push(
|
||||
`item "${item.id}" option "${o.k}" needs "text" (the label) and optionally "detail". Options use "text"/"detail", not "label"/"desc".`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (item.verdicts != null) {
|
||||
if (!Array.isArray(item.verdicts) || !item.verdicts.length) {
|
||||
problems.push(`item "${item.id}" "verdicts" must be a non-empty array of { id, label }`);
|
||||
} else {
|
||||
for (const v of item.verdicts) {
|
||||
if (!v || typeof v.id !== "string" || !v.id.trim()) {
|
||||
problems.push(`item "${item.id}" has a verdict with no "id"`);
|
||||
} else if (typeof v.label !== "string" || !v.label.trim()) {
|
||||
problems.push(
|
||||
`item "${item.id}" verdict "${v.id}" needs a "label" (the button text). Verdicts use "label", not "text".`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
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 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) {
|
||||
if (typeof item.pattern !== "string") {
|
||||
problems.push(`item "${item.id}" "pattern" must be a string holding a JavaScript regular expression`);
|
||||
} else {
|
||||
try {
|
||||
new RegExp(item.pattern);
|
||||
} catch (e) {
|
||||
problems.push(`item "${item.id}" "pattern" is not a valid JavaScript regular expression: ${e.message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
const recs = (item.options || []).filter((o) => o.recommended);
|
||||
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
|
||||
}
|
||||
|
||||
// The dashboard's page is the menu: a card posted there is drawn nowhere,
|
||||
// yet counts as open (and keeps Stop live for a question nobody can see).
|
||||
if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) {
|
||||
problems.push(
|
||||
'The dashboard draws no question cards: post its "menu" (and "agent"), and launch the skill a question belongs to.'
|
||||
);
|
||||
}
|
||||
|
||||
// A notice asks nothing (the git board keeps its result line open all
|
||||
// session), so it never takes one of the three slots.
|
||||
const openRequired = state.items.filter((i) => i.required !== false && i.kind !== "notice" && isOpen(i));
|
||||
if (openRequired.length > MAX_OPEN_REQUIRED) {
|
||||
problems.push(
|
||||
`${openRequired.length} questions are open at once. The cap is ${MAX_OPEN_REQUIRED} ` +
|
||||
`(the ceiling is the person's attention, not the screen's). ` +
|
||||
`Send the rest after these are answered, or mark some "required": false.`
|
||||
);
|
||||
}
|
||||
|
||||
// The session's own ending. Absent for every session that is still running,
|
||||
// so only its shape is checked, never its presence. The command is optional:
|
||||
// a finish with no command is a finished session with nothing left to run,
|
||||
// and the page points at the dashboard instead of a next step.
|
||||
const fin = state.finish;
|
||||
if (fin != null) {
|
||||
if (typeof fin !== "object" || Array.isArray(fin)) {
|
||||
problems.push('"finish" must be an object');
|
||||
} else {
|
||||
if (typeof fin.headline !== "string" || !fin.headline.trim()) {
|
||||
problems.push('"finish" needs a plain-English "headline" saying what just happened');
|
||||
}
|
||||
if (fin.command != null && (typeof fin.command !== "string" || !fin.command.trim())) {
|
||||
problems.push('"finish.command" must be a non-empty string, or left out when there is nothing to run');
|
||||
} else if (fin.command != null && (fin.command.includes("<") || fin.command.includes(">"))) {
|
||||
// A rendered command is copied and run verbatim. A leftover
|
||||
// placeholder reaches someone who has no way to know what fills it.
|
||||
problems.push(`"finish.command" still has a placeholder in it ("${fin.command}"). Fill it in.`);
|
||||
}
|
||||
if (fin.console != null && typeof fin.console !== "boolean") {
|
||||
problems.push('"finish.console" must be true or false (or left out, to follow the command)');
|
||||
}
|
||||
if (fin.dashboard != null && typeof fin.dashboard !== "boolean") {
|
||||
problems.push('"finish.dashboard" must be true or false (or left out: no dashboard button)');
|
||||
}
|
||||
if (fin.commit != null && typeof fin.commit !== "boolean") {
|
||||
problems.push('"finish.commit" must be true or false (or left out: no commit button)');
|
||||
}
|
||||
// The review offer on a finished build: true, or an object carrying the
|
||||
// button's heading. The heading is read by the person, so it faces the
|
||||
// same vocabulary check as a title.
|
||||
if (fin.review != null && typeof fin.review !== "boolean") {
|
||||
if (typeof fin.review !== "object" || Array.isArray(fin.review)) {
|
||||
problems.push('"finish.review" must be true, false, or { "label": "..." }');
|
||||
} else if (fin.review.label != null) {
|
||||
if (typeof fin.review.label !== "string") {
|
||||
problems.push('"finish.review.label" must be a string');
|
||||
} else {
|
||||
const hit = JARGON.find((re) => re.test(fin.review.label));
|
||||
if (hit) problems.push(`"finish.review.label" contains internal vocabulary (${hit.source})`);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (const re of JARGON) {
|
||||
if (typeof fin.headline === "string" && re.test(fin.headline)) {
|
||||
problems.push(`"finish.headline" contains internal vocabulary (${re.source})`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// How long a silence is normal while the agent works (a build task). Bounded,
|
||||
// because the page stops calling a quiet agent stuck for this long, and a
|
||||
// huge number would hide a session that really has died.
|
||||
const quiet = state.agent && state.agent.quietMinutes;
|
||||
if (quiet != null && (typeof quiet !== "number" || !(quiet > 0) || quiet > 60)) {
|
||||
problems.push('"agent.quietMinutes" must be a number of minutes between 1 and 60 (or null to clear it)');
|
||||
}
|
||||
// The page reads exactly two: anything else would leave it guessing whose
|
||||
// turn it is.
|
||||
if (state.agent && state.agent.status != null && !["working", "waiting"].includes(state.agent.status)) {
|
||||
problems.push(`"agent.status" must be "working" or "waiting" (not "${state.agent.status}")`);
|
||||
}
|
||||
if (state.agent && state.agent.activity != null && typeof state.agent.activity !== "string") {
|
||||
problems.push('"agent.activity" must be a short sentence saying what you are doing');
|
||||
}
|
||||
|
||||
// Open gates only: an approval already given (last phase's sign-off) is a
|
||||
// record, and must not stop the next phase from asking for its own.
|
||||
const gates = state.items.filter((i) => i.gate && i.gate.authoritative && isOpen(i));
|
||||
if (gates.length > 1) {
|
||||
problems.push(
|
||||
`${gates.length} authoritative approval gates are open (${gates
|
||||
.map((g) => g.id)
|
||||
.join(", ")}). Only one workflow may own sign-off at a time.`
|
||||
);
|
||||
}
|
||||
|
||||
// An image block's alt text is its caption, read by the same newcomers a
|
||||
// title is.
|
||||
for (const d of state.docs || []) {
|
||||
for (const b of (isPlainObject(d) && Array.isArray(d.blocks) ? d.blocks : [])) {
|
||||
if (!isPlainObject(b) || typeof b.image !== "string" || typeof b.alt !== "string") continue;
|
||||
const hit = JARGON.find((re) => re.test(b.alt));
|
||||
if (hit) problems.push(`doc "${d.id}" image "${b.id}" alt text contains internal vocabulary (${hit.source})`);
|
||||
}
|
||||
}
|
||||
|
||||
// Scan what the AGENT wrote, never what the person typed. `submitted` is the
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
// A doc block read from a file (`file`) is the file's own words, already on
|
||||
// disk: the agent cannot reword it, and refusing it would wedge every post
|
||||
// that refreshes it. Only what the agent typed is scanned.
|
||||
const typedDocs = (state.docs || []).map((d) =>
|
||||
isPlainObject(d) && Array.isArray(d.blocks) ? { ...d, blocks: d.blocks.filter((b) => !(isPlainObject(b) && typeof b.file === "string")) } : d
|
||||
);
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(typedDocs) +
|
||||
JSON.stringify(state.finish || {}) +
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A finish ends the session, and a helper still shown as running would sit
|
||||
// on the Subagents tab, spinning, after everything is over.
|
||||
if (state.finish != null && Array.isArray(state.helpers)) {
|
||||
const running = state.helpers.filter((h) => isPlainObject(h) && h.state === "running").map((h) => `"${h.id}"`);
|
||||
if (running.length) {
|
||||
problems.push(`"finish" while helper ${running.join(", ")} still shows as running: post each one as done or failed first, or in the same patch`);
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
export function isOpen(item) {
|
||||
return item.status === "open" || item.status === "reopened";
|
||||
}
|
||||
|
||||
export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
return {
|
||||
schema: SCHEMA,
|
||||
sid,
|
||||
workflow: workflow || "pathfinder",
|
||||
title: title || "Session",
|
||||
project,
|
||||
specDir: specDir || "",
|
||||
created: nowIso(),
|
||||
phase: "collecting",
|
||||
agent: { status: "working", since: nowIso() },
|
||||
headline: { stage: "", cleared: 0, total: 0, confidence: "", note: "" },
|
||||
topics: [],
|
||||
items: [],
|
||||
docs: [],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu), or into Git from any skill
|
||||
* (Commit it now, Changelog's hand-off), is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
*/
|
||||
export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
return { ...blankState({ sid: state.sid, project: state.project, workflow, title, specDir }), created: state.created };
|
||||
}
|
||||
@@ -10,6 +10,9 @@
|
||||
// No DOM, no `local`, no fetch. If a function in here needs any of those, it
|
||||
// belongs in app.js instead.
|
||||
|
||||
import { FIXED_REASON, SKILLS, labelFor, skillByName, skillFor } from "./skills.js";
|
||||
import { SPEC_STATES, stateFor } from "./spec-states.js";
|
||||
|
||||
/* ----------------------------------------------------- the sent answer */
|
||||
|
||||
/**
|
||||
@@ -253,54 +256,18 @@ export function suggestionFrom(item) {
|
||||
|
||||
// The badge each workflow wears. Shared with the server, which writes it into
|
||||
// the page it serves so the first paint already names the session instead of
|
||||
// flashing a placeholder until the script arrives.
|
||||
export const WORKFLOW_LABEL = {
|
||||
dashboard: "Dashboard",
|
||||
init: "Setting up",
|
||||
"init-update": "Refreshing",
|
||||
pathfinder: "Pathfinder",
|
||||
plan: "Planning",
|
||||
"revise-plan": "Revising the plan",
|
||||
document: "Documenting",
|
||||
implement: "Building",
|
||||
"implement-review": "Building + review",
|
||||
review: "Review",
|
||||
"quick-task": "Quick task",
|
||||
finalize: "Wrapping up",
|
||||
handoff: "Handoff",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
xray: "X-ray",
|
||||
diagnose: "Diagnosing",
|
||||
};
|
||||
// flashing a placeholder until the script arrives. Derived from skills.js.
|
||||
export const WORKFLOW_LABEL = Object.fromEntries(SKILLS.map((s) => [s.workflow, s.label]));
|
||||
|
||||
export function workflowLabel(workflow) {
|
||||
return WORKFLOW_LABEL[workflow] || workflow || "Session";
|
||||
return labelFor(workflow) || workflow || "Session";
|
||||
}
|
||||
|
||||
// The workflows that ship the console (install.js bundles it into every
|
||||
// skill as `additionalReferences`). Any other next step has no browser page
|
||||
// to open, and asking for one would send the next session looking for
|
||||
// something that is not there.
|
||||
export const CONSOLE_WORKFLOWS = [
|
||||
"/plan2code",
|
||||
"/plan2code-init",
|
||||
"/plan2code-init-update",
|
||||
"/plan2code-0-pathfinder",
|
||||
"/plan2code-quick-task",
|
||||
"/plan2code-1-plan",
|
||||
"/plan2code-1b-revise-plan",
|
||||
"/plan2code-2-document",
|
||||
"/plan2code-3-implement",
|
||||
"/plan2code-3-implement-review",
|
||||
"/plan2code-review",
|
||||
"/plan2code-4-finalize",
|
||||
"/plan2code-handoff",
|
||||
"/plan2code-git",
|
||||
"/plan2code-changelog",
|
||||
"/plan2code-xray",
|
||||
"/plan2code-diagnose",
|
||||
];
|
||||
// something that is not there. Derived from skills.js: every entry is one.
|
||||
export const CONSOLE_WORKFLOWS = SKILLS.map((s) => s.command);
|
||||
|
||||
// Rides on the end of the command as part of the skill's argument. Every
|
||||
// console skill takes it as the answer to "web console or terminal?" instead
|
||||
@@ -567,192 +534,15 @@ export const CATALOG_GROUPS = [
|
||||
|
||||
// `spec: true` marks the cards that take a spec folder as their target: when
|
||||
// the picker has a spec selected, its `dir` rides along in the `__launch`
|
||||
// action so the launched skill knows which spec it was picked for.
|
||||
export const SKILL_CATALOG = [
|
||||
{
|
||||
skill: "plan2code-init",
|
||||
command: "/plan2code-init",
|
||||
workflow: "init",
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Set up this project",
|
||||
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
|
||||
about:
|
||||
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-init-update",
|
||||
command: "/plan2code-init-update",
|
||||
workflow: "init-update",
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Refresh AGENTS.md",
|
||||
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
|
||||
about:
|
||||
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-0-pathfinder",
|
||||
command: "/plan2code-0-pathfinder",
|
||||
workflow: "pathfinder",
|
||||
group: "pipeline",
|
||||
chip: "Step 0",
|
||||
spec: true,
|
||||
title: "Pathfinder",
|
||||
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
|
||||
about:
|
||||
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-1-plan",
|
||||
command: "/plan2code-1-plan",
|
||||
workflow: "plan",
|
||||
group: "pipeline",
|
||||
chip: "Step 1",
|
||||
spec: true,
|
||||
title: "Plan",
|
||||
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
|
||||
about:
|
||||
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-1b-revise-plan",
|
||||
command: "/plan2code-1b-revise-plan",
|
||||
workflow: "revise-plan",
|
||||
group: "pipeline",
|
||||
chip: "Step 1b",
|
||||
spec: true,
|
||||
title: "Revise the plan",
|
||||
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
|
||||
about:
|
||||
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-2-document",
|
||||
command: "/plan2code-2-document",
|
||||
workflow: "document",
|
||||
group: "pipeline",
|
||||
chip: "Step 2",
|
||||
spec: true,
|
||||
title: "Document",
|
||||
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
|
||||
about:
|
||||
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-3-implement",
|
||||
command: "/plan2code-3-implement",
|
||||
workflow: "implement",
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement",
|
||||
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
|
||||
about:
|
||||
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-3-implement-review",
|
||||
command: "/plan2code-3-implement-review",
|
||||
workflow: "implement-review",
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement + review",
|
||||
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
|
||||
about:
|
||||
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-4-finalize",
|
||||
command: "/plan2code-4-finalize",
|
||||
workflow: "finalize",
|
||||
group: "pipeline",
|
||||
chip: "Step 4",
|
||||
spec: true,
|
||||
title: "Finalize",
|
||||
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
|
||||
about:
|
||||
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-quick-task",
|
||||
command: "/plan2code-quick-task",
|
||||
workflow: "quick-task",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Quick task",
|
||||
blurb: "Too small for the full process? A quick plan, then it just builds it.",
|
||||
about:
|
||||
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-review",
|
||||
command: "/plan2code-review",
|
||||
workflow: "review",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Review",
|
||||
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
|
||||
about:
|
||||
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-xray",
|
||||
command: "/plan2code-xray",
|
||||
workflow: "xray",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Codebase X-ray",
|
||||
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
|
||||
about:
|
||||
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-diagnose",
|
||||
command: "/plan2code-diagnose",
|
||||
workflow: "diagnose",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Diagnose a bug",
|
||||
blurb: "Find a bug's cause and write it up, without fixing it.",
|
||||
about:
|
||||
"Something is broken and nobody knows why. Diagnose asks what goes wrong and how to see it, then builds a command that fails on the bug before it forms a theory. It narrows the cause down to a file and a function, says how sure it is, and sizes the fix. The write-up lands in a spec folder, and the dashboard then offers Quick Task to fix it, or Plan when the fix is big. It never changes code.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-changelog",
|
||||
command: "/plan2code-changelog",
|
||||
workflow: "changelog",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Changelog",
|
||||
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
|
||||
about:
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-git",
|
||||
command: "/plan2code-git",
|
||||
workflow: "git",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
about:
|
||||
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
|
||||
},
|
||||
{
|
||||
skill: "plan2code-handoff",
|
||||
command: "/plan2code-handoff",
|
||||
workflow: "handoff",
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Handoff",
|
||||
blurb: "Pack the current session into a document a fresh session can pick up cold.",
|
||||
about:
|
||||
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
|
||||
},
|
||||
];
|
||||
// action so the launched skill knows which spec it was picked for. Derived from
|
||||
// skills.js: the entries with a card, in their order, each card's fields
|
||||
// beside the skill's name, command and workflow.
|
||||
export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
|
||||
skill: s.skill,
|
||||
command: s.command,
|
||||
workflow: s.workflow,
|
||||
...s.card,
|
||||
}));
|
||||
|
||||
// A workflow by the name its dashboard card gives it ("Implement"), for the
|
||||
// screens that speak of it as a thing being started rather than as a badge.
|
||||
@@ -764,74 +554,79 @@ export function workflowTitle(workflow) {
|
||||
// Every skill gets its own Planny on the starting and waiting screens, drawn
|
||||
// as a <template data-pose> in index.html. A skill that is a variant of
|
||||
// another borrows its pose. Anything else (the dashboard) keeps the flight.
|
||||
export const START_POSES = [
|
||||
"init",
|
||||
"pathfinder",
|
||||
"plan",
|
||||
"document",
|
||||
"implement",
|
||||
"finalize",
|
||||
"quick-task",
|
||||
"review",
|
||||
"handoff",
|
||||
"git",
|
||||
"changelog",
|
||||
"xray",
|
||||
"diagnose",
|
||||
];
|
||||
|
||||
const POSE_ALIASES = { "init-update": "init", "revise-plan": "plan", "implement-review": "implement" };
|
||||
// Derived from skills.js: every pose an entry names, once.
|
||||
export const START_POSES = [...new Set(SKILLS.map((s) => s.pose).filter(Boolean))];
|
||||
|
||||
export function startPose(workflow) {
|
||||
const pose = POSE_ALIASES[workflow] || workflow;
|
||||
return START_POSES.includes(pose) ? pose : null;
|
||||
return skillFor(workflow)?.pose || null;
|
||||
}
|
||||
|
||||
export function catalogEntry(skill) {
|
||||
return SKILL_CATALOG.find((e) => e.skill === skill) || null;
|
||||
const entry = skillByName(skill);
|
||||
return entry && entry.card ? SKILL_CATALOG.find((e) => e.skill === entry.skill) : null;
|
||||
}
|
||||
|
||||
/* ------------------------------------------- dashboard card availability */
|
||||
|
||||
// What the picker shows next to a spec's name — the pipeline position the
|
||||
// server's scan worked out, in plain words.
|
||||
export const SPEC_STATE_LABELS = {
|
||||
diagnosed: "Bug diagnosed",
|
||||
fixed: "Bug fixed",
|
||||
exploring: "Exploring",
|
||||
mapped: "Ready to plan",
|
||||
planned: "Ready to document",
|
||||
documented: "Ready to build",
|
||||
building: "Building",
|
||||
built: "Ready to finalize",
|
||||
unrecognized: "Files on disk",
|
||||
};
|
||||
// server's scan worked out, in plain words. Derived from spec-states.js.
|
||||
export const SPEC_STATE_LABELS = Object.fromEntries(Object.entries(SPEC_STATES).map(([name, s]) => [name, s.label]));
|
||||
|
||||
// The card each spec state exists to light up. Used as the fallback for the
|
||||
// "Suggested" pill when the agent's menu payload names nothing.
|
||||
const NEXT_FOR_STATE = {
|
||||
diagnosed: "plan2code-quick-task",
|
||||
exploring: "plan2code-0-pathfinder",
|
||||
mapped: "plan2code-1-plan",
|
||||
planned: "plan2code-2-document",
|
||||
documented: "plan2code-3-implement",
|
||||
building: "plan2code-3-implement",
|
||||
built: "plan2code-4-finalize",
|
||||
};
|
||||
// "Suggested" pill when the agent's menu payload names nothing. Derived from
|
||||
// spec-states.js: the states that have one.
|
||||
const NEXT_FOR_STATE = Object.fromEntries(
|
||||
Object.entries(SPEC_STATES)
|
||||
.filter(([, s]) => s.next)
|
||||
.map(([name, s]) => [name, s.next])
|
||||
);
|
||||
|
||||
const ON = { on: true };
|
||||
export const GIT_INIT_NOTE = "Not a git repository yet: it offers to start one";
|
||||
export const pendingNote = (n) => `${n} file${n === 1 ? "" : "s"} to commit`;
|
||||
const off = (reason) => ({ on: false, reason });
|
||||
export const FIXED_REASON = "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/.";
|
||||
// Pathfinder's and Plan's reason on a fixed bug, kept on skills.js.
|
||||
export { FIXED_REASON };
|
||||
|
||||
/**
|
||||
* The spec the picker opens on: the most recently touched one that is still
|
||||
* in play. A fixed bug is finished, so it is never the default; with nothing
|
||||
* else on disk the picker opens on "start from scratch" (null).
|
||||
* in play. A finished spec (a fixed bug) is never the default; with nothing
|
||||
* else on disk the picker opens on "start from scratch" (null). `lookup` is
|
||||
* stateFor unless a test hands in its own table.
|
||||
*/
|
||||
export function defaultSpec(specs) {
|
||||
return (Array.isArray(specs) ? specs : []).find((s) => s && s.state !== "fixed") || null;
|
||||
export function defaultSpec(specs, lookup = stateFor) {
|
||||
return (Array.isArray(specs) ? specs : []).find((s) => s && !lookup(s.state)?.finished) || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The reassurance under "Starting up": a calm line at first, a pointer to the
|
||||
* terminal once the start has taken longer than ninety seconds.
|
||||
*/
|
||||
export function startingHint(elapsedMs) {
|
||||
return elapsedMs > 90000
|
||||
? "Still getting ready. Your terminal has the play-by-play if you want to watch it there."
|
||||
: "This page fills in by itself the moment Plan2Code has something for you. No need to touch anything.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the picker still shows the spec it opened on: `picked` is the
|
||||
* selected spec (or null for "start from scratch"), `first` the default one.
|
||||
* The agent's menu note describes that spec only, so another pick gets the
|
||||
* neutral line.
|
||||
*/
|
||||
export function onInitialPick(first, picked) {
|
||||
return first ? Boolean(picked && picked.dir === first.dir) : !picked;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which line the dashboard shows under its title: "agent" (the note the agent
|
||||
* posted), "looking" (the agent has not posted its menu yet and is working)
|
||||
* or "neutral".
|
||||
*/
|
||||
export function dashNoteKind({ menu, hasMenu, onInitial, working }) {
|
||||
if (menu && typeof menu.note === "string" && menu.note.trim() && onInitial) return "agent";
|
||||
if (!hasMenu && working) return "looking";
|
||||
return "neutral";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -845,61 +640,32 @@ export function defaultSpec(specs) {
|
||||
*
|
||||
* Returns { on, reason?, note?, next? } — `reason` is the one line a greyed card
|
||||
* shows, `note` the one line a clickable card shows when there is something to
|
||||
* know before launching it, `next` marks the state's natural step.
|
||||
* know before launching it, `next` marks the state's natural step. `lookup` is
|
||||
* stateFor unless a test hands in its own table.
|
||||
*/
|
||||
export function cardAvailability(entry, scan, sel) {
|
||||
export function cardAvailability(entry, scan, sel, lookup = stateFor) {
|
||||
const hasAgents = Boolean(scan && scan.hasAgents);
|
||||
const state = sel && sel.state && sel.state !== "unrecognized" ? sel.state : null;
|
||||
const next = sel ? Boolean(state) && NEXT_FOR_STATE[state] === entry.skill : entry.skill === "plan2code-0-pathfinder";
|
||||
const rule = skillByName(entry.skill);
|
||||
if (!rule || !rule.states) return ON;
|
||||
|
||||
switch (entry.skill) {
|
||||
case "plan2code-init":
|
||||
return hasAgents ? off("AGENTS.md is already written. Refresh it instead.") : ON;
|
||||
case "plan2code-init-update":
|
||||
return hasAgents ? ON : off("Needs an AGENTS.md. Set the project up first.");
|
||||
case "plan2code-quick-task":
|
||||
// Always on; a diagnosed bug is the one spec it is the next step for.
|
||||
return next ? { ...ON, next } : ON;
|
||||
case "plan2code-review":
|
||||
case "plan2code-handoff":
|
||||
case "plan2code-changelog":
|
||||
case "plan2code-xray":
|
||||
case "plan2code-diagnose":
|
||||
return ON;
|
||||
case "plan2code-git":
|
||||
// Never greyed: a clean tree still has branches to switch, pull and push.
|
||||
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
|
||||
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
|
||||
return ON;
|
||||
case "plan2code-0-pathfinder":
|
||||
if (!state || state === "exploring") return { ...ON, next };
|
||||
if (state === "diagnosed") return off("The cause is found. Fix it in a quick task, or plan it.");
|
||||
if (state === "fixed") return off(FIXED_REASON);
|
||||
return off("This spec is already past the questions");
|
||||
case "plan2code-1-plan":
|
||||
if (state === "exploring") return off("Pathfinder is not finished with this spec yet");
|
||||
if (state === "fixed") return off(FIXED_REASON);
|
||||
if (state === "documented" || state === "building" || state === "built")
|
||||
return off("The plan is written. Revise it instead if it moved.");
|
||||
return { ...ON, next };
|
||||
case "plan2code-1b-revise-plan":
|
||||
if (state === "documented" || state === "building") return ON;
|
||||
return off(state === "built" ? "The spec is fully built" : "Needs a spec that is already written up");
|
||||
case "plan2code-2-document":
|
||||
if (state === "planned") return { ...ON, next };
|
||||
if (state === "documented" || state === "building" || state === "built")
|
||||
return off("The phases are already written up");
|
||||
return off("Needs a drafted plan first");
|
||||
case "plan2code-3-implement":
|
||||
case "plan2code-3-implement-review":
|
||||
if (state === "documented" || state === "building") return { ...ON, next };
|
||||
return off(state === "built" ? "All tasks are already done" : "Needs the phase checklists written up first");
|
||||
case "plan2code-4-finalize":
|
||||
if (state === "built") return { ...ON, next };
|
||||
return off("Needs a spec that is fully built");
|
||||
default:
|
||||
return ON;
|
||||
// The three cards whose rules read the scan rather than the spec.
|
||||
if (entry.skill === "plan2code-init") return hasAgents ? off(rule.greyed.default) : ON;
|
||||
if (entry.skill === "plan2code-init-update") return hasAgents ? ON : off(rule.greyed.default);
|
||||
if (entry.skill === "plan2code-git") {
|
||||
// Never greyed: a clean tree still has branches to switch, pull and push.
|
||||
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
|
||||
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
|
||||
return ON;
|
||||
}
|
||||
|
||||
// Always on; a diagnosed bug is the one spec Quick Task is the next step for.
|
||||
if (rule.states === "any") return next ? { ...ON, next } : ON;
|
||||
// A state the table does not know is treated like files on disk.
|
||||
const taken = !sel || !sel.state ? "none" : lookup(sel.state) ? sel.state : "unrecognized";
|
||||
if (rule.states.includes(taken)) return rule.marksNext ? { ...ON, next } : ON;
|
||||
return off(rule.greyed[taken] || (lookup(taken)?.finished && rule.greyed.finished) || rule.greyed.default);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -946,7 +712,7 @@ export function launchReply(entry, spec) {
|
||||
|
||||
/**
|
||||
* Deleting a spec from the picker. The page only names the folder; the agent
|
||||
* deletes it (`console.mjs delete-spec`, which runs lib.mjs's removeSpec() on
|
||||
* deletes it (`console.mjs delete-spec`, which runs scan.mjs's removeSpec() on
|
||||
* this same rule), because the console never writes into a project. A
|
||||
* deletable dir is exactly `specs/<one name>`: no deeper path, no `.` or `..`,
|
||||
* no dotfolder, no backslash, never specs--completed/.
|
||||
@@ -996,10 +762,10 @@ export function handoffAge(written, now = Date.now()) {
|
||||
return `${days} day${days === 1 ? "" : "s"} ago`;
|
||||
}
|
||||
|
||||
// The line under a spec's name on its chip. A fixed bug's label already says
|
||||
// "Bug fixed", so the scan's "bug fixed" detail would only repeat it.
|
||||
// The line under a spec's name on its chip. A finished spec's label already
|
||||
// says it ("Bug fixed"), so the scan's "bug fixed" detail would only repeat it.
|
||||
export function chipDetail(spec) {
|
||||
return spec.state === "fixed" ? "" : spec.detail || "";
|
||||
return stateFor(spec.state)?.finished ? "" : spec.detail || "";
|
||||
}
|
||||
|
||||
export function deleteSummary(spec) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+50
-9082
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,202 @@
|
||||
// Plan2Code Web Console - a document as the page shows it, and as a file: blocks, Markdown and HTML download; defines only.
|
||||
//
|
||||
// Shared by the documents tab and the finished screen, so neither imports the other.
|
||||
|
||||
import { el, md } from "./render.js";
|
||||
|
||||
// A block's content: its markdown, or for an image block (a screenshot the
|
||||
// agent saved under the session's shots/ folder) a captioned picture.
|
||||
export function blockBody(b) {
|
||||
if (typeof b.image !== "string") return md(b.md, "md");
|
||||
const fig = el("figure", "doc-figure");
|
||||
const img = el("img", "doc-img");
|
||||
img.src = "/shots/" + b.image.split("/").pop();
|
||||
// The caption already says it: an alt repeating it is read twice, and shows
|
||||
// twice in an export whose picture would not load.
|
||||
img.alt = "";
|
||||
img.loading = "lazy";
|
||||
fig.appendChild(img);
|
||||
if (b.alt) fig.appendChild(el("figcaption", null, b.alt));
|
||||
return fig;
|
||||
}
|
||||
|
||||
// Markdown rather than HTML: it is what the agent wrote, what the file under
|
||||
// specs/ already holds, and what survives being pasted into Slack or a ticket.
|
||||
export function downloadDoc(doc) {
|
||||
// The file keeps what the page shows: the title, and which parts are still
|
||||
// assumptions or drafts. Without the marks a half-finished document reads,
|
||||
// once it leaves the page, as a set of decisions.
|
||||
const mark = { assumed: "> **Assumed for now, still open.**\n\n", draft: "> **Draft.**\n\n" };
|
||||
const blocks = (doc.blocks || []).map((b) => (mark[b.state] || "") + (typeof b.image === "string" ? b.alt || "" : b.md || ""));
|
||||
const first = (doc.blocks || [])[0];
|
||||
const titled = first && /^\s*#\s/.test(first.md || "");
|
||||
const body = [titled || !doc.title ? null : `# ${doc.title}`, ...blocks].filter((x) => x != null).join("\n\n");
|
||||
saveFile(`${docFileName(doc)}.md`, body, "text/markdown");
|
||||
}
|
||||
|
||||
function docFileName(doc) {
|
||||
const name = (doc.title || "document").toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
|
||||
return name || "document";
|
||||
}
|
||||
|
||||
function saveFile(name, body, type) {
|
||||
const url = URL.createObjectURL(new Blob([body], { type }));
|
||||
const a = document.createElement("a");
|
||||
a.href = url;
|
||||
a.download = name;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
a.remove();
|
||||
// Give the download a tick to start before the handle goes.
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30000);
|
||||
}
|
||||
|
||||
// The page's own markdown styles, restated with the light palette baked in:
|
||||
// the saved file has no app.css beside it and may be opened years from now,
|
||||
// on any machine, so it carries everything it needs.
|
||||
const DOC_HTML_CSS = `
|
||||
:root { color-scheme: light; }
|
||||
body { margin: 0; background: #f6f3ee; color: #1d1a17; font: 15.5px/1.6 ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; }
|
||||
main { max-width: 880px; margin: 0 auto; padding: 40px 28px 60px; background: #fff; min-height: 100vh; box-sizing: border-box; }
|
||||
.doc-head { display: flex; gap: 12px; align-items: baseline; flex-wrap: wrap; margin-bottom: 16px; padding-bottom: 14px; border-bottom: 1px solid #e4ddd1; }
|
||||
.doc-head h1 { font: 600 27px/1.2 "Iowan Old Style", Charter, Georgia, Cambria, serif; margin: 0; }
|
||||
.doc-version, .doc-meta { font: 700 12px/1 ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; color: #8f8779; }
|
||||
.doc-note { color: #5d564d; margin: 0 0 16px; }
|
||||
.block { border-left: 3px solid transparent; padding: 2px 0 2px 14px; margin: 0 0 4px; }
|
||||
.block.assumed { border-left: 3px dashed #9a6a12; background: #fbf0d8; border-radius: 0 8px 8px 0; }
|
||||
.block.draft { border-left-color: #cfc6b6; opacity: 0.72; }
|
||||
.block.settled { border-left-color: #e4f0e8; }
|
||||
.block-tag { font-size: 10.5px; font-weight: 700; letter-spacing: 0.05em; text-transform: uppercase; color: #9a6a12; display: block; margin-bottom: 4px; }
|
||||
.md-h { font-family: "Iowan Old Style", Charter, Georgia, Cambria, serif; font-weight: 600; margin: 22px 0 9px; line-height: 1.25; }
|
||||
h1.md-h { font-size: 25px; }
|
||||
h2.md-h { font-size: 21px; }
|
||||
h3.md-h { font-size: 17.5px; }
|
||||
h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
.md-p { margin: 0 0 11px; }
|
||||
.md-list { margin: 0 0 11px; padding-left: 22px; }
|
||||
.md-li { margin-bottom: 5px; }
|
||||
.md-task { display: inline-block; width: 16px; color: #8f8779; font-weight: 700; }
|
||||
.md-task.is-done { color: #2f6b45; }
|
||||
.md-li.is-task { list-style: none; margin-left: -18px; display: grid; grid-template-columns: 16px 1fr; column-gap: 4px; align-items: baseline; }
|
||||
.md-li.is-task > :not(.md-task) { grid-column: 2; }
|
||||
.md-li.is-task > .md-p:last-child { margin-bottom: 0; }
|
||||
.md-quote { margin: 0 0 11px; padding: 2px 0 2px 15px; border-left: 3px solid #cfc6b6; color: #5d564d; }
|
||||
.md-code { font: 0.88em ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; background: #fbf9f6; border: 1px solid #e4ddd1; border-radius: 4px; padding: 1px 5px; }
|
||||
.md-pre-wrap { margin: 0 0 13px; }
|
||||
.md-pre { font: 13px/1.5 ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace; background: #fbf9f6; border: 1px solid #e4ddd1; border-radius: 8px; padding: 14px 16px; overflow-x: auto; margin: 0; }
|
||||
.md-hr { border: 0; border-top: 1px solid #e4ddd1; margin: 20px 0; }
|
||||
.md-table-wrap { overflow-x: auto; margin: 0 0 13px; }
|
||||
.md-table { border-collapse: collapse; width: 100%; font-size: 13.5px; }
|
||||
.md-table th, .md-table td { border: 1px solid #e4ddd1; padding: 8px 11px; text-align: left; }
|
||||
.md-table th { background: #fbf9f6; font-weight: 600; }
|
||||
.md-img { max-width: 100%; border-radius: 8px; }
|
||||
.doc-figure { margin: 0 0 13px; }
|
||||
.doc-img { display: block; max-width: 100%; border: 1px solid #e4ddd1; border-radius: 8px; }
|
||||
.doc-figure figcaption { font-size: 13px; color: #5d564d; margin-top: 6px; }
|
||||
.md a { color: #206cc3; }
|
||||
@media print {
|
||||
body { background: #fff; }
|
||||
main { padding: 0; min-height: 0; }
|
||||
.block { break-inside: avoid; }
|
||||
}
|
||||
`;
|
||||
|
||||
// Only this session's uploaded images may ride along in a saved file: any other
|
||||
// address on this origin (/state, say) would copy session data into something
|
||||
// meant to be shared. A remote image keeps its own address; anything else on
|
||||
// this origin becomes its alt text.
|
||||
const INLINE_UPLOAD = /^\/(?:uploads\/[0-9a-f-]{36}\.jpg|shots\/[A-Za-z0-9][A-Za-z0-9._-]{0,99}\.(?:png|jpe?g|webp))$/i;
|
||||
|
||||
function imageToAlt(img) {
|
||||
const alt = img.getAttribute("alt") || "";
|
||||
if (alt) img.replaceWith(document.createTextNode(alt));
|
||||
else img.remove();
|
||||
}
|
||||
|
||||
async function inlineImage(img) {
|
||||
const src = img.getAttribute("src") || "";
|
||||
if (!src || src.startsWith("data:")) return;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(src, location.href);
|
||||
} catch {
|
||||
return imageToAlt(img);
|
||||
}
|
||||
if (url.origin !== location.origin) {
|
||||
img.setAttribute("src", url.href);
|
||||
return;
|
||||
}
|
||||
if (!INLINE_UPLOAD.test(url.pathname) || url.search) return imageToAlt(img);
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const blob = await res.blob();
|
||||
if (!blob.type.startsWith("image/")) throw new Error(blob.type);
|
||||
img.setAttribute(
|
||||
"src",
|
||||
await new Promise((resolve, reject) => {
|
||||
const reader = new FileReader();
|
||||
reader.onload = () => resolve(reader.result);
|
||||
reader.onerror = () => reject(reader.error);
|
||||
reader.readAsDataURL(blob);
|
||||
})
|
||||
);
|
||||
} catch {
|
||||
// Its console address would be a dead link once the server is gone.
|
||||
imageToAlt(img);
|
||||
}
|
||||
}
|
||||
|
||||
function escapeHtml(s) {
|
||||
return String(s).replace(/[&<>"']/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[c]);
|
||||
}
|
||||
|
||||
// The document as its own web page: drawn through the same markdown path the
|
||||
// tab uses, so what is saved is what was on screen, minus the page's controls.
|
||||
export async function downloadDocHtml(doc) {
|
||||
const title = doc.title || "Document";
|
||||
const body = el("div");
|
||||
for (const b of doc.blocks || []) {
|
||||
const box = el("div", "block " + (b.state || "settled"));
|
||||
if (b.state === "assumed") box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
|
||||
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
|
||||
box.appendChild(blockBody(b));
|
||||
body.appendChild(box);
|
||||
}
|
||||
// Copy buttons only work inside the console.
|
||||
for (const n of body.querySelectorAll(".md-copy")) n.remove();
|
||||
// Images the console serves would be dead links once the server is gone, so
|
||||
// they travel inside the file. One that will not load becomes its alt text.
|
||||
await Promise.all([...body.querySelectorAll("img")].map(inlineImage));
|
||||
const saved = new Date().toLocaleString();
|
||||
const html = `<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<title>${escapeHtml(title)}</title>
|
||||
<style>${DOC_HTML_CSS}</style>
|
||||
</head>
|
||||
<body>
|
||||
<main>
|
||||
<header class="doc-head">
|
||||
<h1>${escapeHtml(title)}</h1>
|
||||
<span class="doc-version">v${escapeHtml(doc.version || 1)}</span>
|
||||
<span class="doc-meta">Saved ${escapeHtml(saved)}</span>
|
||||
</header>
|
||||
${doc.note ? `<p class="doc-note">${escapeHtml(doc.note)}</p>\n` : ""}${body.innerHTML}
|
||||
</main>
|
||||
</body>
|
||||
</html>
|
||||
`;
|
||||
saveFile(`${docFileName(doc)}.html`, html, "text/html");
|
||||
}
|
||||
|
||||
// A doc that mirrors a file the agent already wrote needs no download button
|
||||
// -- the path is the useful thing to show instead of it.
|
||||
export function docSavedNote(doc) {
|
||||
const path = typeof doc.saved === "string" ? doc.saved.trim() : "";
|
||||
const note = el("span", "doc-saved", path ? "Saved as " : "Already saved");
|
||||
if (path) note.appendChild(el("code", null, path));
|
||||
return note;
|
||||
}
|
||||
@@ -2,8 +2,10 @@
|
||||
//
|
||||
// The source of truth for which tabs Help has, in what order, and which one
|
||||
// opens. The content itself is HTML in <template id="help-content">
|
||||
// in index.html. No DOM access at module scope and no imports: the page and
|
||||
// `node --test` both import this file.
|
||||
// in index.html. No DOM access at module scope, and its one import is the
|
||||
// data-only skills.js: the page and `node --test` both import this file.
|
||||
|
||||
import { SKILLS, isBuild } from "./skills.js";
|
||||
|
||||
const tab = (id, label, diagram) => Object.freeze({ id, label, diagram });
|
||||
|
||||
@@ -29,8 +31,8 @@ export const HELP_TABS = Object.freeze([
|
||||
]);
|
||||
|
||||
// Not labels.js's BUILD_WORKFLOWS: that one leaves out quick-task, which is a
|
||||
// build as far as the person watching it is concerned.
|
||||
const HELP_BUILD_WORKFLOWS = new Set(["implement", "implement-review", "quick-task"]);
|
||||
// build as far as the person watching it is concerned. Every build in skills.js.
|
||||
const HELP_BUILD_WORKFLOWS = new Set(SKILLS.filter((s) => isBuild(s.workflow)).map((s) => s.workflow));
|
||||
|
||||
// Which tab Help opens on, from where the person is. First match wins.
|
||||
export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow, workspace, meterRed } = {}) {
|
||||
|
||||
@@ -12,6 +12,29 @@
|
||||
can draw anything real. -->
|
||||
<link rel="modulepreload" href="/app.js" />
|
||||
<link rel="modulepreload" href="/answers.js" />
|
||||
<link rel="modulepreload" href="/skills.js" />
|
||||
<link rel="modulepreload" href="/spec-states.js" />
|
||||
<link rel="modulepreload" href="/state.js" />
|
||||
<link rel="modulepreload" href="/doc-files.js" />
|
||||
<link rel="modulepreload" href="/send-state.js" />
|
||||
<link rel="modulepreload" href="/mention-box.js" />
|
||||
<link rel="modulepreload" href="/uploads.js" />
|
||||
<link rel="modulepreload" href="/sound.js" />
|
||||
<link rel="modulepreload" href="/looks.js" />
|
||||
<link rel="modulepreload" href="/selectors.js" />
|
||||
<link rel="modulepreload" href="/screens/core.js" />
|
||||
<link rel="modulepreload" href="/screens/ending.js" />
|
||||
<link rel="modulepreload" href="/screens/docs.js" />
|
||||
<link rel="modulepreload" href="/screens/cards.js" />
|
||||
<link rel="modulepreload" href="/screens/starting.js" />
|
||||
<link rel="modulepreload" href="/screens/dashboard.js" />
|
||||
<link rel="modulepreload" href="/screens/git-host.js" />
|
||||
<link rel="modulepreload" href="/screens/looks.js" />
|
||||
<link rel="modulepreload" href="/screens/cleanup.js" />
|
||||
<link rel="modulepreload" href="/screens/help-dialog.js" />
|
||||
<link rel="modulepreload" href="/screens/workspace.js" />
|
||||
<link rel="modulepreload" href="/screens/ask.js" />
|
||||
<link rel="modulepreload" href="/net.js" />
|
||||
<link rel="modulepreload" href="/render.js" />
|
||||
<link rel="modulepreload" href="/palette.js" />
|
||||
<link rel="modulepreload" href="/labels.js" />
|
||||
|
||||
@@ -1,12 +1,16 @@
|
||||
// Activity-line wording the page corrects on the way in. Kept out of app.js so
|
||||
// `node --test` can import it: no DOM access at module scope.
|
||||
// `node --test` can import it: no DOM access at module scope, and its one
|
||||
// import is the data-only skills.js.
|
||||
//
|
||||
// A build numbers its tasks "Task 4.2" after the phase, but a person watching
|
||||
// the page counts within the phase, so "Task 4.2 of 6" reads as nonsense
|
||||
// beside a progress bar that says 2 of 6.
|
||||
|
||||
// The only workflows whose activity lines get rewritten.
|
||||
export const BUILD_WORKFLOWS = new Set(["implement", "implement-review"]);
|
||||
import { SKILLS, isPhased } from "./skills.js";
|
||||
|
||||
// The only workflows whose activity lines get rewritten: the phased builds,
|
||||
// from skills.js.
|
||||
export const BUILD_WORKFLOWS = new Set(SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow));
|
||||
|
||||
const PHASE_TASK = /^Task (\d+)\.(\d+) of (\d+)/;
|
||||
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
// Plan2Code Web Console - how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches; defines only.
|
||||
//
|
||||
// The one preference that belongs to the person rather than to the session.
|
||||
// `looks` is a live binding: every file reads the current object, and only
|
||||
// this file replaces it.
|
||||
|
||||
import { DEFAULT_ACCENT, soundPrefs, DEFAULT_CARD_WIDTH, ACCENTS, cardWidth, soundKey } from "./palette.js";
|
||||
import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
|
||||
import { bootData, hooks } from "./state.js";
|
||||
import { el } from "./render.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// How the page looks and sounds, which is the one preference that belongs to
|
||||
// the person rather than to the session. Kept per browser, applied before
|
||||
// anything else is drawn, and deliberately touching nothing but presentation:
|
||||
// a session opened in a different theme is the same session.
|
||||
//
|
||||
// The highlight colors live in palette.js, where the tests can reach them.
|
||||
const ACCENT_VARS = ["--accent", "--accent-soft", "--accent-ink", "--accent-line"];
|
||||
|
||||
const LOOKS_KEY = "p2c-console:looks";
|
||||
|
||||
// The per-event sound switches (SOUND_EVENTS) live in palette.js too.
|
||||
export const DEFAULT_LOOKS = {
|
||||
theme: "system",
|
||||
accent: DEFAULT_ACCENT,
|
||||
sound: true,
|
||||
...soundPrefs(null),
|
||||
width: DEFAULT_CARD_WIDTH,
|
||||
hideUnavailable: true,
|
||||
};
|
||||
|
||||
export let looks = { ...DEFAULT_LOOKS };
|
||||
|
||||
let syncedLooks = null;
|
||||
|
||||
export let looksReady = false;
|
||||
|
||||
export function adoptLooks(saved) {
|
||||
looks = { ...DEFAULT_LOOKS, ...saved };
|
||||
if (!ACCENTS[looks.accent]) looks.accent = DEFAULT_LOOKS.accent;
|
||||
if (!["system", "light", "dark"].includes(looks.theme)) looks.theme = DEFAULT_LOOKS.theme;
|
||||
if (typeof looks.sound !== "boolean") looks.sound = DEFAULT_LOOKS.sound;
|
||||
Object.assign(looks, soundPrefs(looks));
|
||||
if (typeof looks.hideUnavailable !== "boolean") looks.hideUnavailable = DEFAULT_LOOKS.hideUnavailable;
|
||||
looks.width = cardWidth(looks.width);
|
||||
if (saved && typeof saved === "object" && Object.hasOwn(saved, "role")) looks.role = normalizeRole(saved.role);
|
||||
else delete looks.role;
|
||||
}
|
||||
|
||||
// The localStorage copy is only a cache now. It exists so the first paint can
|
||||
// apply a theme synchronously rather than flashing the defaults while the
|
||||
// fetch below is in flight; the server's looks.json is the truth, because it
|
||||
// is the copy that follows the app when a new session lands on a new port.
|
||||
export function loadLooks() {
|
||||
try {
|
||||
const raw = localStorage.getItem(LOOKS_KEY);
|
||||
if (raw) adoptLooks(JSON.parse(raw));
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Called once the page is up. Server wins: its copy is shared by every port,
|
||||
// while this origin's localStorage may be a leftover from a previous session
|
||||
// on this port or empty on a fresh one. A 404 means the server has never been
|
||||
// told -- including every install that predates the file -- so a browser that
|
||||
// DOES hold a setting seeds it, which is also the upgrade path.
|
||||
export async function syncLooks() {
|
||||
let saved = null;
|
||||
// The server already put its copy in the page: no request, and no second
|
||||
// repaint a moment after the first. `looks: null` there is the 404 case.
|
||||
const boot = bootData();
|
||||
if (boot && "looks" in boot) saved = boot.looks ? { looks: boot.looks } : null;
|
||||
else {
|
||||
try {
|
||||
const res = await fetch("/looks");
|
||||
if (res.ok) saved = await res.json();
|
||||
} catch {}
|
||||
}
|
||||
if (saved && saved.looks && typeof saved.looks === "object") {
|
||||
adoptLooks(saved.looks);
|
||||
syncedLooks = { ...looks };
|
||||
try {
|
||||
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
|
||||
} catch {}
|
||||
applyLooks();
|
||||
renderSwatches();
|
||||
} else {
|
||||
// Blocked storage throws on read, and that must not stop the page loading.
|
||||
let held = false;
|
||||
try {
|
||||
held = Boolean(localStorage.getItem(LOOKS_KEY));
|
||||
} catch {}
|
||||
if (held) pushLooks();
|
||||
}
|
||||
looksReady = true;
|
||||
// Not inline: with the server's copy in the page this runs before `S` exists.
|
||||
setTimeout(hooks.maybeWelcome, 0);
|
||||
}
|
||||
|
||||
// Fire-and-forget mirror. A failed POST costs nothing the next session would
|
||||
// notice on this port; the localStorage copy still covers the reload case.
|
||||
function pushLooks() {
|
||||
try {
|
||||
// Only what this tab changed since it last synced, so a tab with stale
|
||||
// settings never overwrites another tab's change to a different key.
|
||||
const set = {};
|
||||
for (const [k, v] of Object.entries(looks)) if (!syncedLooks || syncedLooks[k] !== v) set[k] = v;
|
||||
const before = syncedLooks;
|
||||
const partial = Boolean(before);
|
||||
if (partial && !Object.keys(set).length) return;
|
||||
syncedLooks = { ...looks };
|
||||
const body = partial ? { set } : { looks };
|
||||
// A write that did not land must be sent again with the next change.
|
||||
const undo = () => (syncedLooks = before);
|
||||
fetch("/looks", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body),
|
||||
})
|
||||
.then((res) => res.ok || undo())
|
||||
.catch(undo);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
const systemDark = () => matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
|
||||
const effectiveTheme = () => (looks.theme === "system" ? (systemDark() ? "dark" : "light") : looks.theme);
|
||||
|
||||
export function applyLooks() {
|
||||
const root = document.documentElement;
|
||||
// The server's stand-in for the saved accent, which only has to last until
|
||||
// this runs. From here on the colors are set below, and a stale rule left
|
||||
// switched on would win over "Back to default".
|
||||
root.removeAttribute("data-looks-accent");
|
||||
if (looks.theme === "system") root.removeAttribute("data-theme");
|
||||
else root.setAttribute("data-theme", looks.theme);
|
||||
// Tell the browser too, so form controls, scrollbars and the date picker
|
||||
// follow the choice rather than staying on the system's idea of it.
|
||||
root.style.colorScheme = looks.theme === "system" ? "light dark" : looks.theme;
|
||||
// Before the accent's early return, so a default accent never skips it.
|
||||
if (looks.width === DEFAULT_CARD_WIDTH) root.removeAttribute("data-width");
|
||||
else root.dataset.width = looks.width;
|
||||
|
||||
// The default lives in the stylesheet, where it is written once per theme.
|
||||
// Clearing the override is how it gets its own values back.
|
||||
if (looks.accent === DEFAULT_LOOKS.accent) {
|
||||
for (const name of ACCENT_VARS) root.style.removeProperty(name);
|
||||
return;
|
||||
}
|
||||
const shades = ACCENTS[looks.accent][effectiveTheme()];
|
||||
ACCENT_VARS.forEach((name, i) => root.style.setProperty(name, shades[i]));
|
||||
}
|
||||
|
||||
export function saveLooks() {
|
||||
try {
|
||||
localStorage.setItem(LOOKS_KEY, JSON.stringify(looks));
|
||||
} catch {}
|
||||
pushLooks();
|
||||
applyLooks();
|
||||
// A width change reflows the card without resizing the column, so the
|
||||
// column's observer never hears of it: refit the growing box here.
|
||||
hooks.fitGrowBox();
|
||||
renderSwatches();
|
||||
}
|
||||
|
||||
// Built once, repainted in place. Rebuilding the row on every choice destroyed
|
||||
// the button that had just been clicked, so focus fell to <body> and a keyboard
|
||||
// user lost their place in the dialog each time they tried a color.
|
||||
export function renderSwatches() {
|
||||
const box = $("looks-swatches");
|
||||
if (!box.children.length) {
|
||||
for (const [id, a] of Object.entries(ACCENTS)) {
|
||||
const b = el("button", "swatch");
|
||||
b.type = "button";
|
||||
b.dataset.accent = id;
|
||||
b.title = a.name;
|
||||
b.setAttribute("aria-label", a.name);
|
||||
b.addEventListener("click", () => {
|
||||
looks.accent = id;
|
||||
saveLooks();
|
||||
});
|
||||
box.appendChild(b);
|
||||
}
|
||||
}
|
||||
for (const b of box.children) {
|
||||
const id = b.dataset.accent;
|
||||
const [fill, , , line] = ACCENTS[id][effectiveTheme()];
|
||||
b.setAttribute("aria-pressed", String(looks.accent === id));
|
||||
// Fill and ring, so the swatch shows the pair the choice actually sets
|
||||
// rather than half of it. The chosen one is still told apart by its
|
||||
// double ring, which is drawn in ink and owes nothing to the accent.
|
||||
b.style.background = fill;
|
||||
b.style.borderColor = line;
|
||||
}
|
||||
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
|
||||
radio.checked = radio.value === looks.theme;
|
||||
}
|
||||
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
|
||||
radio.checked = radio.value === looks.width;
|
||||
}
|
||||
$("looks-sound").checked = looks.sound;
|
||||
// Each cue keeps its own tick while the master switch is off, so turning
|
||||
// sound back on returns exactly the set that was chosen.
|
||||
$("looks-sound-events").classList.toggle("is-off", !looks.sound);
|
||||
for (const box of document.querySelectorAll("input[data-sound]")) {
|
||||
box.checked = looks[soundKey(box.dataset.sound)];
|
||||
box.disabled = !looks.sound;
|
||||
}
|
||||
$("looks-role").value = looks.role ?? ROLE_NOT_SET;
|
||||
}
|
||||
|
||||
// "Back to default": every look returns to its default, but the role is
|
||||
// marked as asked and the welcome stays seen.
|
||||
export function resetLooks() {
|
||||
looks = { ...DEFAULT_LOOKS, role: ROLE_NOT_SET, welcomeSeen: looks.welcomeSeen };
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
// Plan2Code Web Console - the @name suggestions popover under a text box; defines only.
|
||||
//
|
||||
// Shared by the question cards and the Ask pane, so neither imports the other.
|
||||
|
||||
import { page } from "./state.js";
|
||||
import { el } from "./render.js";
|
||||
import { applyMention, mentionAt, matchNames } from "./mentions.js";
|
||||
import { workspaceFolders } from "./selectors.js";
|
||||
|
||||
export function closeMentions() {
|
||||
if (!page.mentionPop) return;
|
||||
const { box, node } = page.mentionPop;
|
||||
node.remove();
|
||||
removeEventListener("scroll", placeMentions, true);
|
||||
box.setAttribute("aria-expanded", "false");
|
||||
box.removeAttribute("aria-activedescendant");
|
||||
page.mentionPop = null;
|
||||
}
|
||||
|
||||
// Under the box, as wide as it, fixed to the viewport so no card's overflow
|
||||
// can clip it; above it when the window has no room below (the Ask box sits
|
||||
// at the bottom). A box that has been redrawn away takes the list with it.
|
||||
function placeMentions() {
|
||||
if (!page.mentionPop) return;
|
||||
if (!page.mentionPop.box.isConnected) return closeMentions();
|
||||
const r = page.mentionPop.box.getBoundingClientRect();
|
||||
const node = page.mentionPop.node;
|
||||
node.style.left = Math.round(r.left) + "px";
|
||||
node.style.width = Math.round(r.width) + "px";
|
||||
const h = node.offsetHeight;
|
||||
const top = r.bottom + 4 + h <= innerHeight ? r.bottom + 4 : Math.max(4, r.top - 4 - h);
|
||||
node.style.top = Math.round(top) + "px";
|
||||
}
|
||||
|
||||
function paintMentions() {
|
||||
const { node, box, matches, query } = page.mentionPop;
|
||||
node.replaceChildren();
|
||||
if (!matches.length) {
|
||||
node.appendChild(el("div", "mention-empty", `No folder called @${query} in the workspace`));
|
||||
box.removeAttribute("aria-activedescendant");
|
||||
return;
|
||||
}
|
||||
matches.forEach((name, i) => {
|
||||
const opt = el("div", "mention-opt" + (i === page.mentionPop.at ? " is-active" : ""), "@" + name);
|
||||
opt.id = "mention-opt-" + i;
|
||||
opt.setAttribute("role", "option");
|
||||
opt.setAttribute("aria-selected", String(i === page.mentionPop.at));
|
||||
// Held on mousedown, so the box keeps focus and the click can land.
|
||||
opt.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
opt.addEventListener("click", () => pickMention(name));
|
||||
node.appendChild(opt);
|
||||
});
|
||||
box.setAttribute("aria-activedescendant", "mention-opt-" + page.mentionPop.at);
|
||||
}
|
||||
|
||||
function pickMention(name) {
|
||||
if (!page.mentionPop) return;
|
||||
const { box, mention } = page.mentionPop;
|
||||
const next = applyMention(box.value, box.selectionStart, mention, name);
|
||||
closeMentions();
|
||||
box.value = next.text;
|
||||
box.setSelectionRange(next.caret, next.caret);
|
||||
// Whatever the box does with typing (drafts, staging, the counter) runs.
|
||||
box.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
}
|
||||
|
||||
export function attachMentions(box) {
|
||||
box.setAttribute("aria-autocomplete", "list");
|
||||
box.setAttribute("aria-expanded", "false");
|
||||
box.setAttribute("aria-controls", "mention-pop");
|
||||
const update = () => {
|
||||
const mention =
|
||||
box.selectionStart === box.selectionEnd ? mentionAt(box.value, box.selectionStart) : null;
|
||||
const names = workspaceFolders().map((f) => f.name);
|
||||
const matches = mention ? matchNames(names, mention.query) : [];
|
||||
// Nothing to offer with only the original folder and no match; a bigger
|
||||
// workspace says plainly that the name is not in it.
|
||||
if (!mention || (!matches.length && names.length < 2)) {
|
||||
if (page.mentionPop && page.mentionPop.box === box) closeMentions();
|
||||
return;
|
||||
}
|
||||
if (!page.mentionPop || page.mentionPop.box !== box) {
|
||||
closeMentions();
|
||||
const node = el("div", "mention-pop");
|
||||
node.id = "mention-pop";
|
||||
node.setAttribute("role", "listbox");
|
||||
node.setAttribute("aria-label", "Workspace folders");
|
||||
document.body.appendChild(node);
|
||||
page.mentionPop = { box, node, at: 0, matches: [], mention: null, query: "" };
|
||||
addEventListener("scroll", placeMentions, true);
|
||||
box.setAttribute("aria-expanded", "true");
|
||||
}
|
||||
const same = page.mentionPop.matches.join("\n") === matches.join("\n");
|
||||
Object.assign(page.mentionPop, { matches, mention, query: mention.query, at: same ? page.mentionPop.at : 0 });
|
||||
paintMentions();
|
||||
placeMentions();
|
||||
};
|
||||
box.addEventListener("input", update);
|
||||
box.addEventListener("keyup", (e) => {
|
||||
if (!["ArrowUp", "ArrowDown", "Enter", "Tab", "Escape"].includes(e.key)) update();
|
||||
});
|
||||
box.addEventListener("keydown", (e) => {
|
||||
if (!page.mentionPop || page.mentionPop.box !== box || e.isComposing) return;
|
||||
const { matches } = page.mentionPop;
|
||||
const stop = () => {
|
||||
e.preventDefault();
|
||||
e.stopImmediatePropagation();
|
||||
};
|
||||
if (e.key === "Escape") {
|
||||
stop();
|
||||
return closeMentions();
|
||||
}
|
||||
if (!matches.length) return;
|
||||
if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
stop();
|
||||
page.mentionPop.at = (page.mentionPop.at + (e.key === "ArrowDown" ? 1 : matches.length - 1)) % matches.length;
|
||||
return paintMentions();
|
||||
}
|
||||
if ((e.key === "Enter" || e.key === "Tab") && !e.ctrlKey && !e.metaKey && !e.shiftKey && !e.altKey) {
|
||||
stop();
|
||||
pickMention(matches[page.mentionPop.at]);
|
||||
}
|
||||
});
|
||||
box.addEventListener("blur", () => {
|
||||
if (page.mentionPop && page.mentionPop.box === box) closeMentions();
|
||||
});
|
||||
}
|
||||
@@ -3,8 +3,10 @@
|
||||
// The source of truth for how much each piece of work weighs, how the count
|
||||
// is folded out of ledger.ndjson, and what the pill says at each level. The
|
||||
// count is never stored: it is always pointsFrom() over the ledger. No DOM
|
||||
// access at module scope and no imports: the server, console.mjs, the page
|
||||
// and `node --test` all import this file.
|
||||
// access at module scope, and its one import is the data-only skills.js: the
|
||||
// server, console.mjs, the page and `node --test` all import this file.
|
||||
|
||||
import { SKILLS, isMetered, isPhased } from "./skills.js";
|
||||
|
||||
// The one place the weights live (FR-12). Tune here.
|
||||
export const WEIGHTS = Object.freeze({
|
||||
@@ -37,10 +39,9 @@ export const WEIGHTS = Object.freeze({
|
||||
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
|
||||
// implement and implement-review score only through the agent's `run`
|
||||
// reports; dashboard and handoff never score; git, changelog, xray and diagnose score 1 on
|
||||
// launch (Git then adds its commit tally and conflict help).
|
||||
export const LAUNCH_COUNTED = Object.freeze(
|
||||
new Set(["plan", "revise-plan", "document", "review", "quick-task", "init", "init-update", "finalize", "git", "changelog", "xray", "diagnose"])
|
||||
);
|
||||
// launch (Git then adds its commit tally and conflict help). Derived from
|
||||
// skills.js (`metered`).
|
||||
export const LAUNCH_COUNTED = Object.freeze(new Set(SKILLS.filter((s) => isMetered(s.workflow)).map((s) => s.workflow)));
|
||||
|
||||
// Git's commits weigh what they add up to: each `git-commits` run carries
|
||||
// `commits`, and a skill run scores one point per COMMITS_PER_POINT commits,
|
||||
@@ -71,8 +72,9 @@ export const MAX_TASKS = 999;
|
||||
// writes a `progress` ledger entry whenever a build's `headline.cleared`
|
||||
// rises, and the build's row scores those tasks at TASKS_PER_POINT with no
|
||||
// bonus. The phase's `run` then takes the row over with its final score, so
|
||||
// the total only ever climbs. Workflows whose headline counts tasks:
|
||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(["implement", "implement-review"]));
|
||||
// the total only ever climbs. Workflows whose headline counts tasks, derived
|
||||
// from skills.js (`phased`):
|
||||
export const PROGRESS_WORKFLOWS = Object.freeze(new Set(SKILLS.filter((s) => isPhased(s.workflow)).map((s) => s.workflow)));
|
||||
|
||||
// Implement + Review reviews every phase as a stage of the build. A `review`
|
||||
// run inside it is that stage, so it scores the phase's TASK_BONUS when it
|
||||
@@ -125,26 +127,9 @@ export function runPoints(event, tasks, { bonus = true } = {}) {
|
||||
// ANSWERS_PER_POINT answers, rounded down. Tune here.
|
||||
export const ANSWERS_PER_POINT = 2;
|
||||
|
||||
// The skill names the answers row uses ("7 answers in Plan").
|
||||
const WORKFLOW_NAMES = Object.freeze({
|
||||
dashboard: "the dashboard",
|
||||
pathfinder: "Pathfinder",
|
||||
plan: "Plan",
|
||||
"revise-plan": "Revise plan",
|
||||
document: "Document",
|
||||
implement: "Implement",
|
||||
"implement-review": "Implement + Review",
|
||||
review: "Review",
|
||||
"quick-task": "Quick task",
|
||||
init: "Init",
|
||||
"init-update": "Init update",
|
||||
finalize: "Finalize",
|
||||
handoff: "Handoff",
|
||||
git: "Git",
|
||||
changelog: "Changelog",
|
||||
xray: "X-ray",
|
||||
diagnose: "Diagnose",
|
||||
});
|
||||
// The skill names the answers row uses ("7 answers in Plan"), derived from
|
||||
// skills.js (`name`).
|
||||
const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(SKILLS.map((s) => [s.workflow, s.name])));
|
||||
|
||||
// The skill run an entry belongs to, from its ledger id ("L3:..." -> "L3").
|
||||
const launchOf = (id) => (typeof id === "string" && id.includes(":") ? id.slice(0, id.indexOf(":")) : "L0");
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
// Plan2Code Web Console - the page talking to its own server.
|
||||
//
|
||||
// Only defines.
|
||||
|
||||
// POST a JSON body; the status and parsed answer, or status 0 when the
|
||||
// server could not be reached.
|
||||
export async function postJson(url, body) {
|
||||
try {
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify(body || {}),
|
||||
});
|
||||
let answer = {};
|
||||
try {
|
||||
answer = await res.json();
|
||||
} catch {}
|
||||
return { status: res.status, body: answer };
|
||||
} catch {
|
||||
return { status: 0, body: {} };
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@
|
||||
// bypass. `html` tokens render as visible text, on purpose.
|
||||
|
||||
import { marked } from "./vendor/marked.esm.js";
|
||||
import { APPROVAL_TIP } from "./answers.js";
|
||||
|
||||
// A bare `/` path stays on this origin; `//host` (and `/\host`, which browsers
|
||||
// read the same way) is protocol-relative and would not, so it is refused.
|
||||
@@ -359,3 +360,61 @@ function copyButton(text, className, source) {
|
||||
}
|
||||
|
||||
export { el, copyButton, copyText, selectContents };
|
||||
|
||||
// A line whose backticked commands read as code; everything else is text.
|
||||
export function textWithCode(tag, className, text) {
|
||||
const node = el(tag, className);
|
||||
text.split("`").forEach((part, n) => {
|
||||
if (part) node.appendChild(n % 2 ? el("code", "md-code", part) : document.createTextNode(part));
|
||||
});
|
||||
return node;
|
||||
}
|
||||
|
||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
|
||||
export function releasesLink(text) {
|
||||
const a = el("a", null, text);
|
||||
a.href = RELEASES_URL;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
return a;
|
||||
}
|
||||
|
||||
// A quiet line under the menu and the starting screen: the page cannot see a
|
||||
// terminal approval prompt, so it says up front how to avoid one. Backticked
|
||||
// spans become <code>, built as nodes like everything else here.
|
||||
export function approvalTip() {
|
||||
return textWithCode("p", "approval-tip", APPROVAL_TIP);
|
||||
}
|
||||
|
||||
export const SVG_NS = "http://www.w3.org/2000/svg";
|
||||
|
||||
// A time of day for a chat message; empty when the stamp does not parse.
|
||||
export function shortTime(iso) {
|
||||
try {
|
||||
return new Date(iso).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
} catch {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
export function isMac() {
|
||||
return /mac/i.test(navigator.platform || navigator.userAgent);
|
||||
}
|
||||
|
||||
// A click on the backdrop closes a dialog that holds nothing to lose. The
|
||||
// backdrop is the <dialog> itself to the event, and so is its own padding, so
|
||||
// the point has to fall outside its box -- for the press as well as the
|
||||
// release, or selecting text inside and letting go outside would close it.
|
||||
export function lightDismiss(dlg) {
|
||||
const outside = (e) => {
|
||||
const r = dlg.getBoundingClientRect();
|
||||
return e.target === dlg && (e.clientX < r.left || e.clientX > r.right || e.clientY < r.top || e.clientY > r.bottom);
|
||||
};
|
||||
let pressedOutside = false;
|
||||
dlg.addEventListener("pointerdown", (e) => (pressedOutside = outside(e)));
|
||||
dlg.addEventListener("click", (e) => {
|
||||
if (pressedOutside && outside(e)) dlg.close();
|
||||
pressedOutside = false;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,855 @@
|
||||
// Plan2Code Web Console - the Ask chat, the Subagents tab, and attaching files to notes.
|
||||
|
||||
import { page, saveNow, redraw, freshChat, hooks, scrollMemory, setDraft } from "../state.js";
|
||||
import { chatOffline, chatView, sendState as chatSendState, newestReplyId, CHAT_MAX_CHARS, nextAbout, CHAT_MAX_ATTACHMENTS, contextOptions } from "../chat.js";
|
||||
import { finish, activity, agentAdrift, isDashboard, selSpec, byId, isOpen } from "../selectors.js";
|
||||
import { el, md, isMac, lightDismiss, shortTime } from "../render.js";
|
||||
import { startersFor } from "../starters.js";
|
||||
import { looks } from "../looks.js";
|
||||
import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incomingFiles, deleteUrl, sentAttachments, noteImages, attachRow } from "../uploads.js";
|
||||
import { attachMentions } from "../mention-box.js";
|
||||
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { CHECKIN_LINE, helperRows, showSwitch, switchLabel, defaultInstruction, PATHFINDER_RESEARCH_LINE } from "../subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The Quick question chat's page-local state, gone on a reload (the frame's
|
||||
// own `chat` block, the Ask tab's dot and the rest are on `page`, state.js).
|
||||
let chatSending = false;
|
||||
|
||||
let chatResetting = false;
|
||||
|
||||
let askPaintedOffline = false;
|
||||
|
||||
export const declineOpen = new Map();
|
||||
|
||||
const deciding = new Set();
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
// frame was sent: the agent comes and goes between frames, and /ping keeps
|
||||
// agentLastSeen current. The frame's own verdict stands when there is no clock.
|
||||
function askFrame() {
|
||||
const base = page.chatFrame || { conversation: 0, messages: [], typed: 0, limit: 10, offline: false };
|
||||
if (!page.S || !page.agentLastSeen) return base;
|
||||
const offline = chatOffline({
|
||||
finish: finish(),
|
||||
agent: page.S.agent,
|
||||
agentLastSeenMs: Date.parse(page.agentLastSeen),
|
||||
now: Date.now(),
|
||||
});
|
||||
return { ...base, offline };
|
||||
}
|
||||
|
||||
export function askState() {
|
||||
const frame = askFrame();
|
||||
const shown = chatView(frame, { pendingSends: page.local.chat.pending, agentActivity: activity() });
|
||||
const pendingSendCount = shown.rows.filter((r) => r.pending && !r.failed).length;
|
||||
return { frame, view: shown, send: chatSendState({ frameChat: frame, gone: page.gone, pendingSendCount }) };
|
||||
}
|
||||
|
||||
// The conversation a send belongs to. The page's own record wins over the
|
||||
// frame for the moment after a 409 stale, before the new frame lands.
|
||||
const askConversation = () => page.local.chat.conversation ?? askFrame().conversation;
|
||||
|
||||
export function renderAsk(main) {
|
||||
const { frame, view: v, send: ss } = askState();
|
||||
// Anything drawn here has been seen: no dot for it later.
|
||||
const newest = newestReplyId(frame);
|
||||
if (newest && page.local.chat.lastSeenReplyId !== newest) {
|
||||
page.local.chat.lastSeenReplyId = newest;
|
||||
saveNow();
|
||||
}
|
||||
page.chatDot = false;
|
||||
askPaintedOffline = ss.state === "offline";
|
||||
|
||||
const pane = el("section", "ask-pane");
|
||||
const head = el("div", "ask-head");
|
||||
head.appendChild(el("h2", null, "Quick question"));
|
||||
head.appendChild(el("span", "ask-counter", v.counterText));
|
||||
const reset = el("button", "btn small ghost", "New conversation");
|
||||
reset.type = "button";
|
||||
reset.disabled = ss.state === "offline" || chatResetting;
|
||||
reset.addEventListener("click", newConversation);
|
||||
head.appendChild(reset);
|
||||
pane.appendChild(head);
|
||||
|
||||
const list = el("div", "ask-list");
|
||||
list.setAttribute("role", "log");
|
||||
list.setAttribute("aria-live", "polite");
|
||||
if (!v.rows.length) list.appendChild(askStarters(ss));
|
||||
const notes = new Map(v.rows.filter((r) => r.kind === "decision").map((r) => [r.re, r.text]));
|
||||
for (const r of v.rows) list.appendChild(askRow(r, ss, notes));
|
||||
pane.appendChild(list);
|
||||
pane.appendChild(askComposer(ss));
|
||||
main.appendChild(pane);
|
||||
|
||||
// Back where the person left the list, unless something new arrived (or it
|
||||
// is the first look), which brings the newest row into view.
|
||||
const saved = scrollMemory.get("ask");
|
||||
const grew = v.rows.length > page.askRowCount;
|
||||
page.askRowCount = v.rows.length;
|
||||
list.scrollTop = !saved || grew ? list.scrollHeight : saved.top;
|
||||
}
|
||||
|
||||
// An empty conversation offers a few questions for this step, the role's
|
||||
// first. A click only fills the box: nothing is ever sent for the person.
|
||||
function askStarters(ss) {
|
||||
const box = el("div", "ask-starters");
|
||||
box.appendChild(el("p", "ask-starters-lead", "Not sure what to ask? Try one of these:"));
|
||||
for (const starter of startersFor(page.S.workflow, looks.role, { hasContext: Boolean(page.local.chat.about) })) {
|
||||
const b = el("button", "ask-starter", starter.text);
|
||||
b.type = "button";
|
||||
b.disabled = !ss.canType;
|
||||
b.addEventListener("click", () => {
|
||||
page.local.chat.draft = starter.text;
|
||||
saveNow();
|
||||
redraw();
|
||||
const ta = $("ask-input");
|
||||
if (!ta) return;
|
||||
ta.focus();
|
||||
ta.setSelectionRange(ta.value.length, ta.value.length);
|
||||
});
|
||||
box.appendChild(b);
|
||||
}
|
||||
return box;
|
||||
}
|
||||
|
||||
function askRow(r, ss, notes) {
|
||||
if (r.kind === "decision") {
|
||||
const row = el("div", "ask-row decision");
|
||||
row.appendChild(el("p", "ask-decision", r.decision !== "approve" ? "You declined the edit." : r.done ? "You approved the edit." : "You approved the edit, please wait..."));
|
||||
if (r.text) row.appendChild(el("p", "ask-text", r.text));
|
||||
return row;
|
||||
}
|
||||
if (r.kind === "agent") {
|
||||
const row = el("div", "ask-row agent");
|
||||
row.appendChild(el("div", "msg-who", "Plan2Code"));
|
||||
row.appendChild(md(r.md, "md"));
|
||||
if (r.proposal) row.appendChild(askProposal(r, ss, notes.get(r.id)));
|
||||
if (Array.isArray(r.changed) && r.changed.length) {
|
||||
const ul = el("ul", "ask-changed");
|
||||
for (const c of r.changed) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("code", null, c.file));
|
||||
li.appendChild(el("span", "ask-changed-count", ` +${c.added} −${c.removed}`));
|
||||
ul.appendChild(li);
|
||||
}
|
||||
row.appendChild(ul);
|
||||
}
|
||||
return row;
|
||||
}
|
||||
const row = el("div", "ask-row person" + (r.pending ? " pending" : ""));
|
||||
if (r.about && r.about.label) row.appendChild(el("p", "ask-about", "About: " + r.about.label));
|
||||
row.appendChild(el("p", "ask-text", r.text));
|
||||
const hasImages = r.images && r.images.length;
|
||||
const hasFiles = r.files && r.files.length;
|
||||
if (hasImages || hasFiles) {
|
||||
const tray = el("div", "attach-tray");
|
||||
for (const img of r.images || []) {
|
||||
const fig = el("figure", "attach-thumb is-ready");
|
||||
const pic = el("img");
|
||||
pic.src = thumbs.get(img.key) || uploadUrl(img);
|
||||
pic.alt = img.name || "image";
|
||||
fig.appendChild(pic);
|
||||
tray.appendChild(fig);
|
||||
}
|
||||
for (const file of r.files || []) tray.appendChild(docChip(file, "ready"));
|
||||
row.appendChild(tray);
|
||||
}
|
||||
if (r.pending && r.failed) {
|
||||
const fail = el("p", "ask-waiting ask-failed", "Not sent — retry");
|
||||
const retry = el("button", "btn tiny", "Retry");
|
||||
retry.type = "button";
|
||||
retry.disabled = ss.state === "offline" || chatSending;
|
||||
retry.addEventListener("click", () => retryChat(r.tempId));
|
||||
fail.appendChild(retry);
|
||||
row.appendChild(fail);
|
||||
} else if (r.pending) {
|
||||
row.appendChild(el("p", "ask-waiting", "Sending…"));
|
||||
} else if (r.waiting) {
|
||||
const wait = el("p", "ask-waiting");
|
||||
// Picked up and still answering: the ring says so, unless the agent has
|
||||
// gone quiet, when a turning ring would pass a dead session for a slow one.
|
||||
if (r.working && ss.state !== "offline" && !agentAdrift()) {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
wait.appendChild(spin);
|
||||
}
|
||||
wait.appendChild(el("span", null, r.waitingText));
|
||||
row.appendChild(wait);
|
||||
if (r.activity) row.appendChild(el("p", "ask-waiting", "Right now: " + r.activity));
|
||||
}
|
||||
return row;
|
||||
}
|
||||
|
||||
function askProposal(r, ss, note) {
|
||||
const box = el("div", "ask-proposal");
|
||||
box.appendChild(el("p", "note-kicker", "Proposed change"));
|
||||
box.appendChild(md(r.proposal.summary, "md"));
|
||||
const files = el("ul", "ask-proposal-files");
|
||||
for (const f of r.proposal.files || []) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("code", null, f));
|
||||
files.appendChild(li);
|
||||
}
|
||||
box.appendChild(files);
|
||||
|
||||
if (r.decided) {
|
||||
box.appendChild(el("p", "ask-decided " + r.decided, r.decided === "approve" ? "Approved" : "Declined"));
|
||||
if (note) box.appendChild(el("p", "help", note));
|
||||
return box;
|
||||
}
|
||||
const busy = deciding.has(r.id) || ss.state === "offline";
|
||||
const row = el("div", "ask-proposal-actions");
|
||||
const approve = el("button", "btn small primary", "Approve");
|
||||
approve.type = "button";
|
||||
approve.disabled = busy;
|
||||
approve.addEventListener("click", () => decideChat(r.id, "approve", ""));
|
||||
row.appendChild(approve);
|
||||
if (!declineOpen.has(r.id)) {
|
||||
const decline = el("button", "btn small ghost", "Decline");
|
||||
decline.type = "button";
|
||||
decline.disabled = busy;
|
||||
decline.addEventListener("click", () => {
|
||||
declineOpen.set(r.id, "");
|
||||
redraw();
|
||||
$("decline-" + r.id)?.focus();
|
||||
});
|
||||
row.appendChild(decline);
|
||||
} else {
|
||||
const input = el("input");
|
||||
input.type = "text";
|
||||
input.id = "decline-" + r.id;
|
||||
input.placeholder = "Why not? (optional)";
|
||||
input.maxLength = CHAT_MAX_CHARS;
|
||||
input.value = declineOpen.get(r.id) || "";
|
||||
input.addEventListener("input", () => declineOpen.set(r.id, input.value));
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
decideChat(r.id, "decline", input.value);
|
||||
});
|
||||
row.appendChild(input);
|
||||
const go = el("button", "btn small", "Send decline");
|
||||
go.type = "button";
|
||||
go.disabled = busy;
|
||||
go.addEventListener("click", () => decideChat(r.id, "decline", declineOpen.get(r.id) || ""));
|
||||
row.appendChild(go);
|
||||
}
|
||||
box.appendChild(row);
|
||||
if (deciding.has(r.id)) box.appendChild(el("p", "help", "Sent. It will show here once Plan2Code has it."));
|
||||
return box;
|
||||
}
|
||||
|
||||
const COUNTER_FROM = 3500;
|
||||
|
||||
function askComposer(ss) {
|
||||
const comp = el("div", "ask-composer");
|
||||
const about = page.local.chat.about;
|
||||
if (about) {
|
||||
const chip = el("div", "ask-about-chip");
|
||||
chip.appendChild(el("span", null, "About: " + about.label));
|
||||
const x = el("button", "attach-remove", "×");
|
||||
x.type = "button";
|
||||
x.setAttribute("aria-label", "Send without this");
|
||||
x.addEventListener("click", () => {
|
||||
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "drop" }));
|
||||
saveNow();
|
||||
redraw();
|
||||
});
|
||||
chip.appendChild(x);
|
||||
comp.appendChild(chip);
|
||||
}
|
||||
if (page.local.chat.images.length) comp.appendChild(attachTray(CHAT_IMAGES, page.local.chat.images));
|
||||
|
||||
const ta = el("textarea");
|
||||
ta.id = "ask-input";
|
||||
ta.placeholder = "Ask anything about this project";
|
||||
ta.value = page.local.chat.draft || "";
|
||||
ta.disabled = !ss.canType;
|
||||
ta.setAttribute("aria-label", "Your question");
|
||||
attachMentions(ta);
|
||||
comp.appendChild(ta);
|
||||
|
||||
const row = el("div", "ask-actions");
|
||||
const add = el("button", "btn small ghost", "+ Attach file");
|
||||
add.type = "button";
|
||||
add.setAttribute("aria-label", "Add files to this question");
|
||||
add.disabled = !ss.canType || page.local.chat.images.length >= CHAT_MAX_ATTACHMENTS;
|
||||
const picker = el("input");
|
||||
picker.type = "file";
|
||||
picker.accept = pickerAccept();
|
||||
picker.multiple = true;
|
||||
picker.hidden = true;
|
||||
add.addEventListener("click", () => picker.click());
|
||||
picker.addEventListener("change", () => {
|
||||
attachFiles(CHAT_IMAGES, picker.files);
|
||||
picker.value = "";
|
||||
});
|
||||
row.appendChild(add);
|
||||
row.appendChild(picker);
|
||||
if (!page.local.chat.about) row.appendChild(addContext(ss));
|
||||
|
||||
// Where the counter sits, the reason Send is off when it cannot be typed in:
|
||||
// the limit, the last question still waiting, or nobody there to answer.
|
||||
const counter = el("span", "ask-count");
|
||||
if (!ss.canType) {
|
||||
const cls = ss.state === "offline" ? "is-offline" : ss.state === "limit" ? "is-limit" : "is-waiting";
|
||||
row.appendChild(el("p", "ask-disabled-note " + cls, ss.text));
|
||||
} else {
|
||||
row.appendChild(counter);
|
||||
const hint = el("span", "ask-send-hint");
|
||||
hint.appendChild(el("kbd", null, isMac() ? "⌘" : "Ctrl"));
|
||||
hint.appendChild(document.createTextNode(" + "));
|
||||
hint.appendChild(el("kbd", null, "Enter"));
|
||||
row.appendChild(hint);
|
||||
}
|
||||
|
||||
const go = el("button", "btn small primary", "Send");
|
||||
go.type = "button";
|
||||
row.appendChild(go);
|
||||
comp.appendChild(row);
|
||||
if (page.chatError) comp.appendChild(el("p", "ask-error", page.chatError));
|
||||
|
||||
const held = () => page.local.chat.images.some((img) => img.status !== "ready");
|
||||
const sync = () => {
|
||||
const len = ta.value.length;
|
||||
counter.textContent = len >= COUNTER_FROM ? `${len} / ${CHAT_MAX_CHARS}` : "";
|
||||
counter.classList.toggle("is-over", len > CHAT_MAX_CHARS);
|
||||
go.disabled = !ss.canType || chatSending || !ta.value.trim() || len > CHAT_MAX_CHARS || held();
|
||||
};
|
||||
sync();
|
||||
ta.addEventListener("input", () => {
|
||||
page.local.chat.draft = ta.value;
|
||||
saveNow();
|
||||
sync();
|
||||
});
|
||||
// Ctrl/Cmd+Enter sends and a plain Enter is a line break. Every Enter stops
|
||||
// here, so the page-wide Ctrl+Enter never sends the question cards from this box.
|
||||
ta.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.stopPropagation();
|
||||
if (!(e.ctrlKey || e.metaKey) || e.isComposing) return;
|
||||
e.preventDefault();
|
||||
if (!go.disabled) sendChat();
|
||||
});
|
||||
ta.addEventListener("paste", (e) => {
|
||||
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
|
||||
if (!files.length || !ss.canType) return;
|
||||
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
|
||||
attachFiles(CHAT_IMAGES, files);
|
||||
});
|
||||
const canDrop = (e) => ss.canType && e.dataTransfer && [...e.dataTransfer.types].includes("Files");
|
||||
const onOver = (e) => {
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
comp.classList.add("is-dropping");
|
||||
};
|
||||
comp.addEventListener("dragenter", onOver);
|
||||
comp.addEventListener("dragover", onOver);
|
||||
comp.addEventListener("dragleave", (e) => {
|
||||
if (!comp.contains(e.relatedTarget)) comp.classList.remove("is-dropping");
|
||||
});
|
||||
comp.addEventListener("drop", (e) => {
|
||||
comp.classList.remove("is-dropping");
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
attachFiles(CHAT_IMAGES, e.dataTransfer.files);
|
||||
});
|
||||
go.addEventListener("click", sendChat);
|
||||
return comp;
|
||||
}
|
||||
|
||||
const CONTEXT_KIND = { card: "Question", section: "Section", spec: "Spec" };
|
||||
|
||||
// + Add context: the only way a message gets an `about`. A menu of the last
|
||||
// three places visited, then This spec, built fresh on every render.
|
||||
function addContext(ss) {
|
||||
const wrap = el("span", "ask-context");
|
||||
const spec = isDashboard() ? selSpec() : page.S && page.S.specDir ? { dir: page.S.specDir } : null;
|
||||
const options = contextOptions(page.local.chat, spec);
|
||||
const btn = el("button", "btn small ghost", "+ Add context");
|
||||
btn.type = "button";
|
||||
btn.setAttribute("aria-haspopup", "menu");
|
||||
btn.setAttribute("aria-expanded", "false");
|
||||
btn.disabled = !ss.canType || !options.length;
|
||||
if (!options.length) btn.title = "Visit a question or a document section first";
|
||||
wrap.appendChild(btn);
|
||||
|
||||
let menu = null;
|
||||
const outside = (e) => {
|
||||
if (!wrap.contains(e.target)) close();
|
||||
};
|
||||
// Focus moves before the menu goes: removing the focused item fires a
|
||||
// focusout of its own, which would otherwise re-enter here.
|
||||
const close = (refocus) => {
|
||||
if (!menu) return;
|
||||
const gone = menu;
|
||||
menu = null;
|
||||
btn.setAttribute("aria-expanded", "false");
|
||||
document.removeEventListener("pointerdown", outside, true);
|
||||
if (refocus) btn.focus();
|
||||
gone.remove();
|
||||
};
|
||||
const open = () => {
|
||||
menu = el("div", "ask-context-menu");
|
||||
menu.setAttribute("role", "menu");
|
||||
menu.setAttribute("aria-label", "Add context");
|
||||
for (const option of options) {
|
||||
const item = el("button", "ask-context-item");
|
||||
item.type = "button";
|
||||
item.setAttribute("role", "menuitem");
|
||||
item.appendChild(el("span", "ask-context-label", option.label));
|
||||
item.appendChild(el("span", "ask-context-kind", CONTEXT_KIND[option.kind] || ""));
|
||||
item.addEventListener("click", () => {
|
||||
close();
|
||||
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "pick", about: option }));
|
||||
saveNow();
|
||||
redraw();
|
||||
});
|
||||
menu.appendChild(item);
|
||||
}
|
||||
// A press inside the menu never moves focus. Safari (and Firefox on
|
||||
// macOS) do not focus a clicked button, so the press would blur the
|
||||
// focused item to nowhere and the focusout below would close the menu
|
||||
// before the click landed.
|
||||
menu.addEventListener("mousedown", (e) => e.preventDefault());
|
||||
menu.addEventListener("keydown", (e) => {
|
||||
const items = [...menu.querySelectorAll('[role="menuitem"]')];
|
||||
const at = items.indexOf(document.activeElement);
|
||||
if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
close(true);
|
||||
} else if (e.key === "ArrowDown" || e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
const step = e.key === "ArrowDown" ? 1 : -1;
|
||||
items[(at + step + items.length) % items.length].focus();
|
||||
} else if (e.key === "Home" || e.key === "End") {
|
||||
e.preventDefault();
|
||||
items[e.key === "Home" ? 0 : items.length - 1].focus();
|
||||
}
|
||||
});
|
||||
wrap.appendChild(menu);
|
||||
btn.setAttribute("aria-expanded", "true");
|
||||
document.addEventListener("pointerdown", outside, true);
|
||||
menu.querySelector('[role="menuitem"]').focus();
|
||||
};
|
||||
btn.addEventListener("click", () => (menu ? close() : open()));
|
||||
wrap.addEventListener("focusout", (e) => {
|
||||
if (menu && !wrap.contains(e.relatedTarget)) close();
|
||||
});
|
||||
return wrap;
|
||||
}
|
||||
|
||||
const CHAT_ERRORS = {
|
||||
stale: "A new conversation started. Your message is still here — press Send again.",
|
||||
"too-long": `That message is over ${CHAT_MAX_CHARS.toLocaleString()} characters. Shorten it and send again.`,
|
||||
image: "One of the images could not be attached. Remove it and try again.",
|
||||
file: "One of the files could not be attached. Remove it and try again.",
|
||||
};
|
||||
|
||||
async function sendChat() {
|
||||
const text = (page.local.chat.draft || "").trim();
|
||||
const { send: ss } = askState();
|
||||
if (!text || chatSending || !ss.canType || text.length > CHAT_MAX_CHARS) return;
|
||||
if (page.local.chat.images.some((img) => img.status !== "ready")) return;
|
||||
const ofKind = (kind) => page.local.chat.images.filter((a) => attachmentKind(a) === kind);
|
||||
const pend = {
|
||||
tempId: crypto.randomUUID(),
|
||||
text,
|
||||
about: page.local.chat.about,
|
||||
images: ofKind("image").map(({ key, path, name, url }) => ({ key, path, name, url })),
|
||||
files: ofKind("file").map(({ key, path, name, size }) => ({ key, path, name, size })),
|
||||
};
|
||||
page.local.chat.pending.push(pend);
|
||||
saveNow();
|
||||
await postChat(pend);
|
||||
}
|
||||
|
||||
function retryChat(tempId) {
|
||||
const pend = page.local.chat.pending.find((p) => p.tempId === tempId);
|
||||
if (!pend || chatSending) return;
|
||||
pend.failed = false;
|
||||
saveNow();
|
||||
postChat(pend);
|
||||
}
|
||||
|
||||
async function postChat(pend) {
|
||||
chatSending = true;
|
||||
page.chatError = "";
|
||||
redraw();
|
||||
let res = null;
|
||||
let body = {};
|
||||
try {
|
||||
res = await fetch("/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
text: pend.text,
|
||||
about: pend.about || undefined,
|
||||
images: pend.images.length ? pend.images.map(({ path, name }) => ({ path, name })) : undefined,
|
||||
files: pend.files && pend.files.length ? pend.files.map(({ path, name }) => ({ path, name })) : undefined,
|
||||
conversation: askConversation(),
|
||||
}),
|
||||
});
|
||||
body = await res.json().catch(() => ({}));
|
||||
} catch {
|
||||
res = null;
|
||||
}
|
||||
chatSending = false;
|
||||
const still = page.local.chat.pending.find((p) => p.tempId === pend.tempId);
|
||||
if (!res) {
|
||||
if (still) still.failed = true;
|
||||
} else if (res.ok) {
|
||||
if (still) still.seq = body.seq;
|
||||
// What was sent leaves the composer, and the context leaves with it: a
|
||||
// follow-up is a general question unless it is picked again.
|
||||
Object.assign(page.local.chat, nextAbout(page.local.chat, { type: "sent" }));
|
||||
if ((page.local.chat.draft || "").trim() === pend.text) {
|
||||
page.local.chat.draft = "";
|
||||
page.local.chat.images = [];
|
||||
}
|
||||
} else {
|
||||
page.local.chat.pending = page.local.chat.pending.filter((p) => p.tempId !== pend.tempId);
|
||||
if (body.error === "stale" && typeof body.conversation === "number") page.local.chat.conversation = body.conversation;
|
||||
// A limit or offline refusal needs no words: the disabled composer says why.
|
||||
if (body.error !== "limit" && body.error !== "offline") {
|
||||
page.chatError = CHAT_ERRORS[body.error] || "That message could not be sent. Try again.";
|
||||
}
|
||||
}
|
||||
saveNow();
|
||||
redraw();
|
||||
}
|
||||
|
||||
async function newConversation() {
|
||||
// One reset at a time: a second press would only come back stale and put
|
||||
// an error under the clean conversation the first one opened.
|
||||
if (chatResetting) return;
|
||||
chatResetting = true;
|
||||
redraw();
|
||||
let res = null;
|
||||
let body = {};
|
||||
try {
|
||||
res = await fetch("/chat", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ reset: true, conversation: askConversation() }),
|
||||
});
|
||||
body = await res.json().catch(() => ({}));
|
||||
} catch {}
|
||||
if (res && res.ok) {
|
||||
// An explicit fresh start: the unsent draft and its pictures go too.
|
||||
for (const img of page.local.chat.images) if (img.id) fetch(deleteUrl(img), { method: "DELETE" }).catch(() => {});
|
||||
page.local.chat = { ...freshChat(), history: page.local.chat.history, about: null, conversation: body.conversation };
|
||||
page.chatError = "";
|
||||
page.askRowCount = 0;
|
||||
declineOpen.clear();
|
||||
} else if (body.error === "stale" && typeof body.conversation === "number") {
|
||||
page.local.chat.conversation = body.conversation;
|
||||
page.chatError = "A new conversation had already started.";
|
||||
} else if (body.error !== "offline") {
|
||||
page.chatError = "A new conversation could not be started. Try again.";
|
||||
}
|
||||
chatResetting = false;
|
||||
saveNow();
|
||||
redraw();
|
||||
}
|
||||
|
||||
async function decideChat(re, decision, text) {
|
||||
if (deciding.has(re)) return;
|
||||
deciding.add(re);
|
||||
page.chatError = "";
|
||||
redraw();
|
||||
let ok = false;
|
||||
let body = {};
|
||||
try {
|
||||
const res = await fetch("/chat/decision", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ re, decision, text: text.trim() || undefined, conversation: askConversation() }),
|
||||
});
|
||||
ok = res.ok;
|
||||
body = await res.json().catch(() => ({}));
|
||||
} catch {}
|
||||
// Kept in `deciding` on success: the buttons stay off until the frame
|
||||
// brings the decision back, rather than flashing live again in between.
|
||||
if (ok) declineOpen.delete(re);
|
||||
else {
|
||||
deciding.delete(re);
|
||||
page.chatError =
|
||||
body.error === "stale"
|
||||
? "That proposal belongs to an earlier conversation."
|
||||
: "That decision could not be sent. Try again.";
|
||||
}
|
||||
redraw();
|
||||
}
|
||||
|
||||
export function renderAside() {
|
||||
const aside = $("aside");
|
||||
// Redrawing empties the panel, which drops its scroll to the top. An image
|
||||
// upload redraws two or three times while the person watches its tray, so
|
||||
// the place is kept while the same question stays on screen.
|
||||
const place = aside.dataset.item === String(page.selected) ? aside.scrollTop : 0;
|
||||
aside.replaceChildren();
|
||||
aside.dataset.item = String(page.selected);
|
||||
// The end page is about the session, not any one question: the notes that
|
||||
// belong to a question stay on its own page.
|
||||
const item = page.view === "end" ? null : byId(page.selected);
|
||||
if (!item) {
|
||||
// The menu has no questions, so no notes either: the pane stays empty.
|
||||
if (!isDashboard()) aside.appendChild(el("p", "aside-empty", "Pick a question to see its notes."));
|
||||
return;
|
||||
}
|
||||
// Off the question's own page (a doc tab, Ask) "this" points at nothing on
|
||||
// screen, so the pane names the question a note here will go to.
|
||||
const onQuestion = page.view === "questions" || page.view === "end";
|
||||
aside.appendChild(el("h2", null, onQuestion ? "Notes on this" : `Notes on “${item.title || "this question"}”`));
|
||||
|
||||
const thread = item.thread || [];
|
||||
if (!thread.length && !(isOpen(item) && !finish() && noteAwaiting(item))) {
|
||||
aside.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"aside-empty",
|
||||
isOpen(item) && !finish()
|
||||
? "No back and forth yet. Anything you type here goes with your next send."
|
||||
: "Nothing was said about this one."
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
box.appendChild(who);
|
||||
if (waiting.text) box.appendChild(md(waiting.text, "md"));
|
||||
const tray = sentAttachments(waiting);
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A finished session has nobody left for a note to reach, so the box would
|
||||
// be a place to type words that go nowhere.
|
||||
if (!isOpen(item) || finish()) {
|
||||
aside.scrollTop = place;
|
||||
return;
|
||||
}
|
||||
|
||||
const wrap = el("div", "field");
|
||||
const id = "thread-" + item.id;
|
||||
const label = el("label", null, "Add a note, attach a file, or ask something");
|
||||
label.htmlFor = id;
|
||||
wrap.appendChild(label);
|
||||
|
||||
const attached = noteImages(item.id);
|
||||
wrap.appendChild(attachRow(item.id, "Add files to this note"));
|
||||
|
||||
if (attached.length) wrap.appendChild(attachTray(item.id, attached));
|
||||
|
||||
const ta = el("textarea");
|
||||
ta.id = id;
|
||||
ta.placeholder = "Goes with your next send. It does not answer the question.";
|
||||
ta.value = page.local.drafts[id] || "";
|
||||
attachMentions(ta);
|
||||
ta.addEventListener("input", () => {
|
||||
setDraft(id, ta.value);
|
||||
hooks.renderFooter();
|
||||
});
|
||||
ta.addEventListener("paste", (e) => {
|
||||
const files = incomingFiles(e.clipboardData && e.clipboardData.files);
|
||||
if (!files.length) return;
|
||||
// A copy from some apps carries the picture and its text together; the
|
||||
// text still pastes as it always did.
|
||||
if (!e.clipboardData.getData("text/plain")) e.preventDefault();
|
||||
attachFiles(item.id, files);
|
||||
});
|
||||
wrap.appendChild(ta);
|
||||
aside.appendChild(wrap);
|
||||
aside.scrollTop = place;
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
export function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(page.S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
export function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(page.subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(page.subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(page.subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = page.gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
export function openSubagents() {
|
||||
if (!showSwitch(page.subagentsFrame)) return;
|
||||
const on = Boolean(page.subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
|
||||
$("subagents-max").value = String(page.subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = page.S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
syncSubagentsFields();
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
// Instruction and "at most" only mean anything with helpers on, so they are
|
||||
// inert under Work alone (kept as typed, for when helpers go back on).
|
||||
export function syncSubagentsFields() {
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const off = !picked || picked.value !== "on";
|
||||
for (const id of ["subagents-instruction", "subagents-max", "subagents-default"]) $(id).disabled = off;
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
export async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(page.S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
// Whether the agent coming or going has changed what the Ask pane painted,
|
||||
// with no frame to say so (the page's clock asks, once a second).
|
||||
export const askOfflineFlipped = () => (askState().send.state === "offline") !== askPaintedOffline;
|
||||
|
||||
// The Subagents dialog's buttons, and dropping files onto the notes panel.
|
||||
export function wireAsk() {
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
|
||||
lightDismiss($("subagents-modal"));
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(page.S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
|
||||
// Dropping files onto the notes panel attaches them to the selected
|
||||
// question's note. Bound once here: the panel's contents are redrawn on every
|
||||
// render, the panel itself is not.
|
||||
{
|
||||
const aside = $("aside");
|
||||
const canDrop = (e) => {
|
||||
const item = page.view === "end" ? null : byId(page.selected);
|
||||
return (
|
||||
Array.from((e.dataTransfer && e.dataTransfer.types) || []).includes("Files") &&
|
||||
item &&
|
||||
isOpen(item) &&
|
||||
!finish()
|
||||
);
|
||||
};
|
||||
const onOver = (e) => {
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
aside.classList.add("is-dropping");
|
||||
};
|
||||
aside.addEventListener("dragenter", onOver);
|
||||
aside.addEventListener("dragover", onOver);
|
||||
aside.addEventListener("dragleave", (e) => {
|
||||
// Moving between children fires dragleave too; only leaving the panel counts.
|
||||
if (!aside.contains(e.relatedTarget)) aside.classList.remove("is-dropping");
|
||||
});
|
||||
aside.addEventListener("drop", (e) => {
|
||||
aside.classList.remove("is-dropping");
|
||||
if (!canDrop(e)) return;
|
||||
e.preventDefault();
|
||||
attachFiles(page.selected, e.dataTransfer.files);
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,126 @@
|
||||
// Plan2Code Web Console - User Preferences, Cleanup tab.
|
||||
|
||||
import { formatBytes } from "../answers.js";
|
||||
import { el } from "../render.js";
|
||||
import { postJson } from "../net.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
const CLEANUP_WHERE = { root: "~/.plan2code/", console: "~/.plan2code/console/", completed: "specs--completed/" };
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
return CLEANUP_WHERE[item.where] + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const completed = items.filter((i) => i.where === "completed").length;
|
||||
const strays = items.length - sessions - completed;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (completed) parts.push(completed + (completed === 1 ? " old completed spec" : " old completed specs"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
// The server re-checks every id and keeps anything that changed since the
|
||||
// scan; say so, rather than let a count that came up short pass unremarked.
|
||||
const asked = cleanupFound.items.length;
|
||||
const kept = Math.max(0, asked - removed - failed);
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
const keptLine = kept ? ` ${kept} ${kept === 1 ? "was" : "were"} kept because ${kept === 1 ? "it" : "they"} changed since the scan.` : "";
|
||||
setCleanupStatus((failed ? done + " " + failed + " could not be removed." : done) + keptLine, Boolean(failed));
|
||||
}
|
||||
|
||||
// The Cleanup tab's buttons, and starting over whenever Preferences closes.
|
||||
export function wireCleanup() {
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
$("looks-modal").addEventListener("close", resetCleanup);
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,987 @@
|
||||
// Plan2Code Web Console - the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up; defines only.
|
||||
|
||||
import {
|
||||
selHandoff,
|
||||
scan,
|
||||
selSpec,
|
||||
agentWorking,
|
||||
specList,
|
||||
handoffList,
|
||||
loadOverview,
|
||||
finish,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, renderSwatches, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER } from "../meter.js";
|
||||
import {
|
||||
dashNoteKind,
|
||||
defaultSpec,
|
||||
onInitialPick,
|
||||
cardPresentation,
|
||||
CATALOG_GROUPS,
|
||||
SKILL_CATALOG,
|
||||
SPEC_STATE_LABELS,
|
||||
chipDetail,
|
||||
isDeletableSpecDir,
|
||||
handoffAge,
|
||||
handoffCopyText,
|
||||
pickupAction,
|
||||
pickupReply,
|
||||
launchTarget,
|
||||
cardAvailability,
|
||||
launchReply,
|
||||
deleteSummary,
|
||||
deleteHandoffAction,
|
||||
deleteHandoffReply,
|
||||
deleteAction,
|
||||
deleteReply,
|
||||
} from "../answers.js";
|
||||
import { stateFor } from "../spec-states.js";
|
||||
import { sound, soundOn, fadeSound, dropSounds } from "../sound.js";
|
||||
import { playWake } from "../boot.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The dashboard's first-open wake-up itself is page.wake (state.js). Once per
|
||||
// page, whatever storage allows: a re-render mid-run must never start a
|
||||
// second one.
|
||||
let wakeTried = false;
|
||||
|
||||
// True when a wake-up is waiting on the first click: the page load's opening
|
||||
// chime then gives way to the boot-up sound, played as he powers on.
|
||||
export let wakeHoldsChime = false;
|
||||
|
||||
// His snore while he sleeps (an Audio on loop), or null. Usually silent until
|
||||
// the waking click, since browsers refuse sound before one.
|
||||
let snore = null;
|
||||
|
||||
function roleNudge() {
|
||||
const nudge = el("div", "dash-nudge");
|
||||
nudge.setAttribute("role", "status");
|
||||
nudge.appendChild(el("span", "dash-nudge-text", "Pick your role to get starter templates ordered for you."));
|
||||
const actions = el("div", "dash-nudge-actions");
|
||||
const setUp = el("button", "btn small primary", "Set up preferences");
|
||||
setUp.type = "button";
|
||||
setUp.addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
// Closed without a role is a "Not now" too: having been to the dialog,
|
||||
// they were asked, and the banner does not come back (Help says so).
|
||||
$("looks-modal").addEventListener(
|
||||
"close",
|
||||
() => {
|
||||
if (looks.role === undefined) {
|
||||
looks.role = ROLE_NOT_SET;
|
||||
saveLooks();
|
||||
redraw();
|
||||
}
|
||||
},
|
||||
{ once: true }
|
||||
);
|
||||
$("looks-modal").showModal();
|
||||
});
|
||||
const notNow = el("button", "btn tiny ghost", "Not now");
|
||||
notNow.type = "button";
|
||||
notNow.addEventListener("click", () => {
|
||||
looks.role = ROLE_NOT_SET;
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
actions.append(setUp, notNow);
|
||||
nudge.appendChild(actions);
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + page.S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === page.updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const UPDATE_COMMAND = "plan2code update";
|
||||
|
||||
// For a machine without the plan2code command: the full installer, menu and all.
|
||||
const UPDATE_FALLBACK_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!page.updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + page.updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, page.updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
const fallbackRow = $("update-fallback");
|
||||
const fallback = el("code", null, UPDATE_FALLBACK_COMMAND);
|
||||
fallbackRow.replaceChildren(fallback, copyButton(UPDATE_FALLBACK_COMMAND, "btn small ghost handoff-copy", fallback));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
export function renderDashboard(main) {
|
||||
maybeWake();
|
||||
// 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();
|
||||
settleDeleting();
|
||||
const menu = (page.S && page.S.menu) || {};
|
||||
const wrap = el("div", "dash");
|
||||
if (needsRoleNudge(looks)) wrap.appendChild(roleNudge());
|
||||
// Advice only: words, never a button, and nothing is blocked.
|
||||
if (page.meterFrame && page.meterFrame.level === "red") {
|
||||
const warn = el("div", "dash-nudge meter-banner", RED_BANNER);
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (page.updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + page.updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), page.updateFrame.latest);
|
||||
} catch {}
|
||||
redraw();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
// The agent's note reads the spec the picker opened on (the same "initial"
|
||||
// test cardPresentation uses): another pick, or Start from scratch, gets
|
||||
// the neutral line rather than context about a spec no longer shown.
|
||||
const first = defaultSpec(scan() && scan().specs);
|
||||
const picked = selSpec();
|
||||
const noteKind = dashNoteKind({ menu, hasMenu: Boolean(page.S.menu), onInitial: onInitialPick(first, picked), working: agentWorking() });
|
||||
if (noteKind === "agent") {
|
||||
wrap.appendChild(el("p", "dash-note", menu.note));
|
||||
} else if (noteKind === "looking") {
|
||||
// The cards work from the first paint; the agent's read of the
|
||||
// project arrives a moment later, and this says so meanwhile.
|
||||
const note = el("p", "dash-note");
|
||||
note.appendChild(document.createTextNode("Pick what to do next. "));
|
||||
const working = el("span", "dash-working");
|
||||
working.appendChild(el("span", "spinner tiny"));
|
||||
working.appendChild(
|
||||
el(
|
||||
"span",
|
||||
null,
|
||||
"Plan2Code is still looking over the project and will flag where it would start when it is done."
|
||||
)
|
||||
);
|
||||
note.appendChild(working);
|
||||
wrap.appendChild(note);
|
||||
} else {
|
||||
wrap.appendChild(
|
||||
el("p", "dash-note", "Pick what to do next. It starts right here, and this page becomes its home.")
|
||||
);
|
||||
}
|
||||
|
||||
const specs = specList();
|
||||
if (specs.length || handoffList().length) wrap.appendChild(renderSpecPicker(specs));
|
||||
const handoff = selHandoff();
|
||||
if (handoff) {
|
||||
// A handoff is picked up, not launched: its skill and spec come from its
|
||||
// own record, so the skill cards and their toggle have nothing to say.
|
||||
if (!page.local.launching && !page.launchScoping && page.scopeMine !== "") hooks.syncWorkspaceScope();
|
||||
wrap.appendChild(renderHandoffPreview(handoff));
|
||||
main.appendChild(wrap);
|
||||
queueMicrotask(hooks.maybeWelcome);
|
||||
return;
|
||||
}
|
||||
wrap.appendChild(hideUnavailableToggle());
|
||||
// Only when this tab's own pick moved: another tab changing the scope
|
||||
// sends a frame here too, and re-asserting this tab's pick on every render
|
||||
// had two dashboards trade the workspace back and forth without end.
|
||||
const wantScope = (selSpec() && selSpec().dir) || "";
|
||||
if (!page.local.launching && !page.launchScoping && wantScope !== page.scopeMine) hooks.syncWorkspaceScope();
|
||||
|
||||
// "Unavailable" is the scan's verdict for the selected spec, not the
|
||||
// momentary greying while a launch is in flight or the server is away, so
|
||||
// cards never blink out of the menu mid-handoff.
|
||||
const hide = looks.hideUnavailable;
|
||||
const sel = selSpec();
|
||||
const available = (e) => cardPresentation(e, scan(), sel, menu).on;
|
||||
let shown = 0;
|
||||
for (const g of CATALOG_GROUPS) {
|
||||
const entries = SKILL_CATALOG.filter((e) => e.group === g.id && (!hide || available(e)));
|
||||
if (!entries.length) continue;
|
||||
shown += entries.length;
|
||||
const section = el("section", "dash-group");
|
||||
section.appendChild(el("h3", "dash-group-title", g.title));
|
||||
const grid = el("div", "dash-grid");
|
||||
for (const e of entries) grid.appendChild(dashCard(e, menu));
|
||||
section.appendChild(grid);
|
||||
wrap.appendChild(section);
|
||||
}
|
||||
if (!shown) {
|
||||
wrap.appendChild(
|
||||
el("p", "dash-empty", "Nothing fits this pick right now. Turn off the toggle above to see every workflow.")
|
||||
);
|
||||
}
|
||||
wrap.appendChild(approvalTip());
|
||||
// Mid wake-up: the groups wait hidden until the glide lets them rise in,
|
||||
// and the note shows only as far as it has been typed. Once the entrance
|
||||
// has played, a re-render draws the menu plainly, never replaying it.
|
||||
if (page.wake && !page.wake.entered) wrap.classList.add("waking", ...(page.wake.cards ? ["is-in"] : []));
|
||||
if (page.wake && page.wake.typed != null) {
|
||||
const note = wrap.querySelector(".dash-note");
|
||||
if (note) revealNote(note, page.wake.typed);
|
||||
}
|
||||
main.appendChild(wrap);
|
||||
// Deferred: this runs inside render(), and the dialog is not part of it.
|
||||
queueMicrotask(hooks.maybeWelcome);
|
||||
}
|
||||
|
||||
const WAKE_TYPE_DELAY_MS = 350;
|
||||
|
||||
const WAKE_TYPE_EVERY_MS = 14;
|
||||
|
||||
const WAKE_ENTRANCE_MS = 900;
|
||||
|
||||
// One snore, for a nudge with no sound to time it (sounds off, or refused).
|
||||
const SNORE_MS = 2600;
|
||||
|
||||
// The longest a nudge waits on the snore ending: a hidden tab may never say.
|
||||
const SNORE_MAX_MS = 6000;
|
||||
|
||||
const BOOTUP_FADE_MS = 500;
|
||||
|
||||
const delay = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
||||
|
||||
// Only a newly opened dashboard carries `wake` (console.mjs deletes it on
|
||||
// every resume), and only the first page load in this tab plays it.
|
||||
function maybeWake() {
|
||||
if (wakeTried || page.S.wake !== true || finish()) return;
|
||||
wakeTried = true;
|
||||
const key = "p2c-console:woke:" + page.S.sid;
|
||||
try {
|
||||
if (sessionStorage.getItem(key)) return;
|
||||
sessionStorage.setItem(key, "1");
|
||||
} catch {
|
||||
// Blocked storage only costs the reload guard.
|
||||
}
|
||||
const stage = $("wake");
|
||||
const pilot = $("planny").closest(".pilot");
|
||||
page.wake = { cards: false, entered: false, typed: 0, timers: [], abort: new AbortController() };
|
||||
wakeHoldsChime = !matchMedia("(prefers-reduced-motion: reduce)").matches;
|
||||
if (wakeHoldsChime && soundOn("snore")) {
|
||||
snore = new Audio("/sleeping.mp3");
|
||||
snore.loop = true;
|
||||
snore.play().catch(() => {});
|
||||
}
|
||||
pilot.classList.add("is-waking");
|
||||
playWake({
|
||||
stage,
|
||||
bot: stage.querySelector(".wake-bot"),
|
||||
skipEl: stage.querySelector(".wake-skip"),
|
||||
target: $("planny"),
|
||||
stir: stirWake,
|
||||
onStart: () => sound("bootup"),
|
||||
onGlide: wakeGlide,
|
||||
onSkip: skipWakeSounds,
|
||||
signal: page.wake.abort.signal,
|
||||
}).then(({ skipped }) => {
|
||||
stopSnore();
|
||||
fadeSound("bootup", BOOTUP_FADE_MS);
|
||||
pilot.classList.remove("is-waking");
|
||||
// An abort or reduced motion jumps straight to the finished
|
||||
// dashboard. A run that reached its end leaves the note typing on.
|
||||
if (skipped || (page.wake && !page.wake.cards)) finishWake();
|
||||
});
|
||||
}
|
||||
|
||||
// The nudge: one whole snore from the top, however far the loop had got (or
|
||||
// the first one heard, since the loop is usually refused until this click).
|
||||
// Called inside the click, so the browser lets it play. Settles when it ends,
|
||||
// and never rejects: a refused or silent snore just takes one snore's time.
|
||||
function stirWake() {
|
||||
if (!snore) return delay(SNORE_MS);
|
||||
const heard = new Promise((resolve) => snore.addEventListener("ended", resolve, { once: true }));
|
||||
snore.loop = false;
|
||||
snore.currentTime = 0;
|
||||
return snore.play().then(
|
||||
() => Promise.race([heard, delay(SNORE_MAX_MS)]),
|
||||
() => delay(SNORE_MS)
|
||||
);
|
||||
}
|
||||
|
||||
function stopSnore() {
|
||||
if (!snore) return;
|
||||
snore.pause();
|
||||
snore = null;
|
||||
}
|
||||
|
||||
// The Skip button: silence anything the intro already queued or started. The
|
||||
// promise's .then does the snore and the bootup fade; this only clears cues
|
||||
// still waiting to play.
|
||||
function skipWakeSounds() {
|
||||
dropSounds();
|
||||
}
|
||||
|
||||
// The glide: the menu rises in and the note starts typing. On a skip the run
|
||||
// is already ending and its promise settles everything, so nothing here.
|
||||
function wakeGlide({ instant }) {
|
||||
if (!page.wake) return;
|
||||
page.wake.cards = true;
|
||||
if (instant) return;
|
||||
page.wake.timers.push(
|
||||
setTimeout(() => {
|
||||
page.wake.entered = true;
|
||||
settleWake();
|
||||
}, WAKE_ENTRANCE_MS),
|
||||
setTimeout(typeNote, WAKE_TYPE_DELAY_MS)
|
||||
);
|
||||
redraw();
|
||||
}
|
||||
|
||||
// One more character of the note on the live element. Whatever the note says
|
||||
// right now is what gets typed, so a `menu` note that lands mid-way simply
|
||||
// carries on from the same count.
|
||||
function typeNote() {
|
||||
if (!page.wake || page.wake.typed == null) return;
|
||||
page.wake.typed += 1;
|
||||
const note = $("main").querySelector(":scope > .dash .dash-note");
|
||||
if (!note || page.wake.typed >= revealNote(note, page.wake.typed)) {
|
||||
page.wake.typed = null;
|
||||
if (note) revealNote(note, Infinity);
|
||||
return settleWake();
|
||||
}
|
||||
page.wake.timers.push(setTimeout(typeNote, WAKE_TYPE_EVERY_MS));
|
||||
}
|
||||
|
||||
// Done once the entrance has played and the note is all there. Nothing to
|
||||
// redraw: what is on screen already is the finished dashboard.
|
||||
function settleWake() {
|
||||
if (page.wake && page.wake.entered && page.wake.typed == null) {
|
||||
page.wake = null;
|
||||
hooks.maybeWelcome();
|
||||
}
|
||||
}
|
||||
|
||||
function finishWake() {
|
||||
if (!page.wake) return;
|
||||
for (const t of page.wake.timers) clearTimeout(t);
|
||||
page.wake = null;
|
||||
redraw();
|
||||
}
|
||||
|
||||
// Shows the first `count` characters of a note's text, across its text nodes,
|
||||
// and returns how many there are in all. The full text is kept per node the
|
||||
// first time it is cut, so later calls can grow it back. An element the
|
||||
// typing has not reached yet (the "still looking" pill and its spinner) is
|
||||
// kept out of sight, rather than showing as an empty box.
|
||||
const noteFullText = new WeakMap();
|
||||
|
||||
function revealNote(note, count) {
|
||||
const walker = document.createTreeWalker(note, NodeFilter.SHOW_TEXT | NodeFilter.SHOW_ELEMENT);
|
||||
let total = 0;
|
||||
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
||||
if (n.nodeType === Node.ELEMENT_NODE) {
|
||||
n.classList.toggle("is-untyped", total >= count);
|
||||
continue;
|
||||
}
|
||||
if (!noteFullText.has(n)) noteFullText.set(n, n.data);
|
||||
const full = noteFullText.get(n);
|
||||
n.data = full.slice(0, Math.max(0, count - total));
|
||||
total += full.length;
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
// A page-wide preference, so it rides in `looks` (looks.json) and follows the
|
||||
// person to every session and port rather than resetting per dashboard.
|
||||
function hideUnavailableToggle() {
|
||||
const label = el("label", "dash-toggle");
|
||||
const box = el("input");
|
||||
box.type = "checkbox";
|
||||
// The id is what lets withFocus hand focus back after the rebuild.
|
||||
box.id = "dash-hide-unavailable";
|
||||
box.setAttribute("role", "switch");
|
||||
box.checked = looks.hideUnavailable;
|
||||
box.addEventListener("change", () => {
|
||||
looks.hideUnavailable = box.checked;
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
label.appendChild(box);
|
||||
label.appendChild(el("span", "dash-toggle-track"));
|
||||
label.appendChild(el("span", "dash-toggle-text", "Hide unavailable workflows"));
|
||||
return label;
|
||||
}
|
||||
|
||||
/* The spec picker: every spec the server found under specs/, plus "start
|
||||
from scratch". The selection decides which cards below are lit, and rides
|
||||
along on the launch of any card that takes a spec. Picking is page-local —
|
||||
no send — so it costs nothing to change your mind. */
|
||||
function renderSpecPicker(specs) {
|
||||
const sel = selSpec();
|
||||
const handoffs = handoffList();
|
||||
const pickedHandoff = selHandoff();
|
||||
const box = el("section", "spec-pick");
|
||||
box.appendChild(
|
||||
el("h3", "dash-group-title", handoffs.length ? "Pick up a spec or a handoff, or start fresh" : "Pick up a spec, or start fresh")
|
||||
);
|
||||
const row = el("div", "spec-row");
|
||||
|
||||
const scratchOn = !sel && !pickedHandoff;
|
||||
const scratch = el("button", "spec-chip" + (scratchOn ? " is-sel" : ""));
|
||||
scratch.type = "button";
|
||||
scratch.setAttribute("aria-current", String(scratchOn));
|
||||
scratch.appendChild(el("span", "spec-chip-name", "Start from scratch"));
|
||||
scratch.appendChild(el("span", "spec-chip-state", "a new idea"));
|
||||
scratch.addEventListener("click", () => {
|
||||
page.local.specSel = null;
|
||||
saveNow();
|
||||
redraw();
|
||||
loadOverview();
|
||||
});
|
||||
row.appendChild(scratch);
|
||||
|
||||
for (const spec of specs) {
|
||||
const on = sel && sel.dir === spec.dir;
|
||||
// A finished spec (a fixed bug) is hidden while unavailable workflows
|
||||
// are, dimmed otherwise. A pick already on it stays visible, so it is
|
||||
// never lost.
|
||||
const fixed = Boolean(stateFor(spec.state)?.finished);
|
||||
if (fixed && looks.hideUnavailable && !on) continue;
|
||||
const deleting = Boolean(page.local.deleting && page.local.deleting.dir === spec.dir);
|
||||
const wrap = el("div", "spec-chip-wrap" + (deleting ? " is-deleting" : "") + (fixed ? " is-fixed" : ""));
|
||||
const b = el("button", "spec-chip" + (on ? " is-sel" : ""));
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-current", String(Boolean(on)));
|
||||
b.appendChild(el("span", "spec-chip-name", spec.name));
|
||||
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : SPEC_STATE_LABELS[spec.state] || spec.state));
|
||||
const detail = chipDetail(spec);
|
||||
if (detail) b.appendChild(el("span", "spec-chip-detail", detail));
|
||||
b.addEventListener("click", () => {
|
||||
page.local.specSel = spec.dir;
|
||||
saveNow();
|
||||
redraw();
|
||||
loadOverview();
|
||||
});
|
||||
wrap.appendChild(b);
|
||||
if (isDeletableSpecDir(spec.dir)) {
|
||||
// A fixed bug is done with, so its Delete is a visible button rather
|
||||
// than the hover ✕ every other spec has.
|
||||
const del = fixed ? el("button", "spec-chip-del-label", "Delete") : el("button", "spec-chip-del", "✕");
|
||||
del.type = "button";
|
||||
del.title = `Delete ${spec.dir}/`;
|
||||
del.setAttribute("aria-label", `Delete the spec ${spec.name}`);
|
||||
del.disabled = deleting || Boolean(page.local.deleting) || page.gone || page.pendingResult || Boolean(page.local.launching);
|
||||
del.addEventListener("click", () => openDeleteConfirm(spec));
|
||||
wrap.appendChild(del);
|
||||
}
|
||||
row.appendChild(wrap);
|
||||
}
|
||||
// Handoffs follow the specs: dashed chips, the state word is "Handoff".
|
||||
for (const h of handoffs) {
|
||||
const on = Boolean(pickedHandoff && pickedHandoff.id === h.id);
|
||||
const deleting = Boolean(page.local.deleting && page.local.deleting.dir === "handoff:" + h.id);
|
||||
const b = el("button", "spec-chip is-handoff" + (on ? " is-sel" : "") + (deleting ? " is-deleting" : ""));
|
||||
b.type = "button";
|
||||
b.setAttribute("aria-current", String(on));
|
||||
b.appendChild(el("span", "spec-chip-name", h.title || "Handoff"));
|
||||
b.appendChild(el("span", "spec-chip-state", deleting ? "Deleting…" : "Handoff"));
|
||||
b.appendChild(el("span", "spec-chip-detail", handoffAge(h.written)));
|
||||
b.addEventListener("click", () => {
|
||||
page.local.specSel = "handoff:" + h.id;
|
||||
saveNow();
|
||||
redraw();
|
||||
});
|
||||
row.appendChild(b);
|
||||
}
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// A delete in flight ends when the agent's rescan lands (a new scan), gone
|
||||
// or refused: either way the picker is the truth again.
|
||||
function settleDeleting() {
|
||||
const sc = scan();
|
||||
if (page.local.deleting && sc && sc.at !== page.local.deleting.scanAt) {
|
||||
page.local.deleting = null;
|
||||
saveNow();
|
||||
}
|
||||
}
|
||||
|
||||
// What a picked handoff shows: where it came from and its Next task, with the
|
||||
// four things to do with it.
|
||||
function renderHandoffPreview(h) {
|
||||
const box = el("section", "handoff-preview");
|
||||
box.appendChild(el("h3", "handoff-preview-title", h.title || "Handoff"));
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
const meta = [
|
||||
"Written " + (h.written ? new Date(h.written).toLocaleString() : "at an unknown time"),
|
||||
h.spec ? "spec " + h.spec.replace(/^specs\//, "") : "no spec",
|
||||
"from " + (entry ? entry.title : h.skill),
|
||||
];
|
||||
box.appendChild(el("p", "handoff-preview-meta", meta.join(" · ")));
|
||||
if (h.next) {
|
||||
box.appendChild(el("p", "handoff-preview-label", "Next task"));
|
||||
box.appendChild(el("p", "handoff-preview-next", h.next));
|
||||
}
|
||||
const busy = Boolean(page.local.launching || page.local.deleting) || page.gone || page.pendingResult;
|
||||
const actions = el("div", "handoff-preview-actions");
|
||||
const go = el("button", "btn primary", "Pick it up here");
|
||||
go.type = "button";
|
||||
go.disabled = busy;
|
||||
go.addEventListener("click", () => pickUpHandoff(h));
|
||||
const read = el("button", "btn", "Read it all");
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => readHandoff(h));
|
||||
const copy = el("button", "btn", "Copy for a new conversation");
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", () => {
|
||||
const dir = (scan() && scan().handoffsDir) || "";
|
||||
const sep = dir.includes("\\") ? "\\" : "/";
|
||||
const file = dir ? dir.replace(/[\\/]+$/, "") + sep + h.id + ".md" : h.id + ".md";
|
||||
copyHandoffText(handoffCopyText(file), copy);
|
||||
});
|
||||
const del = el("button", "btn danger", "Delete");
|
||||
del.type = "button";
|
||||
del.disabled = busy;
|
||||
del.addEventListener("click", () => openHandoffDelete(h));
|
||||
actions.append(go, read, copy, del);
|
||||
box.appendChild(actions);
|
||||
return box;
|
||||
}
|
||||
|
||||
// The prompt that sends a new conversation to the handoff. A refused
|
||||
// clipboard gets a plain word on the button instead of a silent nothing.
|
||||
async function copyHandoffText(text, button) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Copy was refused";
|
||||
}
|
||||
setTimeout(() => (button.textContent = "Copy for a new conversation"), 1500);
|
||||
}
|
||||
|
||||
// Pick it up here: a hop like a card launch. The page sends only the id; the
|
||||
// CLI reads the stored skill and spec, marks the handoff used and falls back
|
||||
// to Quick Task if either is gone.
|
||||
async function pickUpHandoff(h) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(h.spec || "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [pickupAction(h)], reply: pickupReply(h) }),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last pick is still being picked up. One moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
sound("startSkill");
|
||||
page.local.launching = { skill: h.skill, title: h.title || "the handoff", at: Date.now() };
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
redraw();
|
||||
} catch {
|
||||
page.launchScoping = false;
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// Read it all: the document, in a dialog, from /handoff?id= (served only for
|
||||
// an id the dashboard's own scan listed).
|
||||
async function readHandoff(h) {
|
||||
$("handoff-title").textContent = h.title || "Handoff";
|
||||
const body = $("handoff-body");
|
||||
body.replaceChildren(el("p", "md-p", "Reading…"));
|
||||
$("handoff-modal").showModal();
|
||||
try {
|
||||
const res = await fetch("/handoff?id=" + encodeURIComponent(h.id), { cache: "no-store" });
|
||||
if (res.status !== 200) throw new Error(String(res.status));
|
||||
mdInto(body, await res.text());
|
||||
} catch {
|
||||
body.replaceChildren(el("p", "md-p", "This handoff could not be read."));
|
||||
}
|
||||
}
|
||||
|
||||
function dashCard(entry, menu) {
|
||||
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
|
||||
// The agent's `recommend` and detail describe the initially selected spec.
|
||||
// Other picker choices derive both from the scan, so stale context never
|
||||
// follows a person to a different spec or to "start from scratch". A greyed
|
||||
// recommendation also yields to the selected spec's actual next step.
|
||||
const going = page.local.launching && page.local.launching.skill === entry.skill;
|
||||
const b = el(
|
||||
"button",
|
||||
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
|
||||
);
|
||||
b.type = "button";
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !presentation.on;
|
||||
if (!presentation.on && presentation.reason) b.title = presentation.reason;
|
||||
|
||||
const head = el("span", "dash-card-head");
|
||||
head.appendChild(el("span", "dash-chip", entry.chip));
|
||||
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
|
||||
b.appendChild(head);
|
||||
b.appendChild(el("span", "dash-card-title", entry.title));
|
||||
b.appendChild(el("span", "dash-card-blurb", entry.blurb));
|
||||
if (presentation.detail) b.appendChild(el("span", "dash-card-detail", presentation.detail));
|
||||
if (!presentation.on && presentation.reason) b.appendChild(el("span", "dash-card-off", presentation.reason));
|
||||
|
||||
const foot = el("span", "dash-card-foot");
|
||||
foot.appendChild(el("code", "dash-card-cmd", entry.command));
|
||||
foot.appendChild(el("span", "dash-card-go", going ? "…" : "→"));
|
||||
b.appendChild(foot);
|
||||
|
||||
b.addEventListener("click", () => {
|
||||
page.dashPick = entry;
|
||||
redraw();
|
||||
});
|
||||
return b;
|
||||
}
|
||||
|
||||
// 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
|
||||
// START that means it. Planny turns up leaning (his "this way" pose) in a
|
||||
// small sky, because a bare paragraph with two buttons is a dialog, not a
|
||||
// moment. BACK returns to the menu; Escape does the same (see the global
|
||||
// keydown in core.js).
|
||||
export function renderConfirm(main, entry) {
|
||||
const menu = (page.S && page.S.menu) || {};
|
||||
const presentation = cardPresentation(entry, scan(), selSpec(), menu);
|
||||
const pane = el("div", "dash-confirm");
|
||||
|
||||
const stage = el("div", "launch-stage confirm-stage");
|
||||
const sky = el("div", "sky launch-sky");
|
||||
const r = (a, b) => a + Math.random() * (b - a);
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const star = el("i", "star" + (i % 5 === 0 ? " hot" : ""));
|
||||
const dur = r(4, 10);
|
||||
star.style.setProperty("--y", r(2, 98).toFixed(1) + "%");
|
||||
star.style.setProperty("--p", r(0, 1).toFixed(3));
|
||||
star.style.setProperty("--s", r(1.2, 2.4).toFixed(2) + "px");
|
||||
star.style.setProperty("--dur", dur.toFixed(2) + "s");
|
||||
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
|
||||
sky.appendChild(star);
|
||||
}
|
||||
stage.appendChild(sky);
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", "planny is-point v0 confirm-planny");
|
||||
stage.appendChild(bot);
|
||||
pane.appendChild(stage);
|
||||
|
||||
const head = el("div", "confirm-head");
|
||||
head.appendChild(el("span", "dash-chip", entry.chip));
|
||||
if (presentation.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
|
||||
pane.appendChild(head);
|
||||
pane.appendChild(el("h2", "dash-title", entry.title));
|
||||
pane.appendChild(el("p", "confirm-about", entry.about || entry.blurb));
|
||||
|
||||
if (presentation.detail) pane.appendChild(el("p", "confirm-detail", presentation.detail));
|
||||
|
||||
// A card that takes a spec names the one the picker is holding, so START
|
||||
// reads as "build THIS spec", not the skill in the abstract.
|
||||
const target = launchTarget(entry, selSpec());
|
||||
if (target) {
|
||||
const specLine = el("p", "confirm-spec");
|
||||
specLine.appendChild(el("span", null, "for "));
|
||||
specLine.appendChild(el("code", null, target.dir));
|
||||
specLine.appendChild(el("span", null, ` · ${SPEC_STATE_LABELS[target.state] || target.state}`));
|
||||
pane.appendChild(specLine);
|
||||
}
|
||||
|
||||
const cmd = el("p", "confirm-cmd");
|
||||
cmd.appendChild(el("code", null, entry.command));
|
||||
pane.appendChild(cmd);
|
||||
|
||||
const actions = el("div", "confirm-actions");
|
||||
const start = el("button", "btn primary", "Start " + entry.title);
|
||||
start.type = "button";
|
||||
start.disabled = page.gone || page.pendingResult;
|
||||
start.addEventListener("click", () => launchSkill(entry));
|
||||
const back = el("button", "btn ghost", "Back");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", () => {
|
||||
page.dashPick = null;
|
||||
redraw();
|
||||
});
|
||||
actions.appendChild(back);
|
||||
actions.appendChild(start);
|
||||
pane.appendChild(actions);
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
// A pick is a send like a brief or a stop: it names no question, so `__launch`
|
||||
// marks the action as being about the session, and it reaches the agent
|
||||
// through the same wait loop. The dashboard reads `skill` off it.
|
||||
async function launchSkill(entry) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || finish()) return;
|
||||
const target = launchTarget(entry, selSpec());
|
||||
// The card was clickable, so this should never fire — but a spec picked in
|
||||
// one tab could have shifted the ground under a stale render in another.
|
||||
if (!cardAvailability(entry, scan(), selSpec()).on) {
|
||||
hooks.banner("That card is not available for the spec you picked.", "warn");
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
page.dashPick = null;
|
||||
const action = {
|
||||
i: "__launch",
|
||||
type: "launch",
|
||||
skill: entry.skill,
|
||||
workflow: entry.workflow,
|
||||
title: entry.title,
|
||||
};
|
||||
// The picker's spec goes to the skill being launched, not to the card:
|
||||
// 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;
|
||||
// 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.
|
||||
page.launchScoping = true;
|
||||
await hooks.syncWorkspaceScope(target ? target.dir : "");
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [action],
|
||||
reply: launchReply(entry, target),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last pick is still being picked up. One moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
sound("startSkill");
|
||||
page.local.launching = { skill: entry.skill, title: entry.title, at: Date.now() };
|
||||
page.launchScoping = false;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
redraw();
|
||||
} catch {
|
||||
page.launchScoping = false;
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// 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
|
||||
// fixed bug skips the second step: its first press sends the delete.
|
||||
// Cancel, Escape or a click on Keep it at either step changes nothing.
|
||||
let deleteTarget = null;
|
||||
|
||||
// The spec warning as index.html writes it, kept so a fixed bug's wording
|
||||
// never sticks for the next spec.
|
||||
let deleteWarnDefault = null;
|
||||
|
||||
// A handoff's Delete reuses the same dialog in one step: no name to type, and
|
||||
// the warning says where the file lives instead of what git does not track.
|
||||
function openHandoffDelete(h) {
|
||||
if (page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
|
||||
deleteTarget = { handoff: h };
|
||||
$("delete-title").textContent = "Delete this handoff?";
|
||||
$("delete-blurb").textContent = "This handoff will be deleted from ~/.plan2code/handoffs/.";
|
||||
$("delete-warn").hidden = true;
|
||||
$("delete-warn-handoff").hidden = false;
|
||||
const facts = $("delete-facts");
|
||||
facts.replaceChildren();
|
||||
const fact = (term, value) => {
|
||||
if (!value) return;
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
fact("Handoff", h.title || h.id);
|
||||
fact("Written", h.written ? new Date(h.written).toLocaleString() : "");
|
||||
fact("Spec", h.spec ? h.spec.replace(/^specs\//, "") : "");
|
||||
fact("From", entry ? entry.title : h.skill);
|
||||
$("delete-confirm").hidden = true;
|
||||
const go = $("delete-go");
|
||||
go.textContent = "Delete it";
|
||||
go.classList.add("is-on");
|
||||
go.disabled = false;
|
||||
$("delete-modal").showModal();
|
||||
}
|
||||
|
||||
function openDeleteConfirm(spec) {
|
||||
if (!isDeletableSpecDir(spec.dir) || page.gone || page.pendingResult || page.local.launching || page.local.deleting) return;
|
||||
deleteTarget = spec;
|
||||
// A finished spec (a fixed bug): one confirm, and a warning that says so.
|
||||
const fixed = Boolean(stateFor(spec.state)?.finished);
|
||||
$("delete-title").textContent = "Delete this spec?";
|
||||
const warn = $("delete-warn");
|
||||
if (!deleteWarnDefault) deleteWarnDefault = [...warn.childNodes].map((n) => n.cloneNode(true));
|
||||
warn.replaceChildren(
|
||||
...(fixed
|
||||
? ["The bug is fixed, so this only clears the write-up. ", el("code", "", "specs/"), " is not tracked by git, so it cannot be brought back."]
|
||||
: deleteWarnDefault.map((n) => n.cloneNode(true)))
|
||||
);
|
||||
warn.hidden = false;
|
||||
$("delete-warn-handoff").hidden = true;
|
||||
const sum = deleteSummary(spec);
|
||||
$("delete-blurb").textContent = `Everything in ${sum.folder} will be deleted from this project.`;
|
||||
const facts = $("delete-facts");
|
||||
facts.replaceChildren();
|
||||
const fact = (term, value) => {
|
||||
if (!value) return;
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
fact("Spec", spec.name);
|
||||
fact("Folder", sum.folder);
|
||||
fact("Stage", sum.stage);
|
||||
fact("Files", sum.files);
|
||||
fact("Last changed", sum.touched ? new Date(sum.touched).toLocaleString() : "");
|
||||
$("delete-name-hint").textContent = spec.name;
|
||||
$("delete-name").value = "";
|
||||
$("delete-confirm").hidden = true;
|
||||
const go = $("delete-go");
|
||||
go.textContent = fixed ? "Delete it" : "Delete this spec…";
|
||||
go.classList.toggle("is-on", fixed);
|
||||
go.disabled = false;
|
||||
$("delete-modal").showModal();
|
||||
}
|
||||
|
||||
function deleteStep() {
|
||||
const go = $("delete-go");
|
||||
if (!deleteTarget) return;
|
||||
if (deleteTarget.handoff) return sendDeleteHandoff(deleteTarget.handoff);
|
||||
if (stateFor(deleteTarget.state)?.finished) return sendDelete(deleteTarget);
|
||||
if ($("delete-confirm").hidden) {
|
||||
$("delete-confirm").hidden = false;
|
||||
go.textContent = "Delete for good";
|
||||
go.classList.add("is-on");
|
||||
go.disabled = true;
|
||||
$("delete-name").focus();
|
||||
return;
|
||||
}
|
||||
if ($("delete-name").value.trim() !== deleteTarget.name) return;
|
||||
sendDelete(deleteTarget);
|
||||
}
|
||||
|
||||
async function sendDeleteHandoff(h) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteHandoffAction(h)], reply: deleteHandoffReply(h) }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const sc = scan();
|
||||
page.local.deleting = { dir: "handoff:" + h.id, scanAt: sc ? sc.at : null };
|
||||
if (page.local.specSel === "handoff:" + h.id) delete page.local.specSel;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
$("delete-modal").close();
|
||||
} catch (err) {
|
||||
$("delete-modal").close();
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
|
||||
: "That did not go through. Nothing was deleted; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
deleteTarget = null;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
async function sendDelete(spec) {
|
||||
const go = $("delete-go");
|
||||
go.disabled = true;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: [deleteAction(spec)], reply: deleteReply(spec) }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
const sc = scan();
|
||||
page.local.deleting = { dir: spec.dir, scanAt: sc ? sc.at : null };
|
||||
// The selection must not outlive the folder: back to the default pick,
|
||||
// which the agent's fresh menu recommends for.
|
||||
if (page.local.specSel === spec.dir) delete page.local.specSel;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
$("delete-modal").close();
|
||||
} catch (err) {
|
||||
$("delete-modal").close();
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last pick is still being picked up, so that could not go yet. Nothing was deleted; try again in a moment."
|
||||
: "That did not go through. Nothing was deleted; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
deleteTarget = null;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// 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() {
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
|
||||
$("handoff-close").addEventListener("click", () => $("handoff-modal").close());
|
||||
$("delete-go").addEventListener("click", deleteStep);
|
||||
$("delete-name").addEventListener("input", () => {
|
||||
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
|
||||
});
|
||||
$("delete-name").addEventListener("keydown", (e) => {
|
||||
if (e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
deleteStep();
|
||||
}
|
||||
});
|
||||
$("delete-modal").addEventListener("close", () => {
|
||||
deleteTarget = null;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,229 @@
|
||||
// Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only.
|
||||
|
||||
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish } from "../selectors.js";
|
||||
import { el, md } from "../render.js";
|
||||
import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
import { sendState } from "../send-state.js";
|
||||
import { briefPhrase } from "../answers.js";
|
||||
|
||||
let docObserver = null;
|
||||
|
||||
// A brief is a Pathfinder thing: a plain-English report of the decisions made
|
||||
// in a date range, the ones still open, and what happens next. It is the
|
||||
// artifact someone takes to a meeting, and the reason a non-engineer is in this
|
||||
// session at all, so it should not need knowing that you can type "brief" at a
|
||||
// terminal to get one.
|
||||
//
|
||||
// The request travels as an ordinary send. The agent's own wait loop returns
|
||||
// it, `reply` carries the range in the grammar its playbook already parses, and
|
||||
// the finished brief comes back as a doc like any other.
|
||||
const BRIEF_RANGES = {
|
||||
today: "today",
|
||||
"this week": "this week",
|
||||
full: "full",
|
||||
};
|
||||
|
||||
function briefRange() {
|
||||
const picked = document.querySelector('input[name="brief-range"]:checked');
|
||||
const value = picked ? picked.value : "today";
|
||||
if (value !== "since") return { range: BRIEF_RANGES[value] || "today" };
|
||||
const on = $("brief-since").value;
|
||||
if (!on) return { problem: "Pick the date to count from, or choose another range." };
|
||||
if (on > localDay()) return { problem: "Pick a date that has already happened: a brief covers what was decided since then." };
|
||||
return { range: `since ${on}` };
|
||||
}
|
||||
|
||||
function openBrief() {
|
||||
const why = $("brief-why");
|
||||
why.textContent = "";
|
||||
syncBriefDate();
|
||||
$("brief-modal").showModal();
|
||||
}
|
||||
|
||||
// The date only means anything for "since", so it is dimmed and inert until
|
||||
// that is the choice, rather than sitting there inviting a value it will ignore.
|
||||
function syncBriefDate() {
|
||||
const picked = document.querySelector('input[name="brief-range"]:checked');
|
||||
const on = Boolean(picked && picked.value === "since");
|
||||
const row = document.querySelector(".since-row");
|
||||
const input = $("brief-since");
|
||||
row.classList.toggle("is-off", !on);
|
||||
input.disabled = !on;
|
||||
input.max = localDay();
|
||||
}
|
||||
|
||||
// Today as YYYY-MM-DD in the person's own time zone, the shape a date input uses.
|
||||
function localDay(d = new Date()) {
|
||||
const p = (n) => String(n).padStart(2, "0");
|
||||
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
||||
}
|
||||
|
||||
export async function sendBrief() {
|
||||
const choice = briefRange();
|
||||
const why = $("brief-why");
|
||||
if (choice.problem) {
|
||||
why.textContent = choice.problem;
|
||||
return;
|
||||
}
|
||||
const state = sendState();
|
||||
// The same guard the Send button uses. A brief is a turn like any other, and
|
||||
// two turns in flight is the one thing this protocol will not do.
|
||||
if (page.gone || page.pendingResult || (agentWorking() && workingMs() <= patience(WORKING_GRACE_MS))) {
|
||||
why.textContent = state.why || "Wait for Plan2Code to finish, then ask again.";
|
||||
return;
|
||||
}
|
||||
|
||||
const go = $("brief-go");
|
||||
go.disabled = true;
|
||||
go.textContent = "Asking…";
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [{ i: "__brief", type: "brief", range: choice.range }],
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
hooks.banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => hooks.banner(null), 5000);
|
||||
page.pendingResult = true;
|
||||
redraw();
|
||||
} catch (err) {
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
}
|
||||
}
|
||||
|
||||
export function renderBriefButton() {
|
||||
const btn = $("btn-brief");
|
||||
// Only Pathfinder has a brief playbook. Offering the button anywhere else
|
||||
// would send the agent a request it has no procedure for.
|
||||
const offer = page.S && page.S.workflow === "pathfinder";
|
||||
btn.hidden = !offer;
|
||||
// A finished (or paused) session has nobody to write it: the request would
|
||||
// wait on disk for a session that may never come.
|
||||
if (offer) btn.disabled = page.gone || page.pendingResult || Boolean(finish());
|
||||
}
|
||||
|
||||
export function renderDoc(main, id) {
|
||||
const doc = docs().find((d) => d.id === id);
|
||||
if (!doc) {
|
||||
main.appendChild(el("p", "doc-empty", "That document is not ready yet."));
|
||||
return;
|
||||
}
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, doc.title || "Document"));
|
||||
head.appendChild(el("span", "doc-version", "v" + (doc.version || 1)));
|
||||
if (doc.stale) {
|
||||
head.appendChild(el("span", "pill staged", "Out of date"));
|
||||
}
|
||||
|
||||
const tools = el("div", "doc-tools");
|
||||
// A brief is handed to people who were not in the room, so it gets a copy
|
||||
// that opens in any browser, formatting and all.
|
||||
if (doc.id === "brief") {
|
||||
const html = el("button", "btn small", "Save as HTML");
|
||||
html.type = "button";
|
||||
html.addEventListener("click", () => downloadDocHtml(doc));
|
||||
tools.appendChild(html);
|
||||
}
|
||||
tools.appendChild(printButton());
|
||||
|
||||
if (doc.saved) {
|
||||
tools.appendChild(docSavedNote(doc));
|
||||
} else {
|
||||
const save = el("button", "btn small", "Download");
|
||||
save.type = "button";
|
||||
save.addEventListener("click", () => downloadDoc(doc));
|
||||
tools.appendChild(save);
|
||||
}
|
||||
head.appendChild(tools);
|
||||
|
||||
main.appendChild(head);
|
||||
if (doc.note) main.appendChild(el("p", "help", doc.note));
|
||||
|
||||
const blocks = doc.blocks || [];
|
||||
if (!blocks.length) {
|
||||
main.appendChild(el("p", "doc-empty", "Nothing written yet. It fills in as you answer."));
|
||||
return;
|
||||
}
|
||||
// The block nearest the top of the column is the section + Add context
|
||||
// offers after leaving this tab. Its label is its first heading.
|
||||
docObserver?.disconnect();
|
||||
if (page.docInView && page.docInView.docId !== doc.id) page.docInView = null;
|
||||
const boxes = [];
|
||||
const topmost = () => {
|
||||
const top = main.getBoundingClientRect().top;
|
||||
const box = boxes.find((x) => x.getBoundingClientRect().bottom > top + 1);
|
||||
if (!box) return;
|
||||
const heading = box.querySelector("h1, h2, h3, h4, h5, h6");
|
||||
page.docInView = {
|
||||
docId: doc.id,
|
||||
blockId: box.dataset.block,
|
||||
label: (heading && heading.textContent.trim()) || doc.title || "Document",
|
||||
};
|
||||
};
|
||||
docObserver = typeof IntersectionObserver === "function" ? new IntersectionObserver(topmost, { root: main, threshold: [0, 0.25, 0.5, 0.75, 1] }) : null;
|
||||
blocks.forEach((b, i) => {
|
||||
const box = el("div", "block " + (b.state || "settled"));
|
||||
box.dataset.block = b.id || String(i);
|
||||
boxes.push(box);
|
||||
docObserver?.observe(box);
|
||||
if (b.state === "assumed") {
|
||||
// Borrowed from grill-with-ui and the best idea in it: show plainly which
|
||||
// parts are still a guess, so nobody mistakes a placeholder for a decision.
|
||||
box.appendChild(el("span", "block-tag", "Assumed for now, still open"));
|
||||
}
|
||||
if (b.state === "draft") box.appendChild(el("span", "block-tag", "Draft"));
|
||||
box.appendChild(blockBody(b));
|
||||
main.appendChild(box);
|
||||
});
|
||||
}
|
||||
|
||||
function printButton() {
|
||||
const print = el("button", "btn small", "Print");
|
||||
print.type = "button";
|
||||
// The print stylesheet drops everything that steers the session, so what
|
||||
// comes out is the document alone. "Save as PDF" in that dialog is also the
|
||||
// most portable save this page can offer.
|
||||
print.addEventListener("click", () => window.print());
|
||||
return print;
|
||||
}
|
||||
|
||||
// The spec's overview.md, read-only and drawn through the same markdown path
|
||||
// as every doc. No Download: the file is already on disk.
|
||||
export function renderOverview(main) {
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, "Overview"));
|
||||
const tools = el("div", "doc-tools");
|
||||
tools.appendChild(printButton());
|
||||
head.appendChild(tools);
|
||||
main.appendChild(head);
|
||||
main.appendChild(el("p", "help", `${page.overview.key}/overview.md · read-only, straight from disk`));
|
||||
const box = el("div", "block settled");
|
||||
box.appendChild(md(page.overview.text, "md"));
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The brief dialog's buttons, wired once at start-up.
|
||||
export function wireDocs() {
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
radio.addEventListener("change", syncBriefDate);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,726 @@
|
||||
// Plan2Code Web Console - how a session ends: the finished screen, its offers, Stop and the way home; defines only.
|
||||
|
||||
import { el, md, copyButton, textWithCode, SVG_NS } from "../render.js";
|
||||
import {
|
||||
finishPaused,
|
||||
reviewOffer,
|
||||
commitOffer,
|
||||
handoffShape,
|
||||
ALL_DONE_LEAD,
|
||||
ALL_DONE_REST,
|
||||
handoffText,
|
||||
DASHBOARD_COMMAND,
|
||||
resumeCommand,
|
||||
afterFinishButton,
|
||||
DASHBOARD_NOTE,
|
||||
turnGate,
|
||||
homeButtonState,
|
||||
HOME_REPLY,
|
||||
stopAction,
|
||||
STOP_HANDOFF_REPLY,
|
||||
STOP_REPLY,
|
||||
REVIEW_REPLY,
|
||||
DONE_REPLY,
|
||||
DASHBOARD_REPLY,
|
||||
COMMIT_REPLY,
|
||||
} from "../answers.js";
|
||||
import { hooks, page, saveNow, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
import {
|
||||
dashboardLive,
|
||||
reviewPending,
|
||||
docs,
|
||||
finish,
|
||||
agentAdrift,
|
||||
agentWorking,
|
||||
awaitingReply,
|
||||
isDashboard,
|
||||
} from "../selectors.js";
|
||||
import { docSavedNote, downloadDoc } from "../doc-files.js";
|
||||
import { pendingNotes } from "../uploads.js";
|
||||
|
||||
// The end of the session, and the only screen in this page whose job is to
|
||||
// send someone somewhere else.
|
||||
//
|
||||
// It reads in three beats, because that is the order the questions arrive in:
|
||||
// what just happened, the one thing to run, and where to run it. The command
|
||||
// is the whole point, so its Copy button is always on show -- the one on a
|
||||
// fenced code block only appears on hover, which is right for a sample buried
|
||||
// in prose and useless for the single action a screen exists to offer. A
|
||||
// finish with nothing left to run skips the last two beats: it gets a quiet
|
||||
// pointer at the dashboard instead of a Next step block.
|
||||
// "Before you close this": the three things someone looking at a finished
|
||||
// screen wonders. Every finish shape gets it; a pause says where the place is
|
||||
// kept, and a session with nothing left to run points at the dashboard alone.
|
||||
const GUIDE_ICONS = {
|
||||
safe: ["M5 12.5 10 17.5 19 7"],
|
||||
fresh: ["M19.5 12a7.5 7.5 0 1 1-2.4-5.5", "M19.5 4v4.5H15"],
|
||||
carry: ["M5 12h13", "M13 6.5 18.5 12 13 17.5"],
|
||||
};
|
||||
|
||||
function guideIcon(kind) {
|
||||
const wrap = el("span", `handoff-guide-icon is-${kind}`);
|
||||
wrap.setAttribute("aria-hidden", "true");
|
||||
const svg = document.createElementNS(SVG_NS, "svg");
|
||||
svg.setAttribute("viewBox", "0 0 24 24");
|
||||
svg.setAttribute("width", "16");
|
||||
svg.setAttribute("height", "16");
|
||||
for (const d of GUIDE_ICONS[kind]) {
|
||||
const path = document.createElementNS(SVG_NS, "path");
|
||||
path.setAttribute("d", d);
|
||||
svg.appendChild(path);
|
||||
}
|
||||
wrap.appendChild(svg);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
function renderCloseGuide(shape, fin = {}) {
|
||||
// A command that is not a skill (a finish's git commit) runs in a terminal,
|
||||
// not "in the new session".
|
||||
const shell = typeof fin.command === "string" && Boolean(fin.command.trim()) && !fin.command.trim().startsWith("/");
|
||||
const panel = el("section", "handoff-guide");
|
||||
panel.setAttribute("aria-labelledby", "handoff-guide-title");
|
||||
const title = el("h3", "handoff-guide-title", "Before you close this");
|
||||
title.id = "handoff-guide-title";
|
||||
panel.appendChild(title);
|
||||
const rows = [
|
||||
["safe", "Safe to close", "This tab is only a window: whatever this session wrote is on disk, and nothing here needs you."],
|
||||
[
|
||||
"fresh",
|
||||
"Start fresh",
|
||||
shape === "paused"
|
||||
? stopWarning()
|
||||
? "Restart your agent window, or close the old session and start a new one. The command above starts it again."
|
||||
: "Restart your agent window, or close the old session and start a new one. Your saved place is picked up by the resume command above."
|
||||
: "Restart your agent window, or close the old session and start a new one. A new session starts from clean context. This one is full of this step's instructions, so continuing in it is slower and can confuse the next step.",
|
||||
],
|
||||
[
|
||||
"carry",
|
||||
"Carry on",
|
||||
shape === "all-done"
|
||||
? `In the new session, start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: shell
|
||||
? `Run the command above in your terminal, then start the next step from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: `Paste the command above in the new session, or start from the dashboard with \`${DASHBOARD_COMMAND}\`.`,
|
||||
],
|
||||
];
|
||||
const list = el("ul", "handoff-guide-rows");
|
||||
for (const [kind, label, text] of rows) {
|
||||
const row = el("li", "handoff-guide-row");
|
||||
row.appendChild(guideIcon(kind));
|
||||
const body = el("div", "handoff-guide-text");
|
||||
body.appendChild(el("strong", "handoff-guide-label", label));
|
||||
body.appendChild(document.createTextNode(" "));
|
||||
body.appendChild(textWithCode("span", "handoff-guide-line", text));
|
||||
row.appendChild(body);
|
||||
list.appendChild(row);
|
||||
}
|
||||
panel.appendChild(list);
|
||||
return panel;
|
||||
}
|
||||
|
||||
// A review, a commit in Git or the dashboard the person just asked for is starting
|
||||
// here, so the page is about to carry on rather than end.
|
||||
function closeGuideHeld() {
|
||||
if (page.gone) return false;
|
||||
return ["review", "commit", "dashboard"].includes(page.local.afterBuild) || reviewPending() === "asked";
|
||||
}
|
||||
|
||||
export function renderHandoff(fin) {
|
||||
const card = el("article", "card handoff");
|
||||
card.appendChild(el("p", "card-kicker", finishPaused(fin) ? "Session paused" : "Session ended"));
|
||||
card.appendChild(el("h2", null, fin.headline));
|
||||
if (fin.body) card.appendChild(md(fin.body, "md prompt"));
|
||||
|
||||
// A finished build offers its review first, above the next step, because it
|
||||
// is the one thing on this screen that has to happen before they leave.
|
||||
const offer = reviewOffer(fin);
|
||||
if (offer && !["done", "dashboard", "commit"].includes(page.local.afterBuild)) {
|
||||
card.appendChild(renderReviewOffer(offer));
|
||||
}
|
||||
|
||||
// The commit, right after the review: one press starts Git's commit flow here.
|
||||
if (commitOffer(fin) && !page.gone && page.local.afterBuild !== "done" && page.local.afterBuild !== "dashboard") {
|
||||
card.appendChild(renderCommitOffer());
|
||||
}
|
||||
|
||||
// Three shapes: a next step to run, a pause with its resume command, or a
|
||||
// session with nothing left to run, which gets a quiet pointer at the
|
||||
// dashboard instead of a Next step block.
|
||||
const shape = handoffShape(fin);
|
||||
if (shape === "all-done") {
|
||||
const done = el("div", "handoff-done");
|
||||
done.appendChild(md(`${ALL_DONE_LEAD} ${ALL_DONE_REST}`, "md handoff-done-text"));
|
||||
const text = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small ghost handoff-copy", code));
|
||||
done.appendChild(row);
|
||||
// Once the server is gone, the row above already is the offer's fallback.
|
||||
if (dashboardLive(fin) && !page.gone) done.appendChild(renderDashboardOffer(true));
|
||||
card.appendChild(done);
|
||||
} else {
|
||||
// A pause always offers its resume command, even when the agent left it out.
|
||||
const command =
|
||||
String(fin.command || "").trim() || resumeCommand({ workflow: page.S.workflow, specDir: page.S.specDir });
|
||||
const step = el("div", "handoff-step");
|
||||
step.appendChild(el("p", "handoff-label", "Next step"));
|
||||
step.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-where",
|
||||
fin.where ||
|
||||
(command.startsWith("/")
|
||||
? "Run this in the terminal where you started Plan2Code, in a new conversation:"
|
||||
: "Run this in your terminal:")
|
||||
)
|
||||
);
|
||||
|
||||
// Shown exactly as copied. Nothing goes on the clipboard that they cannot
|
||||
// read first: it is about to be pasted into a program with their files.
|
||||
const text = handoffText({ ...fin, command });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
step.appendChild(row);
|
||||
if (text !== command) {
|
||||
step.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-note",
|
||||
"The --web at the end asks Plan2Code to open this page again, so you carry on here rather than in the terminal."
|
||||
)
|
||||
);
|
||||
}
|
||||
card.appendChild(step);
|
||||
|
||||
// A finished (never paused) screen always names the way to the dashboard
|
||||
// from a new conversation, unless the offer's own fallback already does.
|
||||
if (shape === "next") {
|
||||
const offerDash = dashboardLive(fin);
|
||||
if (offerDash) card.appendChild(renderDashboardOffer(false));
|
||||
if (!(offerDash && page.gone)) {
|
||||
card.appendChild(
|
||||
textWithCode(
|
||||
"p",
|
||||
"handoff-fresh",
|
||||
`To start something else, run \`${DASHBOARD_COMMAND}\` in a new conversation.`
|
||||
)
|
||||
);
|
||||
const freshText = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const freshRow = el("div", "handoff-command handoff-fresh-row");
|
||||
const freshCode = el("code", "handoff-code", freshText);
|
||||
freshRow.appendChild(freshCode);
|
||||
freshRow.appendChild(copyButton(freshText, "btn small ghost handoff-copy", freshCode));
|
||||
card.appendChild(freshRow);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Not while a hand-off they just asked for is starting on this page: "Safe
|
||||
// to close" and "start a new one" would contradict the line above it. The
|
||||
// press re-renders the page, and so does the agent taking it up.
|
||||
if (!closeGuideHeld()) card.appendChild(renderCloseGuide(shape, fin));
|
||||
|
||||
card.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-close",
|
||||
reviewPending() === "open"
|
||||
? "The review is optional. Skip it and nothing else here needs you."
|
||||
: "That is everything on this page."
|
||||
)
|
||||
);
|
||||
|
||||
// What they were working on is on disk, but only the agent's copy is. This
|
||||
// is the last moment anyone is looking at this page, so the way to take the
|
||||
// document with them belongs here and not only behind a tab they may never
|
||||
// open again — unless the doc is `saved`, in which case the file itself is
|
||||
// already on disk and a download would be a second copy of it.
|
||||
const keep = docs().find((d) => d.id === fin.doc) || docs()[0];
|
||||
if (keep && (keep.blocks || []).length) {
|
||||
const tools = el("div", "handoff-tools");
|
||||
if (keep.saved) {
|
||||
tools.appendChild(docSavedNote(keep));
|
||||
} else {
|
||||
const save = el("button", "btn small", `Download ${keep.title || "the document"}`);
|
||||
save.type = "button";
|
||||
save.addEventListener("click", () => downloadDoc(keep));
|
||||
tools.appendChild(save);
|
||||
}
|
||||
card.appendChild(tools);
|
||||
}
|
||||
|
||||
// Answers staged and never sent are lost the moment this page closes, and
|
||||
// this page's one promise is that nothing gets lost. Say so plainly rather
|
||||
// than letting them walk away from work they thought was safe.
|
||||
const stuck = Object.keys(page.local.staged).length;
|
||||
if (stuck) {
|
||||
card.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"handoff-unsent",
|
||||
`${stuck} answer${stuck === 1 ? "" : "s"} here ${stuck === 1 ? "was" : "were"} never sent, ` +
|
||||
`and Plan2Code has finished. If ${stuck === 1 ? "it" : "they"} still matter, say so in the ` +
|
||||
`next session: nothing on this page will reach it now.`
|
||||
)
|
||||
);
|
||||
}
|
||||
return card;
|
||||
}
|
||||
|
||||
// The review button, on the hand-off of a finished build (a finished quick
|
||||
// task; an implementation phase gets its review offer earlier, as a verdict
|
||||
// on the sign-off card).
|
||||
//
|
||||
// It is a request, not a command: the page cannot run a review, it asks the
|
||||
// agent that is still sitting in its wait loop, the same way "Write a brief"
|
||||
// does. So it is only offered while there is a server to carry the press, and
|
||||
// once there is not, it turns into the command that does the same thing from
|
||||
// the terminal instead of a button that would go nowhere.
|
||||
function renderReviewOffer(offer) {
|
||||
const box = el("section", "review-offer");
|
||||
box.appendChild(el("p", "handoff-label", "Before you go"));
|
||||
box.appendChild(el("h3", "review-offer-title", offer.label));
|
||||
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "review", page.pendingResult);
|
||||
|
||||
if (page.gone) {
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
asked
|
||||
? "The session closed before the review could start. To run it now, use this in the terminal, in a new conversation:"
|
||||
: "This session has closed, so the review cannot start from here any more. To run it, use this in the terminal, in a new conversation:"
|
||||
)
|
||||
);
|
||||
const text = "/plan2code-review";
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
"A careful review of the files this session changed: bugs, gaps against what was asked for, and anything risky. " +
|
||||
"The findings come back on this page and you choose which ones get fixed. Nothing changes until you do."
|
||||
)
|
||||
);
|
||||
const row = el("div", "btn-row");
|
||||
const go = el("button", "btn primary review-go", asked ? "Review requested…" : "Review it now");
|
||||
go.type = "button";
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("review"));
|
||||
row.appendChild(go);
|
||||
if (!asked) {
|
||||
const no = el("button", "btn ghost", "No thanks, I am done");
|
||||
no.type = "button";
|
||||
no.disabled = disabled;
|
||||
no.addEventListener("click", () => sendAfterBuild("done"));
|
||||
row.appendChild(no);
|
||||
}
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// Commit what was just built without leaving the page. Like the review button
|
||||
// it is a request to an agent still in its wait loop, so it is only drawn
|
||||
// while the server is there; the command printed below stays for the terminal.
|
||||
function renderCommitOffer() {
|
||||
const box = el("section", "review-offer");
|
||||
box.appendChild(el("p", "handoff-label", "Commit it"));
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
"Git reads what changed, drafts the message and asks before it commits. It opens right here, on the git board."
|
||||
)
|
||||
);
|
||||
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "commit", page.pendingResult);
|
||||
const row = el("div", "btn-row");
|
||||
const go = el("button", "btn primary", asked ? "Opening Git…" : "Commit it now");
|
||||
go.type = "button";
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("commit"));
|
||||
row.appendChild(go);
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
|
||||
// The way back to the dashboard, on a finished screen whose agent opted in
|
||||
// with `finish.dashboard`. Like the review button it is a request to an agent
|
||||
// still in its wait loop, so once the server is gone it turns into the
|
||||
// command that opens the dashboard from a new conversation instead.
|
||||
function renderDashboardOffer(primary) {
|
||||
const box = el("section", "dashboard-offer");
|
||||
if (page.gone) {
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
null,
|
||||
"This session has closed, so the button cannot reach Plan2Code any more. To open the dashboard, run this in a new conversation:"
|
||||
)
|
||||
);
|
||||
const text = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
box.appendChild(row);
|
||||
return box;
|
||||
}
|
||||
const { asked, disabled } = afterFinishButton(page.local.afterBuild, "dashboard", page.pendingResult);
|
||||
const go = el(
|
||||
"button",
|
||||
primary ? "btn primary" : "btn",
|
||||
asked ? "Opening the dashboard…" : "Back to the dashboard"
|
||||
);
|
||||
go.type = "button";
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("dashboard"));
|
||||
box.appendChild(go);
|
||||
box.appendChild(textWithCode("p", "dashboard-note", DASHBOARD_NOTE));
|
||||
return box;
|
||||
}
|
||||
|
||||
// Any answer to a finished session's offers, as one send through the ordinary
|
||||
// submit. Like a brief, it names no question: `__review`, `__commit`, `__done`
|
||||
// and `__dashboard` are about the session.
|
||||
const AFTER_FINISH_REPLIES = { review: REVIEW_REPLY, done: DONE_REPLY, dashboard: DASHBOARD_REPLY, commit: COMMIT_REPLY };
|
||||
|
||||
async function sendAfterBuild(kind) {
|
||||
if (page.gone || page.pendingResult || page.local.afterBuild) return;
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [{ i: `__${kind}`, type: kind }],
|
||||
reply: AFTER_FINISH_REPLIES[kind],
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last answers are still being picked up. Try again in a moment.", "info");
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
page.local.afterBuild = kind;
|
||||
page.pendingResult = true;
|
||||
saveNow();
|
||||
const started = {
|
||||
review: "Review requested. It starts here in a moment.",
|
||||
dashboard: "Opening the dashboard. It appears here in a moment.",
|
||||
commit: "Opening Git. It appears here in a moment.",
|
||||
}[kind];
|
||||
if (started) {
|
||||
hooks.banner(started, "good");
|
||||
setTimeout(() => hooks.banner(null), 5000);
|
||||
}
|
||||
} catch {
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
} finally {
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
let stoppingHidden = false;
|
||||
|
||||
// A stop is under way if this browser sent one, or if the server is holding
|
||||
// one nobody has collected: the second covers a reload on a resumed session,
|
||||
// a second tab, another machine.
|
||||
export function stopInProgress() {
|
||||
return page.local.stopping || (page.pendingStop ? { at: 0, answers: 0 } : null);
|
||||
}
|
||||
|
||||
export function renderStopButton() {
|
||||
const b = $("btn-stop");
|
||||
if (!page.S || finish()) {
|
||||
b.hidden = true;
|
||||
return;
|
||||
}
|
||||
b.hidden = false;
|
||||
if (stopInProgress()) {
|
||||
b.textContent = "Stopping…";
|
||||
b.disabled = false;
|
||||
b.title = "Show how the stop is going";
|
||||
return;
|
||||
}
|
||||
b.textContent = "Stop session";
|
||||
// Only on the person's turn, unless nothing is coming (see turnGate).
|
||||
const gate = turnGate({ gone: page.gone, pendingResult: page.pendingResult, waiting: agentHasTheBall() });
|
||||
// A way home in flight holds Stop back too, unless the agent went quiet
|
||||
// after collecting it: Stop's resume screen is then the only way out.
|
||||
b.disabled = Boolean(gate) || (Boolean(page.local.homeward) && !agentAdrift());
|
||||
b.title = {
|
||||
gone: "Not connected right now.",
|
||||
pending: "Your last answers are still being picked up. You can stop once they have been.",
|
||||
waiting: "Plan2Code is working on your answers. You can stop once it replies.",
|
||||
}[gate] || (stopWarning() ? "End this session. Work since the last save is not kept." : "Save your place and end this session. You get a command to pick it up later.");
|
||||
}
|
||||
|
||||
// Plan2Code has the ball: it is working, or owes a reply to a send, and has
|
||||
// not gone quiet. What both session buttons wait out.
|
||||
function agentHasTheBall() {
|
||||
return (agentWorking() || awaitingReply().length > 0) && !agentAdrift();
|
||||
}
|
||||
|
||||
// The triangle left of Stop session. Mid-workflow it is a stop that lands on
|
||||
// the menu instead of a finish: the same staged answers ride along, the agent
|
||||
// saves its place the same way, then resumes the session as the dashboard.
|
||||
export function renderHomeButton() {
|
||||
const b = $("btn-home");
|
||||
const st = homeButtonState({
|
||||
workflow: page.S && page.S.workflow,
|
||||
finished: Boolean(page.S && finish()),
|
||||
stopping: Boolean(page.S && stopInProgress()),
|
||||
homeward: Boolean(page.local.homeward),
|
||||
adrift: Boolean(page.S) && agentAdrift(),
|
||||
gone: page.gone,
|
||||
pendingResult: page.pendingResult,
|
||||
waiting: Boolean(page.S) && agentHasTheBall(),
|
||||
warned: Boolean(page.S) && Boolean(stopWarning()),
|
||||
});
|
||||
b.hidden = st.hidden;
|
||||
b.disabled = st.disabled;
|
||||
b.title = st.title;
|
||||
}
|
||||
|
||||
function openHomeConfirm() {
|
||||
const n = Object.keys(page.local.staged).length + pendingNotes().length;
|
||||
const warn = stopWarning();
|
||||
// With a warning, "your place is saved" is the one thing not true: the
|
||||
// warning says what is lost, and the button says the choice is theirs.
|
||||
$("home-blurb").textContent =
|
||||
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
|
||||
(warn ? "Plan2Code takes you back to the dashboard." : "Your place is saved; you can resume it from the dashboard.");
|
||||
$("home-go").textContent = warn ? "Leave anyway" : "Back to the dashboard";
|
||||
$("home-warn").hidden = !warn;
|
||||
$("home-warn").textContent = warn;
|
||||
$("home-modal").showModal();
|
||||
}
|
||||
|
||||
async function goHome() {
|
||||
const go = $("home-go");
|
||||
go.disabled = true;
|
||||
const payload = hooks.stagedPayload();
|
||||
payload.actions.push({ i: "__dashboard", type: "dashboard" });
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, HOME_REPLY].join("\n") }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
hooks.markSent(payload);
|
||||
page.local.homeward = { at: Date.now() };
|
||||
saveNow();
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
: "That did not go through. Nothing was lost; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// Stopping now can lose answers: Planning writes nothing until its plan is
|
||||
// done, and Pathfinder nothing until its map exists. The agent knows where it
|
||||
// is and says so in `stopWarning`; Planning is assumed to lose answers unless
|
||||
// the agent says otherwise, because that is true of most of it.
|
||||
export function stopWarning() {
|
||||
if (typeof page.S.stopWarning === "string") return page.S.stopWarning.trim();
|
||||
if (page.S.workflow === "plan") {
|
||||
return "Planning only saves at set points along the way. Answers since the last save will not be kept, though you can go over them again next time.";
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
function openStopConfirm() {
|
||||
if (stopInProgress()) {
|
||||
stoppingHidden = false;
|
||||
return renderStopping();
|
||||
}
|
||||
const n = Object.keys(page.local.staged).length + pendingNotes().length;
|
||||
const warn = stopWarning();
|
||||
const dash = isDashboard();
|
||||
$("stop-blurb").textContent =
|
||||
(n === 1 ? "The answer you have ready goes with it. " : n ? `The ${n} answers you have ready go with it. ` : "") +
|
||||
(dash ? "Nothing has started yet, so there is nothing to save: this just ends the console session." : "");
|
||||
$("stop-blurb").hidden = !$("stop-blurb").textContent;
|
||||
$("stop-warn").hidden = !warn;
|
||||
$("stop-warn").textContent = warn;
|
||||
// The dashboard has nothing to hand off: one plain Stop. Elsewhere both
|
||||
// choices show, and "Just stop and save" turns into "Stop anyway" where
|
||||
// nothing is saved yet.
|
||||
$("stop-handoff").hidden = dash;
|
||||
const title = $("stop-go").querySelector(".stop-choice-title");
|
||||
const detail = $("stop-go").querySelector(".stop-choice-detail");
|
||||
if (dash) {
|
||||
title.textContent = "Stop";
|
||||
detail.textContent = "Ends the console session.";
|
||||
} else if (warn) {
|
||||
title.textContent = "Stop anyway";
|
||||
detail.textContent = "Ends the session now. What the warning above names is not kept.";
|
||||
} else {
|
||||
title.textContent = "Just stop and save";
|
||||
detail.textContent = "Saves what this step keeps on disk and gives you a command to resume. What we talked about is not kept.";
|
||||
}
|
||||
$("stop-modal").showModal();
|
||||
}
|
||||
|
||||
async function stopSession(handoff = false) {
|
||||
const buttons = [$("stop-handoff"), $("stop-go")];
|
||||
for (const b of buttons) b.disabled = true;
|
||||
const payload = hooks.stagedPayload();
|
||||
payload.actions.push(stopAction({ handoff }));
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ actions: payload.actions, reply: [...payload.replyLines, handoff ? STOP_HANDOFF_REPLY : STOP_REPLY].join("\n") }),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
hooks.markSent(payload);
|
||||
page.local.stopping = { at: Date.now(), answers: payload.sentIds.size };
|
||||
saveNow();
|
||||
$("stop-modal").close();
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) page.pendingResult = true;
|
||||
hooks.banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
: "The stop did not go through. Nothing was lost; try again.",
|
||||
"warn"
|
||||
);
|
||||
} finally {
|
||||
for (const b of buttons) b.disabled = false;
|
||||
redraw();
|
||||
}
|
||||
}
|
||||
|
||||
// The wrapping-up screen, derived every render from what the page already
|
||||
// tracks: whether the request is collected, whether anyone is listening, and
|
||||
// whether the finish has landed.
|
||||
export function renderStopping() {
|
||||
const dlg = $("stopping-modal");
|
||||
const stopping = page.S && stopInProgress();
|
||||
if (!stopping) {
|
||||
if (dlg.open) dlg.close();
|
||||
return;
|
||||
}
|
||||
// The finish is the end of it: the hand-off card on the page says the rest.
|
||||
if (finish()) {
|
||||
page.local.stopping = null;
|
||||
saveNow();
|
||||
if (dlg.open) dlg.close();
|
||||
return;
|
||||
}
|
||||
|
||||
const sent = stopping.answers;
|
||||
const collected = !page.pendingResult;
|
||||
// Nobody is coming: the server stopped with no finish, or the agent has not
|
||||
// checked in for minutes. The request and any answers are on disk either
|
||||
// way, and the next session collects them.
|
||||
const stuck = page.gone || agentAdrift();
|
||||
const steps = [
|
||||
{ text: sent ? `Sent your ${sent === 1 ? "answer" : sent + " answers"} and the stop` : "Sent the stop", state: "done" },
|
||||
{
|
||||
text: collected ? "Plan2Code picked it up" : stuck ? "Plan2Code has not picked it up" : "Waiting for Plan2Code to pick it up",
|
||||
state: collected ? "done" : stuck ? "stuck" : "now",
|
||||
},
|
||||
{ text: "Saving your place and writing the command to pick it up", state: collected ? (stuck ? "stuck" : "now") : "later" },
|
||||
];
|
||||
const list = $("stop-steps");
|
||||
list.replaceChildren(
|
||||
...steps.map((s) => {
|
||||
const li = el("li", "is-" + s.state);
|
||||
li.appendChild(
|
||||
s.state === "now"
|
||||
? el("span", "spinner tiny")
|
||||
: el("span", "stop-mark", s.state === "done" ? "✓" : s.state === "stuck" ? "!" : "·")
|
||||
);
|
||||
li.appendChild(el("span", null, s.text));
|
||||
return li;
|
||||
})
|
||||
);
|
||||
|
||||
const extra = $("stop-extra");
|
||||
extra.replaceChildren();
|
||||
if (stuck) {
|
||||
extra.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"stop-note",
|
||||
page.gone
|
||||
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
)
|
||||
);
|
||||
const text = handoffText({ command: resumeCommand(page.S) });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
extra.appendChild(row);
|
||||
} else {
|
||||
extra.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"stop-note",
|
||||
agentWorking() && !collected
|
||||
? "Plan2Code is in the middle of something. It stops as soon as that is done."
|
||||
: "This usually takes a moment. You can close the tab if you need to: the command also appears in the terminal."
|
||||
)
|
||||
);
|
||||
}
|
||||
|
||||
if (!stoppingHidden && !dlg.open) dlg.showModal();
|
||||
}
|
||||
|
||||
// The top bar's way home and Stop, wired once at start-up.
|
||||
export function wireEnding() {
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
$("stop-cancel").addEventListener("click", () => $("stop-modal").close());
|
||||
$("stop-handoff").addEventListener("click", () => stopSession(true));
|
||||
$("stop-go").addEventListener("click", () => stopSession(false));
|
||||
$("stopping-hide").addEventListener("click", () => {
|
||||
stoppingHidden = true;
|
||||
$("stopping-modal").close();
|
||||
});
|
||||
// Esc on a native dialog closes it without our say; count that as hiding, or
|
||||
// the next render would open it straight back up.
|
||||
$("stopping-modal").addEventListener("cancel", () => (stoppingHidden = true));
|
||||
}
|
||||
|
||||
// The three stop-related controls, drawn again when the agent comes or goes.
|
||||
export function renderStopControls() {
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
renderStopping();
|
||||
}
|
||||
@@ -0,0 +1,370 @@
|
||||
// Plan2Code Web Console - hosts the git board: tabs, panels and what each click sends.
|
||||
|
||||
import { hooks, page, saveNow, redraw } from "../state.js";
|
||||
import { GIT_TABS, busyMode, gitReply, pickTab, nextStep, tabBadges, createSources, BRANCH_TYPES, commitTicks, cleanupGroups } from "../git-board.js";
|
||||
import { finish, agentWorking, agentAdrift, gitAwaiting, myTurn, byId, activity } from "../selectors.js";
|
||||
import { drawGitBoard, activeTab } from "../git-board-view.js";
|
||||
import { el, md, copyButton } from "../render.js";
|
||||
import { helpKeyTarget } from "../help.js";
|
||||
import { postJson } from "../net.js";
|
||||
|
||||
// The git board: drawn from state.git, which only console.mjs writes. A click
|
||||
// never runs git here. It sends one `__git` action through /submit, and the
|
||||
// agent confirms by card, runs the command and posts a `reread`, whose frame
|
||||
// redraws the board. The rules live in git-board.js and the drawing in
|
||||
// git-board-view.js; this is the host: the busy mode, the tab, the scroll,
|
||||
// the keys, and the panels' state.
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// What the person has typed or ticked on the board. Every state frame redraws
|
||||
// the board from state.git, so this is what carries their place across it.
|
||||
// panel the open panel: "create", "commit" or "cleanup", or null
|
||||
// create the Create prompt's fields, while it is open
|
||||
// ticks the commit table's ticked paths; ignore, its .gitignore toggles
|
||||
// sweep the cleanup list's ticked branches
|
||||
// base the pull-request base the picker chose
|
||||
// settled cards the agent settled since the last click on the board
|
||||
// tab the tab on show: "changes", "branches" or "sync", or null before the first draw
|
||||
// scroll how far the column was scrolled on each tab, put back after each redraw
|
||||
// repickAt when their last board click went out (ms): the first agent post
|
||||
// after it moves the board to the new next step's tab
|
||||
export const board = {
|
||||
tab: null,
|
||||
scroll: { changes: 0, branches: 0, sync: 0 },
|
||||
repickAt: null,
|
||||
query: "",
|
||||
showAll: false,
|
||||
remoteOpen: null,
|
||||
panel: null,
|
||||
create: null,
|
||||
ticks: null,
|
||||
ignore: new Set(),
|
||||
sweep: null,
|
||||
base: null,
|
||||
settled: new Set(),
|
||||
};
|
||||
|
||||
// The search, ticks and open panel are also kept in `local`, so a reload (and
|
||||
// a skill hop back) restores them the way card drafts already do. Stale picks
|
||||
// are harmless: the next send re-checks every path against the snapshot. The
|
||||
// restore waits for the first draw: load() has not run when this module does.
|
||||
const boardBlank = {
|
||||
tab: null,
|
||||
scroll: { changes: 0, branches: 0, sync: 0 },
|
||||
repickAt: null,
|
||||
query: "",
|
||||
showAll: false,
|
||||
remoteOpen: null,
|
||||
panel: null,
|
||||
create: null,
|
||||
ticks: null,
|
||||
sweep: null,
|
||||
base: null,
|
||||
};
|
||||
|
||||
// Each reset gets its own scroll memory: boardBlank's must never be the one written to.
|
||||
export const resetBoard = () => {
|
||||
Object.assign(board, boardBlank, { scroll: { ...boardBlank.scroll } });
|
||||
board.ignore.clear();
|
||||
};
|
||||
|
||||
let boardHydrated = false;
|
||||
|
||||
// True from hydration until the first draw has picked its tab: that draw is a reload.
|
||||
let boardReloaded = false;
|
||||
|
||||
const hydrateBoard = () => {
|
||||
boardHydrated = true;
|
||||
const g = page.local.gitBoard;
|
||||
if (!g) return;
|
||||
boardReloaded = true;
|
||||
Object.assign(board, boardBlank, {
|
||||
tab: GIT_TABS.some((t) => t.id === g.tab) ? g.tab : null,
|
||||
scroll: { changes: 0, branches: 0, sync: 0, ...(g.scroll || {}) },
|
||||
repickAt: typeof g.repickAt === "number" ? g.repickAt : null,
|
||||
query: g.query || "",
|
||||
showAll: Boolean(g.showAll),
|
||||
remoteOpen: g.remoteOpen ?? null,
|
||||
panel: g.panel || null,
|
||||
create: g.create || null,
|
||||
ticks: g.ticks ? new Set(g.ticks) : null,
|
||||
sweep: g.sweep ? new Set(g.sweep) : null,
|
||||
base: g.base || null,
|
||||
ignore: new Set(g.ignore || []),
|
||||
});
|
||||
};
|
||||
|
||||
const persistBoard = () => {
|
||||
page.local.gitBoard = {
|
||||
tab: board.tab,
|
||||
scroll: { ...board.scroll },
|
||||
repickAt: board.repickAt,
|
||||
query: board.query,
|
||||
showAll: board.showAll,
|
||||
remoteOpen: board.remoteOpen,
|
||||
panel: board.panel,
|
||||
create: board.create,
|
||||
ticks: board.ticks ? [...board.ticks] : null,
|
||||
sweep: board.sweep ? [...board.sweep] : null,
|
||||
base: board.base,
|
||||
ignore: [...board.ignore],
|
||||
};
|
||||
saveNow();
|
||||
};
|
||||
|
||||
// How busy the board is (busyMode in git-board.js). Running while a send is
|
||||
// uncollected or the agent is mid-turn, and nothing queues. A "working" agent
|
||||
// that has gone adrift lets go, as gitAwaiting() does: collecting a click
|
||||
// marks it working, and an agent that died there must not leave the board
|
||||
// locked for good. A question card of the agent's open in the card slot holds
|
||||
// the board too: the card is the turn, and a board click sent beside it went
|
||||
// alone while the staged answer waited for some later, unrelated send.
|
||||
const gitMode = () =>
|
||||
busyMode({
|
||||
gone: page.gone,
|
||||
pending: page.pendingResult,
|
||||
running: Boolean(finish()) || (agentWorking() && !agentAdrift()) || gitAwaiting(),
|
||||
cardWaiting: myTurn().some((i) => i.kind !== "notice"),
|
||||
});
|
||||
|
||||
const gitLocked = () => gitMode() !== "idle";
|
||||
|
||||
// `wording` only shapes the sentence (the operation an Abort names, say); it
|
||||
// is not part of the action.
|
||||
async function sendGit(op, fields = {}, wording = {}) {
|
||||
if (page.gone || finish()) return;
|
||||
if (page.pendingResult) {
|
||||
hooks.banner("Your last click is still being picked up. One moment.", "info");
|
||||
page.pendingBannerUp = true;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/submit", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
actions: [{ i: "__git", type: "git", op, ...fields }],
|
||||
reply: gitReply(op, { ...fields, ...wording }),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) {
|
||||
page.pendingResult = true;
|
||||
hooks.banner("Your last click is still being picked up. One moment.", "info");
|
||||
page.pendingBannerUp = true;
|
||||
redraw();
|
||||
return;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
board.settled.clear();
|
||||
board.panel = null;
|
||||
board.create = null;
|
||||
board.sweep = null;
|
||||
// The commit table is always on show: a click drops its picks, and the
|
||||
// redraw that follows re-seeds them from the snapshot the page already has.
|
||||
board.ticks = null;
|
||||
board.ignore = new Set();
|
||||
page.pendingResult = true;
|
||||
page.local.gitSentAt = Date.now();
|
||||
saveNow();
|
||||
// The draw after this persists it with the rest of the board.
|
||||
board.repickAt = page.local.gitSentAt;
|
||||
redraw();
|
||||
} catch {
|
||||
hooks.banner("That did not go through. Nothing was lost; try again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// What the view may ask of the page. Built once: every handler reads the
|
||||
// board and state.git at the moment of the click, not at the draw.
|
||||
const gitOn = {
|
||||
send: sendGit,
|
||||
redraw: () => redraw(),
|
||||
pickTab: (id) => {
|
||||
board.tab = id;
|
||||
persistBoard();
|
||||
redraw();
|
||||
},
|
||||
openPanel: (name, opts) => openPanel(name, opts),
|
||||
closePanel: () => closePanel(),
|
||||
pickPrHost: (host, kind) => pickPrHost(host, kind),
|
||||
persist: () => persistBoard(),
|
||||
};
|
||||
|
||||
// The tab drawn last, which the scroll listener files the column's place under.
|
||||
let gitTabDrawn = null;
|
||||
|
||||
// FR-9: their own click that landed (an agent post after it went out) and
|
||||
// arriving at the board go to the next step's tab; a reload and a change they
|
||||
// did not click for keep the tab they had. A frame with no updatedAt has not
|
||||
// landed: never re-pick on a guess.
|
||||
function resolveGitTab(step) {
|
||||
const before = board.tab;
|
||||
let reason = "background";
|
||||
if (board.repickAt && page.S.updatedAt && Date.parse(page.S.updatedAt) > board.repickAt) {
|
||||
reason = "landed";
|
||||
board.repickAt = null;
|
||||
} else if (board.tab == null) reason = "arrival";
|
||||
else if (boardReloaded) reason = "reload";
|
||||
boardReloaded = false;
|
||||
board.tab = pickTab({ current: board.tab, stepTab: step.tab, reason });
|
||||
if (board.tab !== before || reason === "landed") persistBoard();
|
||||
}
|
||||
|
||||
export function renderGitBoard(main, card = null, pager = null) {
|
||||
if (!boardHydrated) hydrateBoard();
|
||||
const git = page.S.git;
|
||||
const step = nextStep(git);
|
||||
resolveGitTab(step);
|
||||
const result = byId("git-result");
|
||||
const { node, cardSlot } = drawGitBoard({
|
||||
git,
|
||||
board,
|
||||
now: Date.now(),
|
||||
mode: gitMode(),
|
||||
offlineReason: page.gone ? "gone" : page.pendingResult ? "pending" : null,
|
||||
step,
|
||||
badges: tabBadges(git, { stepTab: step.tab }),
|
||||
notice: result && result.kind === "notice" ? result : null,
|
||||
activity: activity(),
|
||||
hasCard: Boolean(card),
|
||||
h: { el, md, copyButton },
|
||||
on: gitOn,
|
||||
});
|
||||
if (card) cardSlot.appendChild(card);
|
||||
if (pager) cardSlot.appendChild(pager);
|
||||
const tabs = node.querySelector(".git-tabs");
|
||||
if (tabs) tabs.addEventListener("keydown", gitTabKeys);
|
||||
// The column scrolls, not the board, and every redraw rebuilds the board,
|
||||
// so the column would land back at the top. Each tab keeps its own place,
|
||||
// so a tab switch opens where that tab was left.
|
||||
const tab = activeTab({ board, step });
|
||||
gitTabDrawn = tab;
|
||||
main.addEventListener("scroll", rememberGitTabScroll, { passive: true });
|
||||
main.appendChild(node);
|
||||
main.scrollTop = board.scroll[tab] || 0;
|
||||
persistBoard();
|
||||
}
|
||||
|
||||
// The scroll listener on `main` for each tab's place, kept as a named function
|
||||
// because renderGitBoard re-adds it on every redraw: adding the same listener
|
||||
// twice is a no-op, where a fresh closure would pile up.
|
||||
function rememberGitTabScroll() {
|
||||
const main = $("main");
|
||||
if (!gitTabDrawn || !main || !main.querySelector(":scope > .git-board")) return;
|
||||
board.scroll[gitTabDrawn] = main.scrollTop;
|
||||
}
|
||||
|
||||
// Arrow keys, Home and End move between the tabs, as in the Help dialog. The
|
||||
// board is redrawn, so focus goes to the new tab after the render.
|
||||
function gitTabKeys(e) {
|
||||
const index = GIT_TABS.findIndex((t) => t.id === gitTabDrawn);
|
||||
const to = helpKeyTarget(e.key, Math.max(0, index), GIT_TABS.length);
|
||||
if (to < 0) return;
|
||||
e.preventDefault();
|
||||
board.tab = GIT_TABS[to].id;
|
||||
persistBoard();
|
||||
redraw();
|
||||
$(`git-tab-${board.tab}`)?.focus();
|
||||
}
|
||||
|
||||
// The host is remembered for every project by the server (pr-hosts.json);
|
||||
// the action that follows has the agent re-read, which rebuilds the link.
|
||||
async function pickPrHost(host, kind) {
|
||||
if (gitLocked()) return;
|
||||
const res = await postJson("/pr-host", { host, kind });
|
||||
if (res.status !== 200) {
|
||||
hooks.banner("That could not be saved. Try again in a moment.", "warn");
|
||||
return;
|
||||
}
|
||||
// The save is durable; a state frame that landed mid-POST still wins.
|
||||
if (gitLocked()) return;
|
||||
sendGit("pr-host", { host, kind });
|
||||
}
|
||||
|
||||
// Opening a panel moves to the tab that draws it, so a panel is never open
|
||||
// on a hidden tab. `opts.ticks` / `opts.ignore` set the commit panel's picks
|
||||
// (the held-back .gitignore offer opens it with nothing ticked).
|
||||
function openPanel(name, opts = {}) {
|
||||
if (gitLocked()) return;
|
||||
const git = page.S.git;
|
||||
if (name === "commit") {
|
||||
board.tab = "changes";
|
||||
if (opts.ticks) board.ticks = new Set(opts.ticks);
|
||||
if (opts.ignore) board.ignore = new Set(opts.ignore);
|
||||
if (board.panel !== "commit") return openCommit(git);
|
||||
persistBoard();
|
||||
return redraw();
|
||||
}
|
||||
if (name === "create") {
|
||||
board.tab = opts.commit ? "changes" : "branches";
|
||||
// A branch for the commit takes what the commit table has ticked, not a fresh default.
|
||||
if (opts.commit && !opts.files) return openCreate(git, { ...opts, ...tablePicks(git) });
|
||||
return openCreate(git, opts);
|
||||
}
|
||||
if (name === "cleanup") {
|
||||
board.tab = "branches";
|
||||
return openCleanup(git);
|
||||
}
|
||||
}
|
||||
|
||||
const closePanel = () => {
|
||||
board.panel = null;
|
||||
board.create = null;
|
||||
redraw();
|
||||
};
|
||||
|
||||
// In commit mode the commit panel hands over what it would have sent (its
|
||||
// ticked files and .gitignore picks, already checked against the snapshot);
|
||||
// a detached commit, which never shows the panel, starts from commitTicks().
|
||||
function openCreate(git, { commit = false, files = null, ignore = [] } = {}) {
|
||||
if (gitLocked()) return;
|
||||
// The agent's description is of the changes waiting: with none left (they
|
||||
// were committed since), it describes nothing on this tree.
|
||||
const pending = Number(page.S.git && page.S.git.changes && page.S.git.changes.count) || 0;
|
||||
const describe = pending && page.S.board && typeof page.S.board.describe === "string" ? page.S.board.describe : "";
|
||||
board.create = {
|
||||
from: createSources(git, commit).preset,
|
||||
type: BRANCH_TYPES[0],
|
||||
description: describe,
|
||||
name: null,
|
||||
commit,
|
||||
files: commit ? files || [...commitTicks(git.changes)] : null,
|
||||
ignore: commit ? ignore : [],
|
||||
};
|
||||
board.panel = "create";
|
||||
redraw();
|
||||
$("git-new-desc")?.focus();
|
||||
}
|
||||
|
||||
// The commit table's picks, checked against the snapshot: `{ files, ignore }`.
|
||||
// Seeded from commitTicks() when the table has not been drawn yet.
|
||||
function tablePicks(git) {
|
||||
const ch = git.changes || {};
|
||||
const known = new Set([...(ch.files || []), ...(ch.untrackedDirs || [])].map((f) => f.path));
|
||||
const ticks = board.ticks || (board.ticks = commitTicks(ch));
|
||||
return { files: [...ticks].filter((p) => known.has(p)), ignore: [...board.ignore].filter((p) => known.has(p)) };
|
||||
}
|
||||
|
||||
// The commit table is always on show, so opening its panel keeps what the
|
||||
// person has already ticked; sendGit() re-seeds the picks after each click.
|
||||
function openCommit(git) {
|
||||
if (gitLocked()) return;
|
||||
if (board.panel === "commit") return closePanel();
|
||||
const picks = tablePicks(git);
|
||||
// Detached: there is no branch to commit on, so the commit makes one.
|
||||
if (git.hasCommits !== false && !(git.head || {}).branch) return openCreate(git, { commit: true, ...picks });
|
||||
board.panel = "commit";
|
||||
board.create = null;
|
||||
redraw();
|
||||
}
|
||||
|
||||
function openCleanup(git) {
|
||||
if (gitLocked()) return;
|
||||
if (board.panel === "cleanup") return closePanel();
|
||||
const { merged, gone } = cleanupGroups(git);
|
||||
board.sweep = new Set([...merged, ...gone].map((b) => b.name));
|
||||
board.panel = "cleanup";
|
||||
board.create = null;
|
||||
redraw();
|
||||
}
|
||||
@@ -0,0 +1,217 @@
|
||||
// Plan2Code Web Console - the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js).
|
||||
|
||||
import { looksReady, looks, saveLooks } from "../looks.js";
|
||||
import { page } from "../state.js";
|
||||
import { isDashboard, finish, agentAdrift } from "../selectors.js";
|
||||
import { releasesLink, el, copyButton, lightDismiss } from "../render.js";
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// The first dashboard a person ever sees gets a Welcome dialog. Closing it by
|
||||
// any route (button, Esc, backdrop) saves looks.welcomeSeen, which rides in
|
||||
// looks.json like every other preference. Waits out the wake-up animation and
|
||||
// never lands on top of another open dialog.
|
||||
export function maybeWelcome() {
|
||||
if (!looksReady || looks.welcomeSeen === true || !page.S || !isDashboard() || finish() || page.wake) return;
|
||||
if (document.querySelector("dialog[open]")) return;
|
||||
openWelcome();
|
||||
}
|
||||
|
||||
export function openWelcome() {
|
||||
if ($("help-modal").open) $("help-modal").close();
|
||||
const slot = $("welcome-bot");
|
||||
if (!slot.firstElementChild) {
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", "planny is-point v1");
|
||||
slot.appendChild(bot);
|
||||
}
|
||||
const dlg = $("welcome-modal");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
$("welcome-done").focus();
|
||||
}
|
||||
|
||||
// Whether the two halves are actually talking, in the one place someone goes
|
||||
// when they are asking that question. Written on open rather than kept live,
|
||||
// because a line that rewrites itself under a reader is worse than a stale one
|
||||
// they can close and reopen.
|
||||
function renderAbout() {
|
||||
const line = $("about-live");
|
||||
line.className = "about-live";
|
||||
if (finish()) {
|
||||
line.textContent = "Right now: the session is finished, and the command above is all that is left to do.";
|
||||
} else if (page.gone) {
|
||||
line.classList.add("is-bad");
|
||||
line.textContent =
|
||||
"Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The link from the terminal will bring it back.";
|
||||
} else if (agentAdrift()) {
|
||||
line.classList.add("is-bad");
|
||||
line.textContent =
|
||||
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
|
||||
} else {
|
||||
line.classList.add("is-good");
|
||||
line.textContent = "Right now: both halves are talking to each other.";
|
||||
}
|
||||
}
|
||||
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
const HELP_MOODS = [
|
||||
["point", "Your turn"],
|
||||
["work", "Working"],
|
||||
["happy", "All caught up"],
|
||||
["done", "Done"],
|
||||
["adrift", "Not running"],
|
||||
["gone", "Not connected"],
|
||||
];
|
||||
|
||||
// The help content waits in its <template> until the first time ? is pressed,
|
||||
// so none of it costs the first paint. The tab buttons come from HELP_TABS.
|
||||
function buildHelp() {
|
||||
const content = $("help-content").content.cloneNode(true);
|
||||
const modal = $("help-modal");
|
||||
const tabs = $("help-tabs");
|
||||
const panels = $("help-panels");
|
||||
// In the dialog itself, so every <use href="#hi-..."> resolves.
|
||||
modal.appendChild(content.querySelector(".help-icons"));
|
||||
for (const panel of content.querySelectorAll("section.help-panel")) panels.appendChild(panel);
|
||||
// Tab 3 shows the real Planny in each mood, cloned the way the dashboard's
|
||||
// confirm pane does, so the moods can never drift from the drawing.
|
||||
const moods = panels.querySelector(".help-moods-row");
|
||||
for (const [mood, label] of HELP_MOODS) {
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", `planny is-${mood} v0 help-mood-bot`);
|
||||
bot.setAttribute("aria-hidden", "true");
|
||||
const cell = el("div", "help-mood");
|
||||
cell.appendChild(bot);
|
||||
cell.appendChild(el("span", null, label));
|
||||
moods.appendChild(cell);
|
||||
}
|
||||
for (const row of panels.querySelectorAll("[data-copy]")) {
|
||||
const code = row.querySelector("code");
|
||||
row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code));
|
||||
}
|
||||
for (const t of HELP_TABS) {
|
||||
const btn = el("button", "help-tab");
|
||||
btn.type = "button";
|
||||
btn.id = "help-tab-" + t.id;
|
||||
btn.setAttribute("role", "tab");
|
||||
btn.setAttribute("aria-controls", "help-panel-" + t.id);
|
||||
btn.setAttribute("aria-selected", "false");
|
||||
btn.tabIndex = -1;
|
||||
const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
|
||||
svg.setAttribute("class", "help-tab-icon");
|
||||
svg.setAttribute("aria-hidden", "true");
|
||||
const use = document.createElementNS("http://www.w3.org/2000/svg", "use");
|
||||
use.setAttribute("href", "#hi-" + t.id);
|
||||
svg.appendChild(use);
|
||||
btn.appendChild(svg);
|
||||
btn.appendChild(el("span", null, t.label));
|
||||
btn.addEventListener("click", () => selectHelpTab(t.id));
|
||||
tabs.appendChild(btn);
|
||||
const panel = panels.querySelector(`section.help-panel[data-tab="${t.id}"]`);
|
||||
panel.id = "help-panel-" + t.id;
|
||||
panel.setAttribute("role", "tabpanel");
|
||||
panel.setAttribute("aria-labelledby", "help-tab-" + t.id);
|
||||
panel.tabIndex = 0;
|
||||
panel.hidden = true;
|
||||
}
|
||||
helpBuilt = true;
|
||||
}
|
||||
|
||||
export function selectHelpTab(id) {
|
||||
for (const t of HELP_TABS) {
|
||||
const on = t.id === id;
|
||||
const btn = $("help-tab-" + t.id);
|
||||
btn.setAttribute("aria-selected", String(on));
|
||||
btn.tabIndex = on ? 0 : -1;
|
||||
$("help-panel-" + t.id).hidden = !on;
|
||||
}
|
||||
$("help-panels").scrollTop = 0;
|
||||
}
|
||||
|
||||
export function openHelp() {
|
||||
if (!helpBuilt) buildHelp();
|
||||
const id = helpTabFor({
|
||||
view: page.view,
|
||||
dashboard: isDashboard(),
|
||||
gone: page.gone,
|
||||
adrift: agentAdrift(),
|
||||
finished: !!finish(),
|
||||
workflow: page.S && page.S.workflow,
|
||||
workspace: $("workspace-modal").open,
|
||||
meterRed: page.meterFrame?.level === "red",
|
||||
});
|
||||
selectHelpTab(id);
|
||||
renderAbout();
|
||||
renderHelpVersion();
|
||||
$("help-modal").showModal();
|
||||
$("help-tab-" + id).focus();
|
||||
}
|
||||
|
||||
// Help opened straight on one topic, when Help has that topic; otherwise it
|
||||
// stays wherever openHelp() landed.
|
||||
export function openHelpOn(id) {
|
||||
openHelp();
|
||||
if (!HELP_TABS.some((t) => t.id === id)) return;
|
||||
selectHelpTab(id);
|
||||
$("help-tab-" + id).focus();
|
||||
}
|
||||
|
||||
// Help's and Welcome's buttons and keys, and the Workspace dialog's link to Help.
|
||||
export function wireHelp() {
|
||||
$("workspace-help").addEventListener("click", openHelp);
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
|
||||
$("welcome-done").addEventListener("click", () => $("welcome-modal").close());
|
||||
$("welcome-modal").addEventListener("close", () => {
|
||||
if (looks.welcomeSeen !== true) {
|
||||
looks.welcomeSeen = true;
|
||||
saveLooks();
|
||||
}
|
||||
$("btn-about").focus();
|
||||
});
|
||||
$("help-panels").addEventListener("click", (e) => {
|
||||
if (e.target.closest && e.target.closest('[data-action="welcome"]')) openWelcome();
|
||||
});
|
||||
|
||||
$("btn-about").addEventListener("click", () => {
|
||||
openHelp();
|
||||
});
|
||||
$("help-done").addEventListener("click", () => $("help-modal").close());
|
||||
// Opened from inside the Workspace dialog, focus goes back there.
|
||||
$("help-modal").addEventListener("close", () =>
|
||||
($("workspace-modal").open ? $("workspace-help") : $("btn-about")).focus()
|
||||
);
|
||||
$("help-modal").addEventListener("keydown", (e) => {
|
||||
// The page-wide Ctrl/Cmd+Enter already stands down while any dialog is open;
|
||||
// this keeps the key inside Help as well.
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
return;
|
||||
}
|
||||
if (!e.target.classList || !e.target.classList.contains("help-tab")) return;
|
||||
const current = HELP_TABS.findIndex((t) => "help-tab-" + t.id === e.target.id);
|
||||
const n = helpKeyTarget(e.key, current, HELP_TABS.length);
|
||||
if (n < 0) return;
|
||||
e.preventDefault();
|
||||
selectHelpTab(HELP_TABS[n].id);
|
||||
$("help-tab-" + HELP_TABS[n].id).focus();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
// Plan2Code Web Console - User Preferences: looks, sounds and the launcher's model menus.
|
||||
|
||||
import { adoptLooks, applyLooks, loadLooks, looks, renderSwatches, resetLooks, saveLooks, syncLooks } from "../looks.js";
|
||||
import { dropHeldSound, releaseHeldSound, sound, soundOn } from "../sound.js";
|
||||
import { SOUND_EVENTS, soundKey } from "../palette.js";
|
||||
import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, needsRoleNudge, normalizeRole } from "../starters.js";
|
||||
import { isDashboard } from "../selectors.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { page, redraw } from "../state.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
function setModelsStatus(text, isError) {
|
||||
const status = $("models-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
// Models: the launcher's menu. The built-in list ships with every install and is read-only
|
||||
// here; what the person adds is saved to the server, which the launcher reads on its next run.
|
||||
let modelsData = null;
|
||||
|
||||
// The CLIs the launcher reads a model list for, in tab order (routes.mjs MODEL_CLIS).
|
||||
const MODEL_CLIS = ["claude", "devin", "codex"];
|
||||
|
||||
let modelsTab = "claude";
|
||||
|
||||
function renderModels() {
|
||||
for (const cli of MODEL_CLIS) {
|
||||
$("models-tab-" + cli).setAttribute("aria-pressed", String(cli === modelsTab));
|
||||
}
|
||||
const shipped = $("models-shipped");
|
||||
const user = $("models-user");
|
||||
shipped.replaceChildren();
|
||||
user.replaceChildren();
|
||||
if (!modelsData) {
|
||||
setModelsStatus("Models could not be loaded.", true);
|
||||
return;
|
||||
}
|
||||
for (const m of modelsData.shipped[modelsTab] || []) {
|
||||
const row = el("div", "models-row locked");
|
||||
row.append(el("span", null, m.id), el("span", null, m.label || ""));
|
||||
shipped.appendChild(row);
|
||||
}
|
||||
const mine = modelsData.user[modelsTab];
|
||||
mine.forEach((m, i) => {
|
||||
const row = el("div", "models-row");
|
||||
const id = el("input");
|
||||
id.value = m.id;
|
||||
id.placeholder = "Model id";
|
||||
id.setAttribute("aria-label", "Model id");
|
||||
const label = el("input");
|
||||
label.value = m.label;
|
||||
label.placeholder = "Name shown in the menu";
|
||||
label.setAttribute("aria-label", "Name shown in the menu");
|
||||
const remove = el("button", "btn small ghost", "Remove");
|
||||
remove.type = "button";
|
||||
id.addEventListener("change", () => { m.id = id.value.trim(); saveModels(); });
|
||||
label.addEventListener("change", () => { m.label = label.value.trim(); saveModels(); });
|
||||
remove.addEventListener("click", () => {
|
||||
mine.splice(i, 1);
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
row.append(id, label, remove);
|
||||
user.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
async function saveModels() {
|
||||
try {
|
||||
const res = await fetch("/models", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ models: modelsData.user }),
|
||||
});
|
||||
const body = await res.json();
|
||||
if (!res.ok) return setModelsStatus(body.error || "Could not save.", true);
|
||||
setModelsStatus("Saved. Restart plan2code to use it.", false);
|
||||
} catch {
|
||||
setModelsStatus("Could not save.", true);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadModelsData() {
|
||||
try {
|
||||
const res = await fetch("/models");
|
||||
if (res.ok) modelsData = await res.json();
|
||||
} catch {}
|
||||
renderModels();
|
||||
}
|
||||
|
||||
// Following the system, the saved looks painted before anything is drawn, and
|
||||
// the sound cues let go on the next touch. `boot` is the page's boot data.
|
||||
export function startLooks(boot) {
|
||||
// Following the system means following it as it changes, including the accent,
|
||||
// whose light and dark shades are different colors.
|
||||
matchMedia("(prefers-color-scheme: dark)").addEventListener("change", () => {
|
||||
if (looks.theme === "system") {
|
||||
applyLooks();
|
||||
renderSwatches();
|
||||
}
|
||||
});
|
||||
|
||||
loadLooks();
|
||||
if (boot && boot.looks && typeof boot.looks === "object") adoptLooks(boot.looks);
|
||||
applyLooks();
|
||||
syncLooks();
|
||||
|
||||
for (const evt of ["pointerdown", "keydown"]) {
|
||||
window.addEventListener(evt, releaseHeldSound);
|
||||
}
|
||||
}
|
||||
|
||||
// Preferences' buttons and fields.
|
||||
export function wireLooks() {
|
||||
lightDismiss($("looks-modal"));
|
||||
$("btn-looks").addEventListener("click", () => {
|
||||
renderSwatches();
|
||||
setModelsStatus("", false);
|
||||
loadModelsData();
|
||||
$("looks-modal").showModal();
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) redraw();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
resetLooks();
|
||||
saveLooks();
|
||||
redraw();
|
||||
});
|
||||
for (const [value, label] of [[ROLE_NOT_SET, ROLE_NOT_SET_LABEL], ...ROLES.map((r) => [r.id, r.label])]) {
|
||||
const option = el("option", null, label);
|
||||
option.value = value;
|
||||
$("looks-role").appendChild(option);
|
||||
}
|
||||
$("looks-role").addEventListener("change", (e) => {
|
||||
looks.role = normalizeRole(e.target.value);
|
||||
saveLooks();
|
||||
// The dashboard banner, and the starter templates and Ask starters on any
|
||||
// page, all order themselves by the role.
|
||||
if (page.S) redraw();
|
||||
});
|
||||
for (const radio of document.querySelectorAll('input[name="looks-theme"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.theme = radio.value;
|
||||
saveLooks();
|
||||
});
|
||||
}
|
||||
for (const radio of document.querySelectorAll('input[name="looks-width"]')) {
|
||||
radio.addEventListener("change", () => {
|
||||
looks.width = radio.value;
|
||||
saveLooks();
|
||||
});
|
||||
}
|
||||
$("looks-sound").addEventListener("change", (e) => {
|
||||
looks.sound = e.target.checked;
|
||||
// Held cues are moments, not mail: muted, they are dropped rather than
|
||||
// saved up to fire all at once the next time sound comes back on.
|
||||
if (!looks.sound) dropHeldSound();
|
||||
saveLooks();
|
||||
// Turning them on is the one change you can hear: the question chime, or
|
||||
// the first cue still ticked when that one is not.
|
||||
const preview = ["question", ...Object.keys(SOUND_EVENTS)].find(soundOn);
|
||||
if (preview) sound(preview);
|
||||
});
|
||||
for (const box of document.querySelectorAll("input[data-sound]")) {
|
||||
box.addEventListener("change", () => {
|
||||
const event = box.dataset.sound;
|
||||
looks[soundKey(event)] = box.checked;
|
||||
if (!box.checked) dropHeldSound(event);
|
||||
saveLooks();
|
||||
// Ticking one plays it, so the label has a sound to go with it.
|
||||
if (box.checked) sound(event);
|
||||
});
|
||||
}
|
||||
|
||||
for (const cli of MODEL_CLIS) {
|
||||
$("models-tab-" + cli).addEventListener("click", () => {
|
||||
modelsTab = cli;
|
||||
renderModels();
|
||||
});
|
||||
}
|
||||
$("models-add").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user[modelsTab].push({ id: "", label: "" });
|
||||
renderModels();
|
||||
$("models-user").querySelector(".models-row:last-child input")?.focus();
|
||||
});
|
||||
$("models-reset").addEventListener("click", () => {
|
||||
if (!modelsData) return;
|
||||
modelsData.user = Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
|
||||
saveModels();
|
||||
renderModels();
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
// Plan2Code Web Console - the launching, starting and waiting screens, with Planny's poses; defines only.
|
||||
|
||||
import { page, redraw } from "../state.js";
|
||||
import { el, approvalTip } from "../render.js";
|
||||
import { startPose, startingHint, SKILL_CATALOG, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { agentAdrift, doingNow, docs } from "../selectors.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const LAUNCH_QUIPS = [
|
||||
"Passing Planny the baton…",
|
||||
"Reading the manual…",
|
||||
"Polishing the star…",
|
||||
"Warming up the engines…",
|
||||
"Laying out the good pens…",
|
||||
"Consulting the map…",
|
||||
"Putting the kettle on…",
|
||||
"Rolling out the checklist…",
|
||||
];
|
||||
|
||||
let launchTicker = null;
|
||||
|
||||
// Planny flies centre stage: the same drawing as the dock's, cloned so the
|
||||
// markup stays the single source of him, and the same sky the dock fills.
|
||||
function flightStage() {
|
||||
const stage = el("div", "launch-stage");
|
||||
const sky = el("div", "sky launch-sky");
|
||||
const r = (a, b) => a + Math.random() * (b - a);
|
||||
for (let i = 0; i < 30; i++) {
|
||||
const star = el("i", "star" + (i % 6 === 0 ? " hot" : ""));
|
||||
const dur = r(3, 9);
|
||||
star.style.setProperty("--y", r(2, 98).toFixed(1) + "%");
|
||||
star.style.setProperty("--p", r(0, 1).toFixed(3));
|
||||
star.style.setProperty("--s", r(1.2, 2.6).toFixed(2) + "px");
|
||||
star.style.setProperty("--dur", dur.toFixed(2) + "s");
|
||||
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
|
||||
sky.appendChild(star);
|
||||
}
|
||||
stage.appendChild(sky);
|
||||
const bot = $("planny").cloneNode(true);
|
||||
bot.removeAttribute("id");
|
||||
bot.setAttribute("class", "planny is-work v1 launch-planny");
|
||||
stage.appendChild(bot);
|
||||
return stage;
|
||||
}
|
||||
|
||||
// A skill's own Planny, acting out the skill while it starts and works: the
|
||||
// pose is cloned from its <template> in index.html, so the drawing stays
|
||||
// markup and the motion stays in app.css. A skill with none keeps the flight.
|
||||
function startStage(workflow) {
|
||||
const pose = startPose(workflow);
|
||||
const art = pose && $("start-poses")?.content.querySelector(`[data-pose="${pose}"]`);
|
||||
if (!art) return flightStage();
|
||||
const stage = el("div", "launch-stage pose-stage");
|
||||
stage.appendChild(art.cloneNode(true));
|
||||
return stage;
|
||||
}
|
||||
|
||||
// The pane Planny's stage sits in, for the launching, starting and waiting
|
||||
// screens alike. A render empties the column, and a stage taken off the page
|
||||
// restarts every animation in it, which a build posting every few seconds
|
||||
// (and the heartbeat pulling what it missed) would turn into a stutter. So
|
||||
// the pane already on screen is reused when the next screen shows the same
|
||||
// pose: its words are rebuilt around a stage that never leaves the page.
|
||||
// That is also what carries him from "Starting…" into the work unbroken.
|
||||
function posePane(main, cls, workflow) {
|
||||
const pose = startPose(workflow) || "flight";
|
||||
const held = page.heldPose;
|
||||
page.heldPose = null;
|
||||
if (held && held.dataset.pose === pose) {
|
||||
held.className = cls;
|
||||
for (const child of [...held.children]) if (!child.classList.contains("launch-stage")) child.remove();
|
||||
return held;
|
||||
}
|
||||
const pane = el("div", cls);
|
||||
pane.dataset.pose = pose;
|
||||
pane.appendChild(startStage(workflow));
|
||||
if (held) main.insertBefore(pane, held);
|
||||
else main.appendChild(pane);
|
||||
return pane;
|
||||
}
|
||||
|
||||
// The getting-ready screen. The pick is sent and the dashboard agent is
|
||||
// turning it into a live skill: it resumes this session under the skill's
|
||||
// workflow, which flips `S.workflow` off "dashboard" and ends this screen
|
||||
// (adopt() clears `local.launching` on exactly that change).
|
||||
//
|
||||
// It is deliberately fun rather than a spinner with a shrug: a launch takes
|
||||
// a few honest seconds (the skill file is read, the session resumed, the
|
||||
// first payload composed) and a dead-quiet wait is when people wonder
|
||||
// whether the click worked. Planny flies, the quips rotate, and after a
|
||||
// while the hint points at the terminal, which narrates the same hand-off.
|
||||
export function renderLaunching(main) {
|
||||
const l = page.local.launching || {};
|
||||
const pane = posePane(main, "launching", l.skill && SKILL_CATALOG.find((e) => e.skill === l.skill)?.workflow);
|
||||
|
||||
const stale = staleLaunchFeedback(l.title, agentAdrift());
|
||||
pane.appendChild(el("p", "card-kicker", stale ? stale.kicker : "On it"));
|
||||
pane.appendChild(el("h2", "launch-title", stale ? stale.title : `Waking up ${l.title || "the next mode"}`));
|
||||
pane.appendChild(el("p", "launch-quip", stale ? stale.quip : LAUNCH_QUIPS[0]));
|
||||
pane.appendChild(
|
||||
el(
|
||||
"p",
|
||||
"launch-hint",
|
||||
stale ? stale.hint : "This page turns into its home the moment it answers. No need to touch anything."
|
||||
)
|
||||
);
|
||||
startLaunchTicker();
|
||||
}
|
||||
|
||||
/* The starting screen: a session is open but the agent has not put anything
|
||||
on it yet. It is what the person looks at while the skill reads the
|
||||
project, finds its files and composes the first questions, so it gets the
|
||||
same flight as a launch rather than a bare spinner, and says which skill
|
||||
is on its way. */
|
||||
const START_QUIPS = [
|
||||
"Reading the project…",
|
||||
"Checking what is already written down…",
|
||||
"Lining up the first questions…",
|
||||
"Polishing the star…",
|
||||
"Laying out the good pens…",
|
||||
"Consulting the map…",
|
||||
];
|
||||
|
||||
function startingElapsed() {
|
||||
const since = page.S && page.S.agent ? Date.parse(page.S.agent.since) : NaN;
|
||||
return Number.isFinite(since) ? Date.now() - since : 0;
|
||||
}
|
||||
|
||||
function renderStarting(main) {
|
||||
const elapsed = startingElapsed();
|
||||
const pane = posePane(main, "launching starting", page.S.workflow);
|
||||
pane.appendChild(el("p", "card-kicker", "Starting up"));
|
||||
pane.appendChild(el("h2", "launch-title", `Starting ${workflowTitle(page.S.workflow)}`));
|
||||
pane.appendChild(el("p", "launch-quip", START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length]));
|
||||
pane.appendChild(el("p", "launch-hint", startingHint(elapsed)));
|
||||
pane.appendChild(approvalTip());
|
||||
startLaunchTicker();
|
||||
}
|
||||
|
||||
// The quips rotate on their own clock rather than on render: state frames
|
||||
// arrive whenever the agent posts, and a waiting screen pinned to them
|
||||
// would sit on one line for most of the wait. The interval looks the
|
||||
// elements up fresh each tick, so it survives the screen being rebuilt,
|
||||
// and it stops itself when neither screen is up any more.
|
||||
function startLaunchTicker() {
|
||||
if (!launchTicker) {
|
||||
launchTicker = setInterval(() => {
|
||||
const kicker = document.querySelector(".launching .card-kicker");
|
||||
const title = document.querySelector(".launch-title");
|
||||
const q = document.querySelector(".launch-quip");
|
||||
const hint = document.querySelector(".launch-hint");
|
||||
const cur = page.local.launching;
|
||||
const starting = !cur && document.querySelector(".launching.starting");
|
||||
if ((!cur && !starting) || !q) {
|
||||
clearInterval(launchTicker);
|
||||
launchTicker = null;
|
||||
return;
|
||||
}
|
||||
if (starting) {
|
||||
const elapsed = startingElapsed();
|
||||
q.textContent = START_QUIPS[Math.floor(elapsed / 2600) % START_QUIPS.length];
|
||||
if (hint) hint.textContent = startingHint(elapsed);
|
||||
return;
|
||||
}
|
||||
const elapsed = Date.now() - cur.at;
|
||||
const stale = staleLaunchFeedback(cur.title, agentAdrift());
|
||||
if (kicker) kicker.textContent = stale ? stale.kicker : "On it";
|
||||
if (title) title.textContent = stale ? stale.title : `Waking up ${cur.title || "the next mode"}`;
|
||||
q.textContent = stale ? stale.quip : LAUNCH_QUIPS[Math.floor(elapsed / 2600) % LAUNCH_QUIPS.length];
|
||||
if (hint) {
|
||||
hint.textContent = stale
|
||||
? stale.hint
|
||||
: elapsed > 90000
|
||||
? "Still getting ready. Your terminal has the play-by-play if you want to watch it there."
|
||||
: "This page turns into its home the moment it answers. No need to touch anything.";
|
||||
}
|
||||
}, 900);
|
||||
}
|
||||
}
|
||||
|
||||
export function renderWaiting(main) {
|
||||
const doing = doingNow();
|
||||
// Nothing asked and nothing said yet: the session is still starting.
|
||||
if (!doing) return renderStarting(main);
|
||||
// The same Planny the session started with, still at it: the spinner that
|
||||
// stood here said less about what was going on than he does.
|
||||
const pane = posePane(main, "waiting-pane", page.S.workflow);
|
||||
// A build with nothing to ask yet. Say what is happening and where to
|
||||
// watch it, instead of promising questions that may not come for a while.
|
||||
const title = el("h2", null, (page.S.headline && page.S.headline.stage) || "Working on it");
|
||||
// Once the agent stops answering nothing is turning, so neither is the ring
|
||||
// (the adrift watcher redraws this pane on the flip).
|
||||
if (!agentAdrift()) {
|
||||
const spin = el("span", "spinner tiny waiting-spin");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
title.prepend(spin);
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"); a quick task ticks the steps of its `plan` in place (an older
|
||||
// agent may still post a separate `tasks` tab). A skill with no task list
|
||||
// (Document, Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
(page.S.workflow === "quick-task" && docs().find((d) => d.id === "plan")) ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
page.view = "doc:" + list.id;
|
||||
redraw();
|
||||
});
|
||||
return b;
|
||||
};
|
||||
const p = el("p");
|
||||
p.append(
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
|
||||
// The stars for Planny's flight, made once. Each gets its place and pace as
|
||||
// custom properties set through the CSSOM: the CSP forbids style attributes
|
||||
// in markup, and the stylesheet cannot roll dice. They sit still, invisible,
|
||||
// until the dock is `is-flying`.
|
||||
export function fillSky() {
|
||||
const sky = $("dock-sky");
|
||||
const r = (a, b) => a + Math.random() * (b - a);
|
||||
for (let i = 0; i < 34; i++) {
|
||||
const star = document.createElement("i");
|
||||
star.className = "star" + (i % 7 === 0 ? " hot" : "");
|
||||
const dur = r(4, 12);
|
||||
star.style.setProperty("--y", r(3, 97).toFixed(1) + "%");
|
||||
star.style.setProperty("--p", r(0, 1).toFixed(3));
|
||||
star.style.setProperty("--s", r(1, 2.2).toFixed(2) + "px");
|
||||
star.style.setProperty("--dur", dur.toFixed(2) + "s");
|
||||
// Negative, so the field starts full rather than every star at the edge.
|
||||
star.style.setProperty("--delay", (-r(0, dur)).toFixed(2) + "s");
|
||||
sky.appendChild(star);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
// Plan2Code Web Console - the read-only Workspace of extra folders, and @mentions.
|
||||
|
||||
import { hooks, page } from "../state.js";
|
||||
import { copyButton, el, lightDismiss, selectContents } from "../render.js";
|
||||
import { selSpec, specList, workspaceFolders } from "../selectors.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { nameProblem } from "../workspace.js";
|
||||
|
||||
// The Workspace dialog. The server is the only writer of workspace.json: the
|
||||
// page asks through /workspace/*, and the new list comes back on the next
|
||||
// frame, which redraws the dialog while it is open.
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
// Folders the agent reported it cannot read, each told once per page load
|
||||
// and launch. The server keeps only the current launch's reports, so a name
|
||||
// that drops out of the list may be told again after the next launch.
|
||||
const issuesTold = new Set();
|
||||
|
||||
let issueBannerTimer = null;
|
||||
|
||||
export function tellFolderIssues() {
|
||||
const issues = (page.wsFrame && page.wsFrame.issues) || [];
|
||||
const names = new Set(issues.map((i) => i.name));
|
||||
for (const name of [...issuesTold]) if (!names.has(name)) issuesTold.delete(name);
|
||||
const fresh = issues.find((i) => !issuesTold.has(i.name));
|
||||
if (!fresh) return;
|
||||
issuesTold.add(fresh.name);
|
||||
const extras = [];
|
||||
if (fresh.hint) {
|
||||
extras.push(document.createTextNode(" "));
|
||||
extras.push(el("code", "banner-hint", fresh.hint));
|
||||
}
|
||||
const open = el("button", "btn tiny banner-action", "Open workspace");
|
||||
open.type = "button";
|
||||
open.addEventListener("click", () => {
|
||||
hooks.banner(null);
|
||||
openWorkspace();
|
||||
});
|
||||
extras.push(open);
|
||||
hooks.banner(`The agent can't read @${fresh.name}: ${fresh.reason}`, "warn", extras);
|
||||
clearTimeout(issueBannerTimer);
|
||||
// Then the next folder waiting to be told, if several came at once.
|
||||
issueBannerTimer = setTimeout(() => {
|
||||
if (page.gone) return;
|
||||
hooks.banner(null);
|
||||
tellFolderIssues();
|
||||
}, 15000);
|
||||
}
|
||||
|
||||
export async function syncWorkspaceScope(spec) {
|
||||
if (!page.S || page.S.workflow !== "dashboard" || page.gone || !page.wsFrame) return;
|
||||
const want = spec === undefined ? (selSpec() && selSpec().dir) || "" : spec;
|
||||
page.scopeMine = want;
|
||||
if ((page.wsFrame.scope || "") === want || scopeAsked === want) return;
|
||||
scopeAsked = want;
|
||||
const { status, body } = await postJson("/workspace/scope", { spec: want });
|
||||
if (status === 200 && body && Array.isArray(body.folders)) page.wsFrame = { ...page.wsFrame, ...body };
|
||||
scopeAsked = null;
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
}
|
||||
|
||||
let scopeAsked = null;
|
||||
|
||||
// The dialog's "Remembered for" line: whose list this is.
|
||||
function workspaceScopeText() {
|
||||
const scope = (page.wsFrame && page.wsFrame.scope) || "";
|
||||
if (!scope) return "Remembered for this project, so your next console session here starts with these folders.";
|
||||
const spec = specList().find((s) => s.dir === scope);
|
||||
const name = spec ? spec.name : scope.split("/").pop();
|
||||
return `Remembered for the ${name} spec, and loaded again whenever it is picked.`;
|
||||
}
|
||||
|
||||
const NAME_RULE = "Names use lowercase letters, numbers and hyphens.";
|
||||
|
||||
const BROWSE_UNAVAILABLE = "Browse isn't available here — type or paste the path.";
|
||||
|
||||
// The folder whose Remove is waiting on its inline confirm, by id.
|
||||
let wsConfirm = null;
|
||||
|
||||
let wsBusy = false;
|
||||
|
||||
export async function openWorkspace() {
|
||||
const dlg = $("workspace-modal");
|
||||
try {
|
||||
const res = await fetch("/workspace?check=1", { cache: "no-store" });
|
||||
if (res.ok) page.wsFrame = await res.json();
|
||||
} catch {}
|
||||
wsConfirm = null;
|
||||
setAddMsg("");
|
||||
renderWorkspace();
|
||||
if (!dlg.open) dlg.showModal();
|
||||
$("workspace-path").focus();
|
||||
}
|
||||
|
||||
function setAddMsg(text, kind, action) {
|
||||
const p = $("workspace-add-msg");
|
||||
p.className = "workspace-add-msg" + (kind ? " is-" + kind : "");
|
||||
p.textContent = text;
|
||||
if (action) p.appendChild(action);
|
||||
}
|
||||
|
||||
// One <li> per folder, original first. A frame that keeps the same folders in
|
||||
// the same order is painted into the rows already there, so a box someone is
|
||||
// typing in keeps its text, caret and focus; any other change rebuilds.
|
||||
export function renderWorkspace() {
|
||||
const list = $("workspace-list");
|
||||
const folders = workspaceFolders();
|
||||
const ids = folders.map((f) => f.id).join("\n");
|
||||
if (list.dataset.ids !== ids) {
|
||||
list.dataset.ids = ids;
|
||||
list.replaceChildren(...folders.map(workspaceRow));
|
||||
}
|
||||
folders.forEach((f, i) => paintWorkspaceRow(list.children[i], f));
|
||||
$("workspace-browse").hidden = Boolean(page.wsFrame && page.wsFrame.remote);
|
||||
$("workspace-scope").textContent = workspaceScopeText();
|
||||
}
|
||||
|
||||
function workspaceRow(f) {
|
||||
const li = el("li", "ws-entry");
|
||||
li.dataset.fid = f.id;
|
||||
|
||||
const head = el("div", "ws-head");
|
||||
head.appendChild(el("span", "ws-chip"));
|
||||
if (f.original) head.appendChild(el("span", "ws-original", "started here — can't be removed"));
|
||||
li.appendChild(head);
|
||||
|
||||
const pathRow = el("div", "ws-path-row");
|
||||
const code = el("code", "ws-path");
|
||||
pathRow.appendChild(code);
|
||||
const copy = el("button", "btn small", "Copy path");
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", async () => {
|
||||
const folder = workspaceFolders().find((x) => x.id === f.id);
|
||||
if (!folder) return;
|
||||
try {
|
||||
await navigator.clipboard.writeText(folder.path);
|
||||
copy.textContent = "Copied";
|
||||
setTimeout(() => (copy.textContent = "Copy path"), 1500);
|
||||
} catch {
|
||||
// Refused: the path is selected instead, ready for Ctrl+C.
|
||||
selectContents(code);
|
||||
copy.textContent = "Press Ctrl+C";
|
||||
}
|
||||
});
|
||||
pathRow.appendChild(copy);
|
||||
if (!f.original) {
|
||||
const remove = el("button", "btn small danger ws-remove", "Remove");
|
||||
remove.type = "button";
|
||||
remove.addEventListener("click", () => {
|
||||
wsConfirm = f.id;
|
||||
renderWorkspace();
|
||||
li.querySelector(".ws-confirm .btn.danger")?.focus();
|
||||
});
|
||||
pathRow.appendChild(remove);
|
||||
}
|
||||
li.appendChild(pathRow);
|
||||
|
||||
li.appendChild(el("div", "ws-marks"));
|
||||
li.appendChild(workspaceField(f, "name", "Name"));
|
||||
li.appendChild(workspaceField(f, "description", "What is it?"));
|
||||
return li;
|
||||
}
|
||||
|
||||
// The Name and What-is-it boxes. Each saves on blur or Enter through
|
||||
// /workspace/edit, and only when it holds something new.
|
||||
function workspaceField(f, field, labelText) {
|
||||
const wrap = el("div", "ws-field");
|
||||
const id = `ws-${field}-${f.id}`;
|
||||
const label = el("label", null, labelText);
|
||||
label.htmlFor = id;
|
||||
const input = el("input");
|
||||
input.type = "text";
|
||||
input.id = id;
|
||||
input.dataset.field = field;
|
||||
input.autocomplete = "off";
|
||||
input.spellcheck = false;
|
||||
if (field === "description") input.maxLength = 200;
|
||||
const err = el("p", "field-error");
|
||||
err.hidden = true;
|
||||
const current = () => workspaceFolders().find((x) => x.id === f.id);
|
||||
const saved = () => (current() ? current()[field] || "" : "");
|
||||
const showError = (text) => {
|
||||
err.textContent = text || "";
|
||||
err.hidden = !text;
|
||||
input.classList.toggle("invalid", Boolean(text));
|
||||
};
|
||||
|
||||
if (field === "name") {
|
||||
input.addEventListener("input", () => showError(nameProblem(input.value.trim()) ? NAME_RULE : ""));
|
||||
}
|
||||
const save = async (leaving) => {
|
||||
const value = input.value.trim();
|
||||
if (value === saved()) return showError("");
|
||||
if (field === "name" && nameProblem(value)) {
|
||||
if (!leaving) return showError(NAME_RULE);
|
||||
input.value = saved();
|
||||
return showError("");
|
||||
}
|
||||
const { status, body } = await postJson("/workspace/edit", { id: f.id, [field]: value });
|
||||
// An earlier "Added as @x" is out of date once the list moves on.
|
||||
if (status === 200) {
|
||||
setAddMsg("");
|
||||
return showError("");
|
||||
}
|
||||
if (body.reason === "name-taken") showError(`@${value} is taken — try @${body.suggest}.`);
|
||||
else if (body.reason === "bad-name") showError(NAME_RULE);
|
||||
else showError("That did not save. Try again.");
|
||||
if (leaving) input.value = saved();
|
||||
};
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
save(false);
|
||||
});
|
||||
input.addEventListener("blur", () => save(true));
|
||||
wrap.append(label, input, err);
|
||||
return wrap;
|
||||
}
|
||||
|
||||
// Everything in a row that follows the frame. A box with focus is left as
|
||||
// the person has it; every other box shows what is saved.
|
||||
function paintWorkspaceRow(li, f) {
|
||||
if (!li) return;
|
||||
const missing = (page.wsFrame.missing || []).includes(f.id);
|
||||
const issue = (page.wsFrame.issues || []).find((x) => x.name === f.name);
|
||||
li.classList.toggle("is-missing", missing);
|
||||
li.querySelector(".ws-chip").textContent = "@" + f.name;
|
||||
li.querySelector(".ws-path").textContent = f.path;
|
||||
for (const input of li.querySelectorAll("input[data-field]")) {
|
||||
if (document.activeElement !== input) input.value = f[input.dataset.field] || "";
|
||||
}
|
||||
|
||||
const marks = li.querySelector(".ws-marks");
|
||||
marks.replaceChildren();
|
||||
if (missing) marks.appendChild(el("p", "ws-mark is-missing", "This folder no longer exists"));
|
||||
if (issue) {
|
||||
marks.appendChild(el("p", "ws-mark is-issue", "The agent can't read this yet: " + issue.reason));
|
||||
if (issue.hint) {
|
||||
const row = el("div", "ws-hint-row");
|
||||
const code = el("code", "ws-hint", issue.hint);
|
||||
row.append(code, copyButton(issue.hint, "btn tiny", code));
|
||||
marks.appendChild(row);
|
||||
}
|
||||
}
|
||||
if (f.nested) marks.appendChild(el("p", "ws-mark is-nested", "Inside another folder in the list"));
|
||||
marks.hidden = !marks.children.length;
|
||||
|
||||
// Built once per confirm, so a frame landing meanwhile keeps its focus.
|
||||
const open = li.querySelector(".ws-confirm");
|
||||
if (wsConfirm !== f.id) open?.remove();
|
||||
else if (open) open.querySelector("span").textContent = `Remove @${f.name}? The agent is told.`;
|
||||
else {
|
||||
const box = el("div", "ws-confirm");
|
||||
box.setAttribute("role", "alert");
|
||||
box.appendChild(el("span", null, `Remove @${f.name}? The agent is told.`));
|
||||
const keep = el("button", "btn small ghost", "Keep it");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
wsConfirm = null;
|
||||
renderWorkspace();
|
||||
li.querySelector(".ws-remove")?.focus();
|
||||
});
|
||||
const go = el("button", "btn small danger", "Remove");
|
||||
go.type = "button";
|
||||
go.addEventListener("click", async () => {
|
||||
go.disabled = true;
|
||||
const { status } = await postJson("/workspace/remove", { id: f.id });
|
||||
wsConfirm = null;
|
||||
if (status === 200) setAddMsg("");
|
||||
if (status !== 200) setAddMsg(`@${f.name} could not be removed. Try again.`, "error");
|
||||
renderWorkspace();
|
||||
$("workspace-path").focus();
|
||||
});
|
||||
box.append(keep, go);
|
||||
li.appendChild(box);
|
||||
}
|
||||
}
|
||||
|
||||
// Add by typed path, or by a path Browse… came back with. `name` is only
|
||||
// sent when the person took a suggested name after a clash.
|
||||
async function addWorkspaceFolder(path, name) {
|
||||
const trimmed = String(path || "").trim();
|
||||
if (!trimmed || wsBusy) return;
|
||||
wsBusy = true;
|
||||
$("workspace-add").disabled = true;
|
||||
const { status, body } = await postJson("/workspace/add", name ? { path: trimmed, name } : { path: trimmed });
|
||||
wsBusy = false;
|
||||
$("workspace-add").disabled = false;
|
||||
if (status === 200) {
|
||||
$("workspace-path").value = "";
|
||||
setAddMsg(`Added as @${body.name}.` + (body.nested ? " It's inside another folder in the list." : ""), "good");
|
||||
if (body.name && page.wsFrame && !workspaceFolders().some((f) => f.id === body.id)) {
|
||||
page.wsFrame = { ...page.wsFrame, folders: [...workspaceFolders(), body] };
|
||||
}
|
||||
renderWorkspace();
|
||||
hooks.renderWhere();
|
||||
return;
|
||||
}
|
||||
switch (body.reason) {
|
||||
case "not-a-folder":
|
||||
return setAddMsg("That isn't a folder on this machine.", "error");
|
||||
case "duplicate":
|
||||
return setAddMsg(`Already in the workspace as @${body.name}.`, "error");
|
||||
case "name-taken": {
|
||||
const taken = name || String(body.suggest || "").replace(/-\d+$/, "");
|
||||
const use = el("button", "btn tiny", `Use @${body.suggest}`);
|
||||
use.type = "button";
|
||||
use.addEventListener("click", () => addWorkspaceFolder(trimmed, body.suggest));
|
||||
return setAddMsg(`@${taken} is taken — try @${body.suggest}.`, "error", use);
|
||||
}
|
||||
case "bad-name":
|
||||
return setAddMsg(NAME_RULE, "error");
|
||||
default:
|
||||
return setAddMsg("That folder could not be added. Try again.", "error");
|
||||
}
|
||||
}
|
||||
|
||||
async function browseWorkspace() {
|
||||
const b = $("workspace-browse");
|
||||
if (b.disabled) return;
|
||||
b.disabled = true;
|
||||
setAddMsg("Waiting for the folder picker…");
|
||||
const { status, body } = await postJson("/workspace/browse", {});
|
||||
b.disabled = false;
|
||||
if (status === 200 && body.path) {
|
||||
setAddMsg("");
|
||||
return addWorkspaceFolder(body.path);
|
||||
}
|
||||
if (status === 200 && body.cancelled) return setAddMsg("");
|
||||
setAddMsg(BROWSE_UNAVAILABLE, "error");
|
||||
}
|
||||
|
||||
// The dialog's buttons, and the footer label that opens it.
|
||||
export function wireWorkspace() {
|
||||
lightDismiss($("workspace-modal"));
|
||||
$("workspace-add").addEventListener("click", () => addWorkspaceFolder($("workspace-path").value));
|
||||
$("workspace-path").addEventListener("keydown", (e) => {
|
||||
if (e.key !== "Enter") return;
|
||||
e.preventDefault();
|
||||
addWorkspaceFolder(e.currentTarget.value);
|
||||
});
|
||||
$("workspace-browse").addEventListener("click", browseWorkspace);
|
||||
$("workspace-done").addEventListener("click", () => $("workspace-modal").close());
|
||||
$("workspace-modal").addEventListener("close", () => {
|
||||
wsConfirm = null;
|
||||
$("footer-where").focus();
|
||||
});
|
||||
// As on Help: the page-wide Ctrl/Cmd+Enter stands down while a dialog is open,
|
||||
// and this keeps the key inside the Workspace dialog as well.
|
||||
$("workspace-modal").addEventListener("keydown", (e) => {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "Enter") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
}
|
||||
});
|
||||
// The workspace label opens the Workspace dialog; each folder's Copy path
|
||||
// lives in there now.
|
||||
$("footer-where").addEventListener("click", openWorkspace);
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
// Plan2Code Web Console - what the page reads off its state: the questions, the finish, the scan, who has the ball; defines only.
|
||||
//
|
||||
// Plain functions over `page` (state.js) that more than one screen asks the
|
||||
// same question of, kept here so no screen has to import another to ask it.
|
||||
|
||||
import { page, redraw } from "./state.js";
|
||||
import { boardAwaiting } from "./git-board.js";
|
||||
import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js";
|
||||
import { activityLabel, workingLine } from "./labels.js";
|
||||
|
||||
export const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
// goes quiet is worth mentioning early, whereas the gap between `wait`
|
||||
// returning and the next patch landing is ordinary and must not be called a
|
||||
// failure. `wait` pokes /health every five seconds, so either threshold is
|
||||
// many missed pokes, not a slow one.
|
||||
const ADRIFT_MS = 3 * 60 * 1000;
|
||||
|
||||
export const items = () => (page.S && Array.isArray(page.S.items) ? page.S.items : []);
|
||||
|
||||
export const topics = () => (page.S && Array.isArray(page.S.topics) ? page.S.topics : []);
|
||||
|
||||
export const docs = () => (page.S && Array.isArray(page.S.docs) ? page.S.docs : []);
|
||||
|
||||
export const byId = (id) => items().find((i) => i.id === id);
|
||||
|
||||
export const isOpen = (i) => i.status === "open" || i.status === "reopened";
|
||||
|
||||
export const asked = () => items().filter((i) => i.kind !== "notice");
|
||||
|
||||
export const openItems = () => asked().filter(isOpen);
|
||||
|
||||
export const stagedCount = () => Object.keys(page.local.staged).length;
|
||||
|
||||
// The one thing the page could never know before: this session is OVER, and
|
||||
// the agent said so rather than the page inferring it. Everything else here is
|
||||
// a pause -- no open questions means "none right now", not "no more ever" --
|
||||
// which is why the end of a session used to read as a lull that never lifted.
|
||||
// A posted finish is the whole signal; its command is optional, because some
|
||||
// sessions end with nothing left to run.
|
||||
export const finish = () => (page.S && page.S.finish && typeof page.S.finish === "object" ? page.S.finish : null);
|
||||
|
||||
// The dashboard is the one workflow that is not a conversation: a menu of the
|
||||
// skills, rendered from the page's own catalog, where a click IS the answer.
|
||||
export const isDashboard = () => page.S && page.S.workflow === "dashboard";
|
||||
|
||||
// The git board is drawn by the page too, from the console's own read-only
|
||||
// snapshot (state.git), with the agent's confirm and result cards above it.
|
||||
export const isGitBoard = () => page.S && page.S.workflow === "git" && page.S.git;
|
||||
|
||||
// A board click or a card send stays with the agent until its next post
|
||||
// (boardAwaiting in git-board.js), not just until `wait` collects it.
|
||||
export function gitAwaiting() {
|
||||
if (!isGitBoard()) return false;
|
||||
return boardAwaiting({
|
||||
sentAt: page.local.gitSentAt || null,
|
||||
updatedAt: page.S.updatedAt || null,
|
||||
cardsAwaiting: awaitingReply().length,
|
||||
adrift: agentAdrift(),
|
||||
});
|
||||
}
|
||||
|
||||
// The server's scan of the repo — AGENTS.md plus every spec under specs/,
|
||||
// classified by pipeline stage and sorted most-recently-touched first.
|
||||
export const scan = () => (page.S && page.S.scan) || null;
|
||||
|
||||
export const specList = () => {
|
||||
const sc = scan();
|
||||
return sc && Array.isArray(sc.specs) ? sc.specs : [];
|
||||
};
|
||||
|
||||
// The spec the picker currently targets. Absent `specSel` means the picker
|
||||
// has not been touched, so it defaults to the most recently touched spec
|
||||
// still in play (defaultSpec: the server's list is already sorted, and a
|
||||
// fixed bug is skipped). An explicit "start from scratch" is stored as null,
|
||||
// which is different.
|
||||
export const selSpec = () => {
|
||||
const specs = specList();
|
||||
if (!specs.length) return null;
|
||||
if (page.local.specSel === undefined) return defaultSpec(specs);
|
||||
return specs.find((s) => s.dir === page.local.specSel) || null;
|
||||
};
|
||||
|
||||
// This checkout's unused handoffs (scan.handoffs, newest first). A handoff is
|
||||
// picked in the same chip row as a spec, stored as `specSel = "handoff:<id>"`;
|
||||
// selSpec() then reads as "no spec", and selHandoff() is the handoff itself,
|
||||
// or null once it is gone from the scan (which also drops the stale pick).
|
||||
export const handoffList = () => {
|
||||
const sc = scan();
|
||||
return sc && Array.isArray(sc.handoffs) ? sc.handoffs : [];
|
||||
};
|
||||
|
||||
export const selHandoff = () => {
|
||||
if (typeof page.local.specSel !== "string" || !page.local.specSel.startsWith("handoff:")) return null;
|
||||
const id = page.local.specSel.slice("handoff:".length);
|
||||
const h = handoffList().find((x) => x.id === id) || null;
|
||||
if (!h) delete page.local.specSel;
|
||||
return h;
|
||||
};
|
||||
|
||||
// The review a finished build offers, and where it has got to:
|
||||
// "open" on offer, and a press would reach the agent
|
||||
// "asked" pressed, and the agent has not taken it up yet
|
||||
// null no offer, declined, or nobody left to take the press
|
||||
// `local.afterBuild` remembers the press across a reload. It is cleared when
|
||||
// the finish goes away, which is the agent taking the review up.
|
||||
export function reviewPending() {
|
||||
const fin = finish();
|
||||
if (!fin || !reviewOffer(fin) || ["done", "dashboard", "commit"].includes(page.local.afterBuild)) return null;
|
||||
if (page.local.afterBuild === "review") return page.gone ? null : "asked";
|
||||
return page.gone ? null : "open";
|
||||
}
|
||||
|
||||
// The dashboard offer on a finish, unless the person already said they are
|
||||
// done: that send closes the session, so a button after it would go nowhere.
|
||||
export const dashboardLive = (fin) => dashboardOffer(fin) && page.local.afterBuild !== "done";
|
||||
|
||||
// Whether the agent has collected this card's send: carried by the last
|
||||
// collected send (state.collected), or sent before that collection.
|
||||
export const sendCollected = (i, sub = i && i.submitted) => {
|
||||
const c = page.S && page.S.collected;
|
||||
if (!c || !sub) return false;
|
||||
if (Array.isArray(c.ids) && c.ids.includes(i.id)) return true;
|
||||
return Boolean(c.at && sub.at && String(sub.at) <= String(c.at));
|
||||
};
|
||||
|
||||
// The durable half of `local.sent`: the server writes every send onto the
|
||||
// item itself (`submitted`), so the send survives a reload, a resume onto a
|
||||
// new port, and a second tab. It also covers an agent that took the answer
|
||||
// and moved on without marking the item settled, which used to hand the
|
||||
// question back looking as though the send never happened. `local.retract`
|
||||
// is the person's "take it back" against exactly that send.
|
||||
export const submittedInFlight = (i) => {
|
||||
const sub = submittedAwaiting(i);
|
||||
if (!sub) return null;
|
||||
// Collected, and the agent is back to waiting without settling it: it left
|
||||
// the card open on purpose (a pick that still owes its recap), so the send
|
||||
// is no longer with it, and nothing stays locked waiting on a reply.
|
||||
// Any send at or before the last collection was collected too, not only the
|
||||
// cards that last one carried.
|
||||
if (!page.pendingResult && !agentWorking() && sendCollected(i, sub)) return null;
|
||||
const r = page.local.retract && page.local.retract[i.id];
|
||||
if (r === "any" || (r != null && r === sub.at)) return null;
|
||||
return sub;
|
||||
};
|
||||
|
||||
// Open questions whose send is with the agent: answers and notes alike. On a
|
||||
// finished session there is nobody left to collect a send, so nothing is in
|
||||
// flight either -- the item is a record of what was sent, not a live wait.
|
||||
export const awaitingReply = () =>
|
||||
finish()
|
||||
? []
|
||||
: openItems().filter((i) => (page.local.sent && page.local.sent[i.id]) || submittedInFlight(i));
|
||||
|
||||
// Open questions that are actually the person's to answer right now. An open
|
||||
// question they have already sent is not one of those, and counting it as one
|
||||
// is how the page ends up telling someone it is their turn while they are
|
||||
// sitting waiting for a reply. A finished session ends everyone's turn:
|
||||
// questions left open are moot, because a send can no longer go anywhere.
|
||||
export const myTurn = () =>
|
||||
finish()
|
||||
? []
|
||||
: openItems().filter((i) => !(page.local.sent && page.local.sent[i.id]) && !submittedInFlight(i));
|
||||
|
||||
export function agentWorking() {
|
||||
return page.S && page.S.agent && page.S.agent.status === "working";
|
||||
}
|
||||
|
||||
export function workingMs() {
|
||||
if (!agentWorking() || !page.S.agent.since) return 0;
|
||||
return Date.now() - Date.parse(page.S.agent.since);
|
||||
}
|
||||
|
||||
// The three silence thresholds below, stretched while the agent has said a
|
||||
// long quiet stretch is normal (a build task). See quietLimitMs.
|
||||
export const patience = (baseMs) => quietLimitMs(page.S && page.S.agent, baseMs);
|
||||
|
||||
// What the agent says it is doing right now, when it has said: "Task 3 of 9:
|
||||
// the user service". Only meaningful while it is working. A build's line is
|
||||
// rewritten (activityLabel() in labels.js) because agents trained on the old
|
||||
// wording still write "Task 4.3 of 9", phase-numbered beside a bar that counts
|
||||
// within the phase; the page puts it right rather than every prompt having to.
|
||||
export function activity() {
|
||||
if (!agentWorking()) return "";
|
||||
const a = page.S.agent.activity;
|
||||
if (typeof a !== "string") return "";
|
||||
return activityLabel(a.trim(), page.S.workflow);
|
||||
}
|
||||
|
||||
export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page.S.headline, page.S && page.S.workflow);
|
||||
|
||||
// The OTHER end of the wire, and the one that was invisible.
|
||||
//
|
||||
// There are two connections here, not one. The page talks to a little server
|
||||
// on this machine (`gone` covers that), and the server is polled by the agent
|
||||
// sitting in `wait` (this covers that). The second is the one that actually
|
||||
// breaks: a page left open pings every five seconds, which keeps the server
|
||||
// well clear of its idle deadline, so the server happily outlives the agent
|
||||
// for hours. Until now nothing said so unless the agent had also declared
|
||||
// itself "working", and the normal state while someone answers is "waiting".
|
||||
export function agentAdrift() {
|
||||
if (!page.agentLastSeen || page.gone || finish()) return false;
|
||||
return Date.now() - Date.parse(page.agentLastSeen) > patience(ADRIFT_MS);
|
||||
}
|
||||
|
||||
// Answers that went nowhere: pressed Send, and nothing has collected them.
|
||||
// They are safe -- the server wrote them to disk and the next session picks
|
||||
// them up -- but "Sent. Waiting for Plan2Code." forever does not say that.
|
||||
export const stranded = () => page.pendingResult && agentAdrift();
|
||||
|
||||
// The spec whose overview.md the Overview tab shows: the dashboard picker's
|
||||
// selection on the dashboard, the session's own spec everywhere else.
|
||||
export const overviewSpec = () => (isDashboard() ? selSpec()?.dir || "" : (page.S && page.S.specDir) || "");
|
||||
|
||||
// Fresh from disk every time, never cached: the file changes under a build,
|
||||
// and the tab is only worth having if it shows what is there now. Repaints
|
||||
// only when the tab would appear, vanish or show different text.
|
||||
export async function loadOverview() {
|
||||
const spec = overviewSpec();
|
||||
let text = null;
|
||||
if (spec) {
|
||||
try {
|
||||
const res = await fetch("/overview?spec=" + encodeURIComponent(spec), { cache: "no-store" });
|
||||
if (res.status === 200) text = await res.text();
|
||||
} catch {}
|
||||
}
|
||||
// The selection moved on while this was in flight; its own fetch will land.
|
||||
if (spec !== overviewSpec()) return;
|
||||
const changed = page.overview.key !== spec || page.overview.text !== text;
|
||||
page.overview = { key: spec, text };
|
||||
if (changed) redraw();
|
||||
}
|
||||
|
||||
// The workspace's folders, original first, or none before a frame has them.
|
||||
export const workspaceFolders = () => (page.wsFrame && Array.isArray(page.wsFrame.folders) ? page.wsFrame.folders : []);
|
||||
@@ -0,0 +1,76 @@
|
||||
// Plan2Code Web Console - whether Send is available, and what its button says; defines only.
|
||||
|
||||
import {
|
||||
finish,
|
||||
stranded,
|
||||
agentWorking,
|
||||
myTurn,
|
||||
stagedCount,
|
||||
workingMs,
|
||||
patience,
|
||||
WORKING_GRACE_MS,
|
||||
openItems,
|
||||
agentAdrift,
|
||||
} from "./selectors.js";
|
||||
import { finishPaused } from "./answers.js";
|
||||
import { page } from "./state.js";
|
||||
import { pendingNotes } from "./uploads.js";
|
||||
|
||||
export function sendState() {
|
||||
// Before `gone`, and before the grace period that can re-enable a send. A
|
||||
// finished session has nobody left to send to, whatever the socket says.
|
||||
if (finish())
|
||||
return finishPaused(finish())
|
||||
? { disabled: true, why: "This session is paused.", short: "Session paused" }
|
||||
: { disabled: true, why: "This session is finished.", short: "Session finished" };
|
||||
if (page.gone) return { disabled: true, why: "Not connected right now.", short: "Not connected" };
|
||||
// A send is still being collected. Blocking here is what keeps someone from
|
||||
// writing over answers nobody has read yet.
|
||||
if (page.pendingResult) {
|
||||
// The server refuses a second submit while one is uncollected, so this
|
||||
// stays disabled either way. Only the reason changes, and "one moment" is
|
||||
// a promise the page cannot keep once nothing is coming to collect them.
|
||||
return stranded()
|
||||
? { disabled: true, why: "Saved, and waiting for Plan2Code to come back for them.", short: "Saved, not picked up" }
|
||||
: { disabled: true, why: "Your last answers are on their way. One moment.", short: "" };
|
||||
}
|
||||
if (agentWorking()) {
|
||||
// A question the agent left open while still working is still a question,
|
||||
// and its answer has nowhere better to wait than the server, which holds
|
||||
// a send until the agent next looks. The contract says to switch to
|
||||
// "waiting" before asking, but an agent that asks and carries on ("while
|
||||
// you decide") must not lock the person out of answering for up to an
|
||||
// hour of quietMinutes.
|
||||
if (myTurn().length && (stagedCount() || pendingNotes().length)) {
|
||||
return {
|
||||
disabled: false,
|
||||
why: "Plan2Code is still working. Your answers wait for it to look.",
|
||||
short: "Still working · it reads this next",
|
||||
};
|
||||
}
|
||||
const ms = workingMs();
|
||||
if (ms > patience(WORKING_GRACE_MS)) {
|
||||
// A stuck agent must not lock someone out of their own session, so the
|
||||
// hatch stays open -- but only once there is something to push through
|
||||
// it. Enabled with an empty payload, Send clicks as a no-op, and the
|
||||
// loud styling on a dead button reads as broken rather than available.
|
||||
// "A while", not the clock: the footer only redraws on events, so a
|
||||
// duration printed here freezes between them, and a frozen number
|
||||
// beside "is it stuck?" makes the page look like the thing it is
|
||||
// warning about. The exact time already ticks away in the dock.
|
||||
if (stagedCount() || pendingNotes().length) {
|
||||
return { disabled: false, why: "Plan2Code has been busy a while. You can send anyway.", short: "Busy · send anyway" };
|
||||
}
|
||||
return openItems().length
|
||||
? {
|
||||
disabled: true,
|
||||
why: "Plan2Code has been busy a while. Answer something or add a note, and you can send anyway.",
|
||||
short: "Busy · a note unlocks Send",
|
||||
}
|
||||
: { disabled: true, why: "Plan2Code has been busy a while.", short: "Busy a while" };
|
||||
}
|
||||
return { disabled: true, why: "Wait for Plan2Code to finish.", short: agentAdrift() ? "Gone quiet" : "" };
|
||||
}
|
||||
if (!stagedCount() && !pendingNotes().length) return { disabled: true, why: "" };
|
||||
return { disabled: false, why: "" };
|
||||
}
|
||||
@@ -0,0 +1,418 @@
|
||||
// Plan2Code Web Console - the skill list.
|
||||
//
|
||||
// Every per-skill fact the console uses; data only, imported by the page and
|
||||
// by Node. One entry per workflow: the dashboard's cards first, in their
|
||||
// order on the page, then the workflows with no card (the dashboard itself).
|
||||
// The older tables (SKILL_CATALOG, START_POSES, LAUNCH_COUNTED and the rest)
|
||||
// are lookups on this list. No imports and no DOM access: nothing runs at
|
||||
// load but building the frozen data.
|
||||
//
|
||||
// Per entry:
|
||||
// skill the installed skill's name; `command` is "/" + skill
|
||||
// workflow the console's name for it (`open --workflow`)
|
||||
// label the badge the page header wears
|
||||
// name how the session meter's rows name it ("7 answers in Plan")
|
||||
// pose the Planny drawn on its starting screen (index.html's
|
||||
// <template id="start-poses">), or null for the flight
|
||||
// builds a build: the header counts tasks done, Help opens on Building
|
||||
// phased a phased build: tasks numbered "Task 4.2" and counted on the
|
||||
// meter as the headline's `cleared` rises
|
||||
// metered the launch itself scores on the session meter
|
||||
// templates the first "What's the idea?" card offers starter templates
|
||||
// subagents the Subagents switch's standing instruction, or null when the
|
||||
// switch is not offered
|
||||
// states the spec states its card takes, as spec-states.js names them,
|
||||
// plus "none" for no spec picked; "any" for a card that is
|
||||
// always on whatever is picked; null for no card
|
||||
// marksNext the card can be a state's natural next step, so its answer
|
||||
// always says whether it is (`next`)
|
||||
// greyed its greyed reasons: `default`, plus one per state whose
|
||||
// wording differs, and `finished` for any finished state
|
||||
// (spec-states.js); Init and Init update use `default` for the
|
||||
// AGENTS.md check, which is a rule on the scan, not on the spec
|
||||
// card the dashboard card (group, chip, title, blurb, about, and
|
||||
// `spec: true` when it takes the picked spec), or null
|
||||
|
||||
// Shared by Implement and Implement + Review.
|
||||
const BUILD_HELPERS =
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.";
|
||||
|
||||
// Pathfinder's and Plan's reason on a finished spec (a fixed bug).
|
||||
export const FIXED_REASON = "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/.";
|
||||
|
||||
// Shared by Implement and Implement + Review.
|
||||
const BUILD_GREYED = { default: "Needs the phase checklists written up first", built: "All tasks are already done" };
|
||||
|
||||
function skill(entry) {
|
||||
const card = entry.card ? Object.freeze({ ...entry.card }) : null;
|
||||
const states = Array.isArray(entry.states) ? Object.freeze([...entry.states]) : entry.states;
|
||||
const greyed = entry.greyed ? Object.freeze({ ...entry.greyed }) : null;
|
||||
return Object.freeze({ marksNext: false, ...entry, command: "/" + entry.skill, states, greyed, card });
|
||||
}
|
||||
|
||||
export const SKILLS = Object.freeze([
|
||||
skill({
|
||||
skill: "plan2code-init",
|
||||
workflow: "init",
|
||||
label: "Setting up",
|
||||
name: "Init",
|
||||
pose: "init",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: { default: "AGENTS.md is already written. Refresh it instead." },
|
||||
card: {
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Set up this project",
|
||||
blurb: "Reads your project and writes AGENTS.md, the guide every later step works from.",
|
||||
about:
|
||||
"Plan2Code reads the whole project: how it is organized, how it runs, and where the sharp edges are. Then it writes AGENTS.md, the guide every later step steers by. It asks a few questions as it goes, so nothing important gets guessed. Run this once per project, or again when the project has moved on.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-init-update",
|
||||
workflow: "init-update",
|
||||
label: "Refreshing",
|
||||
name: "Init update",
|
||||
pose: "init",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: { default: "Needs an AGENTS.md. Set the project up first." },
|
||||
card: {
|
||||
group: "setup",
|
||||
chip: "Set up",
|
||||
title: "Refresh AGENTS.md",
|
||||
blurb: "Brings AGENTS.md and its notes up to date with what the project has learned lately.",
|
||||
about:
|
||||
"The project moved on since AGENTS.md was written: new commands, new habits, new gotchas. This re-reads the project, asks what changed, and folds it into AGENTS.md and the notes beside it. Cheaper than a fresh setup, and whatever is still right is kept.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-0-pathfinder",
|
||||
workflow: "pathfinder",
|
||||
label: "Pathfinder",
|
||||
name: "Pathfinder",
|
||||
pose: "pathfinder",
|
||||
builds: false, phased: false, metered: false, templates: true,
|
||||
subagents: "Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
states: ["none", "unrecognized", "exploring"], marksNext: true,
|
||||
greyed: {
|
||||
default: "This spec is already past the questions",
|
||||
diagnosed: "The cause is found. Fix it in a quick task, or plan it.",
|
||||
finished: FIXED_REASON,
|
||||
},
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 0",
|
||||
spec: true,
|
||||
title: "Pathfinder",
|
||||
blurb: "A foggy idea becomes a clear list of decisions, settled one question at a time.",
|
||||
about:
|
||||
"You have a rough idea and a lot of unknowns. Pathfinder asks one question at a time: who it is for, what it must do, what could go wrong. Each answer is written down in a spec folder. It ends with a list of decisions clear enough to plan from, and nothing gets built yet.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-1-plan",
|
||||
workflow: "plan",
|
||||
label: "Planning",
|
||||
name: "Plan",
|
||||
pose: "plan",
|
||||
builds: false, phased: false, metered: true, templates: true,
|
||||
subagents: null,
|
||||
states: ["none", "unrecognized", "diagnosed", "mapped", "planned"], marksNext: true,
|
||||
greyed: {
|
||||
default: "The plan is written. Revise it instead if it moved.",
|
||||
exploring: "Pathfinder is not finished with this spec yet",
|
||||
finished: FIXED_REASON,
|
||||
},
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 1",
|
||||
spec: true,
|
||||
title: "Plan",
|
||||
blurb: "Requirements, technical design and your approval: the shape of what gets built.",
|
||||
about:
|
||||
"Turns what you bring into a real plan: a finished Pathfinder map, a folder of design notes, or just the idea in your head. You get requirements, a technical design, a phase-by-phase breakdown, and a final version to approve before anything is built. This is where 'what are we building' becomes 'how it gets built'.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-1b-revise-plan",
|
||||
workflow: "revise-plan",
|
||||
label: "Revising the plan",
|
||||
name: "Revise plan",
|
||||
pose: "plan",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: ["documented", "building"],
|
||||
greyed: { default: "Needs a spec that is already written up", built: "The spec is fully built" },
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 1b",
|
||||
spec: true,
|
||||
title: "Revise the plan",
|
||||
blurb: "Requirements changed mid-build? Adjust the plan without starting over.",
|
||||
about:
|
||||
"Requirements moved mid-build: a feature added, a rule dropped, a deadline pulled in. This adjusts the existing spec for the change, shows you what it affects, and only rewrites what actually has to move. The approved plan stays the plan.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-2-document",
|
||||
workflow: "document",
|
||||
label: "Documenting",
|
||||
name: "Document",
|
||||
pose: "document",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: ["planned"], marksNext: true,
|
||||
greyed: {
|
||||
default: "Needs a drafted plan first",
|
||||
documented: "The phases are already written up",
|
||||
building: "The phases are already written up",
|
||||
built: "The phases are already written up",
|
||||
},
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 2",
|
||||
spec: true,
|
||||
title: "Document",
|
||||
blurb: "The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.",
|
||||
about:
|
||||
"Writes the plan as numbered phase files. Each phase is a checklist of tasks small enough to just do, with the details a builder needs right there. This is the file the build step works from, and the thing a later session can pick up cold.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-3-implement",
|
||||
workflow: "implement",
|
||||
label: "Building",
|
||||
name: "Implement",
|
||||
pose: "implement",
|
||||
builds: true, phased: true, metered: false, templates: false,
|
||||
subagents: BUILD_HELPERS,
|
||||
states: ["documented", "building"], marksNext: true,
|
||||
greyed: BUILD_GREYED,
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement",
|
||||
blurb: "Builds the next phase, task by task, with a report and your sign-off at the end.",
|
||||
about:
|
||||
"Builds the next phase of the spec. Tasks get checked off one by one, with progress and the occasional decision landing on this page as it goes. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-3-implement-review",
|
||||
workflow: "implement-review",
|
||||
label: "Building + review",
|
||||
name: "Implement + Review",
|
||||
pose: "implement",
|
||||
builds: true, phased: true, metered: false, templates: false,
|
||||
subagents: BUILD_HELPERS,
|
||||
states: ["documented", "building"], marksNext: true,
|
||||
greyed: BUILD_GREYED,
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 3",
|
||||
spec: true,
|
||||
title: "Implement + review",
|
||||
blurb: "One phase built, then a careful review of the changes, then your sign-off. All in one run.",
|
||||
about:
|
||||
"The same build as Implement, with a review folded in before sign-off. The phase is built, then a fresh pass hunts for problems in exactly what changed, you pick what gets fixed, and only then does the sign-off card arrive.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-4-finalize",
|
||||
workflow: "finalize",
|
||||
label: "Wrapping up",
|
||||
name: "Finalize",
|
||||
pose: "finalize",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: ["built"], marksNext: true,
|
||||
greyed: { default: "Needs a spec that is fully built" },
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 4",
|
||||
spec: true,
|
||||
title: "Finalize",
|
||||
blurb: "Checks the work, writes the summary, files the specs away and suggests the commit message.",
|
||||
about:
|
||||
"The closer. Checks every task against the spec, makes sure the build actually works, writes the summary into overview.md, updates the project docs, and suggests the commit message. Run it when the feature is done. It leaves the project tidy behind it.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-quick-task",
|
||||
workflow: "quick-task",
|
||||
label: "Quick task",
|
||||
name: "Quick task",
|
||||
pose: "quick-task",
|
||||
builds: true, phased: false, metered: true, templates: true,
|
||||
subagents: "Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Quick task",
|
||||
blurb: "Too small for the full process? A quick plan, then it just builds it.",
|
||||
about:
|
||||
"A fix, a tweak, a small feature. Not worth a spec folder. Describe it, confirm the one-line plan, and it builds it right there, with a report at the end. The fast lane for work the full process would over-plan.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-review",
|
||||
workflow: "review",
|
||||
label: "Review",
|
||||
name: "Review",
|
||||
pose: "review",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: "Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Review",
|
||||
blurb: "A second opinion on the changes. Problems ranked, and you pick what gets fixed.",
|
||||
about:
|
||||
"A fresh-eyes pass over what changed: bugs, gaps, and the things the builder was too close to see. Problems come back ranked with a suggestion each, you pick which ones get fixed, and it fixes them.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-xray",
|
||||
workflow: "xray",
|
||||
label: "X-ray",
|
||||
name: "X-ray",
|
||||
pose: "xray",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Codebase X-ray",
|
||||
blurb: "Explain how and why an area works, or find the rough spots worth fixing.",
|
||||
about:
|
||||
"Two ways into code you did not write. Explain an area: how it works, step by step, and why it is that way, citing the files and the commits and pull requests behind it. Or find the rough spots: files that always change together, thin layers, tangled boundaries and busy code with no tests, ranked with a concrete example each. You tick the ones worth fixing and they become a brief for Pathfinder or Plan. It never changes code.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-diagnose",
|
||||
workflow: "diagnose",
|
||||
label: "Diagnosing",
|
||||
name: "Diagnose",
|
||||
pose: "diagnose",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Diagnose a bug",
|
||||
blurb: "Find a bug's cause and write it up, without fixing it.",
|
||||
about:
|
||||
"Something is broken and nobody knows why. Diagnose asks what goes wrong and how to see it, then builds a command that fails on the bug before it forms a theory. It narrows the cause down to a file and a function, says how sure it is, and sizes the fix. The write-up lands in a spec folder, and the dashboard then offers Quick Task to fix it, or Plan when the fix is big. It never changes code.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-changelog",
|
||||
workflow: "changelog",
|
||||
label: "Changelog",
|
||||
name: "Changelog",
|
||||
pose: "changelog",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Changelog",
|
||||
blurb: "Checks the CHANGELOG version against the main branch and suggests entries for what is new.",
|
||||
about:
|
||||
"Works out the right version from the default branch, then compares your branch with the latest CHANGELOG entry and suggests the entries it is missing. You edit them before anything is written, it keeps package.json in step, and it offers to commit the result in Git. If the newest version is not released or on another branch yet, it adds to that entry instead of starting a new one.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-git",
|
||||
workflow: "git",
|
||||
label: "Git",
|
||||
name: "Git",
|
||||
pose: "git",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
about:
|
||||
"Shows your branch, what is ahead or behind, and every local and remote branch. Switch, create, delete or clean up branches, pull (rebasing when they have split, with help on conflicts), push or publish, and commit with a clear message. It asks before every push, publish and delete, and never force-pushes.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-handoff",
|
||||
workflow: "handoff",
|
||||
label: "Handoff",
|
||||
name: "Handoff",
|
||||
pose: "handoff",
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
group: "extra",
|
||||
chip: "Utility",
|
||||
title: "Handoff",
|
||||
blurb: "Pack the current session into a document a fresh session can pick up cold.",
|
||||
about:
|
||||
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code",
|
||||
workflow: "dashboard",
|
||||
label: "Dashboard",
|
||||
name: "the dashboard",
|
||||
pose: null,
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
subagents: null,
|
||||
states: null,
|
||||
greyed: null,
|
||||
card: null,
|
||||
}),
|
||||
]);
|
||||
|
||||
const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s]));
|
||||
const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s]));
|
||||
|
||||
/** The entry for a workflow ("implement"), or null. */
|
||||
export function skillFor(workflow) {
|
||||
return BY_WORKFLOW.get(workflow) || null;
|
||||
}
|
||||
|
||||
/** The entry for an installed skill's name ("plan2code-3-implement"), or null. */
|
||||
export function skillByName(name) {
|
||||
return BY_SKILL.get(name) || null;
|
||||
}
|
||||
|
||||
export const isBuild = (workflow) => Boolean(skillFor(workflow)?.builds);
|
||||
export const isPhased = (workflow) => Boolean(skillFor(workflow)?.phased);
|
||||
export const isMetered = (workflow) => Boolean(skillFor(workflow)?.metered);
|
||||
export const takesTemplates = (workflow) => Boolean(skillFor(workflow)?.templates);
|
||||
|
||||
/** The Subagents switch's instruction for a workflow, or null when it is not offered. */
|
||||
export function subagentsFor(workflow) {
|
||||
return skillFor(workflow)?.subagents || null;
|
||||
}
|
||||
|
||||
/** The badge a workflow wears, or null for one the console does not know. */
|
||||
export function labelFor(workflow) {
|
||||
return skillFor(workflow)?.label || null;
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
// Plan2Code Web Console - the sound cues: which plays, one at a time, held until the first click; defines only.
|
||||
|
||||
import { looks } from "./looks.js";
|
||||
import { soundKey, SOUND_EVENTS } from "./palette.js";
|
||||
|
||||
/* ------------------------------------------------------------- sounds
|
||||
|
||||
The cues are the events in SOUND_EVENTS: a skill started from the
|
||||
dashboard, Planny snoring and waking, the session opening and ending, a
|
||||
new batch of questions, a launched skill ready, a reply on Ask, and a new
|
||||
tab joining the strip (a posted document, a spec's overview). Each plays
|
||||
only while both the master switch and its own switch are on. A browser will
|
||||
not let a page make noise before the person has touched it, so a cue that
|
||||
fires too early is held and let out by the first click or keypress rather
|
||||
than dropped.
|
||||
|
||||
Only ever one at a time, never two overlapping or back to back. Cues asked
|
||||
for in the same task collapse to the highest-ranked one; a cue asked for
|
||||
while another is still playing is dropped unless it outranks it, in which
|
||||
case it cuts the quieter one off. The held cue is a single slot on the same
|
||||
rule, so the first click lets out one sound, not a queue of them.
|
||||
|
||||
Made on first use, not at load: audio downloads racing the page's own
|
||||
scripts at start-up are bytes spent on sounds a browser will not play
|
||||
before the first click anyway. One Audio per file, shared by the events
|
||||
that use it. */
|
||||
const SOUNDS = {};
|
||||
|
||||
let soundQueued = null;
|
||||
|
||||
let soundHeld = null;
|
||||
|
||||
let soundPlaying = null;
|
||||
|
||||
export const soundOn = (event) => looks.sound && looks[soundKey(event)];
|
||||
|
||||
const soundAudio = (event) => SOUNDS[SOUND_EVENTS[event].file];
|
||||
|
||||
const louderSound = (a, b) => (!b || SOUND_EVENTS[a].rank > SOUND_EVENTS[b].rank ? a : b);
|
||||
|
||||
export function sound(event) {
|
||||
if (!soundOn(event)) return;
|
||||
if (!soundQueued) queueMicrotask(flushSound);
|
||||
soundQueued = louderSound(event, soundQueued);
|
||||
}
|
||||
|
||||
function flushSound() {
|
||||
const event = soundQueued;
|
||||
soundQueued = null;
|
||||
if (!soundOn(event)) return;
|
||||
const busy = soundPlaying && !soundAudio(soundPlaying).paused;
|
||||
if (busy && SOUND_EVENTS[event].rank <= SOUND_EVENTS[soundPlaying].rank) return;
|
||||
if (busy) soundAudio(soundPlaying).pause();
|
||||
const { file } = SOUND_EVENTS[event];
|
||||
const a = (SOUNDS[file] ||= new Audio(`/${file}.mp3`));
|
||||
a.currentTime = 0;
|
||||
soundPlaying = event;
|
||||
a.play().catch(() => {
|
||||
if (soundPlaying === event) soundPlaying = null;
|
||||
soundHeld = louderSound(event, soundHeld);
|
||||
});
|
||||
}
|
||||
|
||||
// Fades a cue out over `ms` and stops it, so a long one never outlasts the
|
||||
// moment it belongs to. Timers, not frames: a background tab still finishes.
|
||||
export function fadeSound(event, ms) {
|
||||
const a = soundAudio(event);
|
||||
if (!a || a.paused) return;
|
||||
const from = performance.now();
|
||||
const timer = setInterval(() => {
|
||||
const left = 1 - (performance.now() - from) / ms;
|
||||
if (left > 0 && !a.paused) {
|
||||
a.volume = left;
|
||||
return;
|
||||
}
|
||||
clearInterval(timer);
|
||||
a.pause();
|
||||
a.volume = 1;
|
||||
}, 25);
|
||||
}
|
||||
|
||||
// Drops anything queued or held, for a Skip that wants silence.
|
||||
export function dropSounds() {
|
||||
soundQueued = null;
|
||||
soundHeld = null;
|
||||
}
|
||||
|
||||
// The first click or keypress lets out the one cue that was held.
|
||||
export function releaseHeldSound() {
|
||||
if (!soundHeld) return;
|
||||
const name = soundHeld;
|
||||
soundHeld = null;
|
||||
sound(name);
|
||||
}
|
||||
|
||||
// Drops the held cue: any of them, or only `event`'s.
|
||||
export function dropHeldSound(event) {
|
||||
if (event === undefined || soundHeld === event) soundHeld = null;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
// Plan2Code Web Console - the spec states.
|
||||
//
|
||||
// Each spec state the dashboard scan can report; data only, imported by the
|
||||
// page and by Node. In the order the scan's SPEC_STATES lists them. Which
|
||||
// cards a state lights or greys lives on the skill list (skills.js), and how
|
||||
// a folder's files map to a state stays with the scan (classifySpec in
|
||||
// scan.mjs). No imports and no DOM access: nothing runs at load but building
|
||||
// the frozen data.
|
||||
//
|
||||
// Per state:
|
||||
// label what the picker shows next to the spec's name
|
||||
// next the card the state is the natural next step for (the
|
||||
// "Suggested" fallback when the agent's menu names nothing), or
|
||||
// null when it has none
|
||||
// finished the work is done: the spec is hidden while unavailable
|
||||
// workflows are, never the picker's default, deleted after one
|
||||
// confirm, and greyed with the card's `finished` reason
|
||||
// (skills.js) on the cards that would otherwise take it
|
||||
|
||||
function state(label, next, finished = false) {
|
||||
return Object.freeze({ label, next, finished });
|
||||
}
|
||||
|
||||
export const SPEC_STATES = Object.freeze({
|
||||
diagnosed: state("Bug diagnosed", "plan2code-quick-task"),
|
||||
fixed: state("Bug fixed", null, true),
|
||||
exploring: state("Exploring", "plan2code-0-pathfinder"),
|
||||
mapped: state("Ready to plan", "plan2code-1-plan"),
|
||||
planned: state("Ready to document", "plan2code-2-document"),
|
||||
documented: state("Ready to build", "plan2code-3-implement"),
|
||||
building: state("Building", "plan2code-3-implement"),
|
||||
built: state("Ready to finalize", "plan2code-4-finalize"),
|
||||
unrecognized: state("Files on disk", null),
|
||||
});
|
||||
|
||||
/** The entry for a state's name ("planned"), or null. */
|
||||
export function stateFor(name) {
|
||||
return Object.hasOwn(SPEC_STATES, name) ? SPEC_STATES[name] : null;
|
||||
}
|
||||
@@ -3,8 +3,10 @@
|
||||
// The source of truth for the Role list in User Preferences, the starter
|
||||
// templates on the first "What's the idea?" card of Pathfinder, Plan and Quick
|
||||
// Task, the order each role sees them in, and the starter questions an empty
|
||||
// Ask conversation offers. No DOM access at module scope and no imports: the
|
||||
// page and `node --test` both import this file.
|
||||
// Ask conversation offers. No DOM access at module scope, and its one import is
|
||||
// the data-only skills.js: the page and `node --test` both import this file.
|
||||
|
||||
import { SKILLS, takesTemplates } from "./skills.js";
|
||||
|
||||
const role = (id, label) => Object.freeze({ id, label });
|
||||
|
||||
@@ -20,7 +22,8 @@ export const ROLES = Object.freeze([
|
||||
export const ROLE_NOT_SET = "none";
|
||||
export const ROLE_NOT_SET_LABEL = "Not set / none of these";
|
||||
|
||||
export const TEMPLATE_WORKFLOWS = Object.freeze(["pathfinder", "plan", "quick-task"]);
|
||||
// The workflows whose first idea card offers templates, from skills.js.
|
||||
export const TEMPLATE_WORKFLOWS = Object.freeze(SKILLS.filter((s) => takesTemplates(s.workflow)).map((s) => s.workflow));
|
||||
|
||||
const ROLE_IDS = new Set(ROLES.map((r) => r.id));
|
||||
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// Plan2Code Web Console - the page's shared state and the redraw hook; defines only.
|
||||
//
|
||||
// `page` is the one object the page's state lives on, so every file that
|
||||
// draws reads and writes the same thing:
|
||||
// page.S the server's truth (state.json). Never mutated by the page.
|
||||
// page.local what the person has staged but not sent. Mirrored to
|
||||
// localStorage on every change, so a closed tab or a reload
|
||||
// loses nothing.
|
||||
// page.selected the question on screen, by id.
|
||||
// page.view the tab on screen.
|
||||
// and below them the rest of what more than one file reads or writes: the
|
||||
// server's word on the agent and on sends in flight, the frame's other
|
||||
// blocks, and the few page-local things a screen and the core share.
|
||||
//
|
||||
// A screen never calls the render loop or the draft's save itself: it calls
|
||||
// redraw() and saveNow(), which app.js points at screens/core.js at start-up.
|
||||
// Nothing here touches the page, so `node --test` imports this file and sets
|
||||
// the state directly.
|
||||
|
||||
export function fresh() {
|
||||
// `stopping` is set once a stop request has been accepted, and kept here so
|
||||
// a reload in the middle of wrapping up comes back to the same screen.
|
||||
// `afterBuild` is "review", "commit", "done" or "dashboard" once a finished session's
|
||||
// offer has been answered, so the buttons do not come back on a reload.
|
||||
// `homeward` is set once the top bar's Back to the dashboard request has
|
||||
// been accepted mid-workflow: { at }. The resume through the dashboard
|
||||
// resets `local` wholesale, which is what clears it.
|
||||
// `launching` is the dashboard's pick while the launched skill turns the
|
||||
// page: { skill, title, at }. Kept here so a reload mid-handoff comes back
|
||||
// to the getting-ready screen rather than the menu it already answered.
|
||||
// `specSel` is the dashboard picker's spec dir, or null for "start from
|
||||
// scratch". Left ABSENT until the picker is touched, which is how the
|
||||
// default (most recently touched spec) differs from a deliberate scratch.
|
||||
// `retract` marks a send the person took back, keyed to the send's `at` so
|
||||
// it suppresses exactly that `submitted` record and no later one.
|
||||
// `images` is each note's attachments, keyed by item id:
|
||||
// [{ key, id, path, url, name, status }], status "uploading" | "ready" | "failed".
|
||||
return {
|
||||
staged: {},
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
launching: null,
|
||||
// A picker Delete sent and not yet answered by a rescan: { dir, scanAt }.
|
||||
deleting: null,
|
||||
retract: {},
|
||||
chat: freshChat(),
|
||||
};
|
||||
}
|
||||
|
||||
// The Ask pane's own corner of `local`: the composer's draft and pictures,
|
||||
// what the next message is about, sends still on their way, and the newest
|
||||
// reply already seen (the dot). `conversation` is the one these belong to.
|
||||
export function freshChat() {
|
||||
return {
|
||||
draft: "",
|
||||
history: [],
|
||||
about: null,
|
||||
pending: [],
|
||||
lastSeenReplyId: null,
|
||||
images: [],
|
||||
conversation: null,
|
||||
};
|
||||
}
|
||||
|
||||
export const page = {
|
||||
S: null,
|
||||
local: fresh(),
|
||||
selected: null,
|
||||
view: "questions",
|
||||
|
||||
// What the server says around the state, from the last frame or ping: when
|
||||
// the agent last touched it, and whether a send or a stop is still waiting
|
||||
// to be picked up.
|
||||
agentLastSeen: null,
|
||||
pendingResult: false,
|
||||
pendingStop: false,
|
||||
// Set while a "still being picked up" banner is showing (see the frame handler).
|
||||
pendingBannerUp: false,
|
||||
// No contact with the server: the page is offline.
|
||||
gone: false,
|
||||
// The Quick question chat: the server's view of the current conversation
|
||||
// (the frame's `chat` block). The rest is page-local and gone on a reload:
|
||||
// `chatDot` is the Ask tab's dot as last drawn, so a reply chimes once;
|
||||
// `chatError` the line under the composer; `askRowCount` how many rows the
|
||||
// pane last showed, so a new one scrolls into view; `docInView` the doc
|
||||
// block nearest the top.
|
||||
chatFrame: null,
|
||||
chatDot: false,
|
||||
chatError: "",
|
||||
askRowCount: 0,
|
||||
docInView: null,
|
||||
// The frame's workspace ({ folders, missing, remote, issues }) and meter
|
||||
// ({ points, level, fraction, words, tooltip }), or null before a server that
|
||||
// sends them.
|
||||
wsFrame: null,
|
||||
meterFrame: null,
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
updateFrame: null,
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
subagentsFrame: null,
|
||||
// The spec's overview.md as last fetched: `key` is the spec dir it was read
|
||||
// for, `text` the file, or null when there is none. See loadOverview().
|
||||
overview: { key: null, text: null },
|
||||
// The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns
|
||||
// true at the glide, which lets the menu in; `entered` once its entrance has
|
||||
// played; `typed` is how many characters of the note show, or null once all
|
||||
// of them do. Page-local: the reload guard is sessionStorage (maybeWake).
|
||||
wake: null,
|
||||
// The dashboard pick being looked at on the confirm pane, before START is
|
||||
// pressed. Page-local like `view`: a reload simply shows the menu again.
|
||||
dashPick: null,
|
||||
// The `@name` suggestions popover, owned by whichever box last asked for it.
|
||||
mentionPop: null,
|
||||
// The pose pane on screen when a render began, held back from the clear so
|
||||
// posePane() can take it up again. See posePane.
|
||||
heldPose: null,
|
||||
// The workspace scope (a spec dir, "" for the project) this tab last asked
|
||||
// for: its own pick, not whatever the frame says. And true from a launch's
|
||||
// scope sync until its send has gone (or failed).
|
||||
scopeMine: null,
|
||||
launchScoping: false,
|
||||
};
|
||||
|
||||
let redrawHook = null;
|
||||
let saveHook = null;
|
||||
|
||||
// Draw the page again from `page`. A no-op until start-up sets the hook.
|
||||
export function redraw() {
|
||||
if (redrawHook) redrawHook();
|
||||
}
|
||||
|
||||
export function onRedraw(fn) {
|
||||
redrawHook = fn;
|
||||
}
|
||||
|
||||
// Keep `page.local` (this browser's copy, and the server's draft). A no-op
|
||||
// until start-up sets the hook.
|
||||
export function saveNow() {
|
||||
if (saveHook) saveHook();
|
||||
}
|
||||
|
||||
export function onSave(fn) {
|
||||
saveHook = fn;
|
||||
}
|
||||
|
||||
// What a screen needs from the core or from another screen: a function the
|
||||
// entry hands over once at start-up (useHooks) and the screen calls by name,
|
||||
// never by importing the file that defines it. Calling one before start-up
|
||||
// is a mistake the test suite catches, so it throws rather than doing nothing.
|
||||
const registered = {};
|
||||
export const hooks = new Proxy(registered, {
|
||||
get(target, name) {
|
||||
if (typeof name !== "string") return undefined;
|
||||
if (typeof target[name] !== "function") throw new Error(`hooks.${name} was called before start-up set it`);
|
||||
return target[name];
|
||||
},
|
||||
});
|
||||
|
||||
export function useHooks(fns) {
|
||||
Object.assign(registered, fns);
|
||||
}
|
||||
|
||||
// Stage an answer for a card (or take it back with null), keep the draft, draw.
|
||||
export function stage(id, value) {
|
||||
if (value == null) delete page.local.staged[id];
|
||||
else page.local.staged[id] = value;
|
||||
saveNow();
|
||||
redraw();
|
||||
}
|
||||
|
||||
export function setDraft(id, text) {
|
||||
page.local.drafts[id] = text;
|
||||
saveNow();
|
||||
}
|
||||
|
||||
// The first state, the saved looks and the draft, written into the page by the
|
||||
// server so the first real screen needs no round trip. A data block, never run
|
||||
// as script; read once, on first ask. Null when absent (an older server, a page
|
||||
// opened some other way): the page then asks for each as it always did.
|
||||
let bootBlock;
|
||||
export function bootData() {
|
||||
if (bootBlock === undefined) {
|
||||
try {
|
||||
bootBlock = JSON.parse(document.getElementById("boot").textContent);
|
||||
} catch {
|
||||
bootBlock = null;
|
||||
}
|
||||
}
|
||||
return bootBlock;
|
||||
}
|
||||
|
||||
// Where each tab was scrolled, keyed by view id, so switching away and back
|
||||
// lands where the person left it. Page-side only and never persisted: a reload
|
||||
// starts every tab at its top.
|
||||
export const scrollMemory = new Map();
|
||||
@@ -0,0 +1,179 @@
|
||||
/* ask.css: The Ask pane and its Quick question chat. */
|
||||
|
||||
/* ------------------------------------------------------------ ask pane */
|
||||
|
||||
/* The Quick question chat: one card-framed pane that fills the column. The
|
||||
conversation scrolls; the header and the composer stay put, so the counter,
|
||||
New conversation and Send are always in reach. */
|
||||
.main > .ask-pane {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule);
|
||||
border-radius: var(--radius);
|
||||
box-shadow: var(--shadow);
|
||||
overflow: hidden;
|
||||
}
|
||||
.ask-head {
|
||||
flex: none;
|
||||
display: flex; align-items: center; gap: 12px;
|
||||
padding: 16px 22px 14px;
|
||||
border-bottom: 1px solid var(--rule);
|
||||
}
|
||||
.ask-head h2 { font: 600 21px/1.2 var(--serif); margin: 0; flex: 1; }
|
||||
.ask-counter { font: 700 12px/1 var(--mono); color: var(--ink-3); }
|
||||
|
||||
.ask-list {
|
||||
flex: 1 1 auto;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
overscroll-behavior: contain;
|
||||
padding: 18px 22px;
|
||||
display: flex; flex-direction: column; gap: 10px;
|
||||
}
|
||||
/* An empty conversation's starter questions, centred where the list is empty. */
|
||||
.ask-starters { display: flex; flex-direction: column; gap: 6px; margin: auto 0; width: 100%; max-width: 520px; align-self: center; }
|
||||
.ask-starters-lead { color: var(--ink-3); font-size: 13.5px; margin: 0 0 4px; text-align: center; }
|
||||
.ask-starter {
|
||||
width: 100%;
|
||||
padding: 9px 13px;
|
||||
border: 1px solid var(--rule);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
font: inherit;
|
||||
font-size: 13.5px;
|
||||
color: var(--ink-2);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ask-starter:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent-line); color: var(--ink); }
|
||||
.ask-starter:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
||||
.ask-starter:disabled { opacity: 0.55; cursor: not-allowed; }
|
||||
|
||||
.ask-row {
|
||||
max-width: 86%;
|
||||
border-radius: var(--radius);
|
||||
padding: 10px 14px;
|
||||
font-size: 14px;
|
||||
border: 1px solid var(--rule);
|
||||
}
|
||||
.ask-row.person { align-self: flex-end; background: var(--accent-soft); border-color: var(--accent-line); }
|
||||
.ask-row.pending { border-style: dashed; background: transparent; }
|
||||
.ask-row.agent { align-self: flex-start; background: var(--panel-2); }
|
||||
.ask-row.decision { align-self: flex-end; background: transparent; border-style: dashed; color: var(--ink-2); font-size: 13px; }
|
||||
.ask-row .md { max-width: none; }
|
||||
.ask-row .md > :first-child { margin-top: 0; }
|
||||
.ask-row .md > :last-child { margin-bottom: 0; }
|
||||
.ask-row .attach-tray { margin: 8px 0 0; }
|
||||
.ask-text { margin: 0; white-space: pre-wrap; overflow-wrap: anywhere; }
|
||||
.ask-about { margin: 0 0 4px; font-size: 11.5px; font-weight: 600; color: var(--accent); }
|
||||
.ask-decision { margin: 0; font-weight: 600; }
|
||||
.ask-waiting { margin: 6px 0 0; font-size: 12px; color: var(--ink-3); display: flex; align-items: center; gap: 8px; }
|
||||
.ask-failed { color: var(--warn); }
|
||||
|
||||
.ask-proposal {
|
||||
margin-top: 10px; padding: 10px 12px;
|
||||
border: 1px solid var(--stage); border-radius: 8px;
|
||||
background: var(--stage-soft);
|
||||
}
|
||||
.ask-proposal .note-kicker { margin-bottom: 4px; }
|
||||
.ask-proposal-files, .ask-changed { margin: 6px 0 0; padding-left: 18px; font-size: 12.5px; }
|
||||
.ask-proposal-actions { display: flex; gap: 8px; align-items: center; margin-top: 10px; flex-wrap: wrap; }
|
||||
.ask-proposal-actions input[type="text"] { flex: 1 1 200px; width: auto; padding: 7px 10px; }
|
||||
.ask-decided { margin: 8px 0 0; font-weight: 700; font-size: 13px; }
|
||||
.ask-decided.approve { color: var(--ok); }
|
||||
.ask-decided.decline { color: var(--ink-2); }
|
||||
.ask-changed-count { font: 12px/1 var(--mono); color: var(--ink-3); }
|
||||
|
||||
.ask-composer {
|
||||
flex: none;
|
||||
padding: 12px 22px 16px;
|
||||
border-top: 1px solid var(--rule);
|
||||
background: var(--panel);
|
||||
}
|
||||
.ask-composer.is-dropping { outline: 2px dashed var(--accent); outline-offset: -6px; background: var(--accent-soft); }
|
||||
.ask-composer textarea { min-height: 64px; max-height: 40vh; }
|
||||
.ask-composer textarea:disabled { opacity: 0.6; cursor: not-allowed; }
|
||||
.ask-about-chip {
|
||||
display: inline-flex; align-items: center; gap: 8px;
|
||||
margin-bottom: 8px; padding: 3px 4px 3px 11px;
|
||||
border: 1px solid var(--accent-line); border-radius: 99px;
|
||||
background: var(--accent-soft); color: var(--accent);
|
||||
font-size: 12px; font-weight: 600;
|
||||
max-width: 100%;
|
||||
}
|
||||
.ask-about-chip > span { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ask-about-chip .attach-remove { position: static; flex: none; }
|
||||
.ask-actions { display: flex; flex-wrap: wrap; align-items: center; gap: 10px; margin-top: 8px; }
|
||||
/* + Add context and its menu. It opens upward, over the list: the composer
|
||||
sits at the bottom of a pane that clips anything hanging below it. */
|
||||
.ask-context { position: relative; }
|
||||
.ask-context-menu {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
bottom: calc(100% + 4px);
|
||||
z-index: 20;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: 220px;
|
||||
max-width: 340px;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.ask-context-item {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 10px;
|
||||
padding: 7px 10px;
|
||||
border: 0;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
font: inherit;
|
||||
font-size: 13px;
|
||||
color: var(--ink);
|
||||
text-align: left;
|
||||
cursor: pointer;
|
||||
}
|
||||
.ask-context-item:hover,
|
||||
.ask-context-item:focus-visible { background: var(--accent-soft); outline: none; }
|
||||
.ask-context-label { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.ask-context-kind { flex: none; font-size: 11px; color: var(--ink-3); }
|
||||
.ask-actions .btn.primary { margin-left: auto; }
|
||||
.ask-send-hint { margin-left: auto; font-size: 12px; color: var(--ink-3); white-space: nowrap; }
|
||||
.ask-send-hint + .btn.primary { margin-left: 0; }
|
||||
.ask-count { font: 12px/1 var(--mono); color: var(--ink-3); }
|
||||
.ask-count.is-over { color: var(--warn); font-weight: 700; }
|
||||
.ask-error { color: var(--warn); font-size: 13px; margin: 8px 0 0; }
|
||||
|
||||
/* The two reasons Send is off read differently, as their wording does: the
|
||||
limit is a plain fact, the missing agent is something to fix. */
|
||||
.ask-disabled-note { margin: 0; font-size: 12.5px; line-height: 1.35; padding: 6px 10px; border-radius: 8px; }
|
||||
.ask-disabled-note.is-limit, .ask-disabled-note.is-waiting { color: var(--ink-2); background: var(--panel-2); border: 1px solid var(--rule); }
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
/* A reply landed while another tab was open. */
|
||||
.view-tab .tab-dot {
|
||||
display: inline-block;
|
||||
width: 7px; height: 7px;
|
||||
margin-left: 6px;
|
||||
border-radius: 50%;
|
||||
background: var(--accent);
|
||||
vertical-align: middle;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,487 @@
|
||||
/* dashboard.css: The dashboard: the menu, the spec picker, its confirm and the launching pane. */
|
||||
|
||||
/* ------------------------------------------------------------ dashboard */
|
||||
|
||||
/* The dashboard replaces the question column with a menu, and the send bar
|
||||
with a click on a card. `hidden` alone loses to the bar's own display
|
||||
rule, so it needs saying here. */
|
||||
.footer[hidden] { display: none; }
|
||||
|
||||
.dash { max-width: 860px; padding-top: 8px; }
|
||||
.dash-title { margin: 6px 0 8px; font: 600 clamp(26px, 4vw, 36px)/1.1 var(--serif); }
|
||||
.dash-note { margin: 0 0 26px; font-size: 14.5px; color: var(--ink-2); }
|
||||
/* The first-run role nudge: one line above the title, wrapping on a narrow
|
||||
window, until looks.json carries a role. */
|
||||
.dash-nudge {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
gap: 10px 14px;
|
||||
margin: 0 0 18px;
|
||||
padding: 10px 14px;
|
||||
background: var(--accent-soft);
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: var(--radius);
|
||||
color: var(--ink);
|
||||
font-size: 14px;
|
||||
}
|
||||
.dash-nudge-text { flex: 1 1 16em; }
|
||||
/* The session meter at red: the same slot, in the careful colour. */
|
||||
.dash-nudge.meter-banner {
|
||||
background: var(--warn-soft);
|
||||
border-color: var(--warn);
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
width: fit-content;
|
||||
margin-top: 10px;
|
||||
padding: 7px 14px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-soft);
|
||||
border: 1px solid var(--accent-line);
|
||||
border-radius: 10px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.dash-group { margin-bottom: 30px; }
|
||||
|
||||
/* A switch, not a checkbox look: it filters the menu live rather than being
|
||||
an answer. The real checkbox stays in the tree (visually hidden) so the
|
||||
keyboard, focus ring and screen readers all work as for any input. */
|
||||
.dash-toggle {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
margin: -12px 0 26px;
|
||||
font-size: 13px;
|
||||
color: var(--ink-2);
|
||||
cursor: pointer;
|
||||
user-select: none;
|
||||
}
|
||||
.dash-toggle input { position: absolute; opacity: 0; width: 1px; height: 1px; pointer-events: none; }
|
||||
.dash-toggle-track {
|
||||
position: relative;
|
||||
flex: none;
|
||||
width: 34px;
|
||||
height: 20px;
|
||||
border-radius: 999px;
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2);
|
||||
transition: background 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
.dash-toggle-track::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
top: 2px;
|
||||
left: 2px;
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 50%;
|
||||
background: var(--ink-3);
|
||||
transition: transform 0.15s ease, background 0.15s ease;
|
||||
}
|
||||
.dash-toggle input:checked + .dash-toggle-track { background: var(--accent); border-color: var(--accent); }
|
||||
.dash-toggle input:checked + .dash-toggle-track::after { transform: translateX(14px); background: var(--accent-ink); }
|
||||
.dash-toggle input:focus-visible + .dash-toggle-track { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.dash-toggle:hover .dash-toggle-track { border-color: var(--accent-line); }
|
||||
|
||||
.dash-empty { margin: 0 0 30px; font-size: 13.5px; color: var(--ink-3); font-style: italic; }
|
||||
.dash-group-title {
|
||||
margin: 0 0 12px;
|
||||
font-size: 11.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.09em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ink-3);
|
||||
border-bottom: 1px solid var(--rule);
|
||||
padding-bottom: 8px;
|
||||
}
|
||||
|
||||
.dash-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(240px, 1fr)); gap: 12px; }
|
||||
|
||||
/* A card IS a button, so it carries the reset the page's other big clickable
|
||||
surfaces do; the look is the panel look with a lift on hover, and the
|
||||
accent border that elsewhere means "the thing in play". */
|
||||
.dash-card {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
padding: 16px;
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s ease, box-shadow 0.15s ease, border-color 0.15s ease;
|
||||
}
|
||||
.dash-card:hover:not(:disabled) {
|
||||
transform: translateY(-2px);
|
||||
border-color: var(--accent-line);
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.dash-card:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.dash-card:disabled { cursor: default; opacity: 0.55; }
|
||||
.dash-card.is-suggested { border-color: var(--accent); }
|
||||
.dash-card.is-going { border-color: var(--accent); opacity: 1; }
|
||||
|
||||
.dash-card-head { display: flex; align-items: center; justify-content: space-between; gap: 8px; }
|
||||
.dash-chip {
|
||||
font-size: 10.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--ink-3);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 999px;
|
||||
padding: 2px 8px;
|
||||
}
|
||||
.dash-card.is-suggested .dash-chip { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
.dash-card-title { font-size: 15px; font-weight: 650; }
|
||||
.dash-card-blurb { font-size: 13px; color: var(--ink-2); flex: 1; }
|
||||
.dash-card-detail { font-size: 12px; color: var(--accent); }
|
||||
|
||||
.dash-card-foot {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
margin-top: 4px;
|
||||
padding-top: 10px;
|
||||
border-top: 1px solid var(--rule);
|
||||
}
|
||||
/* Wraps at the dashes rather than cut off: a command missing its end
|
||||
("/plan2code-3-implement-revi…") is no command at all. */
|
||||
.dash-card-cmd {
|
||||
font-family: var(--mono);
|
||||
font-size: 11.5px;
|
||||
color: var(--ink-3);
|
||||
min-width: 0;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-card-go { color: var(--accent); font-weight: 700; transition: transform 0.15s ease; }
|
||||
.dash-card:hover:not(:disabled) .dash-card-go { transform: translateX(3px); }
|
||||
|
||||
/* The reason a card is off. The card greys via :disabled; this line is why,
|
||||
so the menu teaches the pipeline instead of just refusing clicks. */
|
||||
.dash-card-off { font-size: 12px; color: var(--ink-3); font-style: italic; }
|
||||
|
||||
/* -------------------------------------------------------- spec picker */
|
||||
|
||||
/* The picker's chips are the same vocabulary as the rail's items: a bordered
|
||||
lozenge that lights up on the current one. */
|
||||
.spec-pick { margin-bottom: 30px; }
|
||||
.spec-row { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.spec-chip {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 3px;
|
||||
padding: 10px 14px;
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
font: inherit;
|
||||
text-align: left;
|
||||
color: var(--ink);
|
||||
cursor: pointer;
|
||||
transition: border-color 0.15s ease, box-shadow 0.15s ease;
|
||||
}
|
||||
.spec-chip:hover { border-color: var(--accent-line); }
|
||||
.spec-chip:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
.spec-chip.is-sel { border-color: var(--accent); box-shadow: var(--shadow); }
|
||||
.spec-chip-name { font-size: 13.5px; font-weight: 650; }
|
||||
.spec-chip-state {
|
||||
font-size: 10.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--accent);
|
||||
}
|
||||
.spec-chip:not(.is-sel) .spec-chip-state { color: var(--ink-3); }
|
||||
.spec-chip-detail { font-size: 11.5px; color: var(--ink-3); }
|
||||
/* A handoff in the picker: the same lozenge, dashed, in the stage colour. */
|
||||
.spec-chip.is-handoff { border-style: dashed; }
|
||||
.spec-chip.is-handoff .spec-chip-state, .spec-chip.is-handoff:not(.is-sel) .spec-chip-state { color: var(--stage); }
|
||||
.spec-chip.is-handoff.is-sel { border-style: solid; border-color: var(--stage); }
|
||||
.spec-chip.is-handoff.is-deleting { opacity: 0.5; }
|
||||
|
||||
/* What a picked handoff shows under the picker. */
|
||||
.handoff-preview {
|
||||
margin: 0 0 30px;
|
||||
padding: 18px 20px;
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--stage);
|
||||
border-radius: var(--radius);
|
||||
}
|
||||
.handoff-preview-title { font: 600 20px/1.25 var(--serif); margin: 0 0 4px; }
|
||||
.handoff-preview-meta { margin: 0 0 14px; font-size: 12.5px; color: var(--ink-3); }
|
||||
.handoff-preview-label {
|
||||
margin: 0 0 3px;
|
||||
font-size: 10.5px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
color: var(--stage);
|
||||
}
|
||||
.handoff-preview-next { margin: 0 0 16px; font-size: 14px; color: var(--ink); }
|
||||
.handoff-preview-actions { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.handoff-preview-actions .btn.danger { margin-left: auto; }
|
||||
.modal.handoff-read { max-width: 720px; }
|
||||
.modal.handoff-read[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||
.handoff-body { flex: 1; min-height: 0; overflow-y: auto; margin-top: 8px; }
|
||||
.modal.handoff-read .modal-actions { flex: none; }
|
||||
|
||||
/* A spec's Delete button sits beside its chip, not inside it: a button cannot
|
||||
hold a button. Quiet until the chip is hovered or focused. */
|
||||
.spec-chip-wrap { position: relative; display: flex; }
|
||||
.spec-chip-wrap.is-fixed .spec-chip:not(.is-sel) { opacity: 0.6; }
|
||||
.spec-chip-wrap .spec-chip { padding-right: 36px; }
|
||||
.spec-chip-del {
|
||||
position: absolute;
|
||||
top: 6px;
|
||||
right: 6px;
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
padding: 0;
|
||||
border: 1px solid transparent;
|
||||
border-radius: 6px;
|
||||
background: transparent;
|
||||
color: var(--ink-3);
|
||||
font: inherit;
|
||||
font-size: 15px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
opacity: 0.55;
|
||||
}
|
||||
.spec-chip-wrap:hover .spec-chip-del,
|
||||
.spec-chip-del:focus-visible { opacity: 1; }
|
||||
.spec-chip-del:hover { color: var(--warn); border-color: var(--warn); opacity: 1; }
|
||||
.spec-chip-del:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
|
||||
.spec-chip-del:disabled { cursor: default; opacity: 0.3; }
|
||||
/* A fixed bug's Delete is always shown, as a pill at the chip's bottom right;
|
||||
the chip makes room below its lines so the pill never covers the name. The
|
||||
chip's is-fixed dimming targets .spec-chip, so the pill keeps full strength. */
|
||||
.spec-chip-wrap.is-fixed .spec-chip { padding-right: 14px; padding-bottom: 36px; }
|
||||
.spec-chip-del-label {
|
||||
position: absolute;
|
||||
right: 8px;
|
||||
bottom: 8px;
|
||||
padding: 2px 10px;
|
||||
border: 1px solid var(--warn);
|
||||
border-radius: 999px;
|
||||
background: var(--panel);
|
||||
color: var(--warn);
|
||||
font: inherit;
|
||||
font-size: 12.5px;
|
||||
font-weight: 600;
|
||||
line-height: 1.5;
|
||||
cursor: pointer;
|
||||
}
|
||||
.spec-chip-del-label:hover:not(:disabled) { background: var(--warn-soft); }
|
||||
.spec-chip-del-label:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
|
||||
.spec-chip-del-label:disabled { cursor: default; opacity: 0.4; }
|
||||
.spec-chip-wrap.is-deleting .spec-chip { opacity: 0.5; }
|
||||
.delete-facts { display: grid; grid-template-columns: auto 1fr; gap: 6px 14px; margin: 14px 0 0; font-size: 13.5px; }
|
||||
.delete-facts dt { color: var(--ink-3); }
|
||||
.delete-facts dd { margin: 0; overflow-wrap: anywhere; }
|
||||
.delete-confirm { margin-top: 16px; display: flex; flex-direction: column; gap: 8px; font-size: 13.5px; }
|
||||
.delete-confirm[hidden] { display: none; }
|
||||
.delete-confirm input {
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: var(--radius);
|
||||
background: var(--panel);
|
||||
color: var(--ink);
|
||||
font: inherit;
|
||||
}
|
||||
.delete-confirm input:focus-visible { outline: 2px solid var(--warn); outline-offset: 1px; }
|
||||
|
||||
/* ------------------------------------------------- dashboard confirm */
|
||||
|
||||
/* The beat between "I clicked a card" and "it is running": what the pick is,
|
||||
what it will do, and a START that means it. Narrower than the menu, centred
|
||||
like the launching pane it precedes. */
|
||||
.dash-confirm {
|
||||
max-width: 560px;
|
||||
margin: 3vh auto 0;
|
||||
display: grid;
|
||||
gap: 10px;
|
||||
justify-items: center;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
/* A smaller stage than the launching hero: the same sky, a moment shorter. */
|
||||
.confirm-stage { height: 130px; }
|
||||
.confirm-stage .sky .star { animation: star-fly var(--dur, 5s) linear var(--delay, 0s) infinite; }
|
||||
|
||||
.confirm-planny {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 12px;
|
||||
width: 58px;
|
||||
height: 80px;
|
||||
transform: translateX(-50%);
|
||||
filter: drop-shadow(0 6px 12px rgba(0, 0, 0, 0.35));
|
||||
}
|
||||
|
||||
.confirm-head { display: flex; align-items: center; gap: 8px; margin-top: 4px; }
|
||||
.dash-confirm .dash-title { margin: 2px 0 0; }
|
||||
.confirm-about { margin: 0; font-size: 14.5px; line-height: 1.55; color: var(--ink-2); }
|
||||
.confirm-detail { margin: 0; font-size: 13px; color: var(--accent); }
|
||||
.confirm-spec { margin: 0; font-size: 13px; color: var(--ink-2); }
|
||||
.confirm-spec code { font-family: var(--mono); font-size: 12px; }
|
||||
.confirm-cmd { margin: 2px 0 0; }
|
||||
.confirm-cmd code {
|
||||
font-family: var(--mono);
|
||||
font-size: 12.5px;
|
||||
color: var(--ink-2);
|
||||
background: var(--panel-2);
|
||||
border: 1px solid var(--rule);
|
||||
border-radius: 6px;
|
||||
padding: 4px 10px;
|
||||
}
|
||||
.confirm-actions { display: flex; gap: 10px; margin-top: 10px; }
|
||||
|
||||
/* ------------------------------------------------------- launching pane */
|
||||
|
||||
.launching {
|
||||
max-width: 560px;
|
||||
margin: 4vh auto 0;
|
||||
text-align: center;
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
justify-items: center;
|
||||
}
|
||||
|
||||
/* The same sky the dock fills behind Planny, here in a stage sized for a
|
||||
hero: the mask fades the stars at the edges exactly the way it does in
|
||||
the aside. */
|
||||
.launch-stage {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
height: 180px;
|
||||
overflow: hidden;
|
||||
-webkit-mask-image: radial-gradient(120% 100% at 50% 40%, #000 42%, transparent 78%);
|
||||
mask-image: radial-gradient(120% 100% at 50% 40%, #000 42%, transparent 78%);
|
||||
}
|
||||
.launch-sky { opacity: 0.9; }
|
||||
/* The dock only animates its stars while .is-flying; centre stage they are
|
||||
the show, so the flight runs unconditionally. */
|
||||
.launch-stage .sky .star { animation: star-fly var(--dur, 5s) linear var(--delay, 0s) infinite; }
|
||||
|
||||
.launch-planny {
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
bottom: 26px;
|
||||
width: 74px;
|
||||
height: 102px;
|
||||
margin-left: -37px;
|
||||
/* The dock's flight keyframes carry the forward lean; a second, slower bob
|
||||
on top keeps a long wait from reading as a loop on rails. */
|
||||
animation:
|
||||
planny-fly 1.7s ease-in-out infinite,
|
||||
launch-bob 3.4s ease-in-out infinite;
|
||||
}
|
||||
@keyframes launch-bob {
|
||||
0%, 100% { margin-bottom: 0; }
|
||||
50% { margin-bottom: 10px; }
|
||||
}
|
||||
|
||||
.launch-title { margin: 0; font: 600 clamp(24px, 4vw, 34px)/1.12 var(--serif); }
|
||||
.launch-quip {
|
||||
margin: 0;
|
||||
font-size: 14.5px;
|
||||
font-weight: 600;
|
||||
color: var(--accent);
|
||||
/* The line swaps on a timer; a minimum keeps the hint under it from
|
||||
hopping around as the words change length. */
|
||||
min-height: 1.4em;
|
||||
animation: launch-quip-in 0.35s ease-out;
|
||||
}
|
||||
@keyframes launch-quip-in {
|
||||
from { opacity: 0; transform: translateY(5px); }
|
||||
to { opacity: 1; transform: none; }
|
||||
}
|
||||
.launch-hint { margin: 0; font-size: 12.5px; color: var(--ink-3); max-width: 46ch; }
|
||||
/* A line, never a banner: no border, no background, no icon. */
|
||||
.approval-tip { margin: 18px 0 0; font-size: 12.5px; line-height: 1.5; color: var(--ink-3); }
|
||||
|
||||
Loaded 100 of 121 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user