mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
Add the web console Notepad and shared skill tables, release v2.10.0
AI Assisted
This commit is contained in:
1 parent
124beb46db
commit
f8b54ef708
59 files changed
+12549
-321
No files matched your search
@@ -52,6 +52,7 @@ plan2code/
|
||||
│ ├── 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
|
||||
│ ├── vendor-overtype.mjs # Dev-only: loads the vendored OverType in a browser and writes the CSS it would inject into `public/styles/notepad.css`, above the `/* end OverType */` marker; run it after upgrading the vendored file
|
||||
│ ├── 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`)
|
||||
@@ -178,7 +179,7 @@ Do not run `skills add` against the repository root: recursive discovery also fi
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. The list of skills with a console is duplicated as `CONSOLE_WORKFLOWS` in `public/answers.js` (it decides whether a copied hand-off asks the next session for the console); a test fails if the two disagree.
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from each `SKILLS` entry's `card` in `public/skills.js`, through `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. `CONSOLE_WORKFLOWS` in `public/answers.js`, built from the same `SKILLS` list, decides whether a copied hand-off asks the next session for the console.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
@@ -186,21 +187,23 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||
| `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-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
|
||||
| `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 |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
|
||||
| `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()` |
|
||||
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) 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 |
|
||||
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
|
||||
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
|
||||
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
|
||||
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
|
||||
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
|
||||
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, or into Git); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
|
||||
| `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 |
|
||||
@@ -208,7 +211,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `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/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. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
|
||||
| `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 |
|
||||
@@ -244,11 +247,16 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `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, `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/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/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 |
|
||||
| `notepads.mjs` | the notepad store, the only code that names, reads, writes and removes notepads, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests): `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `readNotepad()` (never creates or writes anything), `saveNote()` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures at most, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notepad's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `IMAGE_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), `withoutStyleAttrs()` (OverType's HTML without its inline `style` attributes, which the policy refuses: a link's `anchor-name` moves to `data-anchor`), `topLevelParts()` and `changedRange()` (the styled layer cut into its top-level elements as strings, and which run of them changed) and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notepad: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one OverType editor (made on first open, after setting `OverType.stylesInjected = true`), the text read from `GET /notepad` on every open (the editor is read-only until the first read lands, so nothing typed into an empty editor is saved over the note), and autosave through `nextSave()` to `POST /notepad/text`, flushed on close and when the tab is hidden. Three things lean on OverType's internals: `buildWithoutStyleAttrs()` swaps `document.createElement` only while the editor is built, so the elements OverType makes (its preview and its link tooltip among them) get an `innerHTML` that runs `withoutStyleAttrs()`; `patchPreview()`, behind that same `innerHTML` on the preview, swaps only the lines that changed (a whole-note redraw took about 310 ms a key at 200 KB) and clears the code-fence shading OverType re-applies right after; and `linkTooltip.findAnchorElement` is pointed at `data-anchor` |
|
||||
| `public/vendor/overtype.esm.js` | OverType 2.6.1 (MIT), vendored unchanged from `https://cdn.jsdelivr.net/npm/overtype@2.6.1/dist/overtype.esm.js` (sha256 `87bc797660d2b1cf6bc13551be6fa9ffa6393a98af453293c0530d5ca4950874`): the Notepad's styled-in-place Markdown editor over a real textarea. Regenerate the CSS with `scripts/vendor-overtype.mjs` after any upgrade, then recheck what `screens/notepad.js` relies on: `updatePreview()` setting `preview.innerHTML` then calling `_applyCodeBlockBackgrounds()`, the elements `_createDOM()` and `LinkTooltip.createTooltip()` make with `document.createElement`, `_init()` reporting its first value through `onChange`, the `anchor-name` style on links and `linkTooltip.findAnchorElement()`, and `OverType.stylesInjected` |
|
||||
| `public/styles/notepad.css` | OverType's generated CSS (between its header and `/* end OverType */`, rewritten by `scripts/vendor-overtype.mjs`, since the page's `style-src 'self'` blocks the `<style>` OverType would inject), then the notepad's own rules: OverType's theme mapped onto the console's tokens, one monospace font at one size, the top bar button and the dialog |
|
||||
| `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 |
|
||||
@@ -274,9 +282,9 @@ Key design points:
|
||||
- **`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**.
|
||||
- **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, folder? }], bytes }` (`folder` on `notepad:` items only), 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`, `notepads`), `notepad:<key>` (a month-old notepad, whole; see Notepad below) 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 `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.
|
||||
- **`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`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), 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 `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.
|
||||
@@ -310,11 +318,12 @@ Key design points:
|
||||
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
|
||||
- **`__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`).
|
||||
- **Notepad: the person's, one per folder, in `~/.plan2code/notepads/`, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads), and holds `meta.json` (`{ v, folder, created }`, written once), `note.md` and `images/<uuid>.jpg` with `<uuid>.thumb.jpg`. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. The page reaches it through six routes, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad` (`{ text, savedAt, images: [{ id, url, thumb }] }`), `POST /notepad/text` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image` and `POST /notepad/thumb?id=<uuid>` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete` (`{ id }`) and `GET /notepad/images/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`); the four POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }`. None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The CSP workaround.** OverType 2.6.1 (MIT, vendored unchanged as `public/vendor/overtype.esm.js`) adds a `<style>` element and inline `style` attributes, both of which `style-src 'self'` refuses: `screens/notepad.js` sets `OverType.stylesInjected = true` before making the one editor, OverType's own CSS ships at the top of `styles/notepad.css` (in `CSS_ORDER`, so it rides the joined stylesheet), and `withoutStyleAttrs()` strips the attributes from what OverType renders. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading OverType:** replace the vendored file from `https://cdn.jsdelivr.net/npm/overtype@<version>/dist/overtype.esm.js`, update its version and sha256 in its files-table row and the version in `HEADER` in `scripts/vendor-overtype.mjs`, run `node scripts/vendor-overtype.mjs` (needs a local Chrome or Edge; it rewrites only what sits above `/* end OverType */` and refuses a `notepad.css` without the marker), recheck the internals listed in the vendored file's row, then run the two notepad test files. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notepad for <folder>" by `screens/cleanup.js`, the key when it is missing) only when `staleNotepads()` finds the newest file in it (`newestMtime()` in `files.mjs`) `SESSION_MAX_AGE_MS` (30 days) old or more; `removeCleanup()` removes the whole folder through `removeNotepad()` (key checked against `NOTEPAD_KEY_RE`, contained in `notepadsDir()`, a link refused).
|
||||
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 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.
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 18 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **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.
|
||||
|
||||
|
||||
@@ -143,13 +143,12 @@ 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 (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`).
|
||||
3. Register it with the web console. The meter's points and labels, the resume command, Help's card list and `console.mjs help`'s workflow list are all derived from `skills.js`, so the edits are `skills.js`, `install.js` (step 2), the skill's prompt (step 1), its pose and its notes; `npm test` names anything else left out:
|
||||
- `src/web-console/public/skills.js`: one entry (workflow, label, start pose, flags, subagents line, the meter's `weight`, `started` and `ran`, and `resume`) with its card (plus `help` when Help's line should differ from the blurb), and the card's `states` and `greyed`. Utilities go in group `"extra"` before Changelog.
|
||||
- `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`), unless its `pose` borrows an existing one (as Implement + Review borrows Implement's).
|
||||
- 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.
|
||||
- `console.md` (the `open --workflow` list and the `notes/<workflow>.md` row).
|
||||
- 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`.
|
||||
|
||||
+45
-5
@@ -146,6 +146,8 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
- **Files in your notes.** Show instead of describe: attach a screenshot, a
|
||||
photo or a document to any note or quick question (see *Attachments in notes
|
||||
and questions* below).
|
||||
- **A notepad of your own.** One per project folder, for jottings and
|
||||
screenshots that are yours, not the agent's (see *Your notepad* below).
|
||||
- **A nudge when it might be waiting on you.** Your agent may stop in the
|
||||
terminal to ask permission for something, and the page cannot see that. So
|
||||
the dashboard and every starting screen carry a one-line tip about hands-off
|
||||
@@ -406,6 +408,35 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||
they show in the tab too.
|
||||
|
||||
### Your notepad
|
||||
|
||||
The **Notepad** icon in the top bar, on the dashboard, every skill and the
|
||||
finished screen, opens a large dialog with a scratch pad for the folder you are
|
||||
working in.
|
||||
|
||||
- **Markdown, styled as you type.** Headings, lists, bold and code take their
|
||||
look in place while the text itself stays plain Markdown (saved as
|
||||
`note.md`, up to 1 MB).
|
||||
- **Pictures beside it.** Paste a screenshot, drop files on the dialog or press
|
||||
**Add image**: each becomes a thumbnail in a strip under the text (up to 200).
|
||||
Click one for a full-screen preview (arrow keys step through, Esc closes);
|
||||
its **X** asks before it deletes.
|
||||
- **It saves itself**, about a second after you stop typing and when you close
|
||||
the dialog. If the connection drops, your text stays in the page and is
|
||||
retried, and the tab warns before you close it with something unsaved.
|
||||
- **One per folder, kept between sessions.** Every session started in the same
|
||||
folder (each git worktree counts as its own) opens the same notepad, in
|
||||
`~/.plan2code/notepads/<folder-name>-<12 hex>/`: `meta.json` (which folder it
|
||||
belongs to), `note.md` and `images/`. Two pages open on one folder share it,
|
||||
and the last save wins.
|
||||
- **Private.** It never goes into your project, your session or anything the
|
||||
agent reads, so the agent never sees it. It stays on this machine.
|
||||
- **Removed only when you say.** No automatic cleanup touches it. Once the
|
||||
newest file in a notepad is 30 days old or more, *User Preferences →
|
||||
Cleanup* offers it as one item named after its folder's full path
|
||||
(*Notepad for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notepad, text and pictures.
|
||||
|
||||
### Session meter
|
||||
|
||||
A small ring pill in the top bar — **Session: fresh** (green), **Session:
|
||||
@@ -707,6 +738,7 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notepad for one folder: `meta.json`, `note.md` and `images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
||||
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
||||
@@ -738,8 +770,10 @@ needed: sessions untouched for 30 days (never the one you are in), anything at
|
||||
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||
`console/`, `bin/`, `launcher.json`, `install.json` (what you installed, which
|
||||
`plan2code update` reads), `models.json` and `handoffs/` (old handoffs go by
|
||||
age, above). It also lists each
|
||||
`plan2code update` reads), `models.json`, `handoffs/` (old handoffs go by
|
||||
age, above) and `notepads/`. Each notepad whose newest file is 30 days old or
|
||||
more is listed as one item, *Notepad for* its folder, and goes whole; no
|
||||
automatic sweep ever removes one. It also lists each
|
||||
folder in the project's `specs--completed/` whose newest file is more than 30
|
||||
days old: archived specs Finalize moved there. Deleting one is permanent:
|
||||
`specs--completed/` is usually gitignored, so git can't restore it. A stray is listed once
|
||||
@@ -778,7 +812,7 @@ this:
|
||||
|
||||
### Routes
|
||||
|
||||
The upload routes, the send, the overview and handoff reads, and the workspace. Like every page route, they are on `127.0.0.1`
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the notepad. Like every page route, they are on `127.0.0.1`
|
||||
behind the session cookie, and the ones that write also check the request's
|
||||
origin.
|
||||
|
||||
@@ -797,6 +831,12 @@ origin.
|
||||
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||
| `GET /notepad` | The notepad for the folder this session runs in: `{ text, savedAt, images: [{ id, url, thumb }] }`. Reading never creates a file. |
|
||||
| `POST /notepad/text` | `{ text }`. Saves `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 413 `too-long` (over 1 MB). |
|
||||
| `POST /notepad/image` | Raw `image/jpeg` (the page re-encodes every picture first). Writes `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures). |
|
||||
| `POST /notepad/thumb?id=<uuid>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found`, 415 `not-jpeg`, 413 `too-large`. |
|
||||
| `POST /notepad/image/delete` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found`. |
|
||||
| `GET /notepad/images/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
||||
|
||||
## For maintainers
|
||||
@@ -805,12 +845,12 @@ origin.
|
||||
| --- | --- |
|
||||
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
|
||||
| Ships as | `skills/<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`) |
|
||||
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/skills.js` (each entry's `card`; `SKILL_CATALOG` in `public/answers.js` is a lookup on it) |
|
||||
| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/<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 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 |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and OverType 2.6.1 (MIT) for the notepad's editor; the page's policy blocks the `<style>` OverType injects, so its CSS ships in `public/styles/notepad.css`, regenerated by `node scripts/vendor-overtype.mjs` after an upgrade (steps in the architecture doc's Notepad point) |
|
||||
|
||||
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
|
||||
`npm run build:skills` and commit it with the source change, since `npm test`
|
||||
|
||||
@@ -42,7 +42,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notepad** in the top bar (Markdown and pictures, one per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -103,5 +103,6 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- 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 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.
|
||||
- When `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", 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, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone).
|
||||
- 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`.
|
||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||
@@ -2,6 +2,27 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v2.10.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: a private **Notepad** in the top bar, on every screen. It opens a modal with a Markdown editor that styles as you type (OverType 2.6.1, vendored, MIT) and saves as you go, with pictures: paste, drag and drop or **Add image**, each shrunk to JPEG in the browser, shown as a thumbnail strip with an X that asks before deleting, and a full-screen preview. There is one notepad per project folder, kept in `~/.plan2code/notepads/` (`notepads.mjs`) and never shown to the agent. User Preferences → Cleanup offers a notepad for removal only when its newest file is 30 days old or more, as one item that removes the whole folder; the automatic sweep at open never touches it.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the dashboard has one Implement card instead of Implement and Implement + Review. Its confirm pane has a Review checkbox, ticked by default, that launches Implement + Review when ticked and plain Implement when not; the command shown follows the box.
|
||||
- **web console**: `open` and `handoff new` refuse a `--workflow` the console does not know (exit 2, naming the valid ones), instead of opening a session no skill answers. `open` with no `--workflow` still opens Pathfinder.
|
||||
- **web console**: Help's list of dashboard cards is built from the cards themselves, so it can never name a card the dashboard lacks: it follows the dashboard's order (Handoff last under *Useful any time*), and X-ray's line is its card's.
|
||||
- **web console**: a hop into Git from any skill now starts the page clean on both sides. The server always cleared it; the page kept the last skill's tab and staged answers.
|
||||
- **contributors**: the per-skill tables that were still kept by hand now come from `public/skills.js`: the meter's weights and labels (`WEIGHTS`, `LAUNCH_LABELS`, `RUN_LABELS` in `meter.js`), `resumeCommand()`'s switch in `answers.js`, Help's card list in `index.html` (now filled by `buildHelp()` in `screens/help-dialog.js`) and `cmd-help.mjs`'s workflow list. Each entry gains `weight`, `started`, `ran`, `resume` and an optional `card.help`, and `skills.js` exports `WORKFLOWS` and `isWorkflow()`. A test fails, naming the file and the name, when `console.md`, `src/plan2code.md` or the CLI's help drift from the list.
|
||||
- **contributors**: two new shared modules. `src/web-console/spec-files.mjs` holds the task markers and the task-line, checkbox and Status-line patterns with `statusOf()` and `countTasks()`, read by `scan.mjs` and the `specs.mjs` skill script, which no longer keep copies of their own; `patches.mjs` now takes `TASK_LINE_RE` from it instead of from `scan.mjs`. `src/web-console/public/hops.js` holds `startsClean()`, the rule for which hops start the page clean, called by `cmd-open.mjs`, `server.mjs` and `screens/core.js`.
|
||||
- **contributors**: for the upstream port, these moved: the meter tables, `resumeCommand()`'s switch, Help's card markup and `cmd-help`'s workflow list into `skills.js` fields; the markers and patterns in `scan.mjs` and `specs.mjs` into `spec-files.mjs` (and `TASK_LINE_RE` tightened on the way: exactly one space before the box and a case-sensitive `Task`, matching `TASK_ID_RE`; keep that when porting); the hop test in `cmd-open.mjs`, `server.mjs` and `screens/core.js` into `hops.js`. Port upstream's changes to those tables into `skills.js` and the two modules, not back into the old files.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: Workspace's Browse… folder picker (and the launcher's) no longer opens behind the browser on Windows. Windows refused the picker's `SetForegroundWindow`, because the picker is spawned by the detached console server and is not the process that last had input; the existing topmost flag is ignored by that dialog. It now waits until the dialog is visible, taps Alt (which lifts the foreground lock for the next call), and takes the foreground.
|
||||
- **dashboard**: an assumed task (`[?]`) counts as done and is named in the spec's line ("3 of 4 tasks done, 1 assumed"). It used to be left out of the count altogether, so that phase read "2 of 3 tasks done", and a spec whose tasks were all assumed read as not started. Numbered task lines (`1. [x] **Task ...`) count too, on the dashboard and in the `specs.mjs` skill script.
|
||||
|
||||
## v2.9.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
||||
|
||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||
|
||||
Version 2.9.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 2.10.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -417,7 +417,7 @@ edits out through the skills CLI.
|
||||
|
||||
Core reference:
|
||||
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notepad in the top bar
|
||||
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
|
||||
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
|
||||
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.9.0",
|
||||
"version": "2.10.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -8,7 +8,7 @@
|
||||
"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-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"
|
||||
"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-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0",
|
||||
|
||||
@@ -245,6 +245,29 @@ test("specs: open tasks under approved phases are a checkoff, and tick checks th
|
||||
assert.equal(S("tick", "lunch-vote", "--task", "nope").code, 2);
|
||||
});
|
||||
|
||||
test("specs: numbered task lines are tasks, counted by status and ticked by tick", () => {
|
||||
const root = specFixture();
|
||||
// phase() writes "- [m]" lines; renumber phase 1 as a numbered list.
|
||||
write(root, "specs/lunch-vote/phase-1.md", phase(1, "In Progress", [["x", "1.1"], [" ", "1.2"]]).replace("- [x] **Task 1.1:**", "1. [x] **Task 1.1:**").replace("- [ ] **Task 1.2:**", "2. [ ] **Task 1.2:**"));
|
||||
assert.match(read(root, "specs/lunch-vote/phase-1.md"), /^1\. \[x\] \*\*Task 1\.1:\*\* Do 1\.1\n2\. \[ \] \*\*Task 1\.2:\*\* Do 1\.2$/m);
|
||||
const S = (...a) => runScript("plan2code-3-implement", "specs.mjs", [...a, "--root", root]);
|
||||
const st = S("status", "lunch-vote");
|
||||
assert.equal(st.code, 0, st.stderr);
|
||||
const p1 = st.json.phases.find((p) => p.number === 1);
|
||||
assert.equal(p1.tasks.total, 2);
|
||||
assert.equal(p1.tasks.complete, 1);
|
||||
assert.deepEqual(p1.openTasks, ["1.2"]);
|
||||
assert.ok(!st.json.checks.some((c) => c.code === "uncounted-task" && /phase-1/.test(c.message)), JSON.stringify(st.json.checks));
|
||||
|
||||
const t = S("tick", "lunch-vote", "--task", "1.2");
|
||||
assert.equal(t.code, 0, t.stderr);
|
||||
assert.equal(t.json.changed, true);
|
||||
assert.match(read(root, "specs/lunch-vote/phase-1.md"), /^2\. \[x\] \*\*Task 1\.2:\*\* Do 1\.2\n > Confirmed done by the user on \d{4}-\d{2}-\d{2}\.$/m);
|
||||
const after = S("status", "lunch-vote").json.phases.find((p) => p.number === 1);
|
||||
assert.equal(after.tasks.complete, 2);
|
||||
assert.deepEqual(after.openTasks, []);
|
||||
});
|
||||
|
||||
test("specs status: drift between the checklist and the phase files is an error", () => {
|
||||
const root = specFixture();
|
||||
write(root, "specs/lunch-vote/overview.md", OVERVIEW.replace("- [/] [Phase 2", "- [x] [Phase 2"));
|
||||
@@ -516,7 +539,9 @@ test("specs: --set cannot override computed fields; empty overview exists; uncou
|
||||
assert.equal(runScript("plan2code-2-document", "specs.mjs", ["metrics", "lunch-vote", "--step", "document", "--set", "verification_items_added=1", "--set", "total_tasks=99", "--root", root]).code, 2);
|
||||
write(root, "specs/lunch-vote/phase-2.md", read(root, "specs/lunch-vote/phase-2.md") + "- [ ] **Task 2.4A:** odd\n1. [ ] **Task 2.5:** numbered\n");
|
||||
const j = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 2);
|
||||
// Task 2.4A is flagged; a numbered task line is counted like any other (spec-files.mjs).
|
||||
assert.equal(j.checks.filter((c) => c.code === "uncounted-task").length, 1);
|
||||
assert.ok(j.phases.find((p) => p.number === 2).openTasks.includes("2.5"));
|
||||
write(root, "specs/lunch-vote/overview.md", "");
|
||||
const e = runScript("plan2code-3-implement", "specs.mjs", ["status", "lunch-vote", "--root", root]).json;
|
||||
assert.equal(e.overview, "overview.md");
|
||||
|
||||
@@ -339,6 +339,13 @@ test("handoff new refuses bad usage with 2 and a bad value with 3", () => {
|
||||
assert.equal(run(["handoff", "new", "--skill", "plan2code-quick-task"]).status, 2);
|
||||
assert.equal(run(["handoff", "list"]).status, 2);
|
||||
assert.equal(run(["handoff"]).status, 2);
|
||||
// A name newHandoff() would take (lowercase and dashes) but no workflow
|
||||
// the console knows: refused as usage before anything is written (FR-5).
|
||||
const before = fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR).sort() : [];
|
||||
const unknown = run(["handoff", "new", "--workflow", "x-ray", "--skill", "plan2code-xray"]);
|
||||
assert.equal(unknown.status, 2, unknown.stderr);
|
||||
assert.match(unknown.stderr, /unknown workflow "x-ray"; one of: .*, xray, /);
|
||||
assert.deepEqual(fs.existsSync(HANDOFFS_DIR) ? fs.readdirSync(HANDOFFS_DIR).sort() : [], before, "no new file in the handoffs folder");
|
||||
const bad = run(["handoff", "new", "--workflow", "quick-task", "--skill", "plan2code-quick-task", "--spec", "../x"]);
|
||||
assert.equal(bad.status, 3);
|
||||
assert.equal(bad.json.ok, false);
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
} from "../src/web-console/public/answers.js";
|
||||
import { WORKFLOWS } from "../src/web-console/public/skills.js";
|
||||
import {
|
||||
HOME,
|
||||
MODELS_DIR,
|
||||
@@ -214,6 +215,38 @@ test("open --resume restates workflow, title and spec on the live session", () =
|
||||
fs.writeFileSync(stateFile, snapshot);
|
||||
});
|
||||
|
||||
// A workflow name the console does not know (x-ray for xray) is refused as bad
|
||||
// usage before anything is made: no session folder for a fresh open, and no
|
||||
// write over the resumed session's good name (FR-5).
|
||||
test("open refuses an unknown --workflow and makes no session folder", () => {
|
||||
const sessionsDir = path.join(HOME, "sessions");
|
||||
const before = fs.readdirSync(sessionsDir).sort();
|
||||
const res = cli(["open", "--no-open", "--workflow", "x-ray"], { expectFail: true });
|
||||
assert.equal(res.status, 2, res.stderr);
|
||||
assert.match(res.stderr, /unknown workflow "x-ray"/);
|
||||
for (const name of WORKFLOWS) assert.ok(res.stderr.includes(name), `stderr lists ${name}`);
|
||||
assert.deepEqual(fs.readdirSync(sessionsDir).sort(), before, "no session folder was created");
|
||||
});
|
||||
|
||||
test("open --resume refuses an unknown --workflow and leaves the state alone", () => {
|
||||
const stateFile = path.join(session, "state.json");
|
||||
const bytes = fs.readFileSync(stateFile);
|
||||
const res = cli(["open", "--resume", sid, "--no-open", "--workflow", "x-ray"], { expectFail: true });
|
||||
assert.equal(res.status, 2, res.stderr);
|
||||
assert.match(res.stderr, /unknown workflow "x-ray"/);
|
||||
assert.ok(fs.readFileSync(stateFile).equals(bytes), "state.json is byte for byte the same");
|
||||
});
|
||||
|
||||
test("open with no --workflow still opens a Pathfinder session", () => {
|
||||
const res = cli(["open", "--no-open"]);
|
||||
try {
|
||||
assert.equal(res.json.ok, true);
|
||||
assert.equal(readState(res.json.session).workflow, "pathfinder");
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
// Plan -> Back to the dashboard -> Document used to show Plan's questions,
|
||||
// sections and doc tabs under Document's name: the resume only renamed the
|
||||
// workflow. A switch through the dashboard is a fresh start, so it is blank.
|
||||
|
||||
@@ -66,6 +66,7 @@ import {
|
||||
pendingNote,
|
||||
reviewOffer,
|
||||
SKILL_CATALOG,
|
||||
launchVariant,
|
||||
SPEC_STATE_LABELS,
|
||||
STALE_MS,
|
||||
STOP_REPLY,
|
||||
@@ -118,6 +119,8 @@ import {
|
||||
runPoints,
|
||||
tooltipFor,
|
||||
WEIGHTS,
|
||||
LAUNCH_LABELS,
|
||||
RUN_LABELS,
|
||||
} from "../src/web-console/public/meter.js";
|
||||
import {
|
||||
blockFor,
|
||||
@@ -156,6 +159,7 @@ import {
|
||||
} 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 { startsClean } from "../src/web-console/public/hops.js";
|
||||
import { chatReplyLines } from "../src/web-console/inbox.mjs";
|
||||
import {
|
||||
initialWorkspace,
|
||||
@@ -329,6 +333,34 @@ test("the page's own resume command is built only from what the session says", (
|
||||
assert.equal(resumeCommand({ workflow: "handoff" }), "/plan2code-handoff");
|
||||
});
|
||||
|
||||
// resumeCommand() reads the entry's `resume`: one case per kind.
|
||||
test("the resume command follows the entry's resume kind, and an unknown workflow resumes as Pathfinder", () => {
|
||||
// "overview"
|
||||
assert.equal(resumeCommand({ workflow: "document", specDir: "specs/lunch-vote" }), "/plan2code-2-document specs/lunch-vote/overview.md");
|
||||
assert.equal(resumeCommand({ workflow: "document" }), "/plan2code-2-document");
|
||||
// "folder"
|
||||
assert.equal(resumeCommand({ workflow: "pathfinder", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
|
||||
assert.equal(resumeCommand({ workflow: "pathfinder" }), "/plan2code-0-pathfinder");
|
||||
// null: a spec is ignored
|
||||
assert.equal(resumeCommand({ workflow: "review", specDir: "specs/lunch-vote" }), "/plan2code-review");
|
||||
// An old session's workflow the console no longer knows
|
||||
assert.equal(resumeCommand({ workflow: "made-up", specDir: "specs/lunch-vote" }), "/plan2code-0-pathfinder specs/lunch-vote/pathfinder");
|
||||
assert.equal(resumeCommand({}), "/plan2code-0-pathfinder");
|
||||
});
|
||||
|
||||
test("a hop starts the page clean to or from the dashboard and into Git, and nowhere else", () => {
|
||||
assert.equal(startsClean("implement", "dashboard"), true);
|
||||
assert.equal(startsClean("dashboard", "plan"), true);
|
||||
assert.equal(startsClean("changelog", "git"), true);
|
||||
assert.equal(startsClean("finalize", "git"), true);
|
||||
assert.equal(startsClean("git", "changelog"), false);
|
||||
assert.equal(startsClean("implement", "review"), false);
|
||||
assert.equal(startsClean("git", "git"), false);
|
||||
assert.equal(startsClean("dashboard", "dashboard"), false);
|
||||
assert.equal(startsClean(undefined, "git"), false);
|
||||
assert.equal(startsClean("plan", undefined), false);
|
||||
});
|
||||
|
||||
test("the review offer is read from true or a label, and absent otherwise", () => {
|
||||
assert.equal(reviewOffer({ command: "/x" }), null);
|
||||
assert.equal(reviewOffer({ command: "/x", review: false }), null);
|
||||
@@ -1017,7 +1049,10 @@ test("a verdict's button text never renders blank", () => {
|
||||
test("the dashboard matrix lights only the cards a spec state allows", () => {
|
||||
const scan = { hasAgents: true };
|
||||
const sel = (state) => ({ dir: "specs/x", name: "x", state });
|
||||
const entry = (skill) => SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
const entry = (skill) => {
|
||||
const own = SKILL_CATALOG.find((e) => e.skill === skill);
|
||||
return own || launchVariant(SKILL_CATALOG.find((e) => e.review === skill), true);
|
||||
};
|
||||
const on = (skill, sc, s) => cardAvailability(entry(skill), sc, s).on;
|
||||
|
||||
// AGENTS.md gates the setup pair, whatever the picker holds.
|
||||
@@ -2142,3 +2177,30 @@ test("initialWorkspace names the original folder after itself and marks it origi
|
||||
assert.deepEqual(ws.folders[0], { id: "f0", path: path.join("C:", "git", "My Repo"), name: "my-repo", description: "", original: true });
|
||||
assert.deepEqual([ws.missing, ws.changes, ws.remote], [[], [], ""]);
|
||||
});
|
||||
|
||||
// The meter's tables are built from skills.js plus the events that are not a
|
||||
// skill's own. Held to their values when they were written by hand.
|
||||
test("meter: the weights and labels built from the skill list are the ones written by hand before", () => {
|
||||
assert.deepEqual({ ...WEIGHTS }, {
|
||||
"pathfinder-chart": 2, "pathfinder-question": 0, "pathfinder-research": 1,
|
||||
plan: 2, "revise-plan": 1, document: 2, "implement-phase": 2, "implement-review-phase": 3,
|
||||
review: 2, "quick-task": 1, init: 2, "init-update": 2, finalize: 1, handoff: 0, git: 1,
|
||||
"git-commits": 0, "git-conflict": 1, changelog: 1, xray: 1, diagnose: 1,
|
||||
});
|
||||
assert.deepEqual({ ...LAUNCH_LABELS }, {
|
||||
plan: "Plan started", "revise-plan": "Revise plan started", document: "Document started",
|
||||
review: "Review started", "quick-task": "Quick task started", init: "Init started",
|
||||
"init-update": "Init update started", finalize: "Finalize started", git: "Git started",
|
||||
changelog: "Changelog started", xray: "X-ray started", diagnose: "Diagnose started",
|
||||
});
|
||||
assert.deepEqual({ ...RUN_LABELS }, {
|
||||
"pathfinder-chart": "Pathfinder map written", "pathfinder-question": "Pathfinder question settled",
|
||||
"pathfinder-research": "Pathfinder research done", plan: "Plan drafted", "revise-plan": "Plan revised",
|
||||
document: "Spec documented", "implement-phase": "Implement phase built",
|
||||
"implement-review-phase": "Implement + Review phase built", review: "Code review run",
|
||||
"quick-task": "Quick task built", init: "Init run", "init-update": "Init update run",
|
||||
finalize: "Finalize run", handoff: "Handoff written", git: "Git run", "git-commits": "Commits in Git",
|
||||
"git-conflict": "Git conflict help", changelog: "Changelog run", xray: "X-ray run", diagnose: "Diagnose run",
|
||||
});
|
||||
for (const t of [WEIGHTS, LAUNCH_LABELS, RUN_LABELS]) assert.ok(Object.isFrozen(t));
|
||||
});
|
||||
@@ -0,0 +1,728 @@
|
||||
// Web console tests, the notepad: the store in notepads.mjs (names, reads,
|
||||
// saves, pictures, path checks), its /notepad routes, that nothing in a
|
||||
// notepad ever reaches the agent, how Cleanup treats the folder, and the
|
||||
// page's pure rules in public/notepad.js (saving, status words, errors).
|
||||
// Run with: node --test scripts/test-web-console-notepad.mjs
|
||||
//
|
||||
// Shared setup (a per-process console home, the CLI runner, fixtures) lives in
|
||||
// web-console-test-helpers.mjs; see the comment at its top. Every notepad here
|
||||
// lands in its throwaway NOTEPADS_DIR, never the real home folder.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { DAY_MS, HOME, JPEG, NOTEPADS_DIR, ROOT, backdate, cli, openSession, sleep } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const store = await import("../src/web-console/notepads.mjs");
|
||||
const rules = await import("../src/web-console/public/notepad.js");
|
||||
const { cleanupFindings, removeCleanup } = await import("../src/web-console/sessions.mjs");
|
||||
const {
|
||||
IMAGE_ID_RE,
|
||||
NOTE_MAX_BYTES,
|
||||
NOTEPAD_KEY_RE,
|
||||
NOTEPAD_MAX_IMAGES,
|
||||
addImage,
|
||||
addThumb,
|
||||
imagePath,
|
||||
notepadFolder,
|
||||
notepadKey,
|
||||
notepadsDir,
|
||||
readNotepad,
|
||||
removeImage,
|
||||
removeNotepad,
|
||||
saveNote,
|
||||
staleNotepads,
|
||||
} = store;
|
||||
|
||||
const FOLD_CASE = process.platform === "win32" || process.platform === "darwin";
|
||||
let folders = 0;
|
||||
// A project folder of its own per test, so no two tests share a notepad.
|
||||
const freshFolder = (name = "proj") => path.join(HOME, "projects", `${name}-${++folders}`);
|
||||
const refusal = (fn, code) =>
|
||||
assert.throws(fn, (e) => e instanceof store.NotepadError && e.code === code, `expected ${code}`);
|
||||
|
||||
/* ----------------------------------------------------------------- store */
|
||||
|
||||
test("notepadsDir follows PLAN2CODE_NOTEPADS_DIR at call time", () => {
|
||||
assert.equal(notepadsDir(), NOTEPADS_DIR);
|
||||
});
|
||||
|
||||
test("notepadKey is the folder name and a hash, folded where the file system ignores case", () => {
|
||||
const key = notepadKey(path.join(HOME, "My Project"));
|
||||
assert.match(key, NOTEPAD_KEY_RE);
|
||||
assert.ok(key.startsWith("my-project-"), key);
|
||||
const upper = notepadKey(path.join(HOME.toUpperCase(), "MY PROJECT"));
|
||||
if (FOLD_CASE) assert.equal(upper, key);
|
||||
else assert.notEqual(upper, key);
|
||||
// Two worktrees, two notepads.
|
||||
assert.notEqual(notepadKey(path.join(HOME, "repo")), notepadKey(path.join(HOME, "repo-feature")));
|
||||
// Nothing usable in the name still gives a key the pattern accepts.
|
||||
assert.match(notepadKey(path.join(HOME, "ÄÖÜ")), /^folder-[0-9a-f]{12}$/);
|
||||
assert.match(notepadKey(path.join(HOME, "a-".repeat(40))), NOTEPAD_KEY_RE);
|
||||
});
|
||||
|
||||
test("reading a folder with no notepad creates nothing", () => {
|
||||
const folder = freshFolder();
|
||||
assert.deepEqual(readNotepad(folder), { text: "", savedAt: null, images: [] });
|
||||
assert.equal(fs.existsSync(notepadFolder(folder)), false);
|
||||
});
|
||||
|
||||
test("saveNote round-trips text atomically, with meta.json written once", () => {
|
||||
const folder = freshFolder();
|
||||
const { savedAt } = saveNote(folder, "# Ideas\n\n- one ✓\n");
|
||||
assert.ok(!Number.isNaN(Date.parse(savedAt)));
|
||||
const read = readNotepad(folder);
|
||||
assert.equal(read.text, "# Ideas\n\n- one ✓\n");
|
||||
assert.equal(read.savedAt, savedAt);
|
||||
const dir = notepadFolder(folder);
|
||||
const meta = JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8"));
|
||||
assert.equal(meta.v, 1);
|
||||
assert.equal(meta.folder, path.resolve(folder));
|
||||
saveNote(folder, "second");
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(path.join(dir, "meta.json"), "utf8")), meta);
|
||||
assert.deepEqual(fs.readdirSync(dir).sort(), ["images", "meta.json", "note.md"]);
|
||||
});
|
||||
|
||||
test("saveNote refuses a non-string and a note one byte over the cap", () => {
|
||||
const folder = freshFolder();
|
||||
refusal(() => saveNote(folder, 5), "bad");
|
||||
refusal(() => saveNote(folder, null), "bad");
|
||||
refusal(() => saveNote(folder, "x".repeat(NOTE_MAX_BYTES + 1)), "too-long");
|
||||
// Bytes, not characters: a multi-byte character counts for its bytes.
|
||||
refusal(() => saveNote(folder, "é".repeat(NOTE_MAX_BYTES / 2 + 1)), "too-long");
|
||||
assert.ok(saveNote(folder, "x".repeat(NOTE_MAX_BYTES)).savedAt);
|
||||
});
|
||||
|
||||
test("reading a notepad leaves every file time alone", () => {
|
||||
const folder = freshFolder();
|
||||
saveNote(folder, "text");
|
||||
const { id } = addImage(folder, JPEG);
|
||||
const dir = notepadFolder(folder);
|
||||
const files = [path.join(dir, "note.md"), path.join(dir, "meta.json"), path.join(dir, "images", id + ".jpg")];
|
||||
const old = new Date(Date.now() - 40 * DAY_MS);
|
||||
for (const f of files) fs.utimesSync(f, old, old);
|
||||
readNotepad(folder);
|
||||
imagePath(folder, id, false);
|
||||
for (const f of files) assert.equal(Math.round(fs.statSync(f).mtimeMs), old.getTime(), f);
|
||||
});
|
||||
|
||||
test("pictures: JPEG only, listed oldest first, with thumbnails when sent", () => {
|
||||
const folder = freshFolder();
|
||||
refusal(() => addImage(folder, Buffer.from("not a jpeg")), "not-jpeg");
|
||||
refusal(() => addImage(folder, "string"), "not-jpeg");
|
||||
const first = addImage(folder, JPEG);
|
||||
const second = addImage(folder, JPEG);
|
||||
assert.match(first.id, IMAGE_ID_RE);
|
||||
assert.equal(first.url, `/notepad/images/${first.id}.jpg`);
|
||||
const dir = notepadFolder(folder);
|
||||
// Make the order unambiguous: the first is older.
|
||||
const older = new Date(Date.now() - 60_000);
|
||||
fs.utimesSync(path.join(dir, "images", first.id + ".jpg"), older, older);
|
||||
addThumb(folder, second.id, JPEG);
|
||||
assert.deepEqual(readNotepad(folder).images, [
|
||||
{ id: first.id, url: first.url, thumb: null },
|
||||
{ id: second.id, url: second.url, thumb: `/notepad/images/${second.id}.thumb.jpg` },
|
||||
]);
|
||||
});
|
||||
|
||||
test("addThumb and removeImage refuse bad and unknown ids", () => {
|
||||
const folder = freshFolder();
|
||||
const { id } = addImage(folder, JPEG);
|
||||
for (const bad of ["../x", "", null, 7, "00000000-0000-0000-0000-000000000000"]) {
|
||||
refusal(() => addThumb(folder, bad, JPEG), "not-found");
|
||||
refusal(() => removeImage(folder, bad), "not-found");
|
||||
}
|
||||
refusal(() => addThumb(folder, id, Buffer.from("png")), "not-jpeg");
|
||||
addThumb(folder, id, JPEG);
|
||||
removeImage(folder, id);
|
||||
assert.deepEqual(readNotepad(folder).images, []);
|
||||
assert.deepEqual(fs.readdirSync(path.join(notepadFolder(folder), "images")), []);
|
||||
});
|
||||
|
||||
test("a refused delete or thumb on a folder with no notepad creates nothing", () => {
|
||||
const folder = freshFolder();
|
||||
refusal(() => removeImage(folder, "00000000-0000-0000-0000-000000000000"), "not-found");
|
||||
refusal(() => addThumb(folder, "00000000-0000-0000-0000-000000000000", JPEG), "not-found");
|
||||
assert.equal(fs.existsSync(notepadFolder(folder)), false);
|
||||
});
|
||||
|
||||
test("a thumbnail replaced again leaves the newest bytes and no temp file", () => {
|
||||
const folder = freshFolder();
|
||||
const { id } = addImage(folder, JPEG);
|
||||
addThumb(folder, id, JPEG);
|
||||
const second = Buffer.concat([JPEG, Buffer.from("second")]);
|
||||
addThumb(folder, id, second);
|
||||
const images = path.join(notepadFolder(folder), "images");
|
||||
assert.deepEqual(fs.readFileSync(path.join(images, id + ".thumb.jpg")), second);
|
||||
assert.deepEqual(fs.readdirSync(images).filter((n) => n.endsWith(".tmp")), []);
|
||||
});
|
||||
|
||||
test("the image cap refuses one past NOTEPAD_MAX_IMAGES", () => {
|
||||
const folder = freshFolder();
|
||||
const images = path.join(notepadFolder(folder), "images");
|
||||
addImage(folder, JPEG);
|
||||
// Fill the rest directly: 200 real round trips would only slow the suite.
|
||||
for (let i = 1; i < NOTEPAD_MAX_IMAGES; i++) fs.writeFileSync(path.join(images, crypto.randomUUID() + ".jpg"), JPEG);
|
||||
refusal(() => addImage(folder, JPEG), "too-many");
|
||||
});
|
||||
|
||||
test("imagePath refuses anything but this notepad's own regular files", (t) => {
|
||||
const folder = freshFolder();
|
||||
const { id } = addImage(folder, JPEG);
|
||||
assert.equal(imagePath(folder, id, false), fs.realpathSync(path.join(notepadFolder(folder), "images", id + ".jpg")));
|
||||
assert.equal(imagePath(folder, id, true), null, "no thumb yet");
|
||||
assert.equal(imagePath(folder, "../meta", false), null);
|
||||
assert.equal(imagePath(folder, "00000000-0000-0000-0000-000000000000", false), null);
|
||||
// A planted link is refused even under a valid name.
|
||||
const outside = path.join(HOME, "outside.jpg");
|
||||
fs.writeFileSync(outside, JPEG);
|
||||
const linkId = crypto.randomUUID();
|
||||
try {
|
||||
fs.symlinkSync(outside, path.join(notepadFolder(folder), "images", linkId + ".jpg"));
|
||||
} catch (e) {
|
||||
if (["EPERM", "EACCES"].includes(e.code)) return t.skip("symlinks need extra rights here");
|
||||
throw e;
|
||||
}
|
||||
assert.equal(imagePath(folder, linkId, false), null);
|
||||
});
|
||||
|
||||
test("no lock or temp file is left behind after writes", () => {
|
||||
const folder = freshFolder();
|
||||
saveNote(folder, "a");
|
||||
const { id } = addImage(folder, JPEG);
|
||||
addThumb(folder, id, JPEG);
|
||||
addThumb(folder, id, JPEG);
|
||||
const dir = notepadFolder(folder);
|
||||
const all = [...fs.readdirSync(dir), ...fs.readdirSync(path.join(dir, "images"))];
|
||||
assert.equal(all.filter((n) => n.endsWith(".lock") || n.endsWith(".tmp")).length, 0, all.join(", "));
|
||||
});
|
||||
|
||||
/* ---------------------------------------------------------------- routes */
|
||||
|
||||
const getJson = async (s, pathname) => {
|
||||
const res = await fetch(`${s.base}${pathname}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
return { status: res.status, body: await res.json(), headers: res.headers };
|
||||
};
|
||||
const postJpeg = (s, pathname, buf, extra = {}) =>
|
||||
fetch(`${s.base}${pathname}`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "image/jpeg", cookie: s.cookie, connection: "close", ...extra },
|
||||
body: buf,
|
||||
});
|
||||
|
||||
test("GET /notepad answers an empty notepad, then the saved text", async () => {
|
||||
const s = openSession();
|
||||
// The session's folder is this repo; start from a clean notepad for it.
|
||||
fs.rmSync(NOTEPADS_DIR, { recursive: true, force: true });
|
||||
const empty = await getJson(s, "/notepad");
|
||||
assert.equal(empty.status, 200);
|
||||
assert.deepEqual(empty.body, { text: "", savedAt: null, images: [] });
|
||||
const saved = await s.send("/notepad/text", { text: "# Route note" });
|
||||
assert.equal(saved.status, 200);
|
||||
const body = await saved.json();
|
||||
assert.equal(body.ok, true);
|
||||
const read = await getJson(s, "/notepad");
|
||||
assert.equal(read.body.text, "# Route note");
|
||||
assert.equal(read.body.savedAt, body.savedAt);
|
||||
});
|
||||
|
||||
test("POST /notepad/text refuses a non-string, an oversized note and bad JSON", async () => {
|
||||
const s = openSession();
|
||||
const bad = await s.send("/notepad/text", { text: 7 });
|
||||
assert.equal(bad.status, 400);
|
||||
assert.deepEqual(await bad.json(), { error: "bad" });
|
||||
const long = await s.send("/notepad/text", { text: "x".repeat(NOTE_MAX_BYTES + 1) });
|
||||
assert.equal(long.status, 413);
|
||||
assert.deepEqual(await long.json(), { error: "too-long" });
|
||||
const notJson = await fetch(`${s.base}/notepad/text`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
|
||||
body: "{nope",
|
||||
});
|
||||
assert.equal(notJson.status, 400);
|
||||
});
|
||||
|
||||
test("notepad writes need the session cookie and refuse a foreign origin", async () => {
|
||||
const s = openSession();
|
||||
const noCookie = await fetch(`${s.base}/notepad/text`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", connection: "close" },
|
||||
body: JSON.stringify({ text: "x" }),
|
||||
});
|
||||
assert.equal(noCookie.status, 403);
|
||||
const foreign = await fetch(`${s.base}/notepad/text`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, origin: "http://evil.example", connection: "close" },
|
||||
body: JSON.stringify({ text: "x" }),
|
||||
});
|
||||
assert.equal(foreign.status, 403);
|
||||
const foreignImage = await postJpeg(s, "/notepad/image", JPEG, { origin: "http://evil.example" });
|
||||
assert.equal(foreignImage.status, 403);
|
||||
const noCookieRead = await fetch(`${s.base}/notepad`, { headers: { connection: "close" } });
|
||||
assert.equal(noCookieRead.status, 403);
|
||||
});
|
||||
|
||||
test("pictures through the routes: upload, thumb, fetch, delete and every refusal", async () => {
|
||||
const s = openSession();
|
||||
const wrongType = await fetch(`${s.base}/notepad/image`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "image/png", cookie: s.cookie, connection: "close" },
|
||||
body: JPEG,
|
||||
});
|
||||
assert.equal(wrongType.status, 415);
|
||||
assert.deepEqual(await wrongType.json(), { error: "not-jpeg" });
|
||||
const notJpeg = await postJpeg(s, "/notepad/image", Buffer.from("plain text"));
|
||||
assert.equal(notJpeg.status, 415);
|
||||
const tooLarge = await postJpeg(s, "/notepad/image", Buffer.concat([JPEG, Buffer.alloc(4 * 1024 * 1024)]));
|
||||
assert.equal(tooLarge.status, 413);
|
||||
assert.deepEqual(await tooLarge.json(), { error: "too-large" });
|
||||
|
||||
const up = await postJpeg(s, "/notepad/image", JPEG);
|
||||
assert.equal(up.status, 200);
|
||||
const { id, url } = await up.json();
|
||||
assert.match(id, IMAGE_ID_RE);
|
||||
|
||||
const unknownThumb = await postJpeg(s, "/notepad/thumb?id=00000000-0000-0000-0000-000000000000", JPEG);
|
||||
assert.equal(unknownThumb.status, 404);
|
||||
assert.deepEqual(await unknownThumb.json(), { error: "not-found" });
|
||||
const thumbNotJpeg = await postJpeg(s, `/notepad/thumb?id=${id}`, Buffer.from("png"));
|
||||
assert.equal(thumbNotJpeg.status, 415);
|
||||
assert.deepEqual(await thumbNotJpeg.json(), { error: "not-jpeg" });
|
||||
const thumbTooLarge = await postJpeg(s, `/notepad/thumb?id=${id}`, Buffer.concat([JPEG, Buffer.alloc(4 * 1024 * 1024)]));
|
||||
assert.equal(thumbTooLarge.status, 413);
|
||||
assert.deepEqual(await thumbTooLarge.json(), { error: "too-large" });
|
||||
assert.equal((await postJpeg(s, `/notepad/thumb?id=${id}`, JPEG)).status, 200);
|
||||
|
||||
const img = await fetch(`${s.base}${url}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
assert.equal(img.status, 200);
|
||||
assert.equal(img.headers.get("content-type"), "image/jpeg");
|
||||
assert.equal(img.headers.get("cache-control"), "no-store");
|
||||
assert.equal(img.headers.get("x-content-type-options"), "nosniff");
|
||||
assert.deepEqual(Buffer.from(await img.arrayBuffer()), JPEG);
|
||||
const thumb = await fetch(`${s.base}/notepad/images/${id}.thumb.jpg`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
assert.equal(thumb.status, 200);
|
||||
|
||||
for (const bad of ["/notepad/images/../meta.json", "/notepad/images/nope.jpg", `/notepad/images/${id}.png`, "/notepad/images/%2e%2e%2fmeta.json"]) {
|
||||
const res = await fetch(`${s.base}${bad}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
assert.equal(res.status, 404, bad);
|
||||
}
|
||||
|
||||
const gone = await s.send("/notepad/image/delete", { id: "00000000-0000-0000-0000-000000000000" });
|
||||
assert.equal(gone.status, 404);
|
||||
const del = await s.send("/notepad/image/delete", { id });
|
||||
assert.equal(del.status, 200);
|
||||
const after = await fetch(`${s.base}${url}`, { headers: { cookie: s.cookie, connection: "close" } });
|
||||
assert.equal(after.status, 404);
|
||||
});
|
||||
|
||||
test("POST /notepad/image refuses one past the cap with 409", async (t) => {
|
||||
const s = openSession();
|
||||
// The session runs in this repo, so its notepad is the one for ROOT. Fill it
|
||||
// directly (200 round trips would only slow the suite), and empty it after
|
||||
// so the tests below start from a notepad with room.
|
||||
const images = path.join(notepadFolder(ROOT), "images");
|
||||
t.after(() => fs.rmSync(notepadFolder(ROOT), { recursive: true, force: true }));
|
||||
assert.equal((await postJpeg(s, "/notepad/image", JPEG)).status, 200);
|
||||
const have = fs.readdirSync(images).filter((n) => !n.endsWith(".thumb.jpg")).length;
|
||||
for (let i = have; i < NOTEPAD_MAX_IMAGES; i++) fs.writeFileSync(path.join(images, crypto.randomUUID() + ".jpg"), JPEG);
|
||||
const full = await postJpeg(s, "/notepad/image", JPEG);
|
||||
assert.equal(full.status, 409);
|
||||
assert.deepEqual(await full.json(), { error: "too-many" });
|
||||
});
|
||||
|
||||
test("two folders get two notepads through their own sessions", async (t) => {
|
||||
const a = path.join(os.tmpdir(), `p2c-notepad-a-${process.pid}`);
|
||||
const b = path.join(os.tmpdir(), `p2c-notepad-b-${process.pid}`);
|
||||
for (const d of [a, b]) fs.mkdirSync(d, { recursive: true });
|
||||
const { cliIn, payload, BASE, sessionUrl, until } = await import("./web-console-test-helpers.mjs");
|
||||
const sids = [];
|
||||
// Each server runs in its folder, and Windows will not remove a folder a
|
||||
// live process sits in: stop both, and wait until neither answers, before
|
||||
// cleaning up (stop returns before the process has gone).
|
||||
t.after(async () => {
|
||||
for (const [cwd, sid] of sids) cliIn(cwd, ["stop", "--session", sid]);
|
||||
const gone = async ({ base }) => {
|
||||
try {
|
||||
await fetch(`${base}/health`, { signal: AbortSignal.timeout(1000) });
|
||||
return false;
|
||||
} catch {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
for (const [, , s] of sids) await until(() => gone(s), 5000);
|
||||
for (const d of [a, b]) fs.rmSync(d, { recursive: true, force: true, maxRetries: 10, retryDelay: 200 });
|
||||
});
|
||||
const open = (cwd) => {
|
||||
const res = cliIn(cwd, ["open", "--file", payload(`np-${path.basename(cwd)}.json`, BASE), "--no-open"]);
|
||||
const s = sessionUrl(res.json.url);
|
||||
sids.push([cwd, res.json.sid, s]);
|
||||
return s;
|
||||
};
|
||||
const sa = open(a);
|
||||
const sb = open(b);
|
||||
const save = (s, text) =>
|
||||
fetch(`${s.base}/notepad/text`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie: s.cookie, connection: "close" },
|
||||
body: JSON.stringify({ text }),
|
||||
});
|
||||
assert.equal((await save(sa, "from a")).status, 200);
|
||||
assert.equal((await save(sb, "from b")).status, 200);
|
||||
assert.equal((await getJson(sa, "/notepad")).body.text, "from a");
|
||||
assert.equal((await getJson(sb, "/notepad")).body.text, "from b");
|
||||
assert.notEqual(notepadFolder(a), notepadFolder(b));
|
||||
});
|
||||
|
||||
/* -------------------------------------------- never to the agent, Cleanup */
|
||||
|
||||
test("nothing in a notepad reaches the session folder or the agent's wait", async () => {
|
||||
const s = openSession();
|
||||
const marker = `NOTEPAD-MARKER-${process.pid}-${Date.now()}`;
|
||||
assert.equal((await s.send("/notepad/text", { text: `secret ${marker}` })).status, 200);
|
||||
const picture = Buffer.concat([JPEG, Buffer.from(marker)]);
|
||||
assert.equal((await postJpeg(s, "/notepad/image", picture)).status, 200);
|
||||
|
||||
const seen = [];
|
||||
const walk = (dir) => {
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) walk(p);
|
||||
else seen.push(p);
|
||||
}
|
||||
};
|
||||
walk(s.session);
|
||||
for (const file of seen) {
|
||||
assert.ok(!fs.readFileSync(file).includes(marker), `${path.relative(s.session, file)} carries notepad content`);
|
||||
}
|
||||
assert.equal(fs.existsSync(path.join(s.session, "uploads")) && fs.readdirSync(path.join(s.session, "uploads")).length > 0, false);
|
||||
|
||||
const waited = cli(["wait", "--session", s.sid, "--seconds", "1"]);
|
||||
assert.ok(!waited.stdout.includes(marker));
|
||||
const status = cli(["status"]);
|
||||
assert.ok(!status.stdout.includes(marker));
|
||||
});
|
||||
|
||||
test("Cleanup never lists the notepads folder as a stray, fresh or old", async () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-notepad-cleanup-"));
|
||||
const consoleDir = path.join(root, "console");
|
||||
fs.mkdirSync(path.join(consoleDir, "sessions"), { recursive: true });
|
||||
const note = path.join(root, "notepads", "proj-0123456789ab", "note.md");
|
||||
fs.mkdirSync(path.dirname(note), { recursive: true });
|
||||
fs.writeFileSync(note, "x");
|
||||
const ids = async (now) => (await cleanupFindings({ consoleDir, plan2codeDir: root, now })).items.map((i) => i.id);
|
||||
assert.ok(!(await ids(Date.now())).includes("root:notepads"));
|
||||
// Two hours on: past the stray grace, so only the kept list protects it.
|
||||
assert.ok(!(await ids(Date.now() + 2 * 60 * 60 * 1000)).includes("root:notepads"));
|
||||
// A real stray beside it is still listed, so the scan did run.
|
||||
const stray = path.join(root, "leftover.txt");
|
||||
fs.writeFileSync(stray, "x");
|
||||
assert.ok((await ids(Date.now() + 2 * 60 * 60 * 1000)).includes("root:leftover.txt"));
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
// Every file and folder under `dir`, and `dir` itself, moved `days` back.
|
||||
function backdateAll(dir, days) {
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) backdateAll(p, days);
|
||||
else backdate(p, days);
|
||||
}
|
||||
backdate(dir, days);
|
||||
}
|
||||
|
||||
// Cleanup's scan with no console or ~/.plan2code strays in the way: only the
|
||||
// notepads folder (the file's NOTEPADS_DIR) has anything to find.
|
||||
function quietCleanup() {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-notepad-stale-"));
|
||||
fs.mkdirSync(path.join(root, "console", "sessions"), { recursive: true });
|
||||
const opts = { consoleDir: path.join(root, "console"), plan2codeDir: root };
|
||||
return { opts, done: () => fs.rmSync(root, { recursive: true, force: true }) };
|
||||
}
|
||||
|
||||
test("Cleanup lists a notepad only once its newest file is a month old, as one item that removes the whole folder", async () => {
|
||||
const q = quietCleanup();
|
||||
// Old text, but a picture added today: still in use.
|
||||
const mixed = freshFolder("mixed");
|
||||
saveNote(mixed, "old words");
|
||||
backdateAll(notepadFolder(mixed), 31);
|
||||
addImage(mixed, JPEG);
|
||||
// Every file a month old.
|
||||
const old = freshFolder("old");
|
||||
saveNote(old, "forgotten");
|
||||
addImage(old, JPEG);
|
||||
backdateAll(notepadFolder(old), 31);
|
||||
// Written today.
|
||||
const fresh = freshFolder("fresh");
|
||||
saveNote(fresh, "today");
|
||||
|
||||
const { items } = await cleanupFindings(q.opts);
|
||||
const notepads = items.filter((i) => i.where === "notepad");
|
||||
assert.deepEqual(
|
||||
notepads.map((i) => i.id),
|
||||
["notepad:" + notepadKey(old)],
|
||||
);
|
||||
assert.equal(notepads[0].name, notepadKey(old));
|
||||
assert.equal(notepads[0].kind, "folder");
|
||||
assert.equal(notepads[0].folder, path.resolve(old));
|
||||
assert.ok(notepads[0].bytes > JPEG.length, "the item counts the whole folder");
|
||||
assert.deepEqual(
|
||||
staleNotepads(Date.now(), 30 * DAY_MS).map((n) => n.key),
|
||||
[notepadKey(old)],
|
||||
);
|
||||
|
||||
const done = await removeCleanup(["notepad:" + notepadKey(old), "notepad:" + notepadKey(fresh)], q.opts);
|
||||
assert.deepEqual(done.removed, ["notepad:" + notepadKey(old)], "only what the fresh scan still finds is removed");
|
||||
assert.equal(fs.existsSync(notepadFolder(old)), false, "the whole folder went");
|
||||
assert.equal(readNotepad(fresh).text, "today");
|
||||
assert.equal(readNotepad(mixed).images.length, 1);
|
||||
q.done();
|
||||
});
|
||||
|
||||
test("a notepad with no meta.json is listed by its key alone", async () => {
|
||||
const q = quietCleanup();
|
||||
const folder = freshFolder("nometa");
|
||||
saveNote(folder, "x");
|
||||
fs.rmSync(path.join(notepadFolder(folder), "meta.json"));
|
||||
backdateAll(notepadFolder(folder), 31);
|
||||
const item = (await cleanupFindings(q.opts)).items.find((i) => i.id === "notepad:" + notepadKey(folder));
|
||||
assert.ok(item, "still listed");
|
||||
assert.equal(item.folder, null);
|
||||
removeNotepad(notepadKey(folder));
|
||||
q.done();
|
||||
});
|
||||
|
||||
test("removeNotepad refuses a bad key and a linked folder, and staleNotepads skips both", (t) => {
|
||||
for (const key of ["", "../proj-0123456789ab", "Proj-0123456789ab", "proj-0123456789a", "proj", "proj-0123456789ab/..", 7, null]) {
|
||||
refusal(() => removeNotepad(key), "bad");
|
||||
}
|
||||
refusal(() => removeNotepad("gone-0123456789ab"), "not-found");
|
||||
|
||||
// A link under a valid key, pointing at a folder that must survive.
|
||||
const target = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-notepad-target-"));
|
||||
fs.writeFileSync(path.join(target, "keep.md"), "mine");
|
||||
backdateAll(target, 60);
|
||||
const key = "linked-" + crypto.randomBytes(6).toString("hex");
|
||||
const link = path.join(notepadsDir(), key);
|
||||
fs.mkdirSync(notepadsDir(), { recursive: true });
|
||||
try {
|
||||
fs.symlinkSync(target, link, process.platform === "win32" ? "junction" : "dir");
|
||||
} catch (e) {
|
||||
fs.rmSync(target, { recursive: true, force: true });
|
||||
if (["EPERM", "EACCES"].includes(e.code)) return t.skip("links need extra rights here");
|
||||
throw e;
|
||||
}
|
||||
try {
|
||||
assert.ok(!staleNotepads(Date.now(), 30 * DAY_MS).some((n) => n.key === key), "a link is never listed");
|
||||
refusal(() => removeNotepad(key), "bad");
|
||||
assert.equal(fs.readFileSync(path.join(target, "keep.md"), "utf8"), "mine");
|
||||
} finally {
|
||||
// The link alone: a Windows junction goes with rmdir, a symlink with unlink.
|
||||
try {
|
||||
fs.unlinkSync(link);
|
||||
} catch {
|
||||
fs.rmdirSync(link);
|
||||
}
|
||||
fs.rmSync(target, { recursive: true, force: true });
|
||||
}
|
||||
// A plain file under a valid key is no notepad either.
|
||||
const file = path.join(notepadsDir(), "file-" + crypto.randomBytes(6).toString("hex"));
|
||||
fs.writeFileSync(file, "x");
|
||||
backdate(file, 60);
|
||||
assert.ok(!staleNotepads(Date.now(), 30 * DAY_MS).some((n) => n.path === file));
|
||||
refusal(() => removeNotepad(path.basename(file)), "bad");
|
||||
fs.rmSync(file);
|
||||
});
|
||||
|
||||
test("the sweeps at open leave a 60-day-old notepad untouched", async () => {
|
||||
const folder = freshFolder("sixty");
|
||||
saveNote(folder, "kept for months");
|
||||
addImage(folder, JPEG);
|
||||
backdateAll(notepadFolder(folder), 60);
|
||||
const before = fs.statSync(path.join(notepadFolder(folder), "note.md")).mtimeMs;
|
||||
const s = openSession();
|
||||
// The sweeps run after open prints; give them their moment.
|
||||
await sleep(500);
|
||||
assert.equal(readNotepad(folder).text, "kept for months");
|
||||
assert.equal(readNotepad(folder).images.length, 1);
|
||||
assert.equal(fs.statSync(path.join(notepadFolder(folder), "note.md")).mtimeMs, before, "not even touched");
|
||||
cli(["stop", "--session", s.sid]);
|
||||
removeNotepad(notepadKey(folder));
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ page rules */
|
||||
|
||||
// Drives nextSave() through a list of events from a start state, returning
|
||||
// every step's status, attempt and timer.
|
||||
function run(events, from = rules.SAVE_START) {
|
||||
let state = from;
|
||||
return events.map((event) => {
|
||||
const next = rules.nextSave(state, event);
|
||||
state = next.state;
|
||||
return [state.status, state.attempt, next.timer];
|
||||
});
|
||||
}
|
||||
|
||||
test("page rules: the caps equal the server's", () => {
|
||||
assert.equal(rules.NOTE_MAX_BYTES, NOTE_MAX_BYTES);
|
||||
assert.equal(rules.NOTEPAD_MAX_IMAGES, NOTEPAD_MAX_IMAGES);
|
||||
assert.equal(String(rules.IMAGE_ID_RE), String(IMAGE_ID_RE));
|
||||
assert.equal(rules.SAVE_DEBOUNCE_MS, 800);
|
||||
assert.deepEqual([...rules.RETRY_STEPS_MS], [1000, 2000, 4000, 8000, 16000, 30000]);
|
||||
});
|
||||
|
||||
test("page rules: noteBytes counts UTF-8 bytes, and a non-string as nothing", () => {
|
||||
assert.equal(rules.noteBytes("abc"), 3);
|
||||
assert.equal(rules.noteBytes("é"), 2);
|
||||
assert.equal(rules.noteBytes("😀"), 4);
|
||||
assert.equal(rules.noteBytes(null), 0);
|
||||
});
|
||||
|
||||
test("page rules: typing arms the debounce, then due, sent and ok land saved", () => {
|
||||
assert.deepEqual(run([{ type: "typed", bytes: 5 }, "due", "sent", "ok"]), [
|
||||
["pending", 0, rules.SAVE_DEBOUNCE_MS],
|
||||
["saving", 0, null],
|
||||
["saving", 0, null],
|
||||
["saved", 0, null],
|
||||
]);
|
||||
// Typing again from saved starts over.
|
||||
assert.deepEqual(run([{ type: "typed", bytes: 1 }], { status: "saved", attempt: 0 }), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
|
||||
});
|
||||
|
||||
test("page rules: failures back off step by step, hold at the last step, and reset on typed or ok", () => {
|
||||
const events = [{ type: "typed", bytes: 1 }, "due"];
|
||||
for (let i = 0; i < 8; i++) events.push({ type: "error", code: "bad" }, "retry");
|
||||
const steps = run(events).filter(([status]) => status === "failed").map(([, , timer]) => timer);
|
||||
assert.deepEqual(steps, [1000, 2000, 4000, 8000, 16000, 30000, 30000, 30000]);
|
||||
const failed = { status: "failed", attempt: 4 };
|
||||
assert.deepEqual(run([{ type: "typed", bytes: 1 }], failed), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
|
||||
assert.deepEqual(run(["retry", "ok", { type: "error" }], failed), [
|
||||
["saving", 4, null],
|
||||
["saved", 0, null],
|
||||
["failed", 1, 1000],
|
||||
]);
|
||||
// A flush (due) on a failed save sends now, keeping the count.
|
||||
assert.deepEqual(run(["due"], failed), [["saving", 4, null]]);
|
||||
});
|
||||
|
||||
test("page rules: a note past the cap never sends, and a server too-long stops retrying", () => {
|
||||
assert.deepEqual(run([{ type: "typed", bytes: NOTE_MAX_BYTES + 1 }, "due", "retry"]), [
|
||||
["too-long", 0, null],
|
||||
["too-long", 0, null],
|
||||
["too-long", 0, null],
|
||||
]);
|
||||
assert.deepEqual(run([{ type: "typed", bytes: NOTE_MAX_BYTES }]), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
|
||||
assert.deepEqual(run([{ type: "error", code: "too-long" }], { status: "saving", attempt: 2 }), [["too-long", 0, null]]);
|
||||
// Typing it back under the cap saves again.
|
||||
assert.deepEqual(run([{ type: "typed", bytes: 10 }], { status: "too-long", attempt: 0 }), [["pending", 0, rules.SAVE_DEBOUNCE_MS]]);
|
||||
});
|
||||
|
||||
test("page rules: due and retry do nothing where there is nothing to send, and bad input changes nothing", () => {
|
||||
for (const status of ["idle", "saving", "saved", "too-long"]) {
|
||||
const state = { status, attempt: 0 };
|
||||
assert.equal(rules.nextSave(state, "due").state, state, `due from ${status}`);
|
||||
assert.equal(rules.nextSave(state, "due").timer, null);
|
||||
}
|
||||
for (const status of ["idle", "pending", "saving", "saved", "too-long"]) {
|
||||
const state = { status, attempt: 0 };
|
||||
assert.equal(rules.nextSave(state, "retry").state, state, `retry from ${status}`);
|
||||
}
|
||||
const state = { status: "pending", attempt: 0 };
|
||||
assert.equal(rules.nextSave(state, "nonsense").state, state);
|
||||
assert.equal(rules.nextSave({ status: "weird" }, "typed").state.status, "weird");
|
||||
// Never mutates its input.
|
||||
const frozen = Object.freeze({ status: "failed", attempt: 1 });
|
||||
rules.nextSave(frozen, { type: "error" });
|
||||
assert.deepEqual(frozen, { status: "failed", attempt: 1 });
|
||||
});
|
||||
|
||||
test("page rules: saveStatus words and unsaved()", () => {
|
||||
const words = {
|
||||
idle: "",
|
||||
pending: "Saving",
|
||||
saving: "Saving",
|
||||
saved: "Saved",
|
||||
failed: "Not saved (retrying)",
|
||||
"too-long": "Too long to save (over 1 MB)",
|
||||
};
|
||||
for (const [status, text] of Object.entries(words)) {
|
||||
assert.equal(rules.saveStatus({ status, attempt: 0 }), text);
|
||||
assert.equal(rules.saveStatus(status), text);
|
||||
}
|
||||
assert.equal(rules.saveStatus(undefined), "");
|
||||
assert.deepEqual(
|
||||
Object.keys(words).filter((status) => rules.unsaved({ status })),
|
||||
["pending", "saving", "failed"],
|
||||
);
|
||||
});
|
||||
|
||||
test("page rules: keepsText holds unsaved and too-long text against a reload", () => {
|
||||
const statuses = ["idle", "pending", "saving", "saved", "failed", "too-long"];
|
||||
assert.deepEqual(
|
||||
statuses.filter((status) => rules.keepsText({ status })),
|
||||
["pending", "saving", "failed", "too-long"],
|
||||
);
|
||||
assert.match(rules.NOT_LOADED, /^[A-Z].*\.$/);
|
||||
});
|
||||
|
||||
test("page rules: errorSentence covers every server code, and anything else is a lost connection", () => {
|
||||
// Every code the store can raise.
|
||||
const raised = new Set();
|
||||
for (const m of fs.readFileSync(path.join(ROOT, "src", "web-console", "notepads.mjs"), "utf8").matchAll(/new NotepadError\("([a-z-]+)"/g)) raised.add(m[1]);
|
||||
// The routes add too-large for an oversized picture.
|
||||
raised.add("too-large");
|
||||
assert.deepEqual([...raised].sort(), [...rules.ERROR_CODES].sort());
|
||||
const lost = rules.errorSentence(null);
|
||||
const seen = new Set([lost]);
|
||||
for (const code of rules.ERROR_CODES) {
|
||||
const sentence = rules.errorSentence(code);
|
||||
assert.match(sentence, /^[A-Z].*\.$/, code);
|
||||
assert.ok(!seen.has(sentence), `${code} has a sentence of its own`);
|
||||
seen.add(sentence);
|
||||
}
|
||||
assert.equal(rules.errorSentence("teapot"), lost);
|
||||
assert.equal(rules.errorSentence(undefined), lost);
|
||||
assert.match(rules.errorSentence("too-many"), new RegExp(String(NOTEPAD_MAX_IMAGES)));
|
||||
});
|
||||
|
||||
test("page rules: step wraps at both ends, and an empty list has nowhere to go", () => {
|
||||
assert.equal(rules.step(0, 1, 3), 1);
|
||||
assert.equal(rules.step(2, 1, 3), 0);
|
||||
assert.equal(rules.step(0, -1, 3), 2);
|
||||
assert.equal(rules.step(1, -1, 3), 0);
|
||||
assert.equal(rules.step(0, 1, 1), 0);
|
||||
assert.equal(rules.step(0, 1, 0), -1);
|
||||
assert.equal(rules.step(0, -1, 0), -1);
|
||||
});
|
||||
|
||||
test("page rules: withoutStyleAttrs moves a link's anchor name to data-anchor and drops any other style", () => {
|
||||
assert.equal(
|
||||
rules.withoutStyleAttrs('<div><a href="x" style="anchor-name: --link-3"><span class="syntax-marker">[</span>a</a></div>'),
|
||||
'<div><a href="x" data-anchor="--link-3"><span class="syntax-marker">[</span>a</a></div>',
|
||||
);
|
||||
assert.equal(rules.withoutStyleAttrs('<span style="display: flex; gap: 6px;"><svg style="flex-shrink: 0;"></svg></span>'), "<span><svg></svg></span>");
|
||||
// Typed text reaches it with its quotes escaped, so it is never touched.
|
||||
const typed = "<div><b style="color: red"></div>";
|
||||
assert.equal(rules.withoutStyleAttrs(typed), typed);
|
||||
});
|
||||
|
||||
test("page rules: topLevelParts cuts the HTML into its top-level elements, or says it cannot", () => {
|
||||
const parts = ["<div><h1><span class=\"syntax-marker\"># </span>Hi</h1></div>", "<ul><li class=\"bullet-list\">a</li><li class=\"bullet-list\">b</li></ul>", "<div> </div>", "<div>a<br>b<img src=\"x\"></div>", "<div><span/></div>"];
|
||||
assert.deepEqual(rules.topLevelParts(parts.join("")), parts);
|
||||
assert.deepEqual(rules.topLevelParts(""), []);
|
||||
assert.equal(rules.topLevelParts("<div>open"), null, "unbalanced");
|
||||
assert.equal(rules.topLevelParts("<div>a</div></div>"), null, "closes more than it opens");
|
||||
assert.equal(rules.topLevelParts("text<div>a</div>"), null, "text at the top level");
|
||||
assert.equal(rules.topLevelParts("<div>a</div>trailing"), null);
|
||||
});
|
||||
|
||||
test("page rules: changedRange finds the unchanged head and tail, never overlapping", () => {
|
||||
assert.deepEqual(rules.changedRange(["a", "b", "c"], ["a", "x", "c"]), { head: 1, tail: 1 });
|
||||
assert.deepEqual(rules.changedRange(["a", "b", "c"], ["a", "b", "c"]), { head: 3, tail: 0 });
|
||||
assert.deepEqual(rules.changedRange(["a", "b"], ["a", "b", "b"]), { head: 2, tail: 0 });
|
||||
assert.deepEqual(rules.changedRange(["a", "a"], ["a"]), { head: 1, tail: 0 });
|
||||
assert.deepEqual(rules.changedRange([], ["a"]), { head: 0, tail: 0 });
|
||||
assert.deepEqual(rules.changedRange(["x", "a", "b"], ["a", "b"]), { head: 0, tail: 2 });
|
||||
});
|
||||
@@ -14,6 +14,7 @@ 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";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../src/web-console/public/answers.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
@@ -204,6 +205,50 @@ test("the Welcome stays away when the person has seen it, and off the dashboard"
|
||||
assert.equal(await plan.page.locator("#welcome-modal").isVisible(), false, "the Welcome showed on a workflow page");
|
||||
});
|
||||
|
||||
test("Help's dashboard topic lists every card once, grouped and in the dashboard's order, by its Help line or blurb", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: { agent: { status: "waiting" } }, project: tempProject() });
|
||||
await toTheDashboard(s);
|
||||
await openHelp(s);
|
||||
await tabButton(s, "dashboard").click();
|
||||
const panel = s.page.locator("#help-panel-dashboard");
|
||||
await panel.waitFor();
|
||||
|
||||
// Read back as drawn: each group's heading, then its list's title and line.
|
||||
const drawnGroups = await panel.locator(".help-cards").evaluate((box) => {
|
||||
const out = [];
|
||||
for (const node of box.children) {
|
||||
if (node.tagName === "P") out.push({ title: node.textContent, cards: [] });
|
||||
else
|
||||
out.at(-1).cards.push(
|
||||
...[...node.children].map((li) => ({
|
||||
title: li.firstElementChild.textContent,
|
||||
line: li.textContent.slice(li.firstElementChild.textContent.length),
|
||||
}))
|
||||
);
|
||||
}
|
||||
return out;
|
||||
});
|
||||
const expected = CATALOG_GROUPS.map((g) => ({
|
||||
title: g.title,
|
||||
cards: SKILL_CATALOG.filter((e) => e.group === g.id).map((e) => ({ title: e.title + ".", line: " " + (e.help || e.blurb) })),
|
||||
}));
|
||||
assert.deepEqual(drawnGroups, expected);
|
||||
|
||||
// Each card's title and line appear exactly once in the whole topic.
|
||||
const text = await panel.evaluate((n) => n.textContent);
|
||||
const titles = await panel.locator(".help-cards li > strong").allTextContents();
|
||||
for (const e of SKILL_CATALOG) {
|
||||
assert.equal(titles.filter((x) => x === e.title + ".").length, 1, `${e.title} is listed once`);
|
||||
assert.equal(text.split(e.help || e.blurb).length - 1, 1, `${e.title}'s line appears once`);
|
||||
}
|
||||
// Built once: a second open adds no second list.
|
||||
await s.page.keyboard.press("Escape");
|
||||
await helpModal(s).waitFor({ state: "hidden" });
|
||||
await openHelp(s);
|
||||
assert.equal(await panel.locator(".help-cards li").count(), SKILL_CATALOG.length);
|
||||
});
|
||||
|
||||
// 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.
|
||||
|
||||
@@ -0,0 +1,754 @@
|
||||
// Page tests for the Notepad: the top bar icon on every screen, the styled
|
||||
// editor, autosave and what survives a reload or a restart, one notepad per
|
||||
// folder, the page's content-security policy with the editor open, hostile
|
||||
// Markdown, typing speed on a long note, the editor's two layers lining up,
|
||||
// both themes, and the pictures: adding, deleting, the preview and the cap.
|
||||
// Run with:
|
||||
// node --test scripts/test-web-console-page-notepad.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. Notes land in the file's throwaway NOTEPADS_DIR.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, drawn } from "./page-test-helpers.mjs";
|
||||
import { backdate, cli, until } from "./web-console-test-helpers.mjs";
|
||||
import {
|
||||
NOTEPAD_MAX_IMAGES,
|
||||
NOTE_MAX_BYTES,
|
||||
addImage,
|
||||
notepadFolder,
|
||||
notepadKey,
|
||||
readNotepad,
|
||||
removeImage,
|
||||
saveNote,
|
||||
} from "../src/web-console/notepads.mjs";
|
||||
import { NOT_LOADED, SAVE_DEBOUNCE_MS, errorSentence } from "../src/web-console/public/notepad.js";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
// A plan session on the person's turn.
|
||||
const PLAN_QUESTION = {
|
||||
items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name for the export." }],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
const input = (s) => s.page.locator("#notepad-editor .overtype-input");
|
||||
|
||||
// Opens the notepad and, unless told the note cannot load, waits until it has:
|
||||
// the editor is read-only until then.
|
||||
async function openNotepad(s, { loads = true } = {}) {
|
||||
await s.page.click("#btn-notepad");
|
||||
await s.page.locator("#notepad-modal[open]").waitFor();
|
||||
await input(s).waitFor();
|
||||
if (loads) await s.page.waitForFunction(() => !document.querySelector("#notepad-editor .overtype-input").readOnly);
|
||||
}
|
||||
|
||||
async function closeNotepad(s) {
|
||||
await s.page.click("#notepad-close");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-modal").open);
|
||||
}
|
||||
|
||||
// The editor's text once the page has read the note in: opening reads it from
|
||||
// the server, so the first value can still be the empty editor.
|
||||
async function shows(s, text) {
|
||||
await s.page.waitForFunction((want) => document.querySelector("#notepad-editor .overtype-input").value === want, text, { timeout: 5000 });
|
||||
return input(s).inputValue();
|
||||
}
|
||||
|
||||
// The note on disk for the session's folder, as the store reads it.
|
||||
const onDisk = (s) => readNotepad(s.project).text;
|
||||
|
||||
async function iconUsable(s, where) {
|
||||
const btn = s.page.locator("#btn-notepad");
|
||||
assert.ok(await btn.isVisible(), `the icon shows on ${where}`);
|
||||
assert.ok(await btn.isEnabled(), `the icon is usable on ${where}`);
|
||||
assert.equal(await btn.getAttribute("aria-label"), "Notepad");
|
||||
assert.equal(await btn.getAttribute("title"), "Notepad");
|
||||
}
|
||||
|
||||
test("the notepad icon shows on the dashboard, a skill session and a finished screen", async (t) => {
|
||||
const dash = await openSession(await suite.browser(), { t, workflow: "dashboard" });
|
||||
await iconUsable(dash, "the dashboard");
|
||||
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await iconUsable(s, "a skill session");
|
||||
// Right of Stop session and Subagents, in the same row.
|
||||
const order = await s.page.evaluate(() =>
|
||||
[...document.querySelectorAll(".topbar-row.second .row-left > button")].map((b) => b.id),
|
||||
);
|
||||
assert.ok(order.indexOf("btn-notepad") > order.indexOf("btn-stop"), order.join(", "));
|
||||
assert.equal(order.indexOf("btn-notepad"), order.indexOf("btn-subagents") + 1, order.join(", "));
|
||||
|
||||
s.post({ settle: true, finish: { headline: "The plan is done", body: "All written down." } });
|
||||
await s.page.locator(".handoff, .end-pane, #main").first().waitFor();
|
||||
await s.page.waitForFunction(() => document.getElementById("btn-stop").hidden);
|
||||
await iconUsable(s, "the finished screen");
|
||||
await openNotepad(s);
|
||||
});
|
||||
|
||||
test("typing Markdown styles it in place, saves within two seconds, and survives close, reload and a restart", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
assert.equal(await input(s).getAttribute("aria-label"), "Notepad text");
|
||||
await input(s).focus();
|
||||
await s.page.keyboard.type("# Shopping list\n\nSome **bold** text");
|
||||
const typedAt = Date.now();
|
||||
// Styled in place: the preview layer under the textarea holds a heading.
|
||||
await s.page.locator("#notepad-editor .overtype-preview h1").waitFor();
|
||||
assert.match(await s.page.locator("#notepad-editor .overtype-preview h1").innerText(), /Shopping list/);
|
||||
assert.equal(await s.page.locator("#notepad-editor .overtype-preview strong").count(), 1);
|
||||
|
||||
await until(() => onDisk(s) === "# Shopping list\n\nSome **bold** text", 4000);
|
||||
assert.ok(Date.now() - typedAt < 2000, `saved ${Date.now() - typedAt} ms after the last key`);
|
||||
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent === "Saved");
|
||||
|
||||
// Close flushes at once, without waiting out the debounce.
|
||||
await s.page.keyboard.type("\nmore");
|
||||
await s.page.click("#notepad-close");
|
||||
const closedAt = Date.now();
|
||||
await until(() => onDisk(s).endsWith("\nmore"), 4000);
|
||||
assert.ok(Date.now() - closedAt < SAVE_DEBOUNCE_MS, `flushed ${Date.now() - closedAt} ms after close`);
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement && document.activeElement.id), "btn-notepad");
|
||||
|
||||
const expected = "# Shopping list\n\nSome **bold** text\nmore";
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await openNotepad(s);
|
||||
assert.equal(await shows(s, expected), expected, "a reload shows the saved note");
|
||||
|
||||
// A server restart (the agent's open --resume) keeps it too.
|
||||
cli(["stop", "--session", s.sid], { cwd: s.project });
|
||||
await until(async () => !(await s.answers()), 5000);
|
||||
const resumed = cli(["open", "--resume", s.sid, "--no-open", "--workflow", "plan"], { cwd: s.project }).json;
|
||||
s.url = resumed.url;
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await openNotepad(s);
|
||||
assert.equal(await shows(s, expected), expected, "a restarted server shows the saved note");
|
||||
});
|
||||
|
||||
test("two sessions in two folders keep two separate notepads", async (t) => {
|
||||
const a = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const b = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(a);
|
||||
await input(a).fill("Folder A's note");
|
||||
await until(() => onDisk(a) === "Folder A's note", 4000);
|
||||
await openNotepad(b);
|
||||
assert.equal(await input(b).inputValue(), "", "the second folder starts empty");
|
||||
await input(b).fill("Folder B's note");
|
||||
await until(() => onDisk(b) === "Folder B's note", 4000);
|
||||
assert.equal(onDisk(a), "Folder A's note");
|
||||
// Reopening each shows its own.
|
||||
await closeNotepad(a);
|
||||
await openNotepad(a);
|
||||
assert.equal(await shows(a, "Folder A's note"), "Folder A's note");
|
||||
});
|
||||
|
||||
test("the editor breaks no content-security rule, and hostile Markdown runs nothing", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const consoleErrors = [];
|
||||
s.page.on("console", (m) => {
|
||||
if (m.type() === "error") consoleErrors.push(m.text());
|
||||
});
|
||||
await s.context.addInitScript(() => {
|
||||
window.__violations = [];
|
||||
document.addEventListener("securitypolicyviolation", (e) =>
|
||||
window.__violations.push(`${e.violatedDirective} ${e.blockedURI} ${e.sourceFile}:${e.lineNumber} ${e.sample}`),
|
||||
);
|
||||
});
|
||||
await s.page.reload({ waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
await openNotepad(s);
|
||||
await input(s).focus();
|
||||
await s.page.keyboard.type(
|
||||
"# Title\n\n- a list with `code` and [a link](https://example.com)\n> quoted\n\n" +
|
||||
'<img src=x onerror="window.__pwned = 1">\n<script>window.__pwned2 = 1</script>\n' +
|
||||
'<a href="javascript:window.__pwned3 = 1">click</a>\n',
|
||||
);
|
||||
await until(() => onDisk(s).includes("__pwned3"), 4000);
|
||||
await s.page.waitForTimeout(300);
|
||||
const result = await s.page.evaluate(() => ({
|
||||
violations: window.__violations,
|
||||
pwned: [window.__pwned, window.__pwned2, window.__pwned3],
|
||||
imgs: document.querySelectorAll("#notepad-editor .overtype-preview img").length,
|
||||
scripts: document.querySelectorAll("#notepad-editor script").length,
|
||||
styleTag: Boolean(document.querySelector("style.overtype-styles")),
|
||||
}));
|
||||
assert.deepEqual(result.violations, [], "no content-security violations with the notepad open");
|
||||
assert.deepEqual(result.pwned, [undefined, undefined, undefined], "nothing typed ran");
|
||||
assert.equal(result.imgs, 0, "typed HTML stays text");
|
||||
assert.equal(result.scripts, 0);
|
||||
assert.equal(result.styleTag, false, "OverType injected no <style>");
|
||||
assert.deepEqual(consoleErrors.filter((e) => /Content.Security.Policy|Refused to/i.test(e)), []);
|
||||
// The heading is styled from the stylesheet the page ships.
|
||||
const h1 = await s.page.locator("#notepad-editor .overtype-preview h1").evaluate((el) => getComputedStyle(el).fontWeight);
|
||||
assert.ok(Number(h1) >= 600 || h1 === "bold", `the heading is bold (${h1})`);
|
||||
});
|
||||
|
||||
// The editor redraws only the lines that changed (patchPreview in
|
||||
// screens/notepad.js): about 90 ms a key at 200 KB on a quiet machine, against
|
||||
// about 310 ms when every key redrew the whole note. The bar is higher than
|
||||
// that because `npm test` runs every test file at once, which alone adds 50 ms
|
||||
// or more; it still catches a slide back toward whole-note redraws.
|
||||
const KEY_BUDGET_MS = 200;
|
||||
|
||||
test("typing into a 200 KB note keeps input-to-paint under the key budget on average", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const block = "## Heading\n\nSome **bold** text with `code` and a [link](https://example.com).\n\n- an item\n- another\n\n";
|
||||
saveNote(s.project, block.repeat(Math.ceil((200 * 1024) / block.length)));
|
||||
await openNotepad(s);
|
||||
await s.page.waitForFunction(() => document.querySelector("#notepad-editor .overtype-input").value.length > 200000);
|
||||
await s.page.evaluate(() => {
|
||||
window.__lags = [];
|
||||
window.addEventListener(
|
||||
"keydown",
|
||||
() => {
|
||||
const t0 = performance.now();
|
||||
requestAnimationFrame(() => requestAnimationFrame(() => window.__lags.push(performance.now() - t0)));
|
||||
},
|
||||
{ capture: true },
|
||||
);
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
ta.focus();
|
||||
ta.setSelectionRange(ta.value.length, ta.value.length);
|
||||
});
|
||||
// `npm test` runs every test file at once, and a round that lands in another
|
||||
// file's busiest moment measures the machine rather than the editor: the
|
||||
// best of up to three rounds is the editor's number.
|
||||
const averages = [];
|
||||
for (let round = 0; round < 3; round++) {
|
||||
await s.page.evaluate(() => (window.__lags = []));
|
||||
await s.page.keyboard.type("typing at the end of a long note", { delay: 60 });
|
||||
await s.page.waitForTimeout(200);
|
||||
const lags = await s.page.evaluate(() => window.__lags);
|
||||
assert.ok(lags.length >= 20, `measured ${lags.length} keys`);
|
||||
averages.push(lags.reduce((a, b) => a + b, 0) / lags.length);
|
||||
if (averages.at(-1) < KEY_BUDGET_MS) break;
|
||||
}
|
||||
const best = Math.min(...averages);
|
||||
assert.ok(best < KEY_BUDGET_MS, `average input-to-paint ${averages.map((a) => a.toFixed(1)).join(", ")} ms`);
|
||||
});
|
||||
|
||||
test("the textarea and the styled layer line up, line for line", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await input(s).fill(
|
||||
"# A heading\n## A smaller one\nPlain text with **bold**, *em* and `code`.\n> a quote\n- a list item\n\n" +
|
||||
"A long line that wraps: " + "word ".repeat(80) + "\nThe last line",
|
||||
);
|
||||
const m = await s.page.evaluate(() => {
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const pv = document.querySelector("#notepad-editor .overtype-preview");
|
||||
const cs = (el) => getComputedStyle(el);
|
||||
const lineHeight = parseFloat(cs(ta).lineHeight);
|
||||
const lines = [...pv.children];
|
||||
const top0 = lines[0].getBoundingClientRect().top;
|
||||
return {
|
||||
lineHeight,
|
||||
count: lines.length,
|
||||
offsets: lines.map((el) => (el.getBoundingClientRect().top - top0) / lineHeight),
|
||||
heights: [ta.scrollHeight, pv.scrollHeight],
|
||||
fonts: [ta, pv, pv.querySelector("h1"), pv.querySelector("h2"), pv.querySelector("strong"), pv.querySelector("code")].map(
|
||||
(el) => `${cs(el).fontFamily} ${cs(el).fontSize}`,
|
||||
),
|
||||
padding: [cs(ta).paddingTop, cs(pv).paddingTop, cs(ta).paddingLeft, cs(pv).paddingLeft],
|
||||
};
|
||||
});
|
||||
assert.equal(m.count, 8, "one preview line per text line");
|
||||
for (const [i, offset] of m.offsets.entries()) {
|
||||
assert.ok(Math.abs(offset - Math.round(offset)) < 0.05, `line ${i + 1} sits on the grid (${offset})`);
|
||||
}
|
||||
assert.ok(Math.abs(m.heights[0] - m.heights[1]) <= 1, `same height: ${m.heights.join(" vs ")}`);
|
||||
assert.equal(new Set(m.fonts).size, 1, `one font and size everywhere: ${[...new Set(m.fonts)].join(" | ")}`);
|
||||
assert.equal(m.padding[0], m.padding[1]);
|
||||
assert.equal(m.padding[2], m.padding[3]);
|
||||
});
|
||||
|
||||
test("the editor follows the console's light and dark themes", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await input(s).fill("# Heading\n\nText");
|
||||
const colours = (theme) =>
|
||||
s.page.evaluate((th) => {
|
||||
document.documentElement.setAttribute("data-theme", th);
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
const probe = (value, prop = "color") => {
|
||||
const el = document.createElement("span");
|
||||
el.style[prop] = value;
|
||||
document.body.appendChild(el);
|
||||
const out = getComputedStyle(el)[prop];
|
||||
el.remove();
|
||||
return out;
|
||||
};
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const pv = document.querySelector("#notepad-editor .overtype-preview");
|
||||
return {
|
||||
ink: probe(root.getPropertyValue("--ink")),
|
||||
accent: probe(root.getPropertyValue("--accent")),
|
||||
panel: probe(root.getPropertyValue("--panel"), "backgroundColor"),
|
||||
text: getComputedStyle(pv).color,
|
||||
heading: getComputedStyle(pv.querySelector("h1")).color,
|
||||
caret: getComputedStyle(ta).caretColor,
|
||||
background: getComputedStyle(document.querySelector("#notepad-editor .overtype-wrapper")).backgroundColor,
|
||||
};
|
||||
}, theme);
|
||||
const light = await colours("light");
|
||||
const dark = await colours("dark");
|
||||
for (const [name, c] of Object.entries({ light, dark })) {
|
||||
assert.equal(c.text, c.ink, `${name}: text in the console's ink`);
|
||||
assert.equal(c.heading, c.accent, `${name}: headings in the highlight colour`);
|
||||
assert.equal(c.caret, c.accent, `${name}: the caret in the highlight colour`);
|
||||
assert.equal(c.background, c.panel, `${name}: the editor on the panel colour`);
|
||||
}
|
||||
assert.notEqual(light.text, dark.text, "the two themes differ");
|
||||
assert.notEqual(light.background, dark.background);
|
||||
});
|
||||
|
||||
test("after edits anywhere, the styled layer matches a full redraw", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const block = "## Heading\n\nSome **bold** and a [link](https://example.com).\n\n- an item\n- another\n1. first\n2. second\n\n```js\nconst x = 1;\n```\n> quote\n";
|
||||
saveNote(s.project, block.repeat(40));
|
||||
await openNotepad(s);
|
||||
await s.page.waitForFunction(() => document.querySelector("#notepad-editor .overtype-input").value.length > 1000);
|
||||
// The layer on the page against one drawn from scratch from the same text.
|
||||
const matches = () =>
|
||||
s.page.evaluate(async () => {
|
||||
const { withoutStyleAttrs } = await import("/notepad.js");
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const pv = document.querySelector("#notepad-editor .overtype-preview");
|
||||
const parser = ta.closest(".overtype-wrapper")._instance.constructor.MarkdownParser;
|
||||
const fresh = document.createElement("div");
|
||||
fresh.className = "overtype-preview";
|
||||
// Parsed into an inert template, so nothing in it reaches the page.
|
||||
const tpl = document.createElement("template");
|
||||
tpl.innerHTML = withoutStyleAttrs(parser.parse(ta.value, -1, false, undefined, false));
|
||||
fresh.append(tpl.content);
|
||||
// OverType shades code fences in pairs, in order, after drawing
|
||||
// (_applyCodeBlockBackgrounds): the fresh copy gets the same, so a stale
|
||||
// mark left on the page shows as a difference.
|
||||
const fences = fresh.querySelectorAll(".code-fence");
|
||||
for (let i = 0; i < fences.length - 1; i += 2) {
|
||||
for (const f of [fences[i], fences[i + 1]]) {
|
||||
f.parentElement.classList.add("code-block-line");
|
||||
f.style.display = "block";
|
||||
}
|
||||
}
|
||||
// An emptied style or class attribute looks exactly like none.
|
||||
const plain = (html) => html.replace(/ (style|class)=""/g, "");
|
||||
return plain(pv.innerHTML) === plain(fresh.innerHTML);
|
||||
});
|
||||
const at = (pos) =>
|
||||
s.page.evaluate((p) => {
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
const i = p < 0 ? ta.value.length + p : p;
|
||||
ta.focus();
|
||||
ta.setSelectionRange(i, i);
|
||||
}, pos);
|
||||
await at(0);
|
||||
await s.page.keyboard.type("# A new first line\n");
|
||||
assert.ok(await matches(), "typing at the top");
|
||||
await at(600);
|
||||
await s.page.keyboard.type("\n- a list item added in the middle\n[another link](https://example.org) ");
|
||||
assert.ok(await matches(), "typing in the middle, adding a link before others");
|
||||
await at(900);
|
||||
for (let i = 0; i < 30; i++) await s.page.keyboard.press("Backspace");
|
||||
assert.ok(await matches(), "deleting across lines");
|
||||
await at(-5);
|
||||
await s.page.keyboard.type("\n```\nopen fence at the end");
|
||||
assert.ok(await matches(), "an unclosed fence at the end");
|
||||
await s.page.keyboard.press("Control+a");
|
||||
await s.page.keyboard.press("Backspace");
|
||||
assert.ok(await matches(), "clearing it all");
|
||||
await s.page.keyboard.type("# Back again");
|
||||
assert.ok(await matches(), "typing into the empty note");
|
||||
// Four fences, two shaded blocks; deleting the first fence leaves three, and
|
||||
// the last one, kept from the drawing before, is no longer paired.
|
||||
// Ending on the last fence, so its line is the one kept unchanged.
|
||||
await s.page.keyboard.type("\n```\ncode\n```\ntext\n```\nmore\n```");
|
||||
assert.ok(await matches(), "two fenced blocks");
|
||||
const firstFence = await s.page.evaluate(() => document.querySelector("#notepad-editor .overtype-input").value.indexOf("```"));
|
||||
await at(firstFence + 4);
|
||||
for (let i = 0; i < 4; i++) await s.page.keyboard.press("Backspace");
|
||||
assert.ok(await matches(), "the first fence deleted, unpairing the last");
|
||||
});
|
||||
|
||||
test("a note that cannot be read leaves the editor read-only, and nothing typed reaches the stored note", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
saveNote(s.project, "The real note");
|
||||
await s.page.route("**/notepad", (route) => (route.request().method() === "GET" ? route.abort() : route.continue()));
|
||||
await openNotepad(s, { loads: false });
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent === want, NOT_LOADED);
|
||||
assert.equal(await input(s).evaluate((el) => el.readOnly), true);
|
||||
await input(s).focus();
|
||||
await s.page.keyboard.type("typed into the empty editor");
|
||||
assert.equal(await input(s).inputValue(), "", "nothing could be typed");
|
||||
await s.page.waitForTimeout(SAVE_DEBOUNCE_MS + 400);
|
||||
assert.equal(onDisk(s), "The real note");
|
||||
// Once it can be read, reopening loads it and the editor opens up.
|
||||
await s.page.unroute("**/notepad");
|
||||
await closeNotepad(s);
|
||||
await openNotepad(s);
|
||||
assert.equal(await shows(s, "The real note"), "The real note");
|
||||
});
|
||||
|
||||
test("a note too long to save keeps its text when the notepad is closed and opened again", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
saveNote(s.project, "Saved earlier");
|
||||
await openNotepad(s);
|
||||
await shows(s, "Saved earlier");
|
||||
const long = "x".repeat(NOTE_MAX_BYTES) + " and some more";
|
||||
await input(s).fill(long);
|
||||
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent.startsWith("Too long to save"));
|
||||
await closeNotepad(s);
|
||||
await openNotepad(s);
|
||||
await s.page.waitForTimeout(300);
|
||||
assert.equal((await input(s).inputValue()).length, long.length, "the long text is still in the editor");
|
||||
assert.equal(onDisk(s), "Saved earlier", "and nothing over the cap was saved");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------ pictures */
|
||||
|
||||
// The stored pictures for the session's folder, and whether each of a
|
||||
// picture's two files is on disk.
|
||||
const stored = (s) => readNotepad(s.project).images;
|
||||
const filesOf = (s, id) => {
|
||||
const dir = path.join(notepadFolder(s.project), "images");
|
||||
return [fs.existsSync(path.join(dir, id + ".jpg")), fs.existsSync(path.join(dir, id + ".thumb.jpg"))];
|
||||
};
|
||||
|
||||
const thumbs = (s) => s.page.locator("#notepad-strip > li");
|
||||
const readyCount = (s, n) =>
|
||||
s.page.waitForFunction((want) => document.querySelectorAll("#notepad-strip > li.is-ready").length === want, n, { timeout: 5000 });
|
||||
|
||||
// A small PNG drawn in the page, as base64: a real picture for reencode() to
|
||||
// decode, one colour per call so the pictures differ.
|
||||
const pngBase64 = (s, colour) =>
|
||||
s.page.evaluate(async (fill) => {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = 320;
|
||||
c.height = 200;
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fillRect(0, 0, 320, 200);
|
||||
const blob = await new Promise((resolve) => c.toBlob(resolve, "image/png"));
|
||||
let bin = "";
|
||||
for (const b of new Uint8Array(await blob.arrayBuffer())) bin += String.fromCharCode(b);
|
||||
return btoa(bin);
|
||||
}, colour);
|
||||
|
||||
const pngFile = async (s, colour, name = "shot.png") => ({ name, mimeType: "image/png", buffer: Buffer.from(await pngBase64(s, colour), "base64") });
|
||||
|
||||
async function addViaButton(s, colour) {
|
||||
const before = stored(s).length;
|
||||
await s.page.setInputFiles("#notepad-file", await pngFile(s, colour));
|
||||
await until(() => stored(s).length === before + 1 && filesOf(s, stored(s).at(-1).id).every(Boolean), 5000);
|
||||
await readyCount(s, before + 1);
|
||||
}
|
||||
|
||||
// A synthetic paste or drop of one PNG, sent to the editor, where a person's
|
||||
// would land. A paste answers whether the page took it from the editor, a
|
||||
// drop whether the dialog lit up while it was dragged over.
|
||||
const sendPicture = (s, kind, colour) =>
|
||||
s.page.evaluate(
|
||||
async ({ kind, fill }) => {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = 240;
|
||||
c.height = 160;
|
||||
const ctx = c.getContext("2d");
|
||||
ctx.fillStyle = fill;
|
||||
ctx.fillRect(0, 0, 240, 160);
|
||||
const blob = await new Promise((resolve) => c.toBlob(resolve, "image/png"));
|
||||
const dt = new DataTransfer();
|
||||
dt.items.add(new File([blob], "pasted.png", { type: "image/png" }));
|
||||
const ta = document.querySelector("#notepad-editor .overtype-input");
|
||||
if (kind === "paste") return !ta.dispatchEvent(new ClipboardEvent("paste", { clipboardData: dt, bubbles: true, cancelable: true }));
|
||||
ta.dispatchEvent(new DragEvent("dragover", { dataTransfer: dt, bubbles: true, cancelable: true }));
|
||||
const lit = document.getElementById("notepad-modal").classList.contains("is-drop");
|
||||
ta.dispatchEvent(new DragEvent("drop", { dataTransfer: dt, bubbles: true, cancelable: true }));
|
||||
return lit;
|
||||
},
|
||||
{ kind, fill: colour },
|
||||
);
|
||||
|
||||
test("Add image, paste and drop each add a thumbnail whose files are on disk and which survives closing", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
assert.equal(await thumbs(s).count(), 0);
|
||||
|
||||
await addViaButton(s, "#c33");
|
||||
|
||||
assert.equal(await sendPicture(s, "paste", "#3c3"), true, "the paste was taken from the editor");
|
||||
await until(() => stored(s).length === 2 && filesOf(s, stored(s)[1].id).every(Boolean), 5000);
|
||||
|
||||
assert.equal(await sendPicture(s, "drop", "#33c"), true, "the dialog lit up while a picture was dragged over it");
|
||||
await until(() => stored(s).length === 3 && filesOf(s, stored(s)[2].id).every(Boolean), 5000);
|
||||
await readyCount(s, 3);
|
||||
assert.equal(await s.page.locator("#notepad-modal.is-drop").count(), 0, "the highlight is gone after the drop");
|
||||
assert.equal(await input(s).inputValue(), "", "no picture landed in the text");
|
||||
|
||||
const alts = await s.page.locator("#notepad-strip img").evaluateAll((imgs) => imgs.map((i) => i.alt));
|
||||
assert.deepEqual(alts, ["Notepad image 1", "Notepad image 2", "Notepad image 3"]);
|
||||
const xs = await s.page.locator("#notepad-strip .notepad-thumb-delete").evaluateAll((b) => b.map((x) => x.getAttribute("aria-label")));
|
||||
assert.deepEqual(xs, ["Delete image 1", "Delete image 2", "Delete image 3"]);
|
||||
|
||||
// Closed and opened again, the strip is drawn from the stored pictures,
|
||||
// oldest first, each from its stored thumbnail.
|
||||
const ids = stored(s).map((img) => img.id);
|
||||
await closeNotepad(s);
|
||||
await openNotepad(s);
|
||||
// Until the re-read lands, the strip still shows the thumbnails made here.
|
||||
await s.page.waitForFunction(() => {
|
||||
const imgs = [...document.querySelectorAll("#notepad-strip img")];
|
||||
return imgs.length === 3 && imgs.every((i) => new URL(i.src).pathname.startsWith("/notepad/images/"));
|
||||
});
|
||||
const srcs = await s.page.locator("#notepad-strip img").evaluateAll((imgs) => imgs.map((i) => new URL(i.src).pathname));
|
||||
assert.deepEqual(srcs, ids.map((id) => `/notepad/images/${id}.thumb.jpg`));
|
||||
await s.page.waitForFunction(() => [...document.querySelectorAll("#notepad-strip img")].every((i) => i.complete && i.naturalWidth > 0));
|
||||
});
|
||||
|
||||
test("a pasted text snippet still lands in the editor", 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 });
|
||||
await openNotepad(s);
|
||||
await s.page.evaluate(() => navigator.clipboard.writeText("a pasted snippet"));
|
||||
await input(s).focus();
|
||||
await s.page.keyboard.press("Control+V");
|
||||
await shows(s, "a pasted snippet");
|
||||
await until(() => onDisk(s) === "a pasted snippet", 4000);
|
||||
assert.equal(stored(s).length, 0, "no picture was added");
|
||||
assert.equal(await thumbs(s).count(), 0);
|
||||
});
|
||||
|
||||
test("the X asks first: Keep keeps the picture, Delete removes both its files", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await addViaButton(s, "#c33");
|
||||
await addViaButton(s, "#3c3");
|
||||
const [first, second] = stored(s).map((img) => img.id);
|
||||
|
||||
await s.page.click("#notepad-strip li:nth-child(1) .notepad-thumb-delete");
|
||||
await s.page.locator(".notepad-ask").waitFor();
|
||||
assert.match(await s.page.locator(".notepad-ask").innerText(), /Delete this image\?/);
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.textContent), "Keep", "Keep has the focus");
|
||||
assert.deepEqual(filesOf(s, first), [true, true], "one click deleted nothing");
|
||||
// Enter on the focused button keeps it.
|
||||
await s.page.keyboard.press("Enter");
|
||||
await s.page.waitForFunction(() => !document.querySelector(".notepad-ask"));
|
||||
await readyCount(s, 2);
|
||||
assert.deepEqual(filesOf(s, first), [true, true]);
|
||||
|
||||
await s.page.click("#notepad-strip li:nth-child(1) .notepad-thumb-delete");
|
||||
await s.page.click(".notepad-ask-delete");
|
||||
await until(() => !filesOf(s, first).some(Boolean), 4000);
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
|
||||
assert.deepEqual(stored(s).map((img) => img.id), [second]);
|
||||
assert.equal(await s.page.locator("#notepad-strip img").getAttribute("alt"), "Notepad image 1");
|
||||
});
|
||||
|
||||
test("the preview opens at the clicked picture, steps and wraps, and Esc closes it before the Notepad", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
for (const colour of ["#c33", "#3c3", "#33c"]) await addViaButton(s, colour);
|
||||
const urls = stored(s).map((img) => img.url);
|
||||
const shown = () =>
|
||||
s.page.evaluate(() => ({
|
||||
src: new URL(document.getElementById("notepad-preview-img").src).pathname,
|
||||
count: document.getElementById("notepad-preview-count").textContent,
|
||||
}));
|
||||
|
||||
await s.page.click("#notepad-strip li:nth-child(2) .notepad-thumb-open");
|
||||
await s.page.locator("#notepad-preview[open]").waitFor();
|
||||
assert.deepEqual(await shown(), { src: urls[1], count: "2 of 3" });
|
||||
await s.page.waitForFunction(() => {
|
||||
const i = document.getElementById("notepad-preview-img");
|
||||
return i.complete && i.naturalWidth > 0;
|
||||
});
|
||||
await s.page.keyboard.press("ArrowRight");
|
||||
assert.deepEqual(await shown(), { src: urls[2], count: "3 of 3" });
|
||||
await s.page.keyboard.press("ArrowRight");
|
||||
assert.deepEqual(await shown(), { src: urls[0], count: "1 of 3" }, "Next wraps to the first");
|
||||
await s.page.keyboard.press("ArrowLeft");
|
||||
assert.deepEqual(await shown(), { src: urls[2], count: "3 of 3" }, "Previous wraps to the last");
|
||||
await s.page.click("#notepad-preview-prev");
|
||||
assert.deepEqual(await shown(), { src: urls[1], count: "2 of 3" });
|
||||
await s.page.click("#notepad-preview-next");
|
||||
assert.deepEqual(await shown(), { src: urls[2], count: "3 of 3" });
|
||||
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-preview").open);
|
||||
assert.equal(await s.page.evaluate(() => document.getElementById("notepad-modal").open), true, "the Notepad stays open");
|
||||
assert.equal(
|
||||
await s.page.evaluate(() => document.activeElement.closest("li") === document.querySelector("#notepad-strip li:nth-child(2)")),
|
||||
true,
|
||||
"the focus is back on the thumbnail it opened from",
|
||||
);
|
||||
await s.page.keyboard.press("Escape");
|
||||
await s.page.waitForFunction(() => !document.getElementById("notepad-modal").open);
|
||||
|
||||
// One picture: nothing to step to.
|
||||
for (const id of stored(s).slice(1).map((img) => img.id)) removeImage(s.project, id);
|
||||
await openNotepad(s);
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
|
||||
await s.page.click("#notepad-strip .notepad-thumb-open");
|
||||
await s.page.locator("#notepad-preview[open]").waitFor();
|
||||
assert.equal(await s.page.locator("#notepad-preview-prev").isVisible(), false);
|
||||
assert.equal(await s.page.locator("#notepad-preview-next").isVisible(), false);
|
||||
assert.equal(await s.page.locator("#notepad-preview-count").innerText(), "1 of 1");
|
||||
});
|
||||
|
||||
test("past the cap, what fits is added and the cap sentence stays up; the 201st alone is refused", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
// The store checks only the JPEG signature, so a stub stands in for 199.
|
||||
const jpeg = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 0xff, 0xd9]);
|
||||
for (let i = 0; i < NOTEPAD_MAX_IMAGES - 1; i++) addImage(s.project, jpeg);
|
||||
await openNotepad(s);
|
||||
await s.page.waitForFunction((n) => document.querySelectorAll("#notepad-strip > li").length === n, NOTEPAD_MAX_IMAGES - 1);
|
||||
const status = () => s.page.locator("#notepad-status").textContent();
|
||||
|
||||
// Two for one place: the first lands, and the sentence outlives its upload.
|
||||
await s.page.setInputFiles("#notepad-file", [await pngFile(s, "#c33", "fits.png"), await pngFile(s, "#3c3", "too-many.png")]);
|
||||
await until(() => stored(s).length === NOTEPAD_MAX_IMAGES && filesOf(s, stored(s).at(-1).id).every(Boolean), 5000);
|
||||
await s.page.waitForFunction((n) => document.querySelectorAll("#notepad-strip > li.is-ready").length === n, NOTEPAD_MAX_IMAGES);
|
||||
assert.ok((await status()).includes(errorSentence("too-many")), `still says the cap: "${await status()}"`);
|
||||
|
||||
await s.page.setInputFiles("#notepad-file", await pngFile(s, "#33c", "one-more.png"));
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence("too-many"));
|
||||
assert.equal(await thumbs(s).count(), NOTEPAD_MAX_IMAGES);
|
||||
assert.equal(stored(s).length, NOTEPAD_MAX_IMAGES);
|
||||
});
|
||||
|
||||
const isPath = (want) => (url) => url.pathname === want;
|
||||
|
||||
test("a failed upload shows Retry, which sends only what did not land and keeps the focus on the thumbnail", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
// The picture lands, its thumbnail does not.
|
||||
await s.page.route(isPath("/notepad/thumb"), (route) => route.abort(), { times: 1 });
|
||||
await s.page.setInputFiles("#notepad-file", await pngFile(s, "#c33"));
|
||||
await s.page.locator("#notepad-strip li.is-failed .notepad-retry").waitFor();
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence(null));
|
||||
assert.equal(stored(s).length, 1);
|
||||
const { id } = stored(s)[0];
|
||||
assert.deepEqual(filesOf(s, id), [true, false]);
|
||||
|
||||
await s.page.locator(".notepad-retry").focus();
|
||||
await s.page.keyboard.press("Enter");
|
||||
await readyCount(s, 1);
|
||||
await until(() => filesOf(s, id).every(Boolean), 4000);
|
||||
assert.deepEqual(stored(s).map((img) => img.id), [id], "Retry did not store the picture twice");
|
||||
assert.equal(await s.page.evaluate(() => Boolean(document.activeElement.closest("#notepad-strip li"))), true, "the focus stayed on the thumbnail");
|
||||
await s.page.waitForFunction(() => document.getElementById("notepad-status").textContent === "", null, { timeout: 4000 });
|
||||
|
||||
// A picture the server turned away for good is taken off, with why.
|
||||
await s.page.route(isPath("/notepad/image"), (route) => route.fulfill({ status: 413, contentType: "application/json", body: '{"error":"too-large"}' }), { times: 1 });
|
||||
await s.page.setInputFiles("#notepad-file", await pngFile(s, "#3c3"));
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence("too-large"));
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-strip > li").length === 1);
|
||||
assert.equal(stored(s).length, 1);
|
||||
});
|
||||
|
||||
test("a delete that fails keeps the thumbnail and says why", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await openNotepad(s);
|
||||
await addViaButton(s, "#c33");
|
||||
const { id } = stored(s)[0];
|
||||
await s.page.route(isPath("/notepad/image/delete"), (route) => route.abort(), { times: 1 });
|
||||
await s.page.click("#notepad-strip .notepad-thumb-delete");
|
||||
await s.page.click(".notepad-ask-delete");
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence(null));
|
||||
await s.page.waitForFunction(() => !document.querySelector(".notepad-ask"));
|
||||
assert.equal(await thumbs(s).count(), 1);
|
||||
assert.deepEqual(filesOf(s, id), [true, true]);
|
||||
assert.equal(await s.page.evaluate(() => document.activeElement.getAttribute("aria-label")), "Delete image 1", "the focus is back on the X");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------- Cleanup, phone, Help */
|
||||
|
||||
// Every file and folder under `dir`, and `dir` itself, moved `days` back.
|
||||
function backdateAll(dir, days) {
|
||||
for (const e of fs.readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = path.join(dir, e.name);
|
||||
if (e.isDirectory()) backdateAll(p, days);
|
||||
else backdate(p, days);
|
||||
}
|
||||
backdate(dir, days);
|
||||
}
|
||||
|
||||
test("User Preferences, Cleanup offers a month-old notepad by its folder and removes it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
saveNote(s.project, "an old idea");
|
||||
backdateAll(notepadFolder(s.project), 31);
|
||||
// Here the notepads folder sits in the console home (NOTEPADS_DIR), where
|
||||
// Cleanup would list it as a stray once everything in it is old; a notepad
|
||||
// written today keeps it in use, as the real ~/.plan2code/notepads is never
|
||||
// inside the console folder.
|
||||
const other = path.join(s.project, "elsewhere");
|
||||
saveNote(other, "today");
|
||||
t.after(() => fs.rmSync(notepadFolder(other), { recursive: true, force: true }));
|
||||
|
||||
await s.page.click("#btn-looks");
|
||||
await s.page.click("#cleanup-scan");
|
||||
const list = s.page.locator("#cleanup-list");
|
||||
const row = list.locator(".cleanup-row").filter({ hasText: "Notepad for" });
|
||||
await row.waitFor();
|
||||
assert.equal(await row.count(), 1, "one item for the whole notepad");
|
||||
assert.equal((await row.locator("span").first().innerText()).trim(), "Notepad for " + path.resolve(s.project));
|
||||
assert.ok((await list.locator(".cleanup-summary").innerText()).includes("1 old notepad"), "the summary counts it as a notepad");
|
||||
assert.equal(await list.locator(".cleanup-row").filter({ hasText: "notepads/" }).count(), 0, "the notepads folder is no stray");
|
||||
assert.equal(fs.existsSync(notepadFolder(s.project)), true, "a scan only looks");
|
||||
|
||||
await s.page.click("#cleanup-delete");
|
||||
await s.page.waitForFunction(() => /^Deleted /.test(document.getElementById("cleanup-status").textContent));
|
||||
assert.equal(fs.existsSync(notepadFolder(s.project)), false, "the whole notepad folder went");
|
||||
assert.equal(readNotepad(s.project).text, "");
|
||||
assert.ok(!fs.readdirSync(path.dirname(notepadFolder(s.project))).includes(notepadKey(s.project)));
|
||||
});
|
||||
|
||||
test("the notepad works at phone width: full screen, nothing wider than the window, fingertip-sized controls", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.setViewportSize({ width: 390, height: 844 });
|
||||
const noSideScroll = async (where) => {
|
||||
const { sw, iw } = await s.page.evaluate(() => ({ sw: document.documentElement.scrollWidth, iw: window.innerWidth }));
|
||||
assert.ok(sw <= iw, `${where}: the page is ${sw}px wide in a ${iw}px window`);
|
||||
};
|
||||
const box = (sel) => s.page.locator(sel).first().boundingBox();
|
||||
await noSideScroll("the session");
|
||||
assert.ok((await box("#btn-notepad")).width >= 44, "the icon is a fingertip wide");
|
||||
|
||||
await openNotepad(s);
|
||||
await addViaButton(s, "#c33");
|
||||
await noSideScroll("the notepad");
|
||||
const modal = await box("#notepad-modal");
|
||||
assert.deepEqual([modal.x, modal.y, modal.width, modal.height], [0, 0, 390, 844], "the notepad fills the screen");
|
||||
const inner = await s.page.$eval("#notepad-modal", (m) => ({ sw: m.scrollWidth, cw: m.clientWidth }));
|
||||
assert.ok(inner.sw <= inner.cw, `the dialog scrolls sideways: ${inner.sw} > ${inner.cw}`);
|
||||
for (const sel of ["#notepad-add", "#notepad-close"]) assert.ok((await box(sel)).height >= 44, `${sel} is a fingertip tall`);
|
||||
const x = await box(".notepad-thumb-delete");
|
||||
assert.ok(x.width >= 30 && x.height >= 30, "the X is big enough to tap");
|
||||
const strip = await box("#notepad-strip");
|
||||
assert.ok(strip.width > 300, "the pictures get the full width under Add image");
|
||||
|
||||
await s.page.click(".notepad-thumb-open");
|
||||
await s.page.locator("#notepad-preview[open]").waitFor();
|
||||
await noSideScroll("the preview");
|
||||
const img = await box("#notepad-preview-img");
|
||||
assert.ok(img.x >= 0 && img.x + img.width <= 390, "the picture fits the window");
|
||||
assert.ok((await box("#notepad-preview-close")).height >= 44);
|
||||
});
|
||||
|
||||
test("Help's Getting around panel describes the notepad", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-about");
|
||||
await s.page.locator("#help-modal").waitFor();
|
||||
await s.page.click("#help-tab-around");
|
||||
const panel = s.page.locator("#help-panel-around");
|
||||
await panel.getByRole("heading", { name: "Your notepad" }).waitFor();
|
||||
const text = await panel.innerText();
|
||||
for (const words of ["Notepad", "never sent to Plan2Code", "last save wins", "Cleanup"]) {
|
||||
assert.ok(text.includes(words), `the panel mentions ${words}`);
|
||||
}
|
||||
});
|
||||
@@ -485,6 +485,50 @@ test("the top bar's back triangle asks first, then sends __dashboard with the ty
|
||||
await s.page.waitForFunction(() => document.getElementById("btn-home").disabled);
|
||||
});
|
||||
|
||||
// What a person sees break: Commit it now, or Changelog's commit offer, hops
|
||||
// into Git without the dashboard, and the board opens over the last skill's
|
||||
// staged answer, its selected question and its open tab.
|
||||
test("a hop into Git from another skill starts the page clean: nothing staged, nothing selected, the questions view", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "changelog",
|
||||
payload: {
|
||||
items: [{ id: "q1", kind: "choice", title: "Which version", body: "The next version number.",
|
||||
options: [{ k: "A", text: "A patch release" }, { k: "B", text: "A minor release" }] }],
|
||||
docs: [{ id: "notes", title: "Release notes", blocks: [{ id: "b1", md: "## Draft\n\nTwo fixes." }] }],
|
||||
agent: { status: "waiting" },
|
||||
},
|
||||
});
|
||||
// The page's own state, from the module app.js loaded (same URL, same instance).
|
||||
const local = () =>
|
||||
s.page.evaluate(async () => {
|
||||
const { page } = await import("/state.js");
|
||||
return { workflow: page.S.workflow, staged: page.local.staged, selected: page.selected, view: page.view };
|
||||
});
|
||||
await itemCard(s.page, "q1").getByText("A minor release").click();
|
||||
await s.page.locator(".view-tab", { hasText: "Release notes" }).click();
|
||||
const before = await local();
|
||||
assert.deepEqual(Object.keys(before.staged), ["q1"], "the answer was never staged");
|
||||
assert.equal(before.selected, "q1");
|
||||
assert.notEqual(before.view, "questions", "the Release notes tab never opened");
|
||||
const draftFile = path.join(s.session, "draft.json");
|
||||
assert.ok(await until(() => fs.existsSync(draftFile) && fs.readFileSync(draftFile, "utf8").includes('"q1"'), 5000), "the staged answer never reached the draft");
|
||||
|
||||
// What Commit it now and Changelog's commit offer run.
|
||||
cli(["open", "--resume", s.sid, "--no-open", "--workflow", "git"], { cwd: s.project });
|
||||
await s.page.waitForFunction(async () => (await import("/state.js")).page.S.workflow === "git", null, { timeout: 10000 });
|
||||
// Long enough for the page's draft push (600 ms after a save) to have run.
|
||||
await new Promise((r) => setTimeout(r, 1500));
|
||||
const after = await local();
|
||||
assert.deepEqual(after.staged, {}, `the page kept the last skill's staged answer: ${JSON.stringify(after.staged)}`);
|
||||
assert.equal(after.selected, null, `the page kept the last skill's selection: ${after.selected}`);
|
||||
assert.equal(after.view, "questions", `the page kept the last skill's tab: ${after.view}`);
|
||||
const stored = await s.page.evaluate((key) => JSON.parse(localStorage.getItem(key) || "{}").staged || {}, `p2c-console:${s.sid}`);
|
||||
assert.deepEqual(stored, {}, "the browser's copy kept the staged answer");
|
||||
const draft = fs.existsSync(draftFile) ? JSON.parse(fs.readFileSync(draftFile, "utf8")) : {};
|
||||
assert.deepEqual(draft.staged || {}, {}, "the server's draft kept the staged answer");
|
||||
});
|
||||
|
||||
// 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 });
|
||||
|
||||
@@ -186,6 +186,7 @@ test("shape: no page module sets a style attribute from script", () => {
|
||||
const ROUTE_ORDER = [
|
||||
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
|
||||
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
|
||||
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/images/",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
|
||||
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
|
||||
];
|
||||
|
||||
@@ -14,8 +14,10 @@ import {
|
||||
subagentsFor,
|
||||
takesTemplates,
|
||||
labelFor,
|
||||
WORKFLOWS,
|
||||
isWorkflow,
|
||||
} 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 { CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, 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";
|
||||
@@ -106,6 +108,27 @@ test("the entries are frozen data", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("the meter, resume and Help fields are well formed on every entry", () => {
|
||||
const label = (v) => v === null || (typeof v === "string" && v.trim() !== "");
|
||||
for (const s of SKILLS) {
|
||||
const w = s.workflow;
|
||||
assert.ok(Object.hasOwn(s, "weight") && (s.weight === null || (typeof s.weight === "number" && s.weight >= 0)), `${w}: weight is a number >= 0, or null`);
|
||||
assert.ok(Object.hasOwn(s, "started") && label(s.started), `${w}: started is a label, or null`);
|
||||
assert.ok(Object.hasOwn(s, "ran") && label(s.ran), `${w}: ran is a label, or null`);
|
||||
assert.ok(Object.hasOwn(s, "resume") && ["overview", "folder", null].includes(s.resume), `${w}: resume is "overview", "folder" or null`);
|
||||
if (s.card && Object.hasOwn(s.card, "help")) assert.ok(typeof s.card.help === "string" && s.card.help.trim(), `${w}: card.help is a line, or absent`);
|
||||
if (s.metered) assert.ok(typeof s.weight === "number" && s.started, `${w}: a metered launch has a weight and a started label`);
|
||||
}
|
||||
});
|
||||
|
||||
test("WORKFLOWS lists every entry once, in order, and isWorkflow() knows only those", () => {
|
||||
assert.deepEqual(WORKFLOWS, SKILLS.map((s) => s.workflow));
|
||||
assert.equal(new Set(WORKFLOWS).size, WORKFLOWS.length);
|
||||
assert.ok(Object.isFrozen(WORKFLOWS));
|
||||
for (const w of WORKFLOWS) assert.equal(isWorkflow(w), true, w);
|
||||
for (const bad of ["x-ray", "", undefined, null, 3, "Plan"]) assert.equal(isWorkflow(bad), false, String(bad));
|
||||
});
|
||||
|
||||
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");
|
||||
@@ -159,7 +182,8 @@ function helpProblems(skills, topics) {
|
||||
|
||||
// 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);
|
||||
const reviews = skills.map((s) => s.review).filter(Boolean);
|
||||
const named = skills.filter((s) => s.card || s.workflow === "dashboard" || reviews.includes(s.skill)).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`),
|
||||
@@ -245,3 +269,114 @@ test("starting screen: the hint stays calm for ninety seconds, then points at th
|
||||
assert.match(startingHint(90000), /fills in by itself/, "ninety seconds is still calm");
|
||||
assert.match(startingHint(90001), /terminal has the play-by-play/);
|
||||
});
|
||||
|
||||
/* ---------------------------------------------- the docs held to the list */
|
||||
|
||||
// What one prose list says against what it should say: the lines naming the
|
||||
// missing and the extra names, empty when they agree.
|
||||
function listProblems(file, said, want) {
|
||||
const have = new Set(said);
|
||||
const should = new Set(want);
|
||||
return [
|
||||
...[...should].filter((n) => !have.has(n)).map((n) => `${file} is missing ${n}`),
|
||||
...[...have].filter((n) => !should.has(n)).map((n) => `${file} names ${n}, which is not in skills.js`),
|
||||
];
|
||||
}
|
||||
|
||||
const readSrc = (...parts) => fs.readFileSync(path.join(ROOT, "src", ...parts), "utf8");
|
||||
|
||||
// A markdown section's text: from its heading to the next heading of the same level.
|
||||
function sectionOf(text, heading) {
|
||||
const at = text.indexOf(heading);
|
||||
assert.ok(at >= 0, `no "${heading}" heading`);
|
||||
const level = heading.match(/^#+/)[0];
|
||||
const rest = text.slice(at + heading.length);
|
||||
const next = rest.search(new RegExp(`\\n${level} `));
|
||||
return next < 0 ? rest : rest.slice(0, next);
|
||||
}
|
||||
|
||||
test("docs: console.md's open step names every workflow", () => {
|
||||
const text = readSrc("web-console", "console.md");
|
||||
const m = text.match(/where `<w>` is one of ([\s\S]*?)\. Get it right/);
|
||||
assert.ok(m, "console.md: the open step's `<w>` sentence is not where the test looks");
|
||||
const said = [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]);
|
||||
assert.deepEqual(listProblems("src/web-console/console.md", said, WORKFLOWS), []);
|
||||
});
|
||||
|
||||
test("docs: the dashboard skill's launch table maps every skill to its workflow", () => {
|
||||
const section = sectionOf(readSrc("plan2code.md"), "## A pick arrives");
|
||||
const pairs = [];
|
||||
for (const line of section.split(/\r?\n/)) {
|
||||
if (!/^\|\s*plan2code-/.test(line)) continue;
|
||||
const cells = line.split("|").map((c) => c.trim()).filter(Boolean);
|
||||
for (let i = 0; i + 1 < cells.length; i += 2) pairs.push(`${cells[i]} -> ${cells[i + 1]}`);
|
||||
}
|
||||
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => `${s.skill} -> ${s.workflow}`);
|
||||
assert.deepEqual(listProblems("src/plan2code.md (A pick arrives)", pairs, want), []);
|
||||
});
|
||||
|
||||
test("docs: the dashboard skill's reads-and-writes table has a row for every skill", () => {
|
||||
const section = sectionOf(readSrc("plan2code.md"), "## What each skill reads and writes");
|
||||
const said = [];
|
||||
for (const line of section.split(/\r?\n/)) {
|
||||
const m = line.match(/^\|\s*([a-z0-9()-]+)\s*\|/);
|
||||
if (!m || m[1] === "skill" || /^-+$/.test(m[1])) continue;
|
||||
// `3-implement(-review)` stands for both build skills.
|
||||
if (m[1] === "3-implement(-review)") said.push("3-implement", "3-implement-review");
|
||||
else said.push(m[1]);
|
||||
}
|
||||
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => s.skill.replace(/^plan2code-/, ""));
|
||||
assert.deepEqual(listProblems("src/plan2code.md (What each skill reads and writes)", said, want), []);
|
||||
});
|
||||
|
||||
test("docs: `console.mjs help` lists every workflow, in order", () => {
|
||||
const out = cli(["help"]).stdout;
|
||||
const m = out.match(/workflows: ([\s\S]*?)\n\s*\n/);
|
||||
assert.ok(m, "console.mjs help prints no workflows: list");
|
||||
const said = m[1].split(/[·\s]+/).filter(Boolean);
|
||||
assert.deepEqual(listProblems("console.mjs help", said, WORKFLOWS), []);
|
||||
assert.deepEqual(said, [...WORKFLOWS], "console.mjs help: the workflows are in skills.js order");
|
||||
});
|
||||
|
||||
// A count goes stale the day a skill is added; the docs say "every skill".
|
||||
// Matched over the whole file, since the docs are hard-wrapped and a count can
|
||||
// sit on one line with "skills" on the next; the line is where the match starts.
|
||||
const SKILL_COUNT_RE = /\b(\d+|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty)\s+skills\b/gi;
|
||||
function skillCounts(files) {
|
||||
return files.flatMap(([file, text]) =>
|
||||
[...text.matchAll(SKILL_COUNT_RE)].map((m) => `${file}:${text.slice(0, m.index).split("\n").length} states a skill count: ${m[0].replace(/\s+/g, " ")}`)
|
||||
);
|
||||
}
|
||||
|
||||
test("docs: no console doc states how many skills there are", () => {
|
||||
const dir = path.join(ROOT, "src", "web-console");
|
||||
const files = [];
|
||||
const walk = (d) => {
|
||||
for (const e of fs.readdirSync(d, { withFileTypes: true })) {
|
||||
const p = path.join(d, e.name);
|
||||
if (e.isDirectory()) walk(p);
|
||||
else if (e.name.endsWith(".md")) files.push([path.relative(ROOT, p).replace(/\\/g, "/"), fs.readFileSync(p, "utf8")]);
|
||||
}
|
||||
};
|
||||
walk(dir);
|
||||
assert.ok(files.some(([f]) => f.endsWith("notes/implement.md")), "the walk reaches notes/");
|
||||
assert.deepEqual(skillCounts(files), []);
|
||||
// The check names the line, and catches a count wrapped across two lines.
|
||||
assert.deepEqual(skillCounts([["x.md", "Intro\nthe dashboard and all twelve skills behind it\n"]]), ["x.md:2 states a skill count: twelve skills"]);
|
||||
assert.deepEqual(skillCounts([["y.md", "Intro\nthe dashboard and all twelve\nskills behind it\n"]]), ["y.md:2 states a skill count: twelve skills"]);
|
||||
});
|
||||
|
||||
test("Implement's card launches Implement + Review when Review is ticked", () => {
|
||||
const card = SKILL_CATALOG.find((e) => e.skill === "plan2code-3-implement");
|
||||
assert.equal(card.title, "Implement");
|
||||
assert.equal(SKILL_CATALOG.some((e) => e.skill === "plan2code-3-implement-review"), false, "no card of its own");
|
||||
assert.equal(launchVariant(card, false), card);
|
||||
const reviewed = launchVariant(card, true);
|
||||
assert.equal(reviewed.skill, "plan2code-3-implement-review");
|
||||
assert.equal(reviewed.workflow, "implement-review");
|
||||
assert.equal(reviewed.command, "/plan2code-3-implement-review");
|
||||
assert.equal(reviewed.spec, true, "still takes the picked spec");
|
||||
assert.equal(catalogEntry("plan2code-3-implement-review").skill, "plan2code-3-implement", "handoffs and recommendations resolve to the card");
|
||||
const quick = SKILL_CATALOG.find((e) => e.skill === "plan2code-quick-task");
|
||||
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
|
||||
});
|
||||
@@ -10,8 +10,69 @@ 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 { SKILL_CATALOG, cardAvailability, defaultSpec, launchVariant } from "../src/web-console/public/answers.js";
|
||||
import { scanProject } from "../src/web-console/scan.mjs";
|
||||
import { MARKERS, TASK_LINE_RE, TASK_ID_RE, CHECKBOX_RE, STATUS_RE, statusOf, countTasks } from "../src/web-console/spec-files.mjs";
|
||||
|
||||
// The task pattern specs.mjs used before spec-files.mjs: TASK_ID_RE must take
|
||||
// a `-` task line apart into the same groups.
|
||||
const OLD_TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
||||
|
||||
test("spec files: every marker names its state, and the table is frozen", () => {
|
||||
assert.deepEqual(MARKERS, { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" });
|
||||
assert.ok(Object.isFrozen(MARKERS));
|
||||
});
|
||||
|
||||
test("spec files: -, * and numbered task lines all match, and TASK_ID_RE keeps the old groups", () => {
|
||||
for (const line of ["- [ ] **Task 1.2:** Do it", "* [x] **Task 1.2:** Do it", "1. [/] **Task 1.2:** Do it", " 12. [?] **Task 3.4:** Do it"]) {
|
||||
assert.ok(TASK_LINE_RE.test(line), `TASK_LINE_RE matches ${line}`);
|
||||
assert.ok(TASK_ID_RE.test(line), `TASK_ID_RE matches ${line}`);
|
||||
assert.ok(CHECKBOX_RE.test(line), `CHECKBOX_RE matches ${line}`);
|
||||
}
|
||||
assert.ok(!TASK_LINE_RE.test("- [ ] Acceptance: it works"), "a plain checkbox is no task line");
|
||||
// A line TASK_ID_RE cannot take apart is no task line for the scan either.
|
||||
for (const line of ["- [x] **task 1.1:** Lowercase", "- [x] **Task 1.1:** Two spaces"]) {
|
||||
assert.ok(!TASK_ID_RE.test(line) && !TASK_LINE_RE.test(line), `neither pattern takes ${line}`);
|
||||
}
|
||||
assert.ok(CHECKBOX_RE.test("- [ ] Acceptance: it works"), "but it is a checkbox");
|
||||
for (const line of ["- [x] **Task 2.3:** Build it", "- [ ] **Task 1.B:** Name it", "- [/] **Task 4.2a:** Split it"]) {
|
||||
assert.deepEqual([...line.match(TASK_ID_RE)], [...line.match(OLD_TASK_RE)], `the same groups for ${line}`);
|
||||
}
|
||||
assert.deepEqual("1. [x] **Task 2.3:** Build it".match(TASK_ID_RE).slice(1), ["x", "2", "3", ""], "a numbered line's groups");
|
||||
});
|
||||
|
||||
test("spec files: statusOf() reads every Status form, LF or CRLF, and is null without one", () => {
|
||||
const forms = { "**Status:** Complete": "Complete", "**Status**: In Progress": "In Progress", "Status: Not Started": "Not Started" };
|
||||
for (const [line, value] of Object.entries(forms)) {
|
||||
for (const eol of ["\n", "\r\n"]) {
|
||||
const text = `# Phase 1${eol}${eol}${line}${eol}**Estimated Tasks:** 3${eol}`;
|
||||
assert.equal(statusOf(text), value, `${line} with ${eol === "\n" ? "LF" : "CRLF"}`);
|
||||
assert.equal(text.match(STATUS_RE)[1] + text.match(STATUS_RE)[2], line, "the prefix and value rebuild the line");
|
||||
}
|
||||
}
|
||||
assert.equal(statusOf("# Phase 1\n\nNo status here.\n"), null);
|
||||
assert.equal(statusOf(""), null);
|
||||
assert.equal(statusOf(undefined), null);
|
||||
});
|
||||
|
||||
test("spec files: countTasks() counts task lines only when there are any, every checkbox otherwise", () => {
|
||||
const phase = [
|
||||
"# Phase 1",
|
||||
"- [x] **Task 1.1:** One",
|
||||
"* [?] **Task 1.2:** Two",
|
||||
"1. [ ] **Task 1.3:** Three",
|
||||
"- [/] **Task 1.4:** Four",
|
||||
"- [!] **Task 1.5:** Five",
|
||||
"- [~] **Task 1.6:** An unknown marker",
|
||||
"## Acceptance Criteria",
|
||||
"- [ ] It works",
|
||||
"- [x] It is fast",
|
||||
].join("\r\n");
|
||||
assert.deepEqual(countTasks(phase), { done: 1, assumed: 1, open: 3, total: 5 });
|
||||
const older = "# Phase 1\n\n- [x] Make it\n- [ ] Ship it\n- [?] Check it\n";
|
||||
assert.deepEqual(countTasks(older), { done: 1, assumed: 1, open: 1, total: 3 });
|
||||
assert.deepEqual(countTasks(""), { done: 0, assumed: 0, open: 0, total: 0 });
|
||||
});
|
||||
|
||||
// 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.
|
||||
@@ -252,6 +313,9 @@ const CARDS = {
|
||||
},
|
||||
};
|
||||
|
||||
// Implement's card also launches Implement + Review, which has the same rules.
|
||||
const CARD_ENTRIES = SKILL_CATALOG.flatMap((e) => (e.review ? [e, launchVariant(e, true)] : [e]));
|
||||
|
||||
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." }],
|
||||
@@ -265,8 +329,8 @@ const SCAN_CASES = [
|
||||
];
|
||||
|
||||
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) {
|
||||
assert.deepEqual(CARD_ENTRIES.map((e) => e.skill), Object.keys(CARDS), "one row per card, in card order");
|
||||
for (const entry of CARD_ENTRIES) {
|
||||
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}`);
|
||||
@@ -275,7 +339,7 @@ test("card rules: every card gives the same answer for every spec state as befor
|
||||
});
|
||||
|
||||
test("card rules: a state the table does not know is treated like files on disk", () => {
|
||||
for (const entry of SKILL_CATALOG) {
|
||||
for (const entry of CARD_ENTRIES) {
|
||||
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`);
|
||||
}
|
||||
@@ -303,7 +367,7 @@ test("finished: any finished state is never the picker's default, not only fixed
|
||||
|
||||
// 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) {
|
||||
for (const entry of CARD_ENTRIES) {
|
||||
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`);
|
||||
}
|
||||
@@ -354,6 +418,30 @@ test("the scan: every state it can return is in the table, and a fixture reaches
|
||||
assert.deepEqual(scanProblems(FIXTURES, known), ["the scan returns unrecognized, which spec-states.js lacks"]);
|
||||
});
|
||||
|
||||
test("the scan: an assumed task counts as done and is named, and numbered task lines count", () => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-spec-assumed-"));
|
||||
const specs = {
|
||||
mixed: "- [x] **Task 1.1:** One\n- [x] **Task 1.2:** Two\n- [?] **Task 1.3:** Three\n- [ ] **Task 1.4:** Four\n",
|
||||
assumed: "- [?] **Task 1.1:** One\n- [?] **Task 1.2:** Two\n",
|
||||
numbered: "1. [x] **Task 1.1:** One\n2. [ ] **Task 1.2:** Two\n3. [ ] **Task 1.3:** Three\n",
|
||||
plain: "- [x] **Task 1.1:** One\n- [x] **Task 1.2:** Two\n",
|
||||
};
|
||||
try {
|
||||
for (const [name, phase] of Object.entries(specs)) {
|
||||
fs.mkdirSync(path.join(root, "specs", name), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "specs", name, "overview.md"), "# Overview\n");
|
||||
fs.writeFileSync(path.join(root, "specs", name, "phase-1.md"), "# Phase 1\n\n" + phase + "\n## Acceptance Criteria\n\n- [ ] It works\n");
|
||||
}
|
||||
const by = Object.fromEntries(scanProject(root).specs.map((sp) => [sp.name, sp]));
|
||||
assert.deepEqual([by.mixed.state, by.mixed.detail], ["building", "3 of 4 tasks done, 1 assumed"]);
|
||||
assert.deepEqual([by.assumed.state, by.assumed.detail], ["built", "all tasks done, 2 assumed"]);
|
||||
assert.deepEqual([by.numbered.state, by.numbered.detail], ["building", "1 of 3 tasks done"]);
|
||||
assert.deepEqual([by.plain.state, by.plain.detail], ["built", "all tasks done"], "no assumed tasks, no \", 0 assumed\"");
|
||||
} finally {
|
||||
fs.rmSync(root, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// The states no card names in its `states` list: a card that is on for "any"
|
||||
// spec does not count, since it would take a state nobody thought about. A
|
||||
// finished state is taken by no card on purpose.
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
#!/usr/bin/env node
|
||||
// Captures the CSS the vendored OverType would inject, as a real stylesheet.
|
||||
// Dev-only: lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// node scripts/vendor-overtype.mjs
|
||||
//
|
||||
// The console's content-security policy (`style-src 'self'`) blocks the
|
||||
// <style> OverType adds to the page, so the notepad sets
|
||||
// `OverType.stylesInjected = true` and ships the same rules in
|
||||
// src/web-console/public/styles/notepad.css instead. This script loads
|
||||
// public/vendor/overtype.esm.js in a blank page, calls
|
||||
// `OverType.injectStyles(true)` and writes what landed in
|
||||
// `style.overtype-styles` between the header and the end marker below. The
|
||||
// notepad's own rules, after the marker, are kept as they are. Run it again
|
||||
// after upgrading the vendored file.
|
||||
//
|
||||
// Needs playwright-core (a root devDependency) and a local Chrome or Edge,
|
||||
// launched through scripts/browser.mjs.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const PUBLIC = path.join(ROOT, "src", "web-console", "public");
|
||||
const VENDOR = path.join(PUBLIC, "vendor", "overtype.esm.js");
|
||||
const OUT = path.join(PUBLIC, "styles", "notepad.css");
|
||||
|
||||
export const HEADER = "/* OverType 2.6.1 generated CSS: regenerate with node scripts/vendor-overtype.mjs */";
|
||||
export const END_MARKER = "/* end OverType */";
|
||||
|
||||
// A made-up origin served from here, so the module loads as it does on the
|
||||
// page: as a module, from a URL, with nothing else around it.
|
||||
const ORIGIN = "http://overtype.invalid";
|
||||
|
||||
async function capture() {
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage();
|
||||
await page.route(`${ORIGIN}/**`, (route) => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.pathname === "/overtype.esm.js") {
|
||||
return route.fulfill({ contentType: "text/javascript", body: fs.readFileSync(VENDOR) });
|
||||
}
|
||||
return route.fulfill({ contentType: "text/html", body: "<!doctype html><title>OverType CSS</title>" });
|
||||
});
|
||||
await page.goto(`${ORIGIN}/`);
|
||||
return await page.evaluate(async (src) => {
|
||||
const { OverType } = await import(src);
|
||||
OverType.injectStyles(true);
|
||||
const style = document.querySelector("style.overtype-styles");
|
||||
return style ? style.textContent : null;
|
||||
}, `${ORIGIN}/overtype.esm.js`);
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
}
|
||||
|
||||
// The generated block, then whatever followed the marker before (the
|
||||
// notepad's own rules), or nothing on a first run. A stylesheet with rules but
|
||||
// no marker is refused: rewriting it would delete them.
|
||||
export function assemble(css, existing) {
|
||||
const at = existing.indexOf(END_MARKER);
|
||||
if (at === -1 && existing.trim()) {
|
||||
throw new Error(`notepad.css has no "${END_MARKER}" marker, so its own rules cannot be told apart: put the marker back, then run this again.`);
|
||||
}
|
||||
const own = at === -1 ? "" : existing.slice(at + END_MARKER.length);
|
||||
const body = css.trim().split("\n").map((line) => line.replace(/\s+$/, "")).join("\n");
|
||||
return `${HEADER}\n${body}\n${END_MARKER}${own || "\n"}`;
|
||||
}
|
||||
|
||||
const css = await capture().catch((e) => {
|
||||
console.error(e.browserProblem ? e.message : `Could not capture OverType's CSS: ${e.message}`);
|
||||
process.exit(1);
|
||||
});
|
||||
if (!css) {
|
||||
console.error("OverType injected no style.overtype-styles element.");
|
||||
process.exit(1);
|
||||
}
|
||||
const existing = fs.existsSync(OUT) ? fs.readFileSync(OUT, "utf8") : "";
|
||||
let out;
|
||||
try {
|
||||
out = assemble(css, existing);
|
||||
} catch (e) {
|
||||
console.error(e.message);
|
||||
process.exit(1);
|
||||
}
|
||||
fs.writeFileSync(OUT, out);
|
||||
console.log(`Wrote ${path.relative(ROOT, OUT)} (${css.length} characters of OverType CSS).`);
|
||||
@@ -31,6 +31,11 @@ export const MODELS_DIR = path.join(HOME, "plan2code");
|
||||
// Handoffs are written outside every repo, under ~/.plan2code/handoffs, so
|
||||
// each test file gets its own throwaway folder for them too.
|
||||
export const HANDOFFS_DIR = path.join(HOME, "handoffs");
|
||||
// Notepads likewise live under ~/.plan2code/notepads. Set here for this
|
||||
// process too, so a test importing notepads.mjs directly never reaches the
|
||||
// real folder (notepadsDir() reads the variable on every call).
|
||||
export const NOTEPADS_DIR = path.join(HOME, "notepads");
|
||||
process.env.PLAN2CODE_NOTEPADS_DIR = NOTEPADS_DIR;
|
||||
// A spawned console server or CLI must not inherit relocation vars (an
|
||||
// exported GIT_DIR would redirect the board's reads), SSH markers (they set
|
||||
// `remote` in open output) or leftover PLAN2CODE_* knobs.
|
||||
@@ -54,7 +59,7 @@ for (const k of AMBIENT_ENV_KEYS) delete scrubbed[k];
|
||||
// cannot open. An empty file is the portable "no global config".
|
||||
const EMPTY_GITCONFIG = path.join(HOME, "empty-gitconfig");
|
||||
fs.writeFileSync(EMPTY_GITCONFIG, "");
|
||||
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
|
||||
export const ENV = { ...scrubbed, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_MODELS_DIR: MODELS_DIR, PLAN2CODE_HANDOFFS_DIR: HANDOFFS_DIR, PLAN2CODE_NOTEPADS_DIR: NOTEPADS_DIR, PLAN2CODE_NO_BROWSER: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: EMPTY_GITCONFIG };
|
||||
// Every server these tests start runs the release check at boot. A fresh
|
||||
// cached failure keeps the whole suite off the network and bannerless.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
+35
-11
@@ -216,26 +216,50 @@ public static class Plan2CodeFolderPicker {
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetSystemMetrics(int index);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void SwitchToThisWindow(IntPtr hWnd, bool altTab);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
|
||||
|
||||
private const uint FOS_PICKFOLDERS = 0x20;
|
||||
private const uint FOS_FORCEFILESYSTEM = 0x40;
|
||||
private const uint FOS_PATHMUSTEXIST = 0x800;
|
||||
private const uint SIGDN_FILESYSPATH = 0x80058000;
|
||||
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
|
||||
|
||||
// Windows refuses SetForegroundWindow from a background process (this one is spawned
|
||||
// by the detached console server), so the dialog opened behind the browser. A tap of
|
||||
// Alt counts as input from this process and lifts the lock for the call after it. The
|
||||
// topmost flag below is ignored by this dialog (SetWindowPos succeeds, the bit stays
|
||||
// off), so taking the foreground is what puts it in front.
|
||||
private static void Raise(string title) {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
IntPtr hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero) {
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
SetForegroundWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
IntPtr hwnd = IntPtr.Zero;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero && IsWindowVisible(hwnd)) break;
|
||||
hwnd = IntPtr.Zero;
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
for (int i = 0; i < 20 && GetForegroundWindow() != hwnd; i++) {
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(hwnd);
|
||||
SwitchToThisWindow(hwnd, true);
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
public static string Pick(IntPtr owner, string title, string start) {
|
||||
|
||||
@@ -46,7 +46,7 @@ Do not proceed without spec files.
|
||||
`🔄 [REVISION] Step 1: Change Analysis`
|
||||
|
||||
1. Read all spec files
|
||||
2. Understand the requested change
|
||||
2. Understand the requested change. Before asking for one, look in the Notes of every `[/]` phase for a waiting `**Plan change:**` line: Implement paused there for this revision (`### Paused <date>` above it). Take that brief as the requested change and present it for confirmation rather than asking from scratch; what the person says in their argument or reply wins over it, and a brief they replace or decline is marked dropped at Step 3.
|
||||
3. Identify affected areas:
|
||||
|
||||
| Affected Area | Files | Sections |
|
||||
@@ -131,6 +131,8 @@ Approve the spec-update plan? (approve / refine / abort). Implementation of any
|
||||
- Update overview.md: `[x]` → `[ ]` (`specs.mjs mark <spec> --phase <N> --to open`, which also sets that phase file's `**Status:**` back to In Progress)
|
||||
- Add comment: `<!-- Re-opened: [date] - [reason] -->`
|
||||
|
||||
6. **A waiting brief:** rewrite its `**Plan change:**` line to `**Plan change (applied <YYYY-MM-DD>):**` when this revision covers it, or `**Plan change (dropped <YYYY-MM-DD>):**` when the person replaced or declined it at Step 1, so the dashboard and Implement stop pointing back here.
|
||||
|
||||
### STEP 4: Consistency Check
|
||||
|
||||
`🔄 [REVISION] Step 4: Consistency Check`
|
||||
|
||||
@@ -73,7 +73,7 @@ Never reset `[/]` to `[ ]`: started work stays marked so resuming is a conscious
|
||||
| `checkoff` | Every phase is approved but tasks in them are still open (manual steps, blockers). Never say "nothing left to do": run Manual Check-Off below. |
|
||||
| `none` | Nothing to implement: say why (`reason`). Every phase complete → `/plan2code-4-finalize --web` |
|
||||
|
||||
After selection, claim it (Process 1), read `phase-X.md`, begin.
|
||||
Before acting on `ask-resume` or `choose`, read the Notes of each `[/]` phase on offer: a waiting `**Plan change:**` line replaces the resume question (Plan Change Mid-Phase). After selection, claim it (Process 1), read `phase-X.md`, begin.
|
||||
|
||||
### Manual Check-Off
|
||||
|
||||
@@ -245,7 +245,21 @@ If user says "abort", "cancel", or similar:
|
||||
| Issue | Solution |
|
||||
|-------|----------|
|
||||
| Lost context mid-phase | Attach specs, say "resume from Task X.Y" |
|
||||
| Need to change plan | Pause, use `/plan2code-1b-revise-plan` |
|
||||
| Need to change plan | Plan Change Mid-Phase, below |
|
||||
|
||||
### Plan Change Mid-Phase
|
||||
|
||||
When the person decides the plan must change before this phase can finish (a new phase first, tasks rewritten), the phase stays `[/]` and the brief goes into its Notes in this exact shape, then the session ends as a pause:
|
||||
|
||||
```markdown
|
||||
### Paused <YYYY-MM-DD>
|
||||
**Plan change:** <what Revise the plan must add or change, complete enough to act on without this conversation>
|
||||
<done and still open by task id in prose ("done 9.1, 9.3-9.5; open 9.2, 9.6-9.9"), never checkbox lines; decisions made so far>
|
||||
```
|
||||
|
||||
NEXT STEP: `/plan2code-1b-revise-plan specs/<feature>/overview.md --web`. The dashboard and Revise the plan look for that `**Plan change:**` line; Revise the plan rewrites it to `**Plan change (applied <date>):**` once the spec is updated.
|
||||
|
||||
A phase whose Notes still hold a waiting `**Plan change:**` gets one question in place of "Resume?" (console: a `choice`): **Revise the plan first** (recommended) or **Resume Phase X anyway**. Revise first: change nothing and end as a pause with the NEXT STEP above (console: that `finish.command`, headline starting "Paused"). Resume anyway: rewrite the line to `**Plan change (dropped <YYYY-MM-DD>):**`, then carry on.
|
||||
|
||||
## Learning Capture
|
||||
|
||||
|
||||
+3
-2
@@ -39,6 +39,7 @@ The page draws the cards itself — you never send the list. It also knows the r
|
||||
- `documented` ("Ready to build"): Implement is next.
|
||||
- `building` ("Building"): Implement is next.
|
||||
- `built` ("Ready to finalize"): Finalize is next.
|
||||
- A `documented` or `building` spec whose `[/]` phase file holds a waiting `**Plan change:**` line in its Notes (Implement paused for a revision; `(applied <date>):` or `(dropped <date>):` means done): recommend Revise the plan instead, `details` "Plan change waiting from Phase N". On a `built` spec the Revise card is greyed, so name the waiting brief in `note`.
|
||||
- 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 ✕.
|
||||
@@ -59,10 +60,10 @@ Ground truth for menu notes and Ask-tab answers. For anything beyond this table,
|
||||
| init-update | `AGENTS.md`, codebase | `AGENTS.md`, `.agents-docs/` |
|
||||
| 0-pathfinder | the idea, loose notes | `pathfinder/map.md`, `pathfinder/questions/NN-<slug>.md`; cleared → `PLAN-DRAFT-<date>.md` |
|
||||
| 1-plan | idea or `PLAN-DRAFT` | `PLAN-DRAFT-<date>.md`, `PLAN-CONVERSATION-<date>.md` |
|
||||
| 1b-revise-plan | `overview.md`, `phase-X.md` | the same, revised |
|
||||
| 1b-revise-plan | `overview.md`, `phase-X.md`, a waiting `**Plan change:**` brief | the same, revised; the brief marked applied or dropped |
|
||||
| quick-task | the ask; a `DIAGNOSIS-*.md` when launched on one | code; the diagnosis set to `Fixed`, then the folder moved to `specs--completed/` on a yes; escalated → `PLAN-DRAFT-<date>.md` |
|
||||
| 2-document | `PLAN-DRAFT`, `PLAN-CONVERSATION` (optional) | `overview.md`, `phase-X.md` |
|
||||
| 3-implement(-review) | `overview.md`, `phase-X.md` | code; `[x]` marks + completion summary in `phase-X.md` |
|
||||
| 3-implement(-review) | `overview.md`, `phase-X.md` | code; `[x]` marks + completion summary in `phase-X.md`; paused for a revision, a `**Plan change:**` brief in its Notes |
|
||||
| review | spec, diff | the fixes picked; no spec writes |
|
||||
| 4-finalize | spec + code | summary in `overview.md`; moves the spec to `specs--completed/` |
|
||||
| handoff | conversation, spec, git | `~/.plan2code/handoffs/<id>.md`, listed on the dashboard |
|
||||
|
||||
@@ -122,19 +122,12 @@ function resolveSpec(root, arg, { allowArchived = false } = {}) {
|
||||
|
||||
/* -------------------------------------------------------------- parsing */
|
||||
|
||||
const MARKERS = { " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" };
|
||||
// Task 2.3, a lettered sub-task 3.6a, or a named one such as a testing task 1.T.
|
||||
const TASK_RE = /^\s*[-*] \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
||||
const CHECKBOX_RE = /^\s*[-*] \[(.)\]/;
|
||||
// The Status line in any of the forms people write it: **Status:**, **Status**:
|
||||
// or a plain Status:, optionally as a list item. Groups: everything up to the
|
||||
// value (kept as written when the value is rewritten), the value, trailing blanks.
|
||||
const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
|
||||
|
||||
function statusOf(text) {
|
||||
const m = (text || "").match(STATUS_RE);
|
||||
return m ? m[2] : null;
|
||||
}
|
||||
// The task markers, the task-line (TASK_RE: marker, phase, task, sub-task
|
||||
// suffix), checkbox and Status-line patterns, and statusOf(), come from the web
|
||||
// console's spec-files.mjs, so this script and the dashboard read a spec the
|
||||
// same way. run() binds them once before any command, so the synchronous
|
||||
// readers below keep using them as plain module bindings.
|
||||
let MARKERS, TASK_RE, CHECKBOX_RE, STATUS_RE, statusOf;
|
||||
|
||||
/** A markdown section's lines: from its heading to the next heading of the same or higher level. */
|
||||
function section(text, headingRe) {
|
||||
@@ -268,8 +261,8 @@ function parsePhaseFile(file, number) {
|
||||
tasks.push({ id: `${t[2]}.${t[3]}${t[4]}`, phase: Number(t[2]), seq: named ? null : Number(t[3]), named, suffix: t[4], marker: t[1], state, line: i + 1, text: said, detail: taskDetail(lines, i) });
|
||||
return;
|
||||
}
|
||||
// A line that looks like a task but is not counted as one (Task 1.4A,
|
||||
// "1. [ ] **Task", a non-bold "- [ ] Task 1.3") would make the audit undercount.
|
||||
// A line that looks like a task but is not counted as one (Task 1.4A, a
|
||||
// non-bold "- [ ] Task 1.3") would make the audit undercount.
|
||||
if (/^\s*(?:[-*]|\d+\.)\s+\[.\].*\bTask\s+\d+\./i.test(line)) unmatchedTasks.push({ line: i + 1, text: line.trim().slice(0, 120) });
|
||||
if (CHECKBOX_RE.test(line)) strayCheckboxes.push({ line: i + 1, section: heading, text: line.trim().slice(0, 120) });
|
||||
});
|
||||
@@ -905,6 +898,7 @@ async function cmdCheckDraft(args) {
|
||||
run(USAGE, async (argv) => {
|
||||
const args = parseArgs(argv, { booleans: ["dry-run"], values: ["root", "step", "phase", "to", "task"], lists: ["set"] });
|
||||
const cmd = args._[0];
|
||||
({ MARKERS, TASK_ID_RE: TASK_RE, CHECKBOX_RE, STATUS_RE, statusOf } = await consoleModule("spec-files.mjs"));
|
||||
const commands = { list: cmdList, status: cmdStatus, metrics: cmdMetrics, mark: cmdMark, tick: cmdTick, archive: cmdArchive, check: cmdCheck, "check-draft": cmdCheckDraft };
|
||||
if (!commands[cmd]) fail(EXIT.USAGE, "unknown-command", cmd ? `Unknown command "${cmd}".` : "No command given.", "Commands: list, status, check, check-draft, metrics, mark, tick, archive. Run with --help.");
|
||||
await commands[cmd](args);
|
||||
|
||||
@@ -4,6 +4,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
|
||||
import { HERE } from "./files.mjs";
|
||||
import { WORKFLOWS, isBuild } from "./public/skills.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.
|
||||
@@ -14,6 +15,25 @@ export function useCli(cli) {
|
||||
|
||||
/* ----------------------------------------------------------------- help */
|
||||
|
||||
// The usage's workflow list, from skills.js: wrapped at the usage's width,
|
||||
// continuation lines indented under the first name.
|
||||
function workflowLines(width = 78) {
|
||||
const lead = " workflows: ";
|
||||
const pad = " ".repeat(lead.length);
|
||||
const lines = [];
|
||||
let line = "";
|
||||
WORKFLOWS.forEach((w, i) => {
|
||||
const piece = i < WORKFLOWS.length - 1 ? `${w} ·` : w;
|
||||
const start = lines.length ? pad : lead;
|
||||
if (line && (start + line + " " + piece).length > width) {
|
||||
lines.push(start + line);
|
||||
line = piece;
|
||||
} else line = line ? `${line} ${piece}` : piece;
|
||||
});
|
||||
lines.push((lines.length ? pad : lead) + line);
|
||||
return lines.join("\n");
|
||||
}
|
||||
|
||||
export function cmdHelp() {
|
||||
const topic = args._[0];
|
||||
if (topic !== undefined) return helpTopic(String(topic));
|
||||
@@ -103,9 +123,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
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
|
||||
${workflowLines()}
|
||||
|
||||
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
|
||||
@@ -113,7 +131,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
|
||||
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
|
||||
them. Build sessions (${WORKFLOWS.filter(isBuild).join(", ")}) also read
|
||||
building.md.
|
||||
`);
|
||||
}
|
||||
|
||||
@@ -48,6 +48,8 @@ import {
|
||||
writeWorkspaceCursor,
|
||||
} from "./workspace.mjs";
|
||||
import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
|
||||
import {
|
||||
@@ -95,6 +97,13 @@ function leavePointer() {
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
// A workflow the console does not know is refused first, before the pointer,
|
||||
// the reap or any session folder: a fresh open would otherwise make a
|
||||
// session under a name no page or skill can show, and a resume would write
|
||||
// that name over a good one. No --workflow at all is still fine (FR-5).
|
||||
if (args.workflow !== undefined && !isWorkflow(args.workflow)) {
|
||||
die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2);
|
||||
}
|
||||
leavePointer();
|
||||
const { project, worktree, branch } = repoRoots();
|
||||
reapHandles(project);
|
||||
@@ -124,22 +133,11 @@ export async function cmdOpen() {
|
||||
// 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");
|
||||
// A hop starts the new skill on a clean page, by the rule in
|
||||
// public/hops.js (the page applies the same one). The staged draft goes
|
||||
// too, since its item ids belonged to the old questions, and so does the
|
||||
// last run's state.git, since switchWorkflow() starts from a blank state.
|
||||
const hop = startsClean(state.workflow, args.workflow);
|
||||
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 --
|
||||
|
||||
@@ -10,6 +10,7 @@ import { isOpen } from "./patches.mjs";
|
||||
import { pendingChatCount } from "./inbox.mjs";
|
||||
import { forgetWorkspace, specKey } from "./workspace.mjs";
|
||||
import { newHandoff, removeHandoff } from "./handoffs.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.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.
|
||||
@@ -153,6 +154,9 @@ 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);
|
||||
// newHandoff() takes any lowercase name; a handoff is only useful to a
|
||||
// workflow the console can launch, so the name must be one it knows (FR-5).
|
||||
if (!isWorkflow(args.workflow)) die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2);
|
||||
if ("from-stop" in args && args["from-stop"] !== true) die("--from-stop takes no value", 2);
|
||||
const { worktree, project } = repoRoots();
|
||||
try {
|
||||
|
||||
@@ -56,7 +56,7 @@ The same closer you are about to print in the terminal, as data:
|
||||
| `review` | optional | A finished `quick-task` only: `true` or `{ "label": "..." }` puts a **Review it now** button on the finished screen (`notes/quick-task.md`, `building-review.md`). `implement` offers the review on its sign-off card instead — before approval, where it can still change the outcome. |
|
||||
|
||||
**Write the bare command.** Every Plan2Code skill has a console — the
|
||||
dashboard and all twelve skills behind it — so for any of them the page
|
||||
dashboard and every skill behind it — so for any of them the page
|
||||
appends ` --web` to what it shows and copies, so someone who worked here
|
||||
lands back here instead of being asked the interface question as though
|
||||
they were new. Every one of those skills takes that flag in its argument as
|
||||
|
||||
@@ -86,20 +86,28 @@ export function ensureDir(dir) {
|
||||
// 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);
|
||||
writeTextAtomic(file, body);
|
||||
return body;
|
||||
}
|
||||
|
||||
// The same write for plain text, as UTF-8 (a Buffer is written as is): a temp
|
||||
// file beside the target, fsync, then a rename, retried while Windows still
|
||||
// holds the old file.
|
||||
export function writeTextAtomic(file, text) {
|
||||
const tmp = file + "." + process.pid + ".tmp";
|
||||
let lastErr;
|
||||
for (let attempt = 0; attempt < 4; attempt++) {
|
||||
try {
|
||||
const fd = fs.openSync(tmp, "w");
|
||||
try {
|
||||
fs.writeFileSync(fd, body);
|
||||
fs.writeFileSync(fd, text, "utf8");
|
||||
fs.fsyncSync(fd);
|
||||
} finally {
|
||||
fs.closeSync(fd);
|
||||
}
|
||||
fs.renameSync(tmp, file);
|
||||
return body;
|
||||
return;
|
||||
} catch (err) {
|
||||
lastErr = err;
|
||||
if (err.code !== "EPERM" && err.code !== "EBUSY" && err.code !== "EACCES") break;
|
||||
@@ -124,6 +132,31 @@ export function fileStamp(file) {
|
||||
}
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays. Cleanup ages
|
||||
// sessions, strays, completed specs and notepads by it.
|
||||
export function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
export function readJson(file, fallback = null) {
|
||||
try {
|
||||
return JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
|
||||
@@ -0,0 +1,254 @@
|
||||
// Plan2Code Web Console - the notepad store.
|
||||
//
|
||||
// One notepad per folder Plan2Code runs in (the session's worktree, else its
|
||||
// project), outside every repo and every session:
|
||||
//
|
||||
// ~/.plan2code/notepads/<folder-name>-<12 hex>/
|
||||
// meta.json { v: 1, folder, created }, written once
|
||||
// note.md the text, UTF-8, written atomically
|
||||
// images/<uuid>.jpg a picture, JPEG from the page
|
||||
// images/<uuid>.thumb.jpg its thumbnail, when the page sent one
|
||||
//
|
||||
// This module is the only code that names, reads, writes, lists and removes
|
||||
// them. The page reaches it through the /notepad routes; the agent CLI never
|
||||
// imports it, so nothing in a notepad can reach the agent. Reading never
|
||||
// creates or touches a file, so only a person's own edits age a notepad.
|
||||
// PLAN2CODE_NOTEPADS_DIR moves the folder, for tests.
|
||||
//
|
||||
// Node built-ins only. No build step.
|
||||
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
import { ensureDir, newestMtime, nowIso, readJson, withStateLock, writeJsonAtomic, writeTextAtomic } from "./files.mjs";
|
||||
import { foldKey } from "./workspace.mjs";
|
||||
|
||||
// Read at call time, so a test that sets the variable after import sees it.
|
||||
export function notepadsDir() {
|
||||
return process.env.PLAN2CODE_NOTEPADS_DIR || path.join(os.homedir(), ".plan2code", "notepads");
|
||||
}
|
||||
|
||||
export const NOTE_MAX_BYTES = 1024 * 1024;
|
||||
export const NOTEPAD_MAX_IMAGES = 200;
|
||||
export const IMAGE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
export const NOTEPAD_KEY_RE = /^[a-z0-9-]{1,40}-[0-9a-f]{12}$/;
|
||||
|
||||
// A refusal the routes turn into `{ error: code }` with this status.
|
||||
export class NotepadError extends Error {
|
||||
constructor(code, status) {
|
||||
super(code);
|
||||
this.code = code;
|
||||
this.status = status;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ names */
|
||||
|
||||
// `<folder-name>-<first 12 hex of sha256(foldKey(folder))>`: recognisable in a
|
||||
// file browser, safe on every OS, and one notepad per folder however its case
|
||||
// is typed where the file system ignores case.
|
||||
export function notepadKey(folder) {
|
||||
const slug =
|
||||
path
|
||||
.basename(path.resolve(String(folder || "")))
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, "-")
|
||||
.replace(/^-+|-+$/g, "")
|
||||
.slice(0, 40)
|
||||
.replace(/-+$/, "") || "folder";
|
||||
const hash = crypto.createHash("sha256").update(foldKey(folder)).digest("hex").slice(0, 12);
|
||||
return slug + "-" + hash;
|
||||
}
|
||||
|
||||
export function notepadFolder(folder) {
|
||||
return path.join(notepadsDir(), notepadKey(folder));
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ write */
|
||||
|
||||
// Every write goes through here: the folder, its images/ and meta.json come
|
||||
// into being on the first one, and each runs under the notepad's own lock so
|
||||
// two pages on one folder never interleave. Nothing that only reads calls it.
|
||||
function withNotepad(folder, fn) {
|
||||
const dir = notepadFolder(folder);
|
||||
ensureDir(path.join(dir, "images"));
|
||||
const meta = path.join(dir, "meta.json");
|
||||
if (!fs.existsSync(meta)) writeJsonAtomic(meta, { v: 1, folder: path.resolve(String(folder)), created: nowIso() });
|
||||
return withStateLock(dir, () => fn(dir), "notepad.lock");
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------- read */
|
||||
|
||||
const fullImage = (name) => name.endsWith(".jpg") && !name.endsWith(".thumb.jpg") && IMAGE_ID_RE.test(name.slice(0, -4));
|
||||
|
||||
function mtimeOf(file) {
|
||||
try {
|
||||
return fs.statSync(file).mtimeMs;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// The full images' ids, oldest first (an image is never rewritten after it is
|
||||
// added, so its mtime is when it arrived).
|
||||
function imageIds(dir) {
|
||||
let names;
|
||||
try {
|
||||
names = fs.readdirSync(path.join(dir, "images"));
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return names
|
||||
.filter(fullImage)
|
||||
.map((name) => ({ id: name.slice(0, -4), at: mtimeOf(path.join(dir, "images", name)) ?? 0 }))
|
||||
.sort((a, b) => a.at - b.at || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0))
|
||||
.map((e) => e.id);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the page shows: `{ text, savedAt, images: [{ id, url, thumb }] }`.
|
||||
* Never creates or writes anything; a folder with no notepad yet reads empty.
|
||||
*/
|
||||
export function readNotepad(folder) {
|
||||
const dir = notepadFolder(folder);
|
||||
if (!fs.existsSync(dir)) return { text: "", savedAt: null, images: [] };
|
||||
const note = path.join(dir, "note.md");
|
||||
let text = "";
|
||||
try {
|
||||
text = fs.readFileSync(note, "utf8");
|
||||
} catch {}
|
||||
const at = mtimeOf(note);
|
||||
const images = imageIds(dir).map((id) => ({
|
||||
id,
|
||||
url: "/notepad/images/" + id + ".jpg",
|
||||
thumb: fs.existsSync(path.join(dir, "images", id + ".thumb.jpg")) ? "/notepad/images/" + id + ".thumb.jpg" : null,
|
||||
}));
|
||||
return { text, savedAt: at === null ? null : new Date(at).toISOString(), images };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ change */
|
||||
|
||||
const isJpeg = (buf) => Buffer.isBuffer(buf) && buf.length >= 3 && buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff;
|
||||
const isImageId = (id) => typeof id === "string" && IMAGE_ID_RE.test(id);
|
||||
|
||||
/** Replace the note's text. Resolves to `{ savedAt }`, the written file's time. */
|
||||
export function saveNote(folder, text) {
|
||||
if (typeof text !== "string") throw new NotepadError("bad", 400);
|
||||
if (Buffer.byteLength(text, "utf8") > NOTE_MAX_BYTES) throw new NotepadError("too-long", 413);
|
||||
return withNotepad(folder, (dir) => {
|
||||
const note = path.join(dir, "note.md");
|
||||
writeTextAtomic(note, text);
|
||||
return { savedAt: new Date(fs.statSync(note).mtimeMs).toISOString() };
|
||||
});
|
||||
}
|
||||
|
||||
/** Add a picture (JPEG bytes). Resolves to `{ id, url }`. */
|
||||
export function addImage(folder, buf) {
|
||||
if (!isJpeg(buf)) throw new NotepadError("not-jpeg", 415);
|
||||
return withNotepad(folder, (dir) => {
|
||||
if (imageIds(dir).length >= NOTEPAD_MAX_IMAGES) throw new NotepadError("too-many", 409);
|
||||
const id = crypto.randomUUID();
|
||||
fs.writeFileSync(path.join(dir, "images", id + ".jpg"), buf, { flag: "wx" });
|
||||
return { id, url: "/notepad/images/" + id + ".jpg" };
|
||||
});
|
||||
}
|
||||
|
||||
/** Set (or replace) a picture's thumbnail. */
|
||||
export function addThumb(folder, id, buf) {
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "images", id + ".jpg"))) {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
if (!isJpeg(buf)) throw new NotepadError("not-jpeg", 415);
|
||||
return withNotepad(folder, (dir) => {
|
||||
if (!fs.existsSync(path.join(dir, "images", id + ".jpg"))) throw new NotepadError("not-found", 404);
|
||||
// Replacing a file is the rename Windows can refuse for a moment, so it
|
||||
// takes the retrying write (a Buffer is written as is).
|
||||
writeTextAtomic(path.join(dir, "images", id + ".thumb.jpg"), buf);
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove a picture and its thumbnail. */
|
||||
export function removeImage(folder, id) {
|
||||
// Checked before the lock too, so a refused delete never brings an empty
|
||||
// notepad into being.
|
||||
if (!isImageId(id) || !fs.existsSync(path.join(notepadFolder(folder), "images", id + ".jpg"))) {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
return withNotepad(folder, (dir) => {
|
||||
const full = path.join(dir, "images", id + ".jpg");
|
||||
if (!fs.existsSync(full)) throw new NotepadError("not-found", 404);
|
||||
fs.rmSync(full, { force: true });
|
||||
fs.rmSync(path.join(dir, "images", id + ".thumb.jpg"), { force: true });
|
||||
return {};
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The file behind `/notepad/images/<id>[.thumb].jpg`, or null: the id must be
|
||||
* a UUID, the file a regular file (never a link) whose real path sits inside
|
||||
* the notepads folder's.
|
||||
*/
|
||||
export function imagePath(folder, id, thumb) {
|
||||
if (!isImageId(id)) return null;
|
||||
const file = path.join(notepadFolder(folder), "images", id + (thumb ? ".thumb.jpg" : ".jpg"));
|
||||
try {
|
||||
if (!fs.lstatSync(file).isFile()) return null;
|
||||
const [realFile, realRoot] = [fs.realpathSync(file), fs.realpathSync(notepadsDir())];
|
||||
// path.relative, not a prefix test, as readOverview() in sessions.mjs does.
|
||||
const rel = path.relative(realRoot, realFile);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null;
|
||||
return realFile;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- cleanup */
|
||||
|
||||
/**
|
||||
* The notepads nobody has touched for `maxAgeMs`, judged by the newest file in
|
||||
* each, as `[{ key, folder, path }]`: only real folders directly under the
|
||||
* notepads folder whose name is a notepad key (never a link, never a file).
|
||||
* `folder` is the one `meta.json` names, or null when it is missing or
|
||||
* unreadable. User Preferences, Cleanup is the only caller: no sweep ever
|
||||
* removes a notepad.
|
||||
*/
|
||||
export function staleNotepads(now = Date.now(), maxAgeMs) {
|
||||
const root = notepadsDir();
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(root, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
return entries
|
||||
.filter((e) => e.isDirectory() && NOTEPAD_KEY_RE.test(e.name))
|
||||
.map((e) => ({ key: e.name, path: path.join(root, e.name) }))
|
||||
.filter((e) => now - newestMtime(e.path) >= maxAgeMs)
|
||||
.map((e) => {
|
||||
const meta = readJson(path.join(e.path, "meta.json"));
|
||||
const folder = meta && typeof meta.folder === "string" && meta.folder ? meta.folder : null;
|
||||
return { key: e.key, folder, path: e.path };
|
||||
});
|
||||
}
|
||||
|
||||
/** Remove a whole notepad by its key: never a bad key, a link or anything outside the notepads folder. */
|
||||
export function removeNotepad(key) {
|
||||
if (typeof key !== "string" || !NOTEPAD_KEY_RE.test(key)) throw new NotepadError("bad", 400);
|
||||
const root = path.resolve(notepadsDir());
|
||||
const dir = path.resolve(root, key);
|
||||
// path.relative, not a prefix test, as imagePath() does.
|
||||
const rel = path.relative(root, dir);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) throw new NotepadError("bad", 400);
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(dir);
|
||||
} catch {
|
||||
throw new NotepadError("not-found", 404);
|
||||
}
|
||||
if (!st.isDirectory()) throw new NotepadError("bad", 400);
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
@@ -6,7 +6,7 @@ Revision is a short run of gates, and each maps onto a kind you already know:
|
||||
|
||||
| Step | On the page |
|
||||
| --- | --- |
|
||||
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. |
|
||||
| 1, Change Analysis | A `recap` item, "Is this the change?", with the affected-areas table in `summary`. Found a waiting `**Plan change:**` brief? Quote it at the top of that `summary` and post no open "what should change" card first. |
|
||||
| 2, Impact Assessment | The Revision Impact Summary as a doc (`id: "impact"`), and a `review` item "Approve the spec changes" pointing at it: verdicts `approve` ("Approve these spec changes"), `refine` ("Refine the plan") and `abort` ("Abort", `"danger": true`), `nothingYet`: "No spec file changes until you approve." |
|
||||
| 3 to 5 | Nothing to ask. Post `activity` while you edit, then the Revision Complete summary as a doc. |
|
||||
| 6, Cleanup | A `confirm` per rename or removal, the paths in `consequences`. |
|
||||
|
||||
@@ -5,7 +5,7 @@ import path from "node:path";
|
||||
|
||||
import { checkHelpers } from "./public/subagents.js";
|
||||
import { nowIso, SCHEMA } from "./files.mjs";
|
||||
import { TASK_LINE_RE } from "./scan.mjs";
|
||||
import { TASK_LINE_RE } from "./spec-files.mjs";
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
|
||||
+35
-11
@@ -75,26 +75,50 @@ public static class Plan2CodeFolderPicker {
|
||||
[DllImport("user32.dll")]
|
||||
private static extern int GetSystemMetrics(int index);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern bool IsWindowVisible(IntPtr hWnd);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern IntPtr GetForegroundWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void SwitchToThisWindow(IntPtr hWnd, bool altTab);
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
private static extern void keybd_event(byte vk, byte scan, uint flags, UIntPtr extra);
|
||||
|
||||
private const uint FOS_PICKFOLDERS = 0x20;
|
||||
private const uint FOS_FORCEFILESYSTEM = 0x40;
|
||||
private const uint FOS_PATHMUSTEXIST = 0x800;
|
||||
private const uint SIGDN_FILESYSPATH = 0x80058000;
|
||||
private const int ERROR_CANCELLED = unchecked((int)0x800704C7);
|
||||
|
||||
// Windows refuses SetForegroundWindow from a background process (this one is spawned
|
||||
// by the detached console server), so the dialog opened behind the browser. A tap of
|
||||
// Alt counts as input from this process and lifts the lock for the call after it. The
|
||||
// topmost flag below is ignored by this dialog (SetWindowPos succeeds, the bit stays
|
||||
// off), so taking the foreground is what puts it in front.
|
||||
private static void Raise(string title) {
|
||||
for (int i = 0; i < 100; i++) {
|
||||
IntPtr hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero) {
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
SetForegroundWindow(hwnd);
|
||||
return;
|
||||
}
|
||||
IntPtr hwnd = IntPtr.Zero;
|
||||
for (int i = 0; i < 200; i++) {
|
||||
hwnd = FindWindow(null, title);
|
||||
if (hwnd != IntPtr.Zero && IsWindowVisible(hwnd)) break;
|
||||
hwnd = IntPtr.Zero;
|
||||
Thread.Sleep(50);
|
||||
}
|
||||
if (hwnd == IntPtr.Zero) return;
|
||||
int w = Math.Min(1100, GetSystemMetrics(0) - 80);
|
||||
int h = Math.Min(750, GetSystemMetrics(1) - 80);
|
||||
int x = (GetSystemMetrics(0) - w) / 2 + 40;
|
||||
int y = (GetSystemMetrics(1) - h) / 2 + 40;
|
||||
SetWindowPos(hwnd, new IntPtr(-1), x, y, w, h, 0x40);
|
||||
for (int i = 0; i < 20 && GetForegroundWindow() != hwnd; i++) {
|
||||
keybd_event(0x12, 0, 0, UIntPtr.Zero);
|
||||
keybd_event(0x12, 0, 2, UIntPtr.Zero);
|
||||
SetForegroundWindow(hwnd);
|
||||
SwitchToThisWindow(hwnd, true);
|
||||
Thread.Sleep(100);
|
||||
}
|
||||
}
|
||||
|
||||
public static string Pick(IntPtr owner, string title, string start) {
|
||||
|
||||
@@ -416,43 +416,12 @@ export function resumeCommand({ workflow, specDir } = {}) {
|
||||
// Only a real relative specs/ path. Anything else would be run verbatim by
|
||||
// someone with no way to tell it was wrong.
|
||||
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
|
||||
const withOverview = (cmd) => (dir ? `${cmd} ${dir}/overview.md` : cmd);
|
||||
switch (workflow) {
|
||||
case "dashboard":
|
||||
return "/plan2code";
|
||||
case "init":
|
||||
return "/plan2code-init";
|
||||
case "init-update":
|
||||
return "/plan2code-init-update";
|
||||
case "plan":
|
||||
return "/plan2code-1-plan";
|
||||
case "quick-task":
|
||||
return "/plan2code-quick-task";
|
||||
case "document":
|
||||
return withOverview("/plan2code-2-document");
|
||||
case "implement":
|
||||
return withOverview("/plan2code-3-implement");
|
||||
case "implement-review":
|
||||
return withOverview("/plan2code-3-implement-review");
|
||||
case "review":
|
||||
return "/plan2code-review";
|
||||
case "revise-plan":
|
||||
return withOverview("/plan2code-1b-revise-plan");
|
||||
case "finalize":
|
||||
return withOverview("/plan2code-4-finalize");
|
||||
case "handoff":
|
||||
return "/plan2code-handoff";
|
||||
case "git":
|
||||
return "/plan2code-git";
|
||||
case "changelog":
|
||||
return "/plan2code-changelog";
|
||||
case "xray":
|
||||
return "/plan2code-xray";
|
||||
case "diagnose":
|
||||
return "/plan2code-diagnose";
|
||||
default:
|
||||
return dir ? `/plan2code-0-pathfinder ${dir}/pathfinder` : "/plan2code-0-pathfinder";
|
||||
}
|
||||
// What follows the command is the entry's `resume` (skills.js). A workflow
|
||||
// the console does not know (an old session's) resumes as Pathfinder.
|
||||
const entry = skillFor(workflow) || skillFor("pathfinder");
|
||||
if (dir && entry.resume === "overview") return `${entry.command} ${dir}/overview.md`;
|
||||
if (dir && entry.resume === "folder") return `${entry.command} ${dir}/pathfinder`;
|
||||
return entry.command;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------ after a build is done */
|
||||
@@ -541,6 +510,7 @@ export const SKILL_CATALOG = SKILLS.filter((s) => s.card).map((s) => ({
|
||||
skill: s.skill,
|
||||
command: s.command,
|
||||
workflow: s.workflow,
|
||||
...(s.review ? { review: s.review } : {}),
|
||||
...s.card,
|
||||
}));
|
||||
|
||||
@@ -563,7 +533,20 @@ export function startPose(workflow) {
|
||||
|
||||
export function catalogEntry(skill) {
|
||||
const entry = skillByName(skill);
|
||||
return entry && entry.card ? SKILL_CATALOG.find((e) => e.skill === entry.skill) : null;
|
||||
if (!entry) return null;
|
||||
// A skill with no card of its own is launched from another's (Implement +
|
||||
// Review from Implement's Review box).
|
||||
const owner = entry.card ? entry : SKILLS.find((s) => s.review === entry.skill);
|
||||
return owner ? SKILL_CATALOG.find((e) => e.skill === owner.skill) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a card launches: the card itself, or, when it has a Review box and the
|
||||
* box is ticked, the review skill's entry under the card's title.
|
||||
*/
|
||||
export function launchVariant(entry, withReview) {
|
||||
const alt = withReview && entry.review ? skillByName(entry.review) : null;
|
||||
return alt ? { ...entry, skill: alt.skill, workflow: alt.workflow, command: alt.command, title: alt.name } : entry;
|
||||
}
|
||||
|
||||
/* ------------------------------------------- dashboard card availability */
|
||||
|
||||
@@ -22,7 +22,7 @@ import {
|
||||
adopt, banner, connect, fillSky, fitGrowBox, loadState, markSent, maybeWelcome, render, renderFooter,
|
||||
renderSidebar, renderWhere, save, startClock, startLooks, stagedPayload, syncWorkspaceScope,
|
||||
wakeHoldsChime, wireAsk, wireCards, wireChrome, wireCleanup, wireDashboard, wireDocs, wireEnding,
|
||||
wireHelp, wireLooks, wireWorkspace,
|
||||
wireHelp, wireLooks, wireNotepad, wireWorkspace,
|
||||
} from "./screens/core.js";
|
||||
import { sound } from "./sound.js";
|
||||
|
||||
@@ -49,6 +49,7 @@ wireLooks();
|
||||
wireCleanup();
|
||||
wireDocs();
|
||||
wireAsk();
|
||||
wireNotepad();
|
||||
wireChrome();
|
||||
startClock();
|
||||
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
// Plan2Code Web Console - the hop rule.
|
||||
//
|
||||
// Which hops from one workflow to another start the new skill on a clean
|
||||
// page. One rule, called by both sides that act on it: the server
|
||||
// (cmd-open.mjs blanks the stored session and drops the staged draft) and the
|
||||
// page (screens/core.js drops what it kept for the last skill: the question
|
||||
// on screen, the open tab, anything staged against its item ids). No imports
|
||||
// and no DOM access: nothing runs at load.
|
||||
|
||||
// True when a hop from workflow `from` to workflow `to` starts clean:
|
||||
// - a launch from the dashboard menu gets a clean page, not the last
|
||||
// skill's questions and tabs under its own name;
|
||||
// - going back to the dashboard clears the last skill;
|
||||
// - 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 board.
|
||||
// A skill run inline from another (a quick task's review) never switches
|
||||
// workflow, so it keeps the page; nor does a resume into the same workflow.
|
||||
export function startsClean(from, to) {
|
||||
if (typeof from !== "string" || typeof to !== "string" || !from || !to || from === to) return false;
|
||||
return from === "dashboard" || to === "dashboard" || to === "git";
|
||||
}
|
||||
@@ -34,6 +34,7 @@
|
||||
<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="/screens/notepad.js" />
|
||||
<link rel="modulepreload" href="/net.js" />
|
||||
<link rel="modulepreload" href="/render.js" />
|
||||
<link rel="modulepreload" href="/palette.js" />
|
||||
@@ -51,6 +52,8 @@
|
||||
<link rel="modulepreload" href="/git-board-view.js" />
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
<link rel="modulepreload" href="/notepad.js" />
|
||||
<link rel="modulepreload" href="/vendor/overtype.esm.js" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<link rel="icon" type="image/png" sizes="192x192" href="/favicon.png" />
|
||||
</head>
|
||||
@@ -211,6 +214,16 @@
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
<!-- Notepad: every screen, never hidden. The person's private notes for this
|
||||
folder; nothing in it reaches the agent. -->
|
||||
<button type="button" class="btn ghost small notepad-btn" id="btn-notepad" title="Notepad" aria-label="Notepad">
|
||||
<!-- A notepad: a page bound at the top by three rings, with three lines. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<rect class="np-page" x="3" y="2.5" width="10" height="12" rx="1.3" />
|
||||
<path class="np-ring" d="M5.5 1.2v2.6M8 1.2v2.6M10.5 1.2v2.6" />
|
||||
<path class="np-line" d="M5.5 7h5M5.5 9.5h5M5.5 12h3.2" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -1160,6 +1173,42 @@
|
||||
right. See "Sending and what happens next".
|
||||
</li>
|
||||
</ul>
|
||||
<h4>Your notepad</h4>
|
||||
<p>
|
||||
The <strong>Notepad</strong> button, a page with three rings at the
|
||||
top, sits beside Stop session on every screen. It opens a notepad of
|
||||
your own for this folder, somewhere to jot things down as you go.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
Text is styled as you type. Write Markdown, such as
|
||||
<code>**bold**</code> or <code># Heading</code>, and it shows that
|
||||
way at once.
|
||||
</li>
|
||||
<li>
|
||||
Images go in the strip under the text. Paste one, drop one on the
|
||||
notepad or press <strong>Add image</strong>. Click a picture to see
|
||||
it full screen: the arrow keys step through them and
|
||||
<kbd>Esc</kbd> closes it. The <strong>×</strong> on a picture asks
|
||||
before it deletes it.
|
||||
</li>
|
||||
<li>
|
||||
Everything saves as you go, one notepad per project folder. There is
|
||||
no Save button.
|
||||
</li>
|
||||
<li>
|
||||
It is private to this machine and never sent to Plan2Code. Nothing
|
||||
in it is shown to the agent.
|
||||
</li>
|
||||
<li>
|
||||
Two open pages on the same folder share one notepad. If both change
|
||||
it, the last save wins.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>, in User Preferences, offers to remove a
|
||||
notepad only after a month untouched. Nothing removes it on its own.
|
||||
</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 4: Your workspace -->
|
||||
@@ -1644,31 +1693,7 @@
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
<ul>
|
||||
<li><strong>Set up this project.</strong> Reads your project and writes AGENTS.md, the guide every later step works from.</li>
|
||||
<li><strong>Refresh AGENTS.md.</strong> Brings AGENTS.md and its notes up to date with what the project has learned lately.</li>
|
||||
</ul>
|
||||
<p><strong>The steps, in order</strong></p>
|
||||
<ul>
|
||||
<li><strong>Pathfinder.</strong> A foggy idea becomes a clear list of decisions, settled one question at a time.</li>
|
||||
<li><strong>Plan.</strong> Requirements, technical design and your approval: the shape of what gets built.</li>
|
||||
<li><strong>Revise the plan.</strong> Requirements changed mid-build? Adjust the plan without starting over.</li>
|
||||
<li><strong>Document.</strong> The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do.</li>
|
||||
<li><strong>Implement.</strong> Builds the next phase, task by task, with a report and your sign-off at the end.</li>
|
||||
<li><strong>Implement + review.</strong> One phase built, then a careful review of the changes, then your sign-off. All in one run.</li>
|
||||
<li><strong>Finalize.</strong> Checks the work, writes the summary, files the specs away and suggests the commit message.</li>
|
||||
</ul>
|
||||
<p><strong>Useful any time</strong></p>
|
||||
<ul>
|
||||
<li><strong>Quick task.</strong> Too small for the full process? A quick plan, then it just builds it.</li>
|
||||
<li><strong>Review.</strong> A second opinion on the changes. Problems ranked, and you pick what gets fixed.</li>
|
||||
<li><strong>Handoff.</strong> Pack the current session into a document a fresh session can pick up cold.</li>
|
||||
<li><strong>Changelog.</strong> Checks the CHANGELOG version against the main branch and suggests entries for what is new.</li>
|
||||
<li><strong>Git.</strong> Branches, pull, push and commits on one board, asking before anything leaves your machine. See "The git board".</li>
|
||||
<li><strong>Codebase X-ray.</strong> Explains how and why an area of the code works, or finds the rough spots worth fixing.</li>
|
||||
<li><strong>Diagnose a bug.</strong> Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.</li>
|
||||
</ul>
|
||||
<div class="help-cards"></div>
|
||||
<h4>Picking a spec</h4>
|
||||
<p>
|
||||
Once your project has specs, <strong>Pick up a spec, or start
|
||||
@@ -2530,6 +2555,37 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad: the person's own notes for this folder, autosaved under
|
||||
~/.plan2code/notepads/ by the /notepad routes. Never part of the
|
||||
session, so nothing in it reaches the agent. screens/notepad.js fills
|
||||
the editor on open. -->
|
||||
<dialog class="modal notepad" id="notepad-modal" aria-labelledby="notepad-title">
|
||||
<h2 id="notepad-title">Notepad</h2>
|
||||
<p class="modal-blurb">Private to this machine and this folder. Never sent to Plan2Code.</p>
|
||||
<div class="notepad-editor" id="notepad-editor"></div>
|
||||
<div class="notepad-images" id="notepad-images">
|
||||
<button type="button" class="btn small ghost notepad-add" id="notepad-add">Add image</button>
|
||||
<input type="file" accept="image/*" multiple id="notepad-file" hidden />
|
||||
<ul class="notepad-strip" id="notepad-strip" role="list" aria-label="Notepad images"></ul>
|
||||
</div>
|
||||
<div class="modal-actions notepad-actions">
|
||||
<p class="help notepad-status" id="notepad-status" aria-live="polite"></p>
|
||||
<button type="button" class="btn ghost" id="notepad-close">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Notepad's full-screen picture preview, opened over the Notepad
|
||||
from a thumbnail by screens/notepad.js. -->
|
||||
<dialog class="modal notepad-preview" id="notepad-preview" aria-label="Image preview">
|
||||
<img class="notepad-preview-img" id="notepad-preview-img" alt="" />
|
||||
<button type="button" class="notepad-preview-step is-prev" id="notepad-preview-prev" aria-label="Previous image">‹</button>
|
||||
<button type="button" class="notepad-preview-step is-next" id="notepad-preview-next" aria-label="Next image">›</button>
|
||||
<div class="notepad-preview-bar">
|
||||
<p class="notepad-preview-count" id="notepad-preview-count" aria-live="polite"></p>
|
||||
<button type="button" class="btn small notepad-preview-close" id="notepad-preview-close">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
|
||||
@@ -8,33 +8,24 @@
|
||||
|
||||
import { SKILLS, isMetered, isPhased } from "./skills.js";
|
||||
|
||||
// The one place the weights live (FR-12). Tune here.
|
||||
export const WEIGHTS = Object.freeze({
|
||||
// The weights (FR-12): the events that are not a skill's own launch live
|
||||
// here, and each skill's weight is its `weight` in skills.js. Tune there or here.
|
||||
const EVENT_WEIGHTS = {
|
||||
"pathfinder-chart": 2,
|
||||
// Scores 0: a Pathfinder question now counts through its answers (below).
|
||||
"pathfinder-question": 0,
|
||||
// Research reads sources and hands its findings back into the context, with
|
||||
// nobody answering anything, so each research question scores on its own.
|
||||
"pathfinder-research": 1,
|
||||
plan: 2,
|
||||
"revise-plan": 1,
|
||||
document: 2,
|
||||
"implement-phase": 2,
|
||||
"implement-review-phase": 3,
|
||||
review: 2,
|
||||
"quick-task": 1,
|
||||
init: 2,
|
||||
"init-update": 2,
|
||||
finalize: 1,
|
||||
handoff: 0,
|
||||
git: 1,
|
||||
// Scores 0 itself: Git's commits are tallied per run (COMMITS_PER_POINT).
|
||||
"git-commits": 0,
|
||||
"git-conflict": 1,
|
||||
changelog: 1,
|
||||
xray: 1,
|
||||
diagnose: 1,
|
||||
});
|
||||
};
|
||||
// A skill's fields as a table by workflow, leaving out the entries without one.
|
||||
const bySkill = (field) => Object.fromEntries(SKILLS.filter((s) => s[field] !== null).map((s) => [s.workflow, s[field]]));
|
||||
export const WEIGHTS = Object.freeze({ ...EVENT_WEIGHTS, ...bySkill("weight") });
|
||||
|
||||
// Workflows whose launch itself scores WEIGHTS[workflow]. Pathfinder,
|
||||
// implement and implement-review score only through the agent's `run`
|
||||
@@ -134,42 +125,19 @@ const WORKFLOW_NAMES = Object.freeze(Object.fromEntries(SKILLS.map((s) => [s.wor
|
||||
// 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");
|
||||
|
||||
// What each scoring event is called in the meter's list of contributions.
|
||||
const LAUNCH_LABELS = Object.freeze({
|
||||
plan: "Plan started",
|
||||
"revise-plan": "Revise plan started",
|
||||
document: "Document started",
|
||||
review: "Review started",
|
||||
"quick-task": "Quick task started",
|
||||
init: "Init started",
|
||||
"init-update": "Init update started",
|
||||
finalize: "Finalize started",
|
||||
git: "Git started",
|
||||
changelog: "Changelog started",
|
||||
xray: "X-ray started",
|
||||
diagnose: "Diagnose started",
|
||||
});
|
||||
const RUN_LABELS = Object.freeze({
|
||||
// What each scoring event is called in the meter's list of contributions: a
|
||||
// skill's launch and run labels are its `started` and `ran` in skills.js, and
|
||||
// the events that are not a skill's own are named here.
|
||||
export const LAUNCH_LABELS = Object.freeze(bySkill("started"));
|
||||
export const RUN_LABELS = Object.freeze({
|
||||
"pathfinder-chart": "Pathfinder map written",
|
||||
"pathfinder-question": "Pathfinder question settled",
|
||||
"pathfinder-research": "Pathfinder research done",
|
||||
plan: "Plan drafted",
|
||||
"revise-plan": "Plan revised",
|
||||
document: "Spec documented",
|
||||
"implement-phase": "Implement phase built",
|
||||
"implement-review-phase": "Implement + Review phase built",
|
||||
review: "Code review run",
|
||||
"quick-task": "Quick task built",
|
||||
init: "Init run",
|
||||
"init-update": "Init update run",
|
||||
finalize: "Finalize run",
|
||||
handoff: "Handoff written",
|
||||
git: "Git run",
|
||||
"git-commits": "Commits in Git",
|
||||
"git-conflict": "Git conflict help",
|
||||
changelog: "Changelog run",
|
||||
xray: "X-ray run",
|
||||
diagnose: "Diagnose run",
|
||||
...bySkill("ran"),
|
||||
});
|
||||
|
||||
// The unit a run names, from its ledger id ("L3:phase-2" -> "phase-2").
|
||||
|
||||
@@ -0,0 +1,201 @@
|
||||
// Plan2Code Web Console - the Notepad's save rules, status words and error sentences.
|
||||
//
|
||||
// The source of truth for when the page saves the note, how it retries, what
|
||||
// the status line says and the sentence each server refusal becomes. The
|
||||
// Notepad screen only runs timers and requests on what these return. No DOM
|
||||
// access at module scope and no imports: the page and `node --test` both
|
||||
// import this file. The limits mirror notepads.mjs (a test keeps them equal),
|
||||
// copied rather than imported because the page cannot load server modules.
|
||||
|
||||
export const SAVE_DEBOUNCE_MS = 800;
|
||||
export const RETRY_STEPS_MS = Object.freeze([1000, 2000, 4000, 8000, 16000, 30000]);
|
||||
export const NOTE_MAX_BYTES = 1024 * 1024;
|
||||
export const NOTEPAD_MAX_IMAGES = 200;
|
||||
export const IMAGE_ID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
|
||||
|
||||
// The codes the /notepad routes send as `{ error: code }`.
|
||||
export const ERROR_CODES = Object.freeze(["bad", "too-long", "not-jpeg", "too-large", "too-many", "not-found"]);
|
||||
|
||||
// UTF-8 bytes, the unit the server's cap is in (a character count would let
|
||||
// non-ASCII text past the page's check and into a 413).
|
||||
export function noteBytes(text) {
|
||||
return new TextEncoder().encode(typeof text === "string" ? text : "").length;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ saving */
|
||||
|
||||
const STATUSES = Object.freeze(["idle", "pending", "saving", "saved", "failed", "too-long"]);
|
||||
|
||||
export const SAVE_START = Object.freeze({ status: "idle", attempt: 0 });
|
||||
|
||||
const known = (state) => !!state && typeof state === "object" && STATUSES.includes(state.status);
|
||||
const attemptOf = (state) => (Number.isInteger(state.attempt) && state.attempt > 0 ? state.attempt : 0);
|
||||
const stay = (state) => ({ state, timer: null });
|
||||
const to = (status, attempt, timer) => ({ state: { status, attempt }, timer });
|
||||
|
||||
/**
|
||||
* The save state after `event`, plus `timer`: the delay in ms the screen arms
|
||||
* before dispatching `due`, or null for no timer. Pure: never mutates `state`,
|
||||
* runs no clock and sends nothing.
|
||||
*/
|
||||
export function nextSave(state, event) {
|
||||
if (!known(state)) return stay(state);
|
||||
const type = event && typeof event === "object" ? event.type : event;
|
||||
const { status } = state;
|
||||
switch (type) {
|
||||
case "typed": {
|
||||
const bytes = event && typeof event.bytes === "number" ? event.bytes : 0;
|
||||
// Over the cap nothing is sent: the server would only refuse it.
|
||||
if (bytes > NOTE_MAX_BYTES) return to("too-long", 0, null);
|
||||
return to("pending", 0, SAVE_DEBOUNCE_MS);
|
||||
}
|
||||
case "due":
|
||||
if (status === "pending" || status === "failed") return to("saving", attemptOf(state), null);
|
||||
return stay(state);
|
||||
case "sent":
|
||||
return stay(state);
|
||||
case "ok":
|
||||
// A change typed while the request was out comes back as a fresh
|
||||
// `typed` from the screen, so `ok` can always land on saved.
|
||||
return to("saved", 0, null);
|
||||
case "error": {
|
||||
// Retrying a size the server refused would never succeed.
|
||||
if (event && event.code === "too-long") return to("too-long", 0, null);
|
||||
const attempt = attemptOf(state);
|
||||
return to("failed", attempt + 1, RETRY_STEPS_MS[Math.min(attempt, RETRY_STEPS_MS.length - 1)]);
|
||||
}
|
||||
case "retry":
|
||||
if (status === "failed") return to("saving", attemptOf(state), null);
|
||||
return stay(state);
|
||||
default:
|
||||
return stay(state);
|
||||
}
|
||||
}
|
||||
|
||||
// "1 MB", "512 KB", "300 bytes": the cap in words for the status line.
|
||||
function sizeWords(bytes) {
|
||||
const trim = (n) => String(Math.round(n * 10) / 10);
|
||||
if (bytes >= 1024 * 1024) return trim(bytes / (1024 * 1024)) + " MB";
|
||||
if (bytes >= 1024) return trim(bytes / 1024) + " KB";
|
||||
return bytes + " bytes";
|
||||
}
|
||||
|
||||
const STATUS_WORDS = Object.freeze({
|
||||
idle: "",
|
||||
pending: "Saving",
|
||||
saving: "Saving",
|
||||
saved: "Saved",
|
||||
failed: "Not saved (retrying)",
|
||||
"too-long": `Too long to save (over ${sizeWords(NOTE_MAX_BYTES)})`,
|
||||
});
|
||||
|
||||
const statusOf = (state) => (typeof state === "string" ? state : state && typeof state === "object" ? state.status : undefined);
|
||||
|
||||
// The status line's words for a state object or a bare status.
|
||||
export function saveStatus(state) {
|
||||
const status = statusOf(state);
|
||||
return Object.prototype.hasOwnProperty.call(STATUS_WORDS, status) ? STATUS_WORDS[status] : "";
|
||||
}
|
||||
|
||||
// True while text on screen may not be on disk yet: the page only asks
|
||||
// before closing then. A too-long note is not asked about, the status line
|
||||
// already says it cannot be saved.
|
||||
export function unsaved(state) {
|
||||
const status = statusOf(state);
|
||||
return status === "pending" || status === "saving" || status === "failed";
|
||||
}
|
||||
|
||||
// True while the editor holds text the stored note must not replace when the
|
||||
// notepad is opened again: anything unsaved, and a note too long to save,
|
||||
// which would otherwise lose everything typed since its last save.
|
||||
export function keepsText(state) {
|
||||
return unsaved(state) || statusOf(state) === "too-long";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ errors */
|
||||
|
||||
const ERROR_SENTENCES = Object.freeze({
|
||||
bad: "Plan2Code could not read that request, so nothing was changed.",
|
||||
"too-long": `This note is too long to save. Notes can be up to ${sizeWords(NOTE_MAX_BYTES)}.`,
|
||||
"not-jpeg": "That picture could not be added. Try a PNG, JPEG or a screenshot.",
|
||||
"too-large": "That picture is too large to add. Try a smaller one.",
|
||||
"too-many": `This notepad already holds ${NOTEPAD_MAX_IMAGES} pictures, the most it can keep. Delete one to add another.`,
|
||||
"not-found": "That picture is no longer in this notepad.",
|
||||
});
|
||||
|
||||
const LOST_CONTACT = "Lost contact with Plan2Code. Your text is kept here and will be saved once it's back.";
|
||||
|
||||
// The status line when the note could not be read on first open: the editor
|
||||
// stays read-only, since anything typed would be saved over the real note.
|
||||
export const NOT_LOADED = "Could not read the note. Close the notepad and open it again.";
|
||||
|
||||
// One plain sentence for a server refusal; anything else (status 0, an
|
||||
// unknown code) is treated as a lost connection.
|
||||
export function errorSentence(code) {
|
||||
return typeof code === "string" && Object.prototype.hasOwnProperty.call(ERROR_SENTENCES, code) ? ERROR_SENTENCES[code] : LOST_CONTACT;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ editor */
|
||||
|
||||
// OverType's HTML without its inline style attributes, which the page's
|
||||
// policy refuses. A link's `anchor-name` (what OverType's link tooltip finds
|
||||
// the link by) moves to `data-anchor`; any other style attribute is dropped,
|
||||
// and the tooltip's own look comes from notepad.css instead. Typed text never
|
||||
// matches: OverType escapes the quotes in it.
|
||||
const STYLE_ATTR = / style="([^"]*)"/g;
|
||||
const ANCHOR_NAME = /^anchor-name: (--link-\d+)$/;
|
||||
|
||||
export function withoutStyleAttrs(html) {
|
||||
return html.replace(STYLE_ATTR, (_, css) => {
|
||||
const anchor = ANCHOR_NAME.exec(css);
|
||||
return anchor ? ` data-anchor="${anchor[1]}"` : "";
|
||||
});
|
||||
}
|
||||
|
||||
// OverType's HTML cut into its top-level elements (one per line, or one per
|
||||
// run of list items), as strings, so the page can tell which lines changed
|
||||
// without parsing the whole note into elements on every key. Tags are
|
||||
// counted, not parsed: OverType escapes `<` and `>` in text and attribute
|
||||
// values, so every `<` here starts a real tag. null when the HTML does not
|
||||
// end balanced, so the caller redraws everything instead.
|
||||
const TAG = /<(\/?)([a-zA-Z][a-zA-Z0-9-]*)\b[^>]*?(\/?)>/g;
|
||||
const VOID_TAGS = new Set(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]);
|
||||
|
||||
export function topLevelParts(html) {
|
||||
const parts = [];
|
||||
let depth = 0;
|
||||
let start = 0;
|
||||
TAG.lastIndex = 0;
|
||||
for (let m; (m = TAG.exec(html)); ) {
|
||||
if (depth === 0 && m.index > start) return null;
|
||||
const [, closing, name, selfClosing] = m;
|
||||
if (closing) depth -= 1;
|
||||
else if (!selfClosing && !VOID_TAGS.has(name.toLowerCase())) depth += 1;
|
||||
if (depth < 0) return null;
|
||||
if (depth === 0) {
|
||||
parts.push(html.slice(start, TAG.lastIndex));
|
||||
start = TAG.lastIndex;
|
||||
}
|
||||
}
|
||||
return depth === 0 && start === html.length ? parts : null;
|
||||
}
|
||||
|
||||
// How many parts at the start (`head`) and at the end (`tail`) are the same
|
||||
// in both lists, never overlapping: everything between them changed.
|
||||
export function changedRange(before, after) {
|
||||
const most = Math.min(before.length, after.length);
|
||||
let head = 0;
|
||||
while (head < most && before[head] === after[head]) head++;
|
||||
let tail = 0;
|
||||
while (tail < most - head && before[before.length - 1 - tail] === after[after.length - 1 - tail]) tail++;
|
||||
return { head, tail };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ viewer */
|
||||
|
||||
// The next index when stepping through `count` pictures, wrapping at both
|
||||
// ends; -1 when there is nothing to step through.
|
||||
export function step(index, delta, count) {
|
||||
if (!(count > 0)) return -1;
|
||||
return (((index + delta) % count) + count) % count;
|
||||
}
|
||||
@@ -27,16 +27,21 @@ const CLEANUP_WHERE = { root: "~/.plan2code/", console: "~/.plan2code/console/",
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
// One notepad is one item, named by the folder it belongs to; its key only
|
||||
// when its meta.json is gone.
|
||||
if (item.where === "notepad") return "Notepad for " + (item.folder || 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 notepads = items.filter((i) => i.where === "notepad").length;
|
||||
const strays = items.length - sessions - completed - notepads;
|
||||
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 (notepads) parts.push(notepads + (notepads === 1 ? " old notepad" : " old notepads"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
} from "../chat.js";
|
||||
import { copyButton, el, isMac, textWithCode } from "../render.js";
|
||||
import { isBuild } from "../skills.js";
|
||||
import { startsClean } from "../hops.js";
|
||||
import { faviconState, setFavicon } from "../favicon.js";
|
||||
import { helperRows, showTab } from "../subagents.js";
|
||||
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
|
||||
@@ -67,6 +68,7 @@ import { renderWorkspace, tellFolderIssues } from "./workspace.js";
|
||||
import { openHelpOn } from "./help-dialog.js";
|
||||
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
|
||||
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderNotepadButton } from "./notepad.js";
|
||||
|
||||
// What the entry needs from the screens at start-up, handed on from here: only
|
||||
// the core imports a screen.
|
||||
@@ -80,6 +82,7 @@ export { maybeWelcome, openHelpOn, wireHelp } from "./help-dialog.js";
|
||||
export { wireCleanup } from "./cleanup.js";
|
||||
export { startLooks, wireLooks } from "./looks.js";
|
||||
export { wireEnding } from "./ending.js";
|
||||
export { wireNotepad } from "./notepad.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -255,14 +258,14 @@ export function adopt(body) {
|
||||
settleStaleUploads();
|
||||
}
|
||||
}
|
||||
// The page passed through the dashboard (a launch from its menu, or back to
|
||||
// it). The server already blanked the session; what this page kept for the
|
||||
// last skill -- the question on screen, the open tab, anything staged or
|
||||
// typed against its item ids -- goes too. The launch in flight and the
|
||||
// dashboard's spec pick are about the hand-off itself, so they stay. A skill
|
||||
// run inline from another (a quick task's review) keeps all of it.
|
||||
const viaDashboard = prevWorkflow === "dashboard" || page.S.workflow === "dashboard";
|
||||
if (prevWorkflow && prevWorkflow !== page.S.workflow && viaDashboard) {
|
||||
// A hop that starts clean (hops.js: a launch from the dashboard menu, back
|
||||
// to it, or into Git from anywhere). The server already blanked the
|
||||
// session; what this page kept for the last skill -- the question on
|
||||
// screen, the open tab, anything staged or typed against its item ids --
|
||||
// goes too. The launch in flight and the dashboard's spec pick are about the
|
||||
// hand-off itself, so they stay. A skill run inline from another (a quick
|
||||
// task's review) keeps all of it.
|
||||
if (startsClean(prevWorkflow, page.S.workflow)) {
|
||||
// The pick rides into the skill it launched, never back home: arriving at
|
||||
// the dashboard, the picker starts on the most recently touched spec still
|
||||
// in play, the one the agent's fresh menu recommends for.
|
||||
@@ -697,6 +700,7 @@ export function render() {
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderNotepadButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
renderSidebar();
|
||||
@@ -1270,7 +1274,7 @@ export function renderSidebar() {
|
||||
b.disabled = Boolean(page.local.launching) || page.gone || page.pendingResult || !av.on;
|
||||
if (!av.on && av.reason) b.title = av.reason;
|
||||
b.setAttribute("aria-current", String(Boolean(page.dashPick && page.dashPick.skill === e.skill)));
|
||||
const isGoing = page.local.launching && page.local.launching.skill === e.skill;
|
||||
const isGoing = page.local.launching && (page.local.launching.skill === e.skill || page.local.launching.skill === e.review);
|
||||
const isPicked = page.dashPick && page.dashPick.skill === e.skill;
|
||||
const mark = el(
|
||||
"span",
|
||||
|
||||
@@ -22,6 +22,8 @@ import {
|
||||
cardPresentation,
|
||||
CATALOG_GROUPS,
|
||||
SKILL_CATALOG,
|
||||
catalogEntry,
|
||||
launchVariant,
|
||||
SPEC_STATE_LABELS,
|
||||
chipDetail,
|
||||
isDeletableSpecDir,
|
||||
@@ -534,7 +536,7 @@ function settleDeleting() {
|
||||
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 entry = catalogEntry(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",
|
||||
@@ -637,7 +639,7 @@ function dashCard(entry, menu) {
|
||||
// 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 going = page.local.launching && (page.local.launching.skill === entry.skill || page.local.launching.skill === entry.review);
|
||||
const b = el(
|
||||
"button",
|
||||
"dash-card" + (presentation.recommended ? " is-suggested" : "") + (going ? " is-going" : "")
|
||||
@@ -719,15 +721,31 @@ export function renderConfirm(main, entry) {
|
||||
pane.appendChild(specLine);
|
||||
}
|
||||
|
||||
// Implement's card reviews the phase before sign-off unless this is unticked.
|
||||
let review = null;
|
||||
if (entry.review) {
|
||||
const label = el("label", "confirm-review");
|
||||
review = el("input");
|
||||
review.type = "checkbox";
|
||||
review.checked = page.dashReview !== false;
|
||||
review.addEventListener("change", () => {
|
||||
page.dashReview = review.checked;
|
||||
cmdCode.textContent = launchVariant(entry, review.checked).command;
|
||||
});
|
||||
label.append(review, el("span", null, "Review: a fresh pass over the phase's changes before sign-off"));
|
||||
pane.appendChild(label);
|
||||
}
|
||||
|
||||
const cmd = el("p", "confirm-cmd");
|
||||
cmd.appendChild(el("code", null, entry.command));
|
||||
const cmdCode = el("code", null, launchVariant(entry, !review || review.checked).command);
|
||||
cmd.appendChild(cmdCode);
|
||||
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));
|
||||
start.addEventListener("click", () => launchSkill(launchVariant(entry, Boolean(review) && review.checked)));
|
||||
const back = el("button", "btn ghost", "Back");
|
||||
back.type = "button";
|
||||
back.addEventListener("click", () => {
|
||||
@@ -830,7 +848,7 @@ function openHandoffDelete(h) {
|
||||
facts.appendChild(el("dt", "", term));
|
||||
facts.appendChild(el("dd", "", value));
|
||||
};
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === h.skill);
|
||||
const entry = catalogEntry(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\//, "") : "");
|
||||
|
||||
@@ -5,6 +5,7 @@ import { page } from "../state.js";
|
||||
import { isDashboard, finish, agentAdrift } from "../selectors.js";
|
||||
import { releasesLink, el, copyButton, lightDismiss } from "../render.js";
|
||||
import { HELP_TABS, helpTabFor, helpKeyTarget } from "../help.js";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../answers.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -101,6 +102,22 @@ function buildHelp() {
|
||||
cell.appendChild(el("span", null, label));
|
||||
moods.appendChild(cell);
|
||||
}
|
||||
// The dashboard topic lists the cards from the catalog, grouped and in the
|
||||
// dashboard's order, so Help can never name a card the dashboard lacks.
|
||||
// A card's help line, when it has one, says more than its blurb.
|
||||
const cards = panels.querySelector(".help-cards");
|
||||
for (const g of CATALOG_GROUPS) {
|
||||
const head = el("p");
|
||||
head.appendChild(el("strong", null, g.title));
|
||||
const list = el("ul");
|
||||
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
|
||||
const li = el("li");
|
||||
li.appendChild(el("strong", null, e.title + "."));
|
||||
li.appendChild(document.createTextNode(" " + (e.help || e.blurb)));
|
||||
list.appendChild(li);
|
||||
}
|
||||
cards.append(head, list);
|
||||
}
|
||||
for (const row of panels.querySelectorAll("[data-copy]")) {
|
||||
const code = row.querySelector("code");
|
||||
row.appendChild(copyButton(code.textContent, "btn small handoff-copy", code));
|
||||
|
||||
@@ -0,0 +1,652 @@
|
||||
// Plan2Code Web Console - the Notepad: the top bar's icon, its dialog, the editor and autosave.
|
||||
//
|
||||
// The person's own notes for the folder this session runs in, kept by the
|
||||
// server under ~/.plan2code/notepads/ through the /notepad routes, never in
|
||||
// the session, so nothing typed here reaches the agent. The editor is the
|
||||
// vendored OverType, which styles Markdown in place over a real textarea. Its
|
||||
// CSS ships in styles/notepad.css, because the page's policy blocks the
|
||||
// <style> OverType would inject. When to save and what the status line says
|
||||
// are notepad.js's pure rules; this file only runs the timers and requests.
|
||||
|
||||
import { page } from "../state.js";
|
||||
import {
|
||||
IMAGE_ID_RE,
|
||||
NOTEPAD_MAX_IMAGES,
|
||||
NOT_LOADED,
|
||||
SAVE_START,
|
||||
changedRange,
|
||||
errorSentence,
|
||||
keepsText,
|
||||
nextSave,
|
||||
noteBytes,
|
||||
saveStatus,
|
||||
step,
|
||||
topLevelParts,
|
||||
unsaved,
|
||||
withoutStyleAttrs,
|
||||
} from "../notepad.js";
|
||||
import { el, lightDismiss } from "../render.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { reencode } from "../uploads.js";
|
||||
import { OverType } from "../vendor/overtype.esm.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
const NOT_CONNECTED = "Not connected right now.";
|
||||
|
||||
// One editor for the page's life, made on first open.
|
||||
let editor = null;
|
||||
|
||||
// The save state (notepad.js), the one timer it arms, and the request in
|
||||
// flight. `rev` counts changes, so an answer to an older text never marks a
|
||||
// newer one saved.
|
||||
let save = SAVE_START;
|
||||
let timer = null;
|
||||
let sending = false;
|
||||
let rev = 0;
|
||||
let problem = "";
|
||||
|
||||
// True while the page itself sets the editor's text: OverType reports that as
|
||||
// a change, and it is not the person typing.
|
||||
let loading = false;
|
||||
|
||||
// Whether the note has been read into the editor yet. Until it has, the
|
||||
// editor is read-only: text typed into the empty editor would be saved over
|
||||
// the real note.
|
||||
let loaded = false;
|
||||
|
||||
// Drawn from the render pass beside Stop: always shown, unusable while the
|
||||
// server is gone (nothing could load or save).
|
||||
export function renderNotepadButton() {
|
||||
const btn = $("btn-notepad");
|
||||
btn.disabled = Boolean(page.gone);
|
||||
btn.title = page.gone ? NOT_CONNECTED : "Notepad";
|
||||
}
|
||||
|
||||
// The last thing a picture went wrong with, said after the save words until
|
||||
// the next batch of pictures starts or the notepad is opened again; and the
|
||||
// picture it was about, if one, whose Retry landing clears it.
|
||||
let notice = "";
|
||||
let noticeKey = null;
|
||||
|
||||
function paintStatus() {
|
||||
const line = $("notepad-status");
|
||||
const words = saveStatus(save);
|
||||
const failed = save.status === "failed" || save.status === "too-long";
|
||||
const saving = save.status === "failed" && problem ? `${words}. ${problem}` : words;
|
||||
line.textContent = [saving, notice].filter(Boolean).join(" ");
|
||||
line.classList.toggle("is-problem", failed || Boolean(notice));
|
||||
}
|
||||
|
||||
function tell(sentence, key = null) {
|
||||
notice = sentence;
|
||||
noticeKey = key;
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
function arm(ms) {
|
||||
clearTimeout(timer);
|
||||
timer = ms == null ? null : setTimeout(() => dispatch(save.status === "failed" ? "retry" : "due"), ms);
|
||||
}
|
||||
|
||||
function dispatch(event) {
|
||||
const next = nextSave(save, event);
|
||||
save = next.state;
|
||||
arm(next.timer);
|
||||
paintStatus();
|
||||
if (save.status === "saving") send();
|
||||
}
|
||||
|
||||
// One save at a time. A save that comes due while another is out goes as
|
||||
// soon as that one answers.
|
||||
async function send() {
|
||||
if (sending || !editor) return;
|
||||
sending = true;
|
||||
const sent = rev;
|
||||
const res = await postJson("/notepad/text", { text: editor.getValue() });
|
||||
sending = false;
|
||||
if (rev !== sent) {
|
||||
// Typed while it was out: the newer text has its own debounce running, or
|
||||
// is already due and waiting for this request to finish.
|
||||
if (save.status === "saving") send();
|
||||
return;
|
||||
}
|
||||
if (res.status === 200) {
|
||||
problem = "";
|
||||
return dispatch("ok");
|
||||
}
|
||||
const code = res.body && res.body.error;
|
||||
problem = errorSentence(res.status === 0 ? null : code);
|
||||
dispatch({ type: "error", code });
|
||||
}
|
||||
|
||||
function changed(text) {
|
||||
if (loading) return;
|
||||
rev += 1;
|
||||
dispatch({ type: "typed", bytes: noteBytes(text) });
|
||||
}
|
||||
|
||||
// Save now rather than after the debounce: closing, the tab going hidden.
|
||||
function flush() {
|
||||
if (save.status === "pending" || save.status === "failed") dispatch("due");
|
||||
}
|
||||
|
||||
function setText(text) {
|
||||
loading = true;
|
||||
try {
|
||||
editor.setValue(text);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
}
|
||||
|
||||
// OverType writes inline style attributes into the HTML it sets: one on every
|
||||
// link it draws (its tooltip's anchor name) and two in the link tooltip. The
|
||||
// page's policy refuses each one with a report, on every keystroke. While the
|
||||
// editor is built, the elements it makes get an innerHTML that drops them
|
||||
// (withoutStyleAttrs); the preview and the tooltip are among them, so this
|
||||
// holds for every later render too. The tooltip then finds a link by the data
|
||||
// attribute its anchor name moved to.
|
||||
function buildWithoutStyleAttrs(build) {
|
||||
const create = document.createElement;
|
||||
const inner = Object.getOwnPropertyDescriptor(Element.prototype, "innerHTML");
|
||||
document.createElement = function (...args) {
|
||||
const node = create.apply(this, args);
|
||||
Object.defineProperty(node, "innerHTML", {
|
||||
configurable: true,
|
||||
get() {
|
||||
return inner.get.call(this);
|
||||
},
|
||||
set(html) {
|
||||
const clean = withoutStyleAttrs(String(html));
|
||||
if (this.classList.contains("overtype-preview")) patchPreview(this, clean);
|
||||
else inner.set.call(this, clean);
|
||||
},
|
||||
});
|
||||
return node;
|
||||
};
|
||||
try {
|
||||
return build();
|
||||
} finally {
|
||||
document.createElement = create;
|
||||
}
|
||||
}
|
||||
|
||||
// The styled layer as OverType last drew it, one HTML string per top-level
|
||||
// element (topLevelParts), matching the preview's children one for one.
|
||||
let drawn = [];
|
||||
|
||||
const parseParts = (html) => {
|
||||
const tpl = document.createElement("template");
|
||||
tpl.innerHTML = html;
|
||||
return [...tpl.content.childNodes];
|
||||
};
|
||||
|
||||
// OverType redraws the whole styled layer on every key: about 43,000 elements
|
||||
// in a 200 KB note, and parsing and laying those out is most of the wait for a
|
||||
// key to show. Only the lines between the first and the last that differ from
|
||||
// the last drawing are parsed and swapped; the rest stays as it was.
|
||||
function patchPreview(preview, html) {
|
||||
const parts = topLevelParts(html);
|
||||
const shown = [...preview.childNodes];
|
||||
const redraw = () => {
|
||||
preview.replaceChildren(...parseParts(html));
|
||||
drawn = parts && preview.childNodes.length === parts.length ? parts : [];
|
||||
};
|
||||
if (!parts || shown.length !== drawn.length) return redraw();
|
||||
const { head, tail } = changedRange(drawn, parts);
|
||||
const changed = parts.slice(head, parts.length - tail);
|
||||
const fresh = parseParts(changed.join(""));
|
||||
// One element per part, or the cut was wrong: draw it all.
|
||||
if (fresh.length !== changed.length) return redraw();
|
||||
const after = shown[shown.length - tail] || null;
|
||||
for (const old of shown.slice(head, shown.length - tail)) old.remove();
|
||||
for (const node of fresh) preview.insertBefore(node, after);
|
||||
drawn = parts;
|
||||
// OverType shades each pair of code fences right after this, and never
|
||||
// takes the shading off: a kept line whose fence lost its partner would keep
|
||||
// it. Cleared here (the attributes removed outright, so a cleared line is
|
||||
// the line OverType drew), and OverType marks only the pairs that still are.
|
||||
for (const line of preview.querySelectorAll(".code-block-line")) {
|
||||
line.classList.remove("code-block-line");
|
||||
if (!line.classList.length) line.removeAttribute("class");
|
||||
}
|
||||
for (const fence of preview.querySelectorAll(".code-fence")) fence.removeAttribute("style");
|
||||
}
|
||||
|
||||
function makeEditor() {
|
||||
// Before the first instance, or it injects its <style> (which the policy
|
||||
// blocks) and the flag would come too late.
|
||||
OverType.stylesInjected = true;
|
||||
// OverType reports its first, empty value as a change: not the person typing,
|
||||
// and saved it would wipe the note.
|
||||
loading = true;
|
||||
try {
|
||||
[editor] = buildWithoutStyleAttrs(
|
||||
() =>
|
||||
new OverType($("notepad-editor"), {
|
||||
toolbar: false,
|
||||
textareaProps: { "aria-label": "Notepad text" },
|
||||
onChange: changed,
|
||||
}),
|
||||
);
|
||||
} finally {
|
||||
loading = false;
|
||||
}
|
||||
editor.linkTooltip.findAnchorElement = (index) => editor.preview.querySelector(`a[data-anchor="--link-${index}"]`);
|
||||
}
|
||||
|
||||
// The stored note (`{ text, images }`), or null when it could not be read.
|
||||
async function readNote() {
|
||||
try {
|
||||
const res = await fetch("/notepad", { cache: "no-store" });
|
||||
if (!res.ok) return null;
|
||||
const body = await res.json();
|
||||
return body && typeof body.text === "string" ? body : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ pictures */
|
||||
|
||||
// The strip's pictures, oldest first, as { key, id, url, thumb, status }:
|
||||
// `key` is the page's own handle, `id` and `url` come from the server once
|
||||
// the upload lands, `thumb` is the stored thumbnail's URL or, for one added
|
||||
// here, the data: URL reencode() made. `status` is ready, uploading or failed.
|
||||
let images = [];
|
||||
|
||||
// What a failed upload needs to go again, by key: the re-encoded picture and
|
||||
// its thumbnail. Kept out of `images`, since both are large.
|
||||
const pending = new Map();
|
||||
|
||||
// Raw JPEG bytes to a /notepad route; the status and parsed answer, or status
|
||||
// 0 when the server could not be reached (as postJson).
|
||||
async function postJpeg(url, blob) {
|
||||
try {
|
||||
const res = await fetch(url, { method: "POST", headers: { "content-type": "image/jpeg" }, body: blob });
|
||||
let answer = {};
|
||||
try {
|
||||
answer = await res.json();
|
||||
} catch {}
|
||||
return { status: res.status, body: answer };
|
||||
} catch {
|
||||
return { status: 0, body: {} };
|
||||
}
|
||||
}
|
||||
|
||||
const imageFiles = (list) => Array.from(list || []).filter((f) => f && f.type && f.type.startsWith("image/"));
|
||||
|
||||
const drop = (key) => {
|
||||
images = images.filter((img) => img.key !== key);
|
||||
pending.delete(key);
|
||||
};
|
||||
|
||||
// The picture, then its thumbnail. One whose picture already landed (only
|
||||
// the thumbnail failed) sends just the thumbnail again.
|
||||
async function upload(entry) {
|
||||
const encoded = pending.get(entry.key);
|
||||
if (!encoded) return;
|
||||
entry.status = "uploading";
|
||||
drawStrip();
|
||||
if (!entry.id) {
|
||||
const res = await postJpeg("/notepad/image", encoded.blob);
|
||||
const id = res.body && res.body.id;
|
||||
if (res.status !== 200 || !IMAGE_ID_RE.test(String(id))) return failed(entry, res);
|
||||
entry.id = id;
|
||||
entry.url = "/notepad/images/" + id + ".jpg";
|
||||
}
|
||||
const res = await postJpeg("/notepad/thumb?id=" + entry.id, encoded.thumbBlob);
|
||||
if (res.status !== 200) return failed(entry, res);
|
||||
pending.delete(entry.key);
|
||||
entry.status = "ready";
|
||||
// Only this picture's own failure goes: a sentence about the batch (the
|
||||
// cap) or another picture stays up while the rest land.
|
||||
if (noticeKey === entry.key) tell("");
|
||||
drawStrip();
|
||||
}
|
||||
|
||||
function failed(entry, res) {
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
// The server said no for good: going again would only be refused again.
|
||||
if (code === "too-many" || code === "not-jpeg" || code === "too-large" || code === "not-found") drop(entry.key);
|
||||
else entry.status = "failed";
|
||||
drawStrip();
|
||||
tell(errorSentence(code), entry.key);
|
||||
}
|
||||
|
||||
export async function addNotepadImages(files) {
|
||||
const given = imageFiles(files);
|
||||
if (!given.length) return;
|
||||
const room = Math.max(0, NOTEPAD_MAX_IMAGES - images.length);
|
||||
tell(given.length > room ? errorSentence("too-many") : "");
|
||||
await Promise.all(
|
||||
given.slice(0, room).map(async (file) => {
|
||||
const entry = { key: crypto.randomUUID(), id: null, url: null, thumb: null, status: "uploading" };
|
||||
images.push(entry);
|
||||
drawStrip();
|
||||
let encoded;
|
||||
try {
|
||||
encoded = await reencode(file);
|
||||
} catch (err) {
|
||||
drop(entry.key);
|
||||
drawStrip();
|
||||
return tell(err.message);
|
||||
}
|
||||
entry.thumb = encoded.thumb;
|
||||
pending.set(entry.key, encoded);
|
||||
await upload(entry);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
// One thumbnail, the `n`th: the picture (its thumbnail, else the picture
|
||||
// itself) as a button, and the X in its corner. A placeholder with a spinner
|
||||
// while it uploads, Retry when it failed.
|
||||
function thumbItem(entry, n) {
|
||||
const item = el("li", `attach-thumb notepad-thumb is-${entry.status}`);
|
||||
item.dataset.key = entry.key;
|
||||
const open = el("button", "notepad-thumb-open");
|
||||
open.type = "button";
|
||||
const src = entry.thumb || entry.url;
|
||||
if (src) {
|
||||
const pic = el("img");
|
||||
pic.src = src;
|
||||
pic.alt = `Notepad image ${n}`;
|
||||
open.appendChild(pic);
|
||||
} else open.setAttribute("aria-label", `Notepad image ${n}`);
|
||||
// Never `disabled`, which would push the focus out of the strip while the
|
||||
// picture uploads: it only does nothing until there is a picture to show.
|
||||
const viewable = Boolean(entry.url) && entry.status !== "uploading";
|
||||
if (!viewable) open.setAttribute("aria-disabled", "true");
|
||||
open.addEventListener("click", () => {
|
||||
if (viewable) openPreview(entry);
|
||||
});
|
||||
item.appendChild(open);
|
||||
if (entry.status !== "uploading" && !entry.asking) {
|
||||
const x = el("button", "attach-remove notepad-thumb-delete", "×");
|
||||
x.type = "button";
|
||||
x.setAttribute("aria-label", `Delete image ${n}`);
|
||||
x.addEventListener("click", () => ask(entry));
|
||||
item.appendChild(x);
|
||||
}
|
||||
if (entry.asking) {
|
||||
// Keep comes first and takes the focus, so Enter keeps the picture.
|
||||
const over = el("div", "attach-overlay notepad-ask");
|
||||
over.appendChild(el("p", null, "Delete this image?"));
|
||||
const row = el("div", "notepad-ask-row");
|
||||
const keep = el("button", "btn tiny notepad-ask-keep", "Keep");
|
||||
keep.type = "button";
|
||||
keep.addEventListener("click", () => {
|
||||
entry.asking = false;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-thumb-delete");
|
||||
});
|
||||
const del = el("button", "btn tiny notepad-ask-delete", "Delete");
|
||||
del.type = "button";
|
||||
del.addEventListener("click", () => remove(entry));
|
||||
keep.disabled = del.disabled = Boolean(entry.deleting);
|
||||
row.appendChild(keep);
|
||||
row.appendChild(del);
|
||||
over.appendChild(row);
|
||||
item.appendChild(over);
|
||||
} else if (entry.status === "uploading") {
|
||||
const over = el("div", "attach-overlay");
|
||||
over.appendChild(el("span", "spinner tiny"));
|
||||
item.appendChild(over);
|
||||
} else if (entry.status === "failed") {
|
||||
const over = el("div", "attach-overlay failed");
|
||||
over.appendChild(el("p", null, "Upload failed"));
|
||||
const again = el("button", "btn tiny notepad-retry", "Retry");
|
||||
again.type = "button";
|
||||
again.addEventListener("click", () => upload(entry));
|
||||
over.appendChild(again);
|
||||
item.appendChild(over);
|
||||
}
|
||||
return item;
|
||||
}
|
||||
|
||||
// The controls a thumbnail can hold the focus on, by class.
|
||||
const THUMB_CONTROLS = ["notepad-thumb-open", "notepad-thumb-delete", "notepad-ask-keep", "notepad-ask-delete", "notepad-retry"];
|
||||
|
||||
// Every redraw rebuilds the thumbnails, which would drop a focused button
|
||||
// out of the page: the focus goes back to the same control, or to that
|
||||
// thumbnail's picture when the control is gone (Retry became a spinner), or
|
||||
// to Add image when the thumbnail itself is gone.
|
||||
function drawStrip() {
|
||||
const strip = $("notepad-strip");
|
||||
const active = document.activeElement;
|
||||
const was = active && strip.contains(active) ? active.closest("li") : null;
|
||||
const control = was && THUMB_CONTROLS.find((cls) => active.classList.contains(cls));
|
||||
strip.replaceChildren(...images.map((entry, i) => thumbItem(entry, i + 1)));
|
||||
if (!was) return;
|
||||
if (!(control && focusIn(was.dataset.key, "." + control)) && !focusIn(was.dataset.key, ".notepad-thumb-open")) {
|
||||
$("notepad-add").focus();
|
||||
}
|
||||
}
|
||||
|
||||
// Focus a control in the thumbnail with this key; whether it could.
|
||||
function focusIn(key, selector) {
|
||||
const item = Array.from($("notepad-strip").children).find((li) => li.dataset.key === key);
|
||||
const target = item && item.querySelector(selector);
|
||||
if (!target || target.disabled) return false;
|
||||
target.focus();
|
||||
return true;
|
||||
}
|
||||
|
||||
// The X asks first, on the thumbnail itself; one question at a time.
|
||||
function ask(entry) {
|
||||
for (const img of images) img.asking = img === entry;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-ask-keep");
|
||||
}
|
||||
|
||||
// Delete for good, then hand the focus to the picture that took its place.
|
||||
// One never stored (its upload failed) is only taken off the strip.
|
||||
async function remove(entry) {
|
||||
if (entry.id) {
|
||||
entry.deleting = true;
|
||||
drawStrip();
|
||||
const res = await postJson("/notepad/image/delete", { id: entry.id });
|
||||
entry.deleting = false;
|
||||
const code = res.status === 0 ? null : res.body && res.body.error;
|
||||
if (res.status !== 200 && code !== "not-found") {
|
||||
entry.asking = false;
|
||||
drawStrip();
|
||||
focusIn(entry.key, ".notepad-thumb-delete");
|
||||
return tell(errorSentence(code));
|
||||
}
|
||||
// Already gone (deleted from another page): off the strip too, with why.
|
||||
if (code === "not-found") tell(errorSentence(code));
|
||||
}
|
||||
const at = images.indexOf(entry);
|
||||
drop(entry.key);
|
||||
drawStrip();
|
||||
const next = images[at] || images[at - 1];
|
||||
if (next) focusIn(next.key, ".notepad-thumb-open");
|
||||
else $("notepad-add").focus();
|
||||
}
|
||||
|
||||
// The stored pictures from GET /notepad, oldest first, then any added here
|
||||
// that are still on their way or waiting for Retry.
|
||||
function takeStored(list) {
|
||||
const stored = (Array.isArray(list) ? list : [])
|
||||
.filter((img) => img && IMAGE_ID_RE.test(String(img.id)))
|
||||
.map((img) => ({ key: img.id, id: img.id, url: img.url, thumb: img.thumb || null, status: "ready" }));
|
||||
const ids = new Set(stored.map((img) => img.id));
|
||||
const local = images.filter((img) => img.status !== "ready" && !(img.id && ids.has(img.id)));
|
||||
for (const key of pending.keys()) if (!local.some((img) => img.key === key)) pending.delete(key);
|
||||
images = [...stored, ...local];
|
||||
drawStrip();
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ preview */
|
||||
|
||||
// What the preview steps through (the pictures with a stored copy, as they
|
||||
// stood when it opened), which one shows, and the thumbnail it opened from.
|
||||
let viewing = { list: [], index: -1, from: null };
|
||||
|
||||
function showAt(index) {
|
||||
const { list } = viewing;
|
||||
const entry = list[index];
|
||||
viewing.index = index;
|
||||
const pic = $("notepad-preview-img");
|
||||
pic.src = entry.url;
|
||||
pic.alt = `Notepad image ${images.indexOf(entry) + 1}`;
|
||||
$("notepad-preview-count").textContent = `${index + 1} of ${list.length}`;
|
||||
$("notepad-preview-prev").hidden = $("notepad-preview-next").hidden = list.length < 2;
|
||||
}
|
||||
|
||||
function openPreview(entry) {
|
||||
const list = images.filter((img) => img.url);
|
||||
const index = list.indexOf(entry);
|
||||
if (index < 0) return;
|
||||
viewing = { list, index, from: entry.key };
|
||||
showAt(index);
|
||||
const dlg = $("notepad-preview");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
$("notepad-preview-close").focus();
|
||||
}
|
||||
|
||||
function move(delta) {
|
||||
const index = step(viewing.index, delta, viewing.list.length);
|
||||
if (index >= 0) showAt(index);
|
||||
}
|
||||
|
||||
// Esc is taken here and closes the preview alone: left to the browser, it
|
||||
// could reach the Notepad underneath too.
|
||||
function wirePreview() {
|
||||
const dlg = $("notepad-preview");
|
||||
$("notepad-preview-prev").addEventListener("click", () => move(-1));
|
||||
$("notepad-preview-next").addEventListener("click", () => move(1));
|
||||
$("notepad-preview-close").addEventListener("click", () => dlg.close());
|
||||
dlg.addEventListener("keydown", (e) => {
|
||||
if (e.key === "ArrowLeft" || e.key === "ArrowRight") {
|
||||
e.preventDefault();
|
||||
move(e.key === "ArrowLeft" ? -1 : 1);
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
dlg.close();
|
||||
}
|
||||
});
|
||||
dlg.addEventListener("close", () => {
|
||||
$("notepad-preview-img").removeAttribute("src");
|
||||
focusIn(viewing.from, ".notepad-thumb-open");
|
||||
});
|
||||
}
|
||||
|
||||
// A paste is a picture paste when it carries image files and no plain text:
|
||||
// a spreadsheet's cells come with a picture of themselves too, and are text.
|
||||
function pastedImages(data) {
|
||||
if (!data || (data.types && Array.from(data.types).includes("text/plain"))) return [];
|
||||
const items = Array.from(data.items || [])
|
||||
.filter((item) => item.kind === "file" && item.type.startsWith("image/"))
|
||||
.map((item) => item.getAsFile())
|
||||
.filter(Boolean);
|
||||
return items.length ? items : imageFiles(data.files);
|
||||
}
|
||||
|
||||
const draggingFiles = (e) => Boolean(e.dataTransfer && Array.from(e.dataTransfer.types || []).includes("Files"));
|
||||
|
||||
// The three ways in: the Add image button, a paste and a drop anywhere on the
|
||||
// dialog. Captured on the dialog, ahead of the editor's own handling, and
|
||||
// only for pictures: text pastes and text drags reach the editor as usual.
|
||||
function wireImages(dlg) {
|
||||
const picker = $("notepad-file");
|
||||
$("notepad-add").addEventListener("click", () => picker.click());
|
||||
picker.addEventListener("change", () => {
|
||||
addNotepadImages(picker.files);
|
||||
picker.value = "";
|
||||
});
|
||||
dlg.addEventListener(
|
||||
"paste",
|
||||
(e) => {
|
||||
const files = pastedImages(e.clipboardData);
|
||||
if (!files.length) return;
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
addNotepadImages(files);
|
||||
},
|
||||
true,
|
||||
);
|
||||
dlg.addEventListener(
|
||||
"dragover",
|
||||
(e) => {
|
||||
if (!draggingFiles(e)) return;
|
||||
e.preventDefault();
|
||||
e.dataTransfer.dropEffect = "copy";
|
||||
dlg.classList.add("is-drop");
|
||||
},
|
||||
true,
|
||||
);
|
||||
dlg.addEventListener("dragleave", (e) => {
|
||||
if (!e.relatedTarget || !dlg.contains(e.relatedTarget)) dlg.classList.remove("is-drop");
|
||||
});
|
||||
dlg.addEventListener(
|
||||
"drop",
|
||||
(e) => {
|
||||
dlg.classList.remove("is-drop");
|
||||
if (!draggingFiles(e)) return;
|
||||
// Taken even when none is a picture, or the browser opens the file.
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
addNotepadImages(e.dataTransfer.files);
|
||||
},
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
// Read again on every open, so saves from another page on the same folder
|
||||
// show up. Text typed here and not yet saved (or too long to save) is never
|
||||
// replaced.
|
||||
async function load() {
|
||||
const note = await readNote();
|
||||
if (note === null) {
|
||||
if (loaded) return;
|
||||
const line = $("notepad-status");
|
||||
line.textContent = NOT_LOADED;
|
||||
line.classList.add("is-problem");
|
||||
return;
|
||||
}
|
||||
takeStored(note.images);
|
||||
if (keepsText(save)) return;
|
||||
setText(note.text);
|
||||
save = SAVE_START;
|
||||
loaded = true;
|
||||
editor.textarea.readOnly = false;
|
||||
paintStatus();
|
||||
}
|
||||
|
||||
export async function openNotepad() {
|
||||
if ($("btn-notepad").disabled) return;
|
||||
const dlg = $("notepad-modal");
|
||||
if (!editor) makeEditor();
|
||||
editor.textarea.readOnly = !loaded;
|
||||
tell("");
|
||||
if (!dlg.open) dlg.showModal();
|
||||
editor.textarea.focus();
|
||||
await load();
|
||||
}
|
||||
|
||||
export function wireNotepad() {
|
||||
const dlg = $("notepad-modal");
|
||||
lightDismiss(dlg);
|
||||
wireImages(dlg);
|
||||
wirePreview();
|
||||
$("btn-notepad").addEventListener("click", openNotepad);
|
||||
$("notepad-close").addEventListener("click", () => dlg.close());
|
||||
dlg.addEventListener("close", () => {
|
||||
flush();
|
||||
$("btn-notepad").focus();
|
||||
});
|
||||
document.addEventListener("visibilitychange", () => {
|
||||
if (document.visibilityState === "hidden") flush();
|
||||
});
|
||||
// Only while something typed may not be on disk yet.
|
||||
window.addEventListener("beforeunload", (e) => {
|
||||
if (!unsaved(save)) return;
|
||||
e.preventDefault();
|
||||
e.returnValue = "";
|
||||
});
|
||||
}
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
import { page, redraw } from "../state.js";
|
||||
import { el, approvalTip } from "../render.js";
|
||||
import { startPose, startingHint, SKILL_CATALOG, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { startPose, startingHint, staleLaunchFeedback, workflowTitle } from "../answers.js";
|
||||
import { skillByName } from "../skills.js";
|
||||
import { agentAdrift, doingNow, docs } from "../selectors.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
@@ -92,7 +93,7 @@ function posePane(main, cls, workflow) {
|
||||
// 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 pane = posePane(main, "launching", l.skill && skillByName(l.skill)?.workflow);
|
||||
|
||||
const stale = staleLaunchFeedback(l.title, agentAdrift());
|
||||
pane.appendChild(el("p", "card-kicker", stale ? stale.kicker : "On it"));
|
||||
|
||||
@@ -19,6 +19,13 @@
|
||||
// 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
|
||||
// weight what the launch and its `run` event score on the session
|
||||
// meter (meter.js WEIGHTS), or null when it has no weight there
|
||||
// started the meter's label for the launch ("Plan started"), or null
|
||||
// ran the meter's label for its `run` event ("Plan drafted"), or null
|
||||
// resume what the resume command takes after the skill's command:
|
||||
// "overview" for <specDir>/overview.md, "folder" for
|
||||
// <specDir>/pathfinder, null for no argument
|
||||
// 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,
|
||||
@@ -30,8 +37,12 @@
|
||||
// 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
|
||||
// review the skill the card launches instead when its Review box is
|
||||
// ticked (Implement's card, which draws the box), or absent
|
||||
// card the dashboard card (group, chip, title, blurb, about, and
|
||||
// `spec: true` when it takes the picked spec), or null
|
||||
// `spec: true` when it takes the picked spec), or null; an
|
||||
// optional `help` is Help's line for the card when it differs
|
||||
// from `blurb`
|
||||
|
||||
// Shared by Implement and Implement + Review.
|
||||
const BUILD_HELPERS =
|
||||
@@ -58,6 +69,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Init",
|
||||
pose: "init",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Init started", ran: "Init run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: { default: "AGENTS.md is already written. Refresh it instead." },
|
||||
@@ -77,6 +89,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Init update",
|
||||
pose: "init",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Init update started", ran: "Init update run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: { default: "Needs an AGENTS.md. Set the project up first." },
|
||||
@@ -96,6 +109,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Pathfinder",
|
||||
pose: "pathfinder",
|
||||
builds: false, phased: false, metered: false, templates: true,
|
||||
weight: null, started: null, ran: null, resume: "folder",
|
||||
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: {
|
||||
@@ -120,6 +134,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Plan",
|
||||
pose: "plan",
|
||||
builds: false, phased: false, metered: true, templates: true,
|
||||
weight: 2, started: "Plan started", ran: "Plan drafted", resume: null,
|
||||
subagents: null,
|
||||
states: ["none", "unrecognized", "diagnosed", "mapped", "planned"], marksNext: true,
|
||||
greyed: {
|
||||
@@ -144,6 +159,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Revise plan",
|
||||
pose: "plan",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Revise plan started", ran: "Plan revised", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["documented", "building"],
|
||||
greyed: { default: "Needs a spec that is already written up", built: "The spec is fully built" },
|
||||
@@ -164,6 +180,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Document",
|
||||
pose: "document",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Document started", ran: "Spec documented", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["planned"], marksNext: true,
|
||||
greyed: {
|
||||
@@ -189,7 +206,9 @@ export const SKILLS = Object.freeze([
|
||||
name: "Implement",
|
||||
pose: "implement",
|
||||
builds: true, phased: true, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: "overview",
|
||||
subagents: BUILD_HELPERS,
|
||||
review: "plan2code-3-implement-review",
|
||||
states: ["documented", "building"], marksNext: true,
|
||||
greyed: BUILD_GREYED,
|
||||
card: {
|
||||
@@ -197,9 +216,9 @@ export const SKILLS = Object.freeze([
|
||||
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.",
|
||||
blurb: "Builds the next phase, task by task, then reviews it, with 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.",
|
||||
"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. With Review ticked, a fresh pass then hunts for problems in exactly what changed and you pick what gets fixed. It ends with a report of what was built and a sign-off card you approve before the phase counts as done.",
|
||||
},
|
||||
}),
|
||||
skill({
|
||||
@@ -209,18 +228,12 @@ export const SKILLS = Object.freeze([
|
||||
name: "Implement + Review",
|
||||
pose: "implement",
|
||||
builds: true, phased: true, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: "overview",
|
||||
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.",
|
||||
},
|
||||
// No card of its own: Implement's card launches it when Review is ticked.
|
||||
card: null,
|
||||
}),
|
||||
skill({
|
||||
skill: "plan2code-4-finalize",
|
||||
@@ -229,6 +242,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Finalize",
|
||||
pose: "finalize",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Finalize started", ran: "Finalize run", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["built"], marksNext: true,
|
||||
greyed: { default: "Needs a spec that is fully built" },
|
||||
@@ -249,6 +263,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Quick task",
|
||||
pose: "quick-task",
|
||||
builds: true, phased: false, metered: true, templates: true,
|
||||
weight: 1, started: "Quick task started", ran: "Quick task built", resume: null,
|
||||
subagents: "Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -268,6 +283,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Review",
|
||||
pose: "review",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Review started", ran: "Code review run", resume: null,
|
||||
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,
|
||||
@@ -287,6 +303,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "X-ray",
|
||||
pose: "xray",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "X-ray started", ran: "X-ray run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -306,6 +323,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Diagnose",
|
||||
pose: "diagnose",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Diagnose started", ran: "Diagnose run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -314,6 +332,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Utility",
|
||||
title: "Diagnose a bug",
|
||||
blurb: "Find a bug's cause and write it up, without fixing it.",
|
||||
help: "Finds a bug's cause and writes it up without fixing it, ready to hand to Quick Task or Plan.",
|
||||
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.",
|
||||
},
|
||||
@@ -325,6 +344,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Changelog",
|
||||
pose: "changelog",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Changelog started", ran: "Changelog run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -344,6 +364,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Git",
|
||||
pose: "git",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Git started", ran: "Git run", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -352,6 +373,7 @@ export const SKILLS = Object.freeze([
|
||||
chip: "Utility",
|
||||
title: "Git",
|
||||
blurb: "Branches, pull, push and commits on one board that stays open while you work.",
|
||||
help: "Branches, pull, push and commits on one board, asking before anything leaves your machine. See \"The git board\".",
|
||||
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.",
|
||||
},
|
||||
@@ -363,6 +385,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "Handoff",
|
||||
pose: "handoff",
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
weight: 0, started: null, ran: "Handoff written", resume: null,
|
||||
subagents: null,
|
||||
states: "any",
|
||||
greyed: null,
|
||||
@@ -382,6 +405,7 @@ export const SKILLS = Object.freeze([
|
||||
name: "the dashboard",
|
||||
pose: null,
|
||||
builds: false, phased: false, metered: false, templates: false,
|
||||
weight: null, started: null, ran: null, resume: null,
|
||||
subagents: null,
|
||||
states: null,
|
||||
greyed: null,
|
||||
@@ -392,6 +416,14 @@ export const SKILLS = Object.freeze([
|
||||
const BY_WORKFLOW = new Map(SKILLS.map((s) => [s.workflow, s]));
|
||||
const BY_SKILL = new Map(SKILLS.map((s) => [s.skill, s]));
|
||||
|
||||
// Every workflow name the console knows, in SKILLS order.
|
||||
export const WORKFLOWS = Object.freeze(SKILLS.map((s) => s.workflow));
|
||||
|
||||
/** Whether a name is one of WORKFLOWS (`open --workflow`, `handoff new --workflow`). */
|
||||
export function isWorkflow(name) {
|
||||
return typeof name === "string" && BY_WORKFLOW.has(name);
|
||||
}
|
||||
|
||||
/** The entry for a workflow ("implement"), or null. */
|
||||
export function skillFor(workflow) {
|
||||
return BY_WORKFLOW.get(workflow) || null;
|
||||
|
||||
@@ -409,6 +409,8 @@
|
||||
.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-review { display: flex; gap: 8px; align-items: center; margin: 4px 0 8px; color: var(--ink-2); cursor: pointer; }
|
||||
.confirm-review input { accent-color: var(--accent, currentColor); }
|
||||
.confirm-cmd { margin: 2px 0 0; }
|
||||
.confirm-cmd code {
|
||||
font-family: var(--mono);
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -52,6 +52,19 @@
|
||||
the one that is only nice to have. */
|
||||
.pager { gap: 8px; }
|
||||
.pager-count { display: none; }
|
||||
/* The Notepad takes the whole screen, and every control in it is a
|
||||
fingertip wide. The pictures go under Add image rather than beside it, so
|
||||
the strip gets the full width, and the preview's side columns narrow to
|
||||
give the picture their room. */
|
||||
.btn.notepad-btn { min-width: 44px; }
|
||||
.modal.notepad { width: 100%; height: 100%; margin: 0; padding: 18px 16px 16px; border: 0; border-radius: 0; }
|
||||
.modal.notepad .notepad-add,
|
||||
.modal.notepad .modal-actions .btn,
|
||||
.btn.notepad-preview-close { min-height: 44px; }
|
||||
.notepad-images { flex-direction: column; align-items: stretch; }
|
||||
.notepad-add { align-self: flex-start; }
|
||||
.notepad-thumb .notepad-thumb-delete { width: 30px; height: 30px; font-size: 18px; }
|
||||
.modal.notepad-preview[open] { grid-template-columns: 52px minmax(0, 1fr) 52px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
|
||||
@@ -171,21 +171,23 @@ function drawScaled(source, edge) {
|
||||
return canvas;
|
||||
}
|
||||
|
||||
// The upload (a JPEG no longer than IMAGE_LONG_EDGE) and the tray's thumbnail
|
||||
// (a small data: URL), from one decode.
|
||||
async function reencode(file) {
|
||||
const toJpeg = (canvas, quality) =>
|
||||
new Promise((resolve, reject) =>
|
||||
canvas.toBlob((b) => (b ? resolve(b) : reject(new Error("That image could not be converted."))), "image/jpeg", quality)
|
||||
);
|
||||
|
||||
// The upload (a JPEG no longer than IMAGE_LONG_EDGE) and its thumbnail, as a
|
||||
// small data: URL for a tray (`thumb`) and as a JPEG for a server that keeps
|
||||
// one (`thumbBlob`, the Notepad's), from one decode.
|
||||
export async function reencode(file) {
|
||||
const source = await decodeImage(file);
|
||||
try {
|
||||
const blob = await new Promise((resolve, reject) =>
|
||||
drawScaled(source, IMAGE_LONG_EDGE).toBlob(
|
||||
(b) => (b ? resolve(b) : reject(new Error("That image could not be converted."))),
|
||||
"image/jpeg",
|
||||
IMAGE_QUALITY
|
||||
)
|
||||
);
|
||||
const blob = await toJpeg(drawScaled(source, IMAGE_LONG_EDGE), IMAGE_QUALITY);
|
||||
if (blob.size > MAX_UPLOAD_BYTES) throw new Error("That image is too large even after shrinking it.");
|
||||
const thumb = drawScaled(source, THUMB_EDGE).toDataURL("image/jpeg", 0.7);
|
||||
return { blob, thumb };
|
||||
const small = drawScaled(source, THUMB_EDGE);
|
||||
const thumb = small.toDataURL("image/jpeg", 0.7);
|
||||
const thumbBlob = await toJpeg(small, 0.7);
|
||||
return { blob, thumb, thumbBlob };
|
||||
} finally {
|
||||
if (typeof source.close === "function") source.close();
|
||||
}
|
||||
|
||||
+7528
File diff suppressed because it is too large.
Load diff
@@ -42,6 +42,7 @@ import { cleanSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { SERVABLE, TYPES, asset } from "./static.mjs";
|
||||
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
|
||||
import { NotepadError, addImage, addThumb, imagePath, readNotepad, removeImage, saveNote } from "./notepads.mjs";
|
||||
|
||||
/* ---------------------------------------------------------------- routes */
|
||||
|
||||
@@ -69,6 +70,12 @@ const ROUTES = [
|
||||
{ path: "/models", method: "POST", origin: true, run: modelsPost },
|
||||
{ path: "/cleanup", method: "POST", origin: true, run: cleanup },
|
||||
{ path: "/upload", method: "POST", origin: true, run: upload },
|
||||
{ path: "/notepad", method: "GET", run: notepadGet },
|
||||
{ path: "/notepad/text", method: "POST", origin: true, run: notepadText },
|
||||
{ path: "/notepad/image", method: "POST", origin: true, run: notepadImage },
|
||||
{ path: "/notepad/thumb", method: "POST", origin: true, run: notepadThumb },
|
||||
{ path: "/notepad/image/delete", method: "POST", origin: true, run: notepadDelete },
|
||||
{ match: (p, req) => p.startsWith("/notepad/images/") || req.url.startsWith("/notepad/images/"), method: "GET", run: notepadImageGet },
|
||||
{ match: (p, req) => p.startsWith("/attachments/") || req.url.startsWith("/attachments/"), run: attachment },
|
||||
{ match: (p, req) => p.startsWith("/shots/") || req.url.startsWith("/shots/"), run: shot },
|
||||
{ match: (p, req) => p.startsWith("/uploads/") || req.url.startsWith("/uploads/"), run: uploads },
|
||||
@@ -539,6 +546,99 @@ function cleanup(req, res, ctx) {
|
||||
});
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- notepad */
|
||||
|
||||
// The person's private notepad for the folder this session runs in, kept by
|
||||
// notepads.mjs outside the session. Nothing here writes to ctx.dir or the
|
||||
// event log: the agent reads both, and the notepad is never the agent's.
|
||||
const notepadRoot = (ctx) => ctx.worktree() || ctx.project;
|
||||
|
||||
function notepadFail(res, e) {
|
||||
if (e instanceof NotepadError) return json(res, e.status, { error: e.code });
|
||||
return json(res, 500, { error: "bad" });
|
||||
}
|
||||
|
||||
function notepadGet(req, res, ctx) {
|
||||
try {
|
||||
return json(res, 200, readNotepad(notepadRoot(ctx)));
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
}
|
||||
|
||||
function notepadText(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-long" : "bad" });
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...saveNote(notepadRoot(ctx), body && body.text) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// A picture's bytes, raw: JPEG only (the page re-encodes everything first).
|
||||
function readJpeg(req, res, then) {
|
||||
if (!String(req.headers["content-type"] || "").startsWith("image/jpeg")) {
|
||||
req.resume();
|
||||
return json(res, 415, { error: "not-jpeg" });
|
||||
}
|
||||
return readRaw(req, MAX_BODY, (err, buf) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too-large" : "bad" });
|
||||
return then(buf);
|
||||
});
|
||||
}
|
||||
|
||||
function notepadImage(req, res, ctx) {
|
||||
return readJpeg(req, res, (buf) => {
|
||||
try {
|
||||
return json(res, 200, { ok: true, ...addImage(notepadRoot(ctx), buf) });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function notepadThumb(req, res, ctx, url) {
|
||||
return readJpeg(req, res, (buf) => {
|
||||
try {
|
||||
addThumb(notepadRoot(ctx), url.searchParams.get("id"), buf);
|
||||
return json(res, 200, { ok: true });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function notepadDelete(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: "bad" });
|
||||
try {
|
||||
removeImage(notepadRoot(ctx), body && body.id);
|
||||
return json(res, 200, { ok: true });
|
||||
} catch (e) {
|
||||
return notepadFail(res, e);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Matched on the raw request line too, as /uploads/ is: URL parsing folds
|
||||
// `..` away, and nothing that needed folding is a notepad picture.
|
||||
const NOTEPAD_IMAGE_ROUTE = /^\/notepad\/images\/([0-9a-f-]{36})(\.thumb)?\.jpg$/;
|
||||
|
||||
function notepadImageGet(req, res, ctx, url) {
|
||||
const m = NOTEPAD_IMAGE_ROUTE.exec(req.url);
|
||||
const file = m && m[0] === url.pathname ? imagePath(notepadRoot(ctx), m[1], Boolean(m[2])) : null;
|
||||
if (!file) return json(res, 404, { error: "not-found" });
|
||||
let buf;
|
||||
try {
|
||||
buf = fs.readFileSync(file);
|
||||
} catch {
|
||||
return json(res, 404, { error: "not-found" });
|
||||
}
|
||||
return send(res, 200, buf, "image/jpeg");
|
||||
}
|
||||
|
||||
/* ------------------------------------------- uploads, shots, attachments */
|
||||
|
||||
// Images and documents attached to notes and quick questions. Only ever named
|
||||
|
||||
+21
-28
@@ -7,6 +7,11 @@ import { isDeletableSpecDir } from "./public/answers.js";
|
||||
import { SPEC_STATES as STATE_TABLE } from "./public/spec-states.js";
|
||||
import { nowIso, readText } from "./files.mjs";
|
||||
import { insideGitRepo, pendingFiles } from "./sessions.mjs";
|
||||
import { countTasks, statusOf } from "./spec-files.mjs";
|
||||
|
||||
// The task-line pattern lives in spec-files.mjs; re-exported for any importer
|
||||
// that still takes it from here.
|
||||
export { TASK_LINE_RE } from "./spec-files.mjs";
|
||||
|
||||
/* ---------------------------------------------------------- project scan */
|
||||
|
||||
@@ -53,20 +58,6 @@ function maxMtime(dir, depth = 4, budget = { n: 400 }, tally = null) {
|
||||
return best;
|
||||
}
|
||||
|
||||
// A spec file's Status line value, in any of the forms the skill scripts
|
||||
// accept (`**Status:**`, `**Status**:`, `Status:`). Same pattern as STATUS_RE
|
||||
// in src/skill-scripts/specs.mjs; the console cannot import it, so keep the
|
||||
// two copies in step. A CRLF file's trailing `\r` is dropped.
|
||||
const STATUS_LINE_RE = /^[ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*(.+?)[ \t\r]*$/m;
|
||||
|
||||
// A phase file's task line (`- [ ] **Task 1.2:**`). The scan counts by it,
|
||||
// and patches.mjs keeps only these lines for a doc block's `select: "tasks"`.
|
||||
export const TASK_LINE_RE = /^\s*(?:[-*]|\d+\.)\s+\[.\]\s+\*\*Task\s/i;
|
||||
function statusOf(text) {
|
||||
const m = text.match(STATUS_LINE_RE);
|
||||
return m ? m[1] : "";
|
||||
}
|
||||
|
||||
// A spec folder's pipeline position, from its files alone. Furthest artifact
|
||||
// wins: an overview beats a draft beats a map, so a spec mid-way through two
|
||||
// stages reports the later one.
|
||||
@@ -79,25 +70,27 @@ function classifySpec(dir, names) {
|
||||
const planDraft = drafts.length > 0;
|
||||
const planConv = has(/^PLAN-CONVERSATION.*\.md$/i);
|
||||
const liveDraft = drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0];
|
||||
const draftStatus = liveDraft ? statusOf(readText(path.join(dir, liveDraft))) : "";
|
||||
const draftStatus = liveDraft ? statusOf(readText(path.join(dir, liveDraft))) || "" : "";
|
||||
const resumeAt = draftStatus.match(/Resume at Phase\s*(\d+)/i);
|
||||
|
||||
if (phases.length) {
|
||||
// countTasks() counts a file's task lines (every checkbox in a file
|
||||
// written before that format). An assumed-done task (`[?]`) counts as
|
||||
// done, and the detail names how many there are.
|
||||
let done = 0;
|
||||
let assumed = 0;
|
||||
let open = 0;
|
||||
for (const f of phases) {
|
||||
const text = readText(path.join(dir, f));
|
||||
// The task lines when the file has them (`- [ ] **Task 1.2:**`), so an
|
||||
// Acceptance Criteria checkbox is not counted as a task; every checkbox
|
||||
// in a file written before that format.
|
||||
const tasks = text.split(/\r?\n/).filter((l) => TASK_LINE_RE.test(l));
|
||||
const lines = tasks.length ? tasks.join("\n") : text;
|
||||
done += (lines.match(/^\s*[-*] \[[xX]\]/gm) || []).length;
|
||||
open += (lines.match(/^\s*[-*] \[[ /!]\]/gm) || []).length;
|
||||
const n = countTasks(readText(path.join(dir, f)));
|
||||
done += n.done;
|
||||
assumed += n.assumed;
|
||||
open += n.open;
|
||||
}
|
||||
const total = done + open;
|
||||
if (open === 0 && done > 0) return { state: "built", detail: "all tasks done" };
|
||||
if (done > 0) return { state: "building", detail: `${done} of ${total} tasks done` };
|
||||
const finished = done + assumed;
|
||||
const total = finished + open;
|
||||
const suffix = assumed > 0 ? `, ${assumed} assumed` : "";
|
||||
if (open === 0 && finished > 0) return { state: "built", detail: `all tasks done${suffix}` };
|
||||
if (finished > 0) return { state: "building", detail: `${finished} of ${total} tasks done${suffix}` };
|
||||
return {
|
||||
state: "documented",
|
||||
detail: `${phases.length} phase${phases.length === 1 ? "" : "s"}, ${total || "?"} tasks ready`,
|
||||
@@ -115,14 +108,14 @@ function classifySpec(dir, names) {
|
||||
// Quick Task marks the write-up Fixed once the bug is gone: then the bug is
|
||||
// done, and the folder waits only to be archived.
|
||||
const diagnosis = names.filter((n) => /^DIAGNOSIS-.*\.md$/i.test(n)).sort().reverse()[0];
|
||||
const diagnosisStatus = diagnosis ? statusOf(readText(path.join(dir, diagnosis))).replace(/\*+/g, "").trim() : "";
|
||||
const diagnosisStatus = diagnosis ? (statusOf(readText(path.join(dir, diagnosis))) || "").replace(/\*+/g, "").trim() : "";
|
||||
if (diagnosis && !planConv && !fs.existsSync(path.join(pfDir, "map.md")))
|
||||
return /^fixed/i.test(diagnosisStatus)
|
||||
? { state: "fixed", detail: "bug fixed" }
|
||||
: { state: "diagnosed", detail: "bug diagnosed, not fixed" };
|
||||
if (isDir(pfDir)) {
|
||||
const mapText = readText(path.join(pfDir, "map.md"));
|
||||
const status = statusOf(mapText).replace(/\*+/g, "").trim();
|
||||
const status = (statusOf(mapText) || "").replace(/\*+/g, "").trim();
|
||||
if (/^cleared/i.test(status)) return { state: "mapped", detail: "all decisions made" };
|
||||
let qTotal = 0;
|
||||
let qDone = 0;
|
||||
|
||||
@@ -47,6 +47,7 @@ import { serverWorkspace } from "./workspace.mjs";
|
||||
import { serverSubagents } from "./settings.mjs";
|
||||
import { chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { SERVABLE, asset } from "./static.mjs";
|
||||
import { handle } from "./routes.mjs";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
@@ -224,12 +225,10 @@ function ensureConversation(state) {
|
||||
if (!last.conversation) {
|
||||
entry = appendChat(DIR, { kind: "reset", conversation: 1, workflow: state.workflow, reason: "start" });
|
||||
} else if (
|
||||
last.workflow !== state.workflow &&
|
||||
// The same switches `open --resume` treats as a hop (a blank page, the
|
||||
// agent's replies included): through the dashboard, or into git from
|
||||
// anywhere (Commit it now, Changelog's "Commit this now?"). Without a new
|
||||
// conversation, the old questions would show as unanswered again.
|
||||
(last.workflow === "dashboard" || state.workflow === "dashboard" || state.workflow === "git")
|
||||
// The same hops `open --resume` treats as a fresh start, by the rule in
|
||||
// public/hops.js (a blank page, the agent's replies included). Without a
|
||||
// new conversation, the old questions would show as unanswered again.
|
||||
startsClean(last.workflow, state.workflow)
|
||||
) {
|
||||
entry = appendChat(DIR, {
|
||||
kind: "reset",
|
||||
|
||||
@@ -8,7 +8,7 @@ import { execFileSync } from "node:child_process";
|
||||
|
||||
import { countPending } from "./git-repo.mjs";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { appendJsonLine, HOME_DIR, nowIso, PLAN2CODE_DIR, readJson, readJsonLines, readText, RUNTIME_DIR, SESSIONS_DIR } from "./files.mjs";
|
||||
import { appendJsonLine, HOME_DIR, newestMtime, nowIso, PLAN2CODE_DIR, readJson, readJsonLines, readText, RUNTIME_DIR, SESSIONS_DIR } from "./files.mjs";
|
||||
|
||||
/* -------------------------------------------------------------- sessions */
|
||||
|
||||
@@ -343,9 +343,10 @@ export async function removeScratch(consoleDir, names) {
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json), the install record that
|
||||
// `plan2code update` reads (install.json), the models the person added and
|
||||
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs).
|
||||
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs) and
|
||||
// the notepads, removed only one at a time through Cleanup (notepads.mjs).
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
@@ -372,29 +373,6 @@ async function diskBytes(p) {
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
@@ -441,8 +419,11 @@ function completedSpecs(project, now, maxAgeMs) {
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Given a `project`, also its completed specs untouched for `maxAgeMs`.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
* Given a `project`, also its completed specs untouched for `maxAgeMs`. Every
|
||||
* notepad whose newest file is `maxAgeMs` old is listed too, one item per
|
||||
* folder carrying the `folder` it belongs to (null when its meta.json is gone):
|
||||
* this is the only way a notepad is ever removed.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
@@ -463,12 +444,21 @@ export async function cleanupFindings({
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
if (project) found.push(...completedSpecs(project, now, maxAgeMs));
|
||||
// Loaded here, not at the top: notepads.mjs reaches files.mjs through
|
||||
// workspace.mjs, and files.mjs imports this module, so a static import
|
||||
// would run workspace.mjs before files.mjs has defined HOME_DIR.
|
||||
const { staleNotepads } = await import("./notepads.mjs");
|
||||
for (const n of staleNotepads(now, maxAgeMs)) {
|
||||
found.push({ id: "notepad:" + n.key, where: "notepad", name: n.key, kind: "folder", path: n.path, folder: n.folder });
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
const item = { id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path };
|
||||
if (f.where === "notepad") item.folder = f.folder;
|
||||
items.push(item);
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
@@ -483,13 +473,15 @@ export async function cleanupFindings({
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const { removeNotepad } = await import("./notepads.mjs");
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
if (item.where === "notepad") removeNotepad(item.name);
|
||||
else if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
|
||||
@@ -0,0 +1,61 @@
|
||||
// Plan2Code Web Console - how a spec's markdown files are read.
|
||||
//
|
||||
// The task markers and the task-line, checkbox and Status-line patterns, in
|
||||
// one place, so every reader of a spec counts and names its tasks the same
|
||||
// way. Imported by scan.mjs (the dashboard's spec states), patches.mjs (a doc
|
||||
// block's `select: "tasks"`) and src/skill-scripts/specs.mjs (through
|
||||
// consoleModule(), so the installed skill reads with this same copy). No
|
||||
// imports and nothing runs at load but building the patterns.
|
||||
|
||||
// What each checkbox marker means on a task line.
|
||||
export const MARKERS = Object.freeze({ " ": "pending", "/": "in-progress", x: "complete", X: "complete", "!": "blocked", "?": "assumed" });
|
||||
|
||||
// A phase file's task line (`- [ ] **Task 1.2:**`, `* [x] **Task 1.2:**` or
|
||||
// `1. [/] **Task 1.2:**`). The scan counts by it, and patches.mjs keeps only
|
||||
// these lines for a doc block's `select: "tasks"`. Same line shape as
|
||||
// TASK_ID_RE and CHECKBOX_RE (one space before the box, a capital Task), so a
|
||||
// line the scan counts is one specs.mjs counts too.
|
||||
export const TASK_LINE_RE = /^\s*(?:[-*]|\d+\.) \[.\]\s+\*\*Task\s/;
|
||||
|
||||
// A task line taken apart: the marker, the phase number, the task (2.3, a
|
||||
// lettered sub-task 3.6a, or a named one such as a testing task 1.T) and the
|
||||
// sub-task suffix.
|
||||
export const TASK_ID_RE = /^\s*(?:[-*]|\d+\.) \[(.)\]\s+\*\*Task\s+(\d+)\.(\d+|[A-Za-z]+)([a-z]*)\b/;
|
||||
|
||||
// Any checkbox list item, task or not; group 1 is the marker.
|
||||
export const CHECKBOX_RE = /^\s*(?:[-*]|\d+\.) \[(.)\]/;
|
||||
|
||||
// The Status line in any of the forms people write it: **Status:**, **Status**:
|
||||
// or a plain Status:, optionally as a list item. Groups: everything up to the
|
||||
// value (kept as written when the value is rewritten), the value, trailing
|
||||
// blanks. A CRLF file's `\r` is never in the value: a multiline `$` stops
|
||||
// before it.
|
||||
export const STATUS_RE = /^([ \t]*(?:[-*][ \t]*)?(?:\*\*Status:\*\*|\*\*Status\*\*:|Status:)[ \t]*)(.+?)([ \t]*)$/m;
|
||||
|
||||
/** A spec file's Status line value, or null when it has none. */
|
||||
export function statusOf(text) {
|
||||
const m = (text || "").match(STATUS_RE);
|
||||
return m ? m[2] : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A phase file's tasks by where they stand. The task lines when the file has
|
||||
* them, so an Acceptance Criteria checkbox is not counted as a task; every
|
||||
* checkbox in a file written before that format. `[?]` (assumed done) is
|
||||
* counted apart from `[x]`; an unknown marker is not counted at all.
|
||||
*/
|
||||
export function countTasks(text) {
|
||||
const lines = (text || "").split(/\r?\n/);
|
||||
const tasks = lines.filter((l) => TASK_LINE_RE.test(l));
|
||||
let done = 0;
|
||||
let assumed = 0;
|
||||
let open = 0;
|
||||
for (const line of tasks.length ? tasks : lines) {
|
||||
const m = line.match(CHECKBOX_RE);
|
||||
if (!m) continue;
|
||||
if (m[1] === "x" || m[1] === "X") done++;
|
||||
else if (m[1] === "?") assumed++;
|
||||
else if (m[1] === " " || m[1] === "/" || m[1] === "!") open++;
|
||||
}
|
||||
return { done, assumed, open, total: done + assumed + open };
|
||||
}
|
||||
@@ -23,6 +23,7 @@ export const SERVABLE = new Set([
|
||||
"app.js",
|
||||
"answers.js",
|
||||
"skills.js",
|
||||
"hops.js",
|
||||
"spec-states.js",
|
||||
"state.js",
|
||||
"doc-files.js",
|
||||
@@ -68,8 +69,11 @@ export const SERVABLE = new Set([
|
||||
"screens/help-dialog.js",
|
||||
"screens/workspace.js",
|
||||
"screens/ask.js",
|
||||
"screens/notepad.js",
|
||||
"net.js",
|
||||
"notepad.js",
|
||||
"vendor/marked.esm.js",
|
||||
"vendor/overtype.esm.js",
|
||||
]);
|
||||
|
||||
/* ------------------------------------------------------------ stylesheet */
|
||||
@@ -79,7 +83,7 @@ export const SERVABLE = new Set([
|
||||
// Layers first, then one file per screen, then responsive and print last so
|
||||
// its overrides still come after everything they override. The files are not
|
||||
// on SERVABLE: they reach the page only through /app.css.
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "git.css", "responsive.css"];
|
||||
export const CSS_ORDER = ["tokens.css", "shell.css", "planny.css", "pieces.css", "dashboard.css", "poses.css", "docs.css", "ask.css", "ending.css", "help.css", "looks.css", "notepad.css", "git.css", "responsive.css"];
|
||||
|
||||
// The files joined with one newline between them (each file's own last newline
|
||||
// is that one), as the server serves them before the accent rules. The test
|
||||
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.9.0",
|
||||
"version": "2.10.0",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-17",
|
||||
"releaseDate": "2026-10-19",
|
||||
"mode": "utility"
|
||||
}
|
||||
Reference in new issue
Block a user