mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-18 21:01:19 -08:00
Compare commits
5
Commits
a2b43d1188
...
899b3a48d8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
899b3a48d8 | ||
|
|
e67aaabdce | ||
|
|
c602dfed57 | ||
|
|
765d2b3536 | ||
|
|
b99a1a701f |
No files matched your search
@@ -16,8 +16,8 @@ plan2code/
|
||||
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
|
||||
│ │ └── trail.md # Every-response map visual + pathed resume command
|
||||
│ ├── shared-references/ # Reference files shared across skills
|
||||
│ │ ├── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review)
|
||||
│ │ └── helper-strength.md # How strong a model and how much effort each helper gets (pathfinder, quick-task, implement, implement-review, review)
|
||||
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review)
|
||||
│ │ └── helper-strength.md # How strong a model and how much effort each helper gets (pathfinder, plan, revise-plan, quick-task, implement, implement-review, review)
|
||||
│ ├── plan2code-review-references/ # Reference files for review skill
|
||||
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
|
||||
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
|
||||
@@ -95,11 +95,19 @@ plan2code/
|
||||
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent |
|
||||
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
|
||||
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
|
||||
| `plan2code-app/src-tauri/src/agents.rs` | Custom agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the console side is `src/web-console/agents.mjs` |
|
||||
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
|
||||
|
||||
### Agents file
|
||||
|
||||
`~/.plan2code/agents.json` holds the person's custom agent CLIs (`{ "schema": 1, "agents": [...] }`). The web console is its only writer (User Preferences → Agents, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. A bad file or entry is skipped with a warning, never a crash. Until the feature is finalized, the rules are written out in `specs/agent-setup-and-taskbar-attention/PLAN-DRAFT-20261025.md` section 4.4.
|
||||
`~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first.
|
||||
|
||||
- **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves.
|
||||
- **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument.
|
||||
- **Rules:** `id` matches `^[a-z0-9][a-z0-9-]{0,31}$`, is not `claude`, `devin` or `codex`, and is unique; `name` is at most 60 characters and unique ignoring case; `command` is not blank. `makeId(name, taken)` makes the id from the name in kebab case (`agent` when nothing is left), with `-2`, `-3` on a clash, at most 32 characters.
|
||||
- **Bad entries:** a bad entry is skipped with a warning naming it (`agents[i]`, 0-based) and the rest still load, in all three readers. `POST /agents` instead refuses the save with `{ error, index, field }`, and answers `409` while the file holds something `GET /agents` could not read, unless the body says `replace: true`.
|
||||
- **Command line:** `buildArgs` returns `args` with `{prompt}` filled (the prompt is appended when no argument holds it, and a blank prompt drops an argument that is exactly `{prompt}`), then `modelArgs` with `{model}` filled when a model is chosen, then `bypassArgs` when checks are off. Arguments travel as a list, never through a shell; the Windows `cmd` wrapper for a `.cmd` or `.bat` belongs to the launcher and the app.
|
||||
|
||||
## Workflow Prompts (in `src/`)
|
||||
|
||||
@@ -115,7 +123,7 @@ plan2code/
|
||||
| `plan2code-2-document.md` | 2 | Create implementation specs |
|
||||
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
|
||||
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
|
||||
| `plan2code-review.md` | review | Post-implementation comprehensive review, analysed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
|
||||
| `plan2code-review.md` | review | Post-implementation comprehensive review, analyzed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
|
||||
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
|
||||
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
|
||||
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
|
||||
@@ -250,7 +258,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
|
||||
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
|
||||
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
|
||||
| `public/styles/tokens.css` | Colours, type, sizes and the light and dark themes: the variables every other file reads |
|
||||
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
|
||||
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
|
||||
@@ -261,7 +269,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `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/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, `plan`, `revise-plan`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
@@ -289,17 +297,17 @@ Key design points:
|
||||
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (canceled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `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.
|
||||
- **`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 honors `?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, 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`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook 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`; 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 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 grayed, 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 seven 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.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
@@ -333,7 +341,7 @@ Key design points:
|
||||
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notebook for <folder>"Line truncated
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labeled "Notebook for <folder>" Line truncated
|
||||
- **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.
|
||||
@@ -388,7 +396,7 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
|
||||
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
|
||||
- **Resolving the CLI** — the launcher walks `PATH` (+ `PATHEXT` on Windows) itself. An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
|
||||
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person cancelled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
|
||||
|
||||
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
|
||||
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
- Interactive CLI via `@inquirer/prompts` (select, input, confirm)
|
||||
- **File operations:** Synchronous fs by default; the web console's fire-and-forget sweeps and `readOverview()` use `fs.promises`
|
||||
- **src/web-console:** ESM, Node built-ins only, no build step. It is bundled into every skill, so it must stay dependency-free and runnable as a plain `node console.mjs`. Anything added under `src/web-console/` ships to users — put tests in `scripts/` instead.
|
||||
- **US English everywhere:** docs, comments, prompts, UI text, test names and commit messages use US spelling: color, gray, behavior, center, canceled, labeled, judgment, license, defense, and -ize / -yze verbs (normalize, analyze, summarize). `scripts/test-us-english.mjs` (in `npm test`) fails on common UK spellings in tracked files. A few names keep the UK spelling because they are data contracts read in several places, and that test allow-lists them: the `greyed` field on `skills.js` entries, `{ cancelled: true }` from the folder picker and `/workspace/browse`, the `"cancelled"` event `routes.mjs` broadcasts, and the loop's `result.cancelled`. Rename one only together with every reader. `aria-labelledby` is HTML and stays; vendored files (`public/vendor/`) stay as shipped.
|
||||
|
||||
## Gotchas / Pitfalls
|
||||
|
||||
@@ -29,7 +30,7 @@
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console-lifecycle.mjs` guards it (its "result handoff (regressions)" tests). Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `patches.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` and `readRaw()` (the `POST /upload` reader) in `routes.mjs` drain the rest of the body past `MAX_BODY` instead of calling `req.destroy()`, so an oversized body gets a 413 rather than a connection reset, and memory still stays capped. A new body reader must drain the same way.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `sessions.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalises its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||
- **Windows temp paths in web console tests:** `os.tmpdir()` can be an 8.3 short path (`C:\Users\JUSTIN~1.PAR\...`), while `server.mjs` canonicalizes its session dir with `fs.realpathSync.native` to the long form. Any test comparing a server-returned path (e.g. an upload's `path`) against the test's `session` must pass the test side through `fs.realpathSync.native()` first, and compare case-insensitively on Windows.
|
||||
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/styles/tokens.css`. No test ties them together.
|
||||
- **Reference file sizing guideline:** Files in `src/plan2code-*-references/` directories target ~100-200 lines each (soft guideline; evaluate splitting above 300). They are NOT subject to the 20,000 character limit. The pre-commit hook (`validate-char-count.js`) only checks `src/plan2code-*.md` flat files — subdirectory contents are automatically excluded.
|
||||
|
||||
@@ -62,7 +62,7 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
| `PLAN2CODE_NO_BROWSER` | `open` does not launch a browser (`NO_BROWSER` also works). |
|
||||
| `PLAN2CODE_BROWSER` | Browser command line to run with the link appended, instead of the system default. |
|
||||
| `PLAN2CODE_MODELS_DIR` | Moves the launcher model menus (`bin/models.json`, `models.json`) away from `~/.plan2code`, for tests. |
|
||||
| `PLAN2CODE_PICKER_ECHO` | Tests only: `/workspace/browse` returns this as the picked folder instead of opening a picker (`-` means cancelled). |
|
||||
| `PLAN2CODE_PICKER_ECHO` | Tests only: `/workspace/browse` returns this as the picked folder instead of opening a picker (`-` means canceled). |
|
||||
| `PLAN2CODE_CONSOLE_TRACE` | Set to `1` on `open` to print a start-up step timeline to stderr. |
|
||||
|
||||
## Installer Menu Options
|
||||
@@ -144,7 +144,7 @@ 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. 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/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 `grayed`. 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).
|
||||
|
||||
@@ -115,7 +115,7 @@ Conventions to follow, drawn from existing entries:
|
||||
|
||||
- Bold lead-in naming the prompt, file, or area, then an em dash (`—`), then the description.
|
||||
- Reference prompts by their command (`/plan2code-1-plan`) or path (`src/plan2code-init.md`), not by informal name.
|
||||
- One paragraph per bullet is fine — this CHANGELOG favours substantive entries over terse one-liners, and a bullet may carry extra indented paragraphs for detail.
|
||||
- One paragraph per bullet is fine — this CHANGELOG favors substantive entries over terse one-liners, and a bullet may carry extra indented paragraphs for detail.
|
||||
- A release with a big theme may open with a one-line summary paragraph directly under the `## vX.Y.Z` heading, before the first `###`.
|
||||
|
||||
Insert the new section directly below the `All notable changes...` line and above the previous version's heading.
|
||||
|
||||
@@ -51,13 +51,13 @@ For each CLI, compare the discovered list with the current one by `id` and show
|
||||
| --- | --- | --- | --- | --- |
|
||||
| added | `new-id` | — | New label | `devin models list` |
|
||||
| gone | `old-id` | Old label | — | not in `devin models list` |
|
||||
| relabelled | `same-id` | Old label | New label | Claude Code docs: <page> |
|
||||
| relabeled | `same-id` | Old label | New label | Claude Code docs: <page> |
|
||||
|
||||
- **added:** offered by the CLI, not in the file.
|
||||
- **gone:** in the file, no longer offered.
|
||||
- **relabelled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
||||
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
||||
|
||||
Summarise unchanged entries as a count under the table ("19 Devin entries unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If both tables are empty, say the file is current and stop.
|
||||
Summarize unchanged entries as a count under the table ("19 Devin entries unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If both tables are empty, say the file is current and stop.
|
||||
|
||||
### Step 6 — Approve each change
|
||||
|
||||
@@ -68,7 +68,7 @@ Ask about each row, one at a time: **yes**, **no**, or **edit the label** (they
|
||||
Apply only the approved rows:
|
||||
|
||||
- Keep `_note` verbatim.
|
||||
- Keep the existing order. Remove a **gone** entry where it stands, change a **relabelled** label in place, and append each **added** entry at the end of its list.
|
||||
- Keep the existing order. Remove a **gone** entry where it stands, change a **relabeled** label in place, and append each **added** entry at the end of its list.
|
||||
- Write two-space-indented JSON with a trailing newline, matching the file's current formatting.
|
||||
|
||||
### Step 8 — Validate
|
||||
|
||||
+2
-2
@@ -38,7 +38,7 @@ plan2code-metrics # → "View metrics status" the dashboard
|
||||
|------|--------------|
|
||||
| **1** | Raw data and a basic dashboard. Start here. |
|
||||
| **3+** | AI analysis unlocks. Pattern detection starts working. |
|
||||
| **5–10+** | Averages stabilise; generation-over-generation comparisons become meaningful. |
|
||||
| **5–10+** | Averages stabilize; generation-over-generation comparisons become meaningful. |
|
||||
|
||||
You're looking for trends, not individual scores.
|
||||
|
||||
@@ -46,7 +46,7 @@ You're looking for trends, not individual scores.
|
||||
|
||||
## Sending feedback upstream
|
||||
|
||||
`/plan2code-4-finalize` can submit an anonymised metrics payload to the maintainers as a
|
||||
`/plan2code-4-finalize` can submit an anonymized metrics payload to the maintainers as a
|
||||
`community-feedback` issue on the repo. Community runs are cohorted by the Plan2Code version that
|
||||
produced them, so your data improves the prompts everyone installs — without displacing the
|
||||
maintainer's own measurements.
|
||||
|
||||
@@ -32,7 +32,7 @@ Every console request carries two extra fields:
|
||||
|
||||
Clicking **Approve** in the browser is then byte-identical to typing `approved` in the terminal. No prompt logic ever forks. If the console is absent, refused, or times out, the agent prints `fallbackText` and the session continues in the terminal with nothing lost. Mid-session switching in either direction is free, because the markdown files under `specs/` remain the only source of truth.
|
||||
|
||||
This one decision is what keeps the integration from metastasising across twelve prompt files.
|
||||
This one decision is what keeps the integration from metastasizing across twelve prompt files.
|
||||
|
||||
---
|
||||
|
||||
@@ -152,22 +152,22 @@ The waiter uses `fs.watch` on the session **directory** (watching a file breaks
|
||||
| --- | --- |
|
||||
| Port | `listen(0, '127.0.0.1')`, handle file in `os.tmpdir()/<tool>/<sha1(cwd).slice(0,8)>/`. This is Jupyter's `jpserver-<pid>.json` pattern and RFC 8252 §7.3. A fixed port is fatal here: you run git worktrees, so two agents in two checkouts of one repo is routine, and a fixed port makes that silently wrong. |
|
||||
| Bind | the literal `127.0.0.1`, never `0.0.0.0`, never the string `localhost` (which may resolve to `::1` and produce the classic "server is up but the browser gets ECONNREFUSED" bug on Windows). |
|
||||
| Auto-open | best-effort, never fatal. Skip when `DISPLAY` and `WAYLAND_DISPLAY` are both unset, or `SSH_CONNECTION` / `REMOTE_CONTAINERS` is set. Honour `BROWSER=` and `--no-open`. |
|
||||
| Auto-open | best-effort, never fatal. Skip when `DISPLAY` and `WAYLAND_DISPLAY` are both unset, or `SSH_CONNECTION` / `REMOTE_CONTAINERS` is set. Honor `BROWSER=` and `--no-open`. |
|
||||
| Orphan prevention | a **server-side idle deadline** (30 min, bumped by any authenticated request) is the mechanism, not a nicety. Windows has no real SIGTERM, and a detached server with no console never sees `SIGINT`, so signal handlers cannot be relied on. Plus a 4h absolute cap, a `pagehide` beacon, an explicit `stop`, and a reap sweep on every `start`. |
|
||||
| Liveness test | `process.kill(pid, 0)` **and** a `/health` check whose returned session id matches the handle. PID reuse is real; the sid match is what disambiguates. |
|
||||
|
||||
Security, six controls, about 60 lines:
|
||||
|
||||
1. Bind `127.0.0.1`.
|
||||
2. **`Host` header allowlist.** This is the DNS-rebinding defence and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
||||
2. **`Host` header allowlist.** This is the DNS-rebinding defense and the highest-value line in the server. Vite shipped GHSA-vg6x-rcgg-rjx6 for exactly this omission.
|
||||
3. 128-bit token **in the URL path**, not the query string. Path placement also kills the Windows `cmd /c start` `&`-injection hazard, because the URL then contains no `&`.
|
||||
4. First `GET /s/<token>/` sets `HttpOnly; SameSite=Strict` cookie and 302s to `/`. Token leaves the address bar, history and pasted screenshots; CSRF protection comes free.
|
||||
5. `Origin` check on every mutating request.
|
||||
6. Strict CSP with no `unsafe-inline`, which is why JS and CSS are separate files rather than one inlined HTML.
|
||||
|
||||
**On whether XSS matters here.** The tempting argument is "it is the user's own machine and the model would not write `<script>`". That misses the real risk. The page is same-origin with a server that reads and writes the user's files and holds the session token, so script in that page can post arbitrary answers back to the agent, which then acts on them with the agent's full tool permissions. And the markdown is only nominally agent-authored: in practice the agent is summarising a dependency README, a scraped page, a PR description, a log. Treat it as attacker-controlled.
|
||||
**On whether XSS matters here.** The tempting argument is "it is the user's own machine and the model would not write `<script>`". That misses the real risk. The page is same-origin with a server that reads and writes the user's files and holds the session token, so script in that page can post arbitrary answers back to the agent, which then acts on them with the agent's full tool permissions. And the markdown is only nominally agent-authored: in practice the agent is summarizing a dependency README, a scraped page, a PR description, a log. Treat it as attacker-controlled.
|
||||
|
||||
The structural fix, rather than a filter: **vendor `marked` for `lexer()` only and render tokens to the DOM with `createElement` and `textContent`.** No HTML string is ever produced, so there is nothing for a sanitiser bypass to bypass, and the strict CSP holds. Roughly 120 lines of renderer. Hand-rolling the parser instead is a trap: hand-rolled markdown fails exactly where agent-authored technical documents live (a table inside a list item, a fenced block containing backticks) and its failure mode is usually an injection hole.
|
||||
The structural fix, rather than a filter: **vendor `marked` for `lexer()` only and render tokens to the DOM with `createElement` and `textContent`.** No HTML string is ever produced, so there is nothing for a sanitizer bypass to bypass, and the strict CSP holds. Roughly 120 lines of renderer. Hand-rolling the parser instead is a trap: hand-rolled markdown fails exactly where agent-authored technical documents live (a table inside a list item, a fenced block containing backticks) and its failure mode is usually an injection hole.
|
||||
|
||||
### 3.4 Browser transport
|
||||
|
||||
@@ -283,7 +283,7 @@ Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a gri
|
||||
### What to take from grill-with-ui
|
||||
|
||||
- **Batch staging with one explicit Send.** Everything is local and reversible until one deliberate press. For a non-technical user this removes the terror of "did I just commit to that?"
|
||||
- **The three-tier commitment vocabulary**: staged (amber, removable) → sent and pending (dashed, spinner) → recorded (green check). Honoured consistently on every surface.
|
||||
- **The three-tier commitment vocabulary**: staged (amber, removable) → sent and pending (dashed, spinner) → recorded (green check). Honored consistently on every surface.
|
||||
- **The whole stuck-agent apparatus**: live elapsed counter, disabled Send while working, a five-minute grace that re-enables Send with an explanation, server-gone detection with self-reconnect. About 40 lines, and more honest about agent latency than most commercial agent UIs.
|
||||
- **Assumed regions.** The best idea in that repo: the generated artifact marks regions that depend on still-open questions with a dashed outline and "assumed, pending Q3". This transplants directly onto a plan taking shape.
|
||||
- **Versioned artifacts with a staleness flag** and a one-line change note.
|
||||
@@ -310,12 +310,12 @@ Built for a mixed product and engineering room reading one screen together.
|
||||
|
||||
- **One width variable.** `--card-width` on `:root` in `styles/tokens.css` sets the column the card, the pager and the document tabs share (`max-width: min(var(--card-width), 100%)`, so a narrow window still wins); no fixed `720px` column rule is left outside a media query. Three presets, picked under *Card width* in the looks panel and saved as `looks.width`: `narrow` 720px, `comfortable` 880px (the default, and the variable's own value), `wide` 1080px, applied as `:root[data-width="…"]`. `CARD_WIDTHS` in `palette.js` is the same list for the page's validation and the server's first-paint `data-width`; **`palette.js` and `app.css` must agree**, which is the one place the number is written twice. The dashboard keeps its own 860px layout. Inside the card the `62ch` / `68ch` measure caps come off (`.card .md, .card .prompt { max-width: none; }`) so a wider card is not a narrow column in a wide frame; documents keep `.md`'s 68ch.
|
||||
- **One box grows.** On the primary card, the answer box that is being typed in — a `text` question's box, a choice's *Something else* box once picked, or the note under a verdict / confirm / recap once shown — is `textarea.grow`, and the card takes the column's full height above the pager (`.card.is-primary.has-grow { flex: 1 1 auto; }`). `fitGrowBox()` in `app.js` writes the card's free height as the box's `min-height`, **never under 160px**; a `ResizeObserver` watches the main column rather than the box, so the box growing can never retrigger it, and it writes only on a change over 1px. `resize: vertical` with that moving floor makes the handle taller-only; past the fill the card scrolls. Every other box keeps its ordinary size, and the notes panel is untouched.
|
||||
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off greys the boxes but keeps their ticks, and ticking a box plays it.
|
||||
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off grays the boxes but keeps their ticks, and ticking a box plays it.
|
||||
- **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off.
|
||||
- **Per-tab scroll memory.** An in-memory `Map` keyed by view id holds the scroller's position (the main column on a document or the Overview, the card on the questions view, with the item it belonged to), restored when the tab comes back. Page-local, never persisted, cleared when the session turns into or out of the dashboard.
|
||||
- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record.
|
||||
- **The footer slot.** The workspace label sits centred in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show.
|
||||
- **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on centre stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there.
|
||||
- **The footer slot.** The workspace label sits centered in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show.
|
||||
- **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on center stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there.
|
||||
|
||||
---
|
||||
|
||||
|
||||
+19
-5
@@ -211,7 +211,7 @@ explains how and why an area works, or ranks its rough spots into
|
||||
available: it finds a bug's cause and writes it up as
|
||||
`specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it. Pick such a spec in
|
||||
the picker and it reads *Bug diagnosed*: Quick Task (suggested) and Plan light
|
||||
up, while Document, Implement, Implement + Review and Finalize stay greyed. Once
|
||||
up, while Document, Implement, Implement + Review and Finalize stay grayed. Once
|
||||
Quick Task has fixed it, the folder reads *Bug fixed*: Quick Task offers to
|
||||
archive it to `specs--completed/`, and until then the picker never opens on it
|
||||
and hides it while *Hide unavailable workflows* is on. Its chip has a visible
|
||||
@@ -386,8 +386,8 @@ it is remembered for next time:
|
||||
|
||||
### Subagents
|
||||
|
||||
On a build (Implement, Implement + review, Quick task), a review and
|
||||
Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
On a build (Implement, Implement + review, Quick task), a review,
|
||||
Pathfinder, Plan and Revise plan, the agent can hand independent pieces of work to helpers
|
||||
(subagents) while it keeps the conversation with you.
|
||||
|
||||
- **The button.** An icon in the top bar, after Stop session (and Write a
|
||||
@@ -701,6 +701,19 @@ keyboard-only navigation work.
|
||||
|
||||
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude, Devin and Codex tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve.
|
||||
|
||||
## Agents and the desktop app in User Preferences
|
||||
|
||||
**User Preferences → Agents** adds agent CLIs Plan2Code did not find on its own. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields:
|
||||
|
||||
- **Arguments**: one per row. `{prompt}` is replaced by the start prompt (for example `--message={prompt}`); with no `{prompt}` anywhere, the prompt is added last.
|
||||
- **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed.
|
||||
- **Bypass arguments**: added when permission checks are off.
|
||||
- **Model arguments**: added when a model is chosen, with `{model}` replaced (`--model` and `{model}` by default), and a list of **models** to offer, each an id and an optional label.
|
||||
|
||||
**Test** on a card shows where the command is found, or "Not found on PATH", and never runs it. Saving a duplicate name, a blank command or a built-in id marks the card and field and writes nothing. The list is plain text in `~/.plan2code/agents.json`, shared by the `plan2code` command and the desktop app; this page is the only thing that writes it, and a broken file or entry is skipped with a warning shown under the list, never a crash. If the file holds something the page could not read, saving asks first (**Save anyway**). `/plan2code` works only in agents that load the installed Plan2Code skills.
|
||||
|
||||
**Desktop app** appears only when the page is open inside the desktop app. Its switch, **Show on the taskbar when Plan2Code needs me** (on by default), controls the app's taskbar signal: on Windows a green dot on your move and a red one when it needs attention, plus one short burst of flashes when the window is not focused (the button stays lit until you look); on macOS a red `!` dock badge when it needs attention and one bounce; on Linux a badge where your desktop supports it. Turning it off clears the dot and stops flashes. The choice is kept by the app in its own `~/.plan2code/app.json`.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
@@ -773,6 +786,7 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.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 |
|
||||
| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents), read by the `plan2code` command and the desktop app | always |
|
||||
| your system temp directory | the port, process id and session token | until reboot |
|
||||
|
||||
Each of the workspace and meter files has exactly one writer: the server owns
|
||||
@@ -948,14 +962,14 @@ session without searching the skill install dirs.
|
||||
The vendored file is `src/web-console/public/vendor/marked.esm.js`,
|
||||
sha256 `7a7d9a521ac9384e0c3a075120a7c486cbd0c3c32cc5601bbb79a23e97403690`.
|
||||
Only `marked.lexer()` is used; the rendering is ours, in `public/render.js`, and
|
||||
builds DOM nodes rather than HTML so nothing needs sanitising.
|
||||
builds DOM nodes rather than HTML so nothing needs sanitizing.
|
||||
|
||||
### Refreshing the screenshots
|
||||
|
||||
The docs and the landing page show the console through the images in
|
||||
`docs/screenshots/`, one light and one dark WebP per screen. Rerun the capture
|
||||
after any change a person would see on the page: a new layout, a renamed
|
||||
button, a different colour.
|
||||
button, a different color.
|
||||
|
||||
```bash
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
|
||||
@@ -42,7 +42,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the five helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder, Plan, Revise plan) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the seven helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -59,7 +59,7 @@ Details: [Development Commands](./.agents-docs/AGENTS-development-commands.md)
|
||||
|
||||
## Code Style & Gotchas
|
||||
|
||||
Language/toolchain conventions for `install.js` vs TypeScript packages, and pitfalls to avoid (version sync, `.gitignore` pre-flight, character limits, User Feedback table format).
|
||||
Language/toolchain conventions for `install.js` vs TypeScript packages, US English spelling, and pitfalls to avoid (version sync, `.gitignore` pre-flight, character limits, User Feedback table format).
|
||||
|
||||
Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
@@ -67,7 +67,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
|
||||
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight color and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
|
||||
```
|
||||
╭───╮
|
||||
@@ -82,7 +82,7 @@ The `Failure log` section below is a recording of mistakes made by previous AI A
|
||||
|
||||
When you make a mistake, get corrected, or discover something about this codebase that wasn't written down:
|
||||
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behaviour.
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behavior.
|
||||
2. Keep it specific to this repo. General advice belongs nowhere.
|
||||
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
|
||||
4. Include the change in the same commit and mention it in your summary.
|
||||
@@ -104,7 +104,8 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- 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, 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). In helper-strength, the page-cards test "a card cut by the window fades at its bottom edge..." did the same.
|
||||
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behaviour outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not.
|
||||
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not.
|
||||
- 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.
|
||||
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
||||
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
|
||||
+31
-23
@@ -10,17 +10,25 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Reconnect the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
|
||||
- **desktop app**: the window's own title (and so its taskbar entry) now reads **Plan2Code - <folder name>** once a project is open, instead of a plain **Plan2Code** every window shares; two or more windows on different projects read apart without opening each one to check.
|
||||
- **helpers**: a helper (subagent) no longer has to run on the session's own model and effort. A new shared reference, `helper-strength.md`, shipped in Pathfinder, Quick Task, Implement, Implement + Review and Review, matches each helper job to a strength (`light`, `standard`, `strongest` or `inherit`) and an effort (`low`, `medium` or `high`) from signals that can be checked, with floors, one-step escalation and a fallback order for tools that cannot set either, and never names a model or vendor. Review, Implement + Review and Pathfinder name the strength for the helpers they start, and the rules apply in terminal sessions too.
|
||||
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows it as one quiet line, such as "Standard, medium effort".
|
||||
- **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review.
|
||||
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort".
|
||||
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
|
||||
- **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli <id>` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed.
|
||||
- **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app.
|
||||
- **desktop app**: the taskbar entry now shows when Plan2Code needs you, mirroring the console's tab icon. Windows: a green dot on your move, a red dot on needs attention, none while busy or finished, and one short burst of flashes when the window is not focused (the button stays lit until focused). macOS: a red `!` dock badge on needs attention and one bounce (the system badge cannot be green). Linux: a count badge where the desktop supports it, plus the urgency hint. The dot clears when the agent ends, the page reloads or the page stops answering. **User Preferences → Desktop app** (inside the app only) has the switch **Show on the taskbar when Plan2Code needs me**, on by default and saved in the app's own `app.json`.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **docs**: all prose, help text, skill prompts and comments now use US English spelling (color, gray, behavior, canceled, -ize), and `npm test` checks it (`scripts/test-us-english.mjs`).
|
||||
- **web console**: **User Preferences → Highlight color** now offers 38 colors in two rows of nineteen, covering the range of a Paint-style picker: new **Maroon**, **Peach**, **Brown**, **Cream**, **Lemon**, **Forest**, **Mint**, **Aqua**, **Lavender**, **Pink** and **Mono** (near-black in light mode, near-white in dark). Five near twins were merged (Copper into Rust, Marigold into Gold, Mustard into Lemon, Jade into Emerald, Lilac into Violet); a saved choice of one of those keeps its twin instead of falling back to Ocean.
|
||||
- **launcher**: when no agent CLI is installed, `plan2code` now prints each supported agent's install command and official page, and points at User Preferences → Agents for another CLI, before it exits.
|
||||
- **desktop app**: the launch card's agent choice is built from the agents that are installed, so a machine with only Devin or Codex starts on it with Start enabled, instead of assuming Claude Code.
|
||||
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
|
||||
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
|
||||
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
|
||||
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching how `plan2code` has always started an agent from the plain terminal. It previously defaulted off, the opposite of the terminal's own long-standing default; untick it for an agent that keeps its normal approval prompts.
|
||||
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
|
||||
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight colour. Its confirmation no longer claims "What it was doing is not saved" (not always true).
|
||||
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight color. Its confirmation no longer claims "What it was doing is not saved" (not always true).
|
||||
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
|
||||
- **desktop app**: docked right and collapsed, the terminal panel's **Expand** label now reads top to bottom instead of running off the edge of the narrow strip.
|
||||
- **desktop app**: the agent no longer prints the console's web address in the terminal panel, since the page is already in the window beside it: `terminalLine` under the app points at the dashboard instead, and the agent contract says to give no link there.
|
||||
@@ -30,7 +38,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web console**: a plan's **Build order** card has a **Combine phases** button beside **No changes**. One click fills the box with a request to merge phases where possible while keeping each to a clear concern. It shows only in Plan and Revise plan, where the breakdown is phases.
|
||||
- **web console**: Help now reads right in the desktop app throughout, not just in the topics fixed before: what this page is and how long it runs, the troubleshooting table and its diagram, scroll memory, drafts, the session meter's red advice, Ask's "no agent" line and Privacy's link and address notes all name the app's window, its terminal panel, **New Session** and **Reconnect the console** instead of a browser tab, a link or a new conversation. The status line's approval hint says "the terminal panel" there too. In a browser, Help is unchanged.
|
||||
- **desktop app**: the top bar's buttons now look like the console's own: rounded, quiet until hovered, then in your highlight color from User Preferences (the app keeps it for the next launch), with **New Session** outlined in it as the likely next step.
|
||||
- **desktop app**: the New Session confirmation shows Planny, drawn like the console's own (outlined shell, star eye, smile), holding a steaming cup of coffee, and its buttons use the console's style: **New Session** in your highlight colour, **Cancel** a plain button. The same highlight applies to the panel's other one-button prompts, such as **Retry** and **Reconnect the console**.
|
||||
- **desktop app**: the New Session confirmation shows Planny, drawn like the console's own (outlined shell, star eye, smile), holding a steaming cup of coffee, and its buttons use the console's style: **New Session** in your highlight color, **Cancel** a plain button. The same highlight applies to the panel's other one-button prompts, such as **Retry** and **Reconnect the console**.
|
||||
- **desktop app**: the top bar is rebuilt around two menus and one next step. The project shows as its folder name, with the full path and **Change project** in its menu; **New Session** always sits just left of the agent's menu, which carries a state dot, an amber **checks off** badge in place of the "Permission checks are off for ..." sentence, and **Change agent** once the agent has ended. The console's and the skills' messages share one slot at the right end that shows the most pressing step with its button (**Reconnect the console**, **Update skills**) and "+N more" for the rest, so the bar no longer overflows when several things go wrong at once. The repeated "Plan2Code" label, the full path, the "agent:" prefix and the long "Nothing starts until you press New Session" line are gone.
|
||||
|
||||
### 🐛 Fixed
|
||||
@@ -92,12 +100,12 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **building habits**: Quick Task, Implement and Implement + Review now read one shared reference file, `references/building-habits.md`, at three moments. When a bug or an unexpected failing test turns up, they find the cause first: build a command that fails on the bug before changing code (or say why they cannot, rank their guesses with the evidence and let you decide), then keep the reproduction as a regression test in the project's existing test runner. When the plan asks for it, they build test first: write the test, see it fail for the right reason, then write the code. Before a restructure meant to change no behaviour, they pin the behaviour with tests that must pass unchanged afterwards. Adapted from Matt Pocock's [`diagnose`, `tdd` and `improve-codebase-architecture`](https://github.com/mattpocock/skills) skills and pstack's debugging playbook (both MIT).
|
||||
- **plan**: the testing question gains a fourth choice, **Approach**: code first (the default) or test first. Test first is recorded in the PLAN-DRAFT's Testing Strategy table, and Document then orders each task's test before its code with a `Test:` line under the task naming where the test drives the behaviour.
|
||||
- **building habits**: Quick Task, Implement and Implement + Review now read one shared reference file, `references/building-habits.md`, at three moments. When a bug or an unexpected failing test turns up, they find the cause first: build a command that fails on the bug before changing code (or say why they cannot, rank their guesses with the evidence and let you decide), then keep the reproduction as a regression test in the project's existing test runner. When the plan asks for it, they build test first: write the test, see it fail for the right reason, then write the code. Before a restructure meant to change no behavior, they pin the behavior with tests that must pass unchanged afterwards. Adapted from Matt Pocock's [`diagnose`, `tdd` and `improve-codebase-architecture`](https://github.com/mattpocock/skills) skills and pstack's debugging playbook (both MIT).
|
||||
- **plan**: the testing question gains a fourth choice, **Approach**: code first (the default) or test first. Test first is recorded in the PLAN-DRAFT's Testing Strategy table, and Document then orders each task's test before its code with a `Test:` line under the task naming where the test drives the behavior.
|
||||
- **review**: reviews run in a fresh helper that never saw the build; reports say how they ran. Wherever the tool can start a helper and the web console's Subagents switch is not off, every review (`/plan2code-review`, Implement + Review's Stage 2, Implement's "review" at sign-off and Quick Task's "Review it now") hands its analysis to one helper briefed only with the spec and the change set (the new `references/reviewer-brief.md`). The main session checks every finding in the source before you see it and drops what it cannot confirm. Each report carries a **Reviewed by** line: a fresh helper (with how many findings were checked and dropped), or this session, said once as not independent. Adapted from pstack's independent reviewer and Matt Pocock's [`code-review`](https://github.com/mattpocock/skills) guidance (both MIT).
|
||||
- **xray**: a new skill, **Codebase X-ray** (`/plan2code-xray`), on the dashboard under *Useful any time*. Explain an area: how it works and why it is that way, citing files and the commits and pull requests behind it (git history always, `gh` when it is installed and signed in, and it says once which sources it could not use). Or find the rough spots: files that always change together, thin wrappers, tangled boundaries and busy code with no tests, ranked with a concrete "to change X today you must touch..." example each. You tick the ones worth fixing and only those go into `specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, ready for Pathfinder or Plan. A new script, `xray.mjs`, does the counting from git history. Pathfinder and Plan point at it when the code is unfamiliar. Adapted from Matt Pocock's [`improve-codebase-architecture`](https://github.com/mattpocock/skills) skill (MIT) and pstack's codebase survey, `how` and `why`.
|
||||
- **diagnose**: a new skill, **Diagnose a bug** (`/plan2code-diagnose`), on the dashboard under *Useful any time*. It finds a bug's cause and writes it up without fixing it, under the find-the-cause-first habit: a command that fails on the bug first (or, when it cannot build one, its guesses ranked with the evidence), then the cause in `specs/<bug-name>/DIAGNOSIS-<date>.md`. It then offers `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big. The dashboard shows such a folder as a new spec state, **Bug diagnosed**, which lights Quick Task (suggested) and Plan and keeps Document, Implement, Implement + Review and Finalize greyed. Adapted from Matt Pocock's [`diagnose`](https://github.com/mattpocock/skills) skill and pstack's debugging playbook (both MIT).
|
||||
- **quick-task**: asks "Write the test first?" when the change alters behaviour and the project already has a test runner, and names the test spot in the plan's Verify section. A bug fix starts with its reproduction.
|
||||
- **diagnose**: a new skill, **Diagnose a bug** (`/plan2code-diagnose`), on the dashboard under *Useful any time*. It finds a bug's cause and writes it up without fixing it, under the find-the-cause-first habit: a command that fails on the bug first (or, when it cannot build one, its guesses ranked with the evidence), then the cause in `specs/<bug-name>/DIAGNOSIS-<date>.md`. It then offers `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big. The dashboard shows such a folder as a new spec state, **Bug diagnosed**, which lights Quick Task (suggested) and Plan and keeps Document, Implement, Implement + Review and Finalize grayed. Adapted from Matt Pocock's [`diagnose`](https://github.com/mattpocock/skills) skill and pstack's debugging playbook (both MIT).
|
||||
- **quick-task**: asks "Write the test first?" when the change alters behavior and the project already has a test runner, and names the test spot in the plan's Verify section. A bug fix starts with its reproduction.
|
||||
- **show me it working**: Implement, Implement + Review, Quick Task and Finalize offer to show the change running before you approve, never required: reply `show me` in the terminal, or press **Show me it working** on the web console. The agent starts the app the way `AGENTS.md` says (working it out from the project and offering the line for `AGENTS.md` when it is missing, or asking you), looks at the change, stops what it started and records one line saying what was run and what was seen. Screenshots appear on the page only, never under `specs/`. Init and Init Update now ask how to start the app and where to view it. Adapted from pstack's proof-on-the-running-app idea (MIT).
|
||||
- **web console**: a doc can show a picture. An image block (`"image": "shots/<name>.png"`) shows a PNG, JPEG or WebP the agent saved under the session's `shots/` folder; anything outside that folder, over 5 MB or not really an image is refused.
|
||||
- **launcher**: `plan2code update` updates everything that was installed (the skills, the `plan2code` command and any of the status line, `plan2code-loop`, `plan2code-metrics` and `plan2code-bot`), with no menu and never uninstalling. Every global install now writes `~/.plan2code/install.json` listing what it installed, which `install.js --update` reads; with no record it updates the skills and the `plan2code` command.
|
||||
@@ -118,9 +126,9 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **docs**: README, the quick reference and the web console guide say to update with `plan2code update` (or re-run the install command).
|
||||
- **handoff**: every handoff now lives in `~/.plan2code/handoffs/` (a Markdown file plus a small `.json` beside it), owned by the web console, and handoffs older than 30 days are swept when the console opens. The Handoff skill writes there with no folder or `.gitignore` question, and Cleanup never lists the folder. Handoffs written to the OS temp folder or a `handoffs/` folder before this change are not listed.
|
||||
- **dashboard**: a **Bug fixed** spec has a visible **Delete** that needs one confirm, and its chip no longer repeats the "bug fixed" line.
|
||||
- **web console**: the review sign-off card lists **Approve this phase** before **Show me it working**, with the approve button outlined in the accent colour.
|
||||
- **web console**: a sign-off's **yes** button (Quick Task's **Build it**, Finalize's **Archive it**) is outlined in your highlight colour too, like **Approve**. So is the yes of a yes/no question (such as Plan's **Write the plan**) and a recap's **Yes, that is right**, except on a question marked dangerous, whose yes stays red.
|
||||
- **web console**: **Skip this one** (and **Do not skip**) on an optional question is a small button in your highlight colour, like a comment box's **No changes**, instead of an underlined link.
|
||||
- **web console**: the review sign-off card lists **Approve this phase** before **Show me it working**, with the approve button outlined in the accent color.
|
||||
- **web console**: a sign-off's **yes** button (Quick Task's **Build it**, Finalize's **Archive it**) is outlined in your highlight color too, like **Approve**. So is the yes of a yes/no question (such as Plan's **Write the plan**) and a recap's **Yes, that is right**, except on a question marked dangerous, whose yes stays red.
|
||||
- **web console**: **Skip this one** (and **Do not skip**) on an optional question is a small button in your highlight color, like a comment box's **No changes**, instead of an underlined link.
|
||||
- **init**, **init-update**: the *Keeping this file current* section they write into `AGENTS.md` gains three rules: a rule broken twice becomes an automated check, a new Failure log line first looks for one on the same topic to sharpen instead, and the log holds 17 entries at most (over the cap, merge entries that share a cause, then drop the lowest-value ones). Init update offers the missing rules to an existing section and tidies the log on every run, showing each merge and removal for a yes before it writes.
|
||||
- **contributors**: this repo's `AGENTS.md` follows the same Failure log rules, and its three post-sync grep entries are merged into one.
|
||||
- **contributors**: the web console's source is split by job: `lib.mjs`, `server.mjs`, `console.mjs`, `app.js` and `app.css` become `routes.mjs`, `static.mjs`, `cmd-*.mjs`, the by-job Node files, `public/screens/` and `public/styles/`. Nothing a person sees changes, and the page starts faster (ready in about 280 ms, was 450 ms).
|
||||
@@ -131,7 +139,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### 🗑️ Removed
|
||||
|
||||
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favour of `console.mjs handoff new`, which every skill can reach.
|
||||
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favor of `console.mjs handoff new`, which every skill can reach.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
@@ -156,9 +164,9 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
- **git**: the web console's git board is now three tabs, **Changes**, **Branches** and **Sync**, and opens on the tab holding the likely next step. Ten fixed rules pick that step from the repository's state (fix or continue a stopped rebase or merge, make the first commit, make a branch on a detached HEAD, commit or start a branch for your changes, pull, push, publish, open a pull request, clean up branches) and show it as one main button with at most one quieter one beside it. Each tab badges what is waiting on it, and the other tabs say "Next step is on ‹tab›" with a link to it. Your own click moves you to the next step's tab once it lands; a refresh or a commit from the terminal leaves you where you are, and a reload keeps your tab.
|
||||
- **git**: held-back files (secrets, files over 5 MB) no longer keep Commit as the next step forever. They get a quiet "held back" line and an **Add … to .gitignore** offer, which commits only `.gitignore`.
|
||||
- **git**: a busy board is read-only. While a git command runs or the agent has not picked up your last click, every button, tick and picker greys out (switching tabs, search and folds still work), and what is running shows where the next step usually sits. Plan2Code's questions now appear under the tab strip.
|
||||
- **git**: a busy board is read-only. While a git command runs or the agent has not picked up your last click, every button, tick and picker grays out (switching tabs, search and folds still work), and what is running shows where the next step usually sits. Plan2Code's questions now appear under the tab strip.
|
||||
- **git**: a rebase or merge stopped on conflicts shows one block on Sync with the files marked *markers left* or *resolved*, one main button and **Abort** once; Changes and Branches wait until it is finished or aborted.
|
||||
- **git**: **Done with git** is a normal button at the right of the tab strip. It greys while a git command runs (Stop session in the top bar still works), and while one of Plan2Code's questions waits it cancels that question and finishes.
|
||||
- **git**: **Done with git** is a normal button at the right of the tab strip. It grays while a git command runs (Stop session in the top bar still works), and while one of Plan2Code's questions waits it cancels that question and finishes.
|
||||
- **web-console**: Help → *The git board* is rewritten for the tabs, badges, the next step, the busy rules and Done with git. Handoff is described as packing the current session, not this conversation.
|
||||
- **docs**: the docs site's "Any time" skills now list **Changelog** and **Git** beside Quick task, Review and Handoff.
|
||||
- **tests**: `scripts/test-web-console-git-board.mjs` checks every sample repository state's next step, tab and badges, proves no control on a busy board is clickable, and that every board function is reachable on some tab.
|
||||
@@ -167,7 +175,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **implement**: Implement no longer says there is nothing left to do while the dashboard keeps Finalize greyed out. When every phase is approved but tasks under them are still open (usually manual steps an agent could not do, left blocked `[!]` with a "User action"), `specs.mjs status` now returns a `checkoff` verdict listing them, and Implement asks about each one in turn: "Is this done?" in the terminal, or a **Done, check it off** / **Not yet** card in the web console. A yes runs the new `specs.mjs tick <spec> --task <id>`, which marks the task `[x]` and adds a "Confirmed done by the user on <date>" line under it. Once nothing is left open, Implement points to `/plan2code-4-finalize` and the dashboard shows the spec as ready to finalize.
|
||||
- **implement**: Implement no longer says there is nothing left to do while the dashboard keeps Finalize grayed out. When every phase is approved but tasks under them are still open (usually manual steps an agent could not do, left blocked `[!]` with a "User action"), `specs.mjs status` now returns a `checkoff` verdict listing them, and Implement asks about each one in turn: "Is this done?" in the terminal, or a **Done, check it off** / **Not yet** card in the web console. A yes runs the new `specs.mjs tick <spec> --task <id>`, which marks the task `[x]` and adds a "Confirmed done by the user on <date>" line under it. Once nothing is left open, Implement points to `/plan2code-4-finalize` and the dashboard shows the spec as ready to finalize.
|
||||
|
||||
## v2.7.0
|
||||
|
||||
@@ -212,7 +220,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web-console**: the dashboard's spec card counts only a phase file's `**Task N.M:**` lines, so an Acceptance Criteria checkbox no longer shows as a task or keeps a built spec from reading "built". `post` and `status` stop reporting `phase: "submitted"` once a send has been collected. Several "New conversation" lines arriving together reach the agent as one. A posted finish (a pause included) no longer leaves the agent shown as working, and resuming a paused session starts a fresh working turn.
|
||||
- **web-console**: **Commit it now** on a finished screen (and Changelog's "Commit this now?") no longer leaves the page stuck on the previous skill's ending. Resuming into Git now clears the previous skill's page, its ending included, as a dashboard launch does.
|
||||
- **web-console**: the top bar's three right-side buttons (Help, Colors & theme, feedback) keep to the right edge when the progress bar is hidden; on the dashboard and the git board they used to sit beside the title.
|
||||
- **web-console**: the git board's action bar (Refresh, Pull/Push, Commit, **Done**) stays pinned to the bottom of the pane while the branch table scrolls, and **Done** shows in the highlight colour when it is live.
|
||||
- **web-console**: the git board's action bar (Refresh, Pull/Push, Commit, **Done**) stays pinned to the bottom of the pane while the branch table scrolls, and **Done** shows in the highlight color when it is live.
|
||||
- **web-console**: a finished screen's buttons (**Review it now**, **Commit it now**, **Back to the dashboard**) stay live for as long as the session is open; the copy-the-command fallback only appears once the session has closed.
|
||||
|
||||
## v2.6.0
|
||||
@@ -222,7 +230,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web-console**: the breakdown question's "Anything else about this breakdown?" field has a **No changes** button. One click fills the box with "no changes", so you no longer type it. The old "(type 'no changes' if none)" hint is gone from the label.
|
||||
- **git-commit**: a new `/plan2code-git-commit` skill and dashboard card. It reads what changed, drafts the commit message for your approval, offers a new branch first on the default branch, suggests splitting work that is really two jobs, and asks before every commit and push (never a force-push). Outside a git repository it offers to start one.
|
||||
- **changelog**: a new `/plan2code-changelog` skill and dashboard card, just left of Git commit. It reads the default branch's latest version, classifies the branch's work and picks the version. When the branch already owns a version that is not released and not on another branch, it adds to that entry instead of starting a new one. It compares the branch with the newest entry, suggests the entries that are missing for you to edit, keeps `package.json` aligned, and offers to run Git commit next. The facts come from `changelog-state.mjs`, with tests in `scripts/test-script-changelog.mjs`.
|
||||
- **web-console**: the Git commit card counts the files waiting ("3 files to commit") and greys out on a clean tree, from a bounded `git status` the scan runs when the dashboard opens. If git cannot answer, the card stays clickable.
|
||||
- **web-console**: the Git commit card counts the files waiting ("3 files to commit") and grays out on a clean tree, from a bounded `git status` the scan runs when the dashboard opens. If git cannot answer, the card stays clickable.
|
||||
- **web-console**: the Commit this? question in Git commit has a collapsed **Show the N files** table of every path and its state, so "15 files" can be read before you say yes.
|
||||
- **web-console**: a finished quick task or phase build gets a **Commit it now** button beside the printed git command. It starts Git commit in the same session, as if you had clicked its dashboard card.
|
||||
- **web-console**: the dashboard scan reports `isGit`, found from the filesystem without spawning git (linked worktrees count). The Git commit card stays clickable outside a repository and says "Not a git repository yet: it offers to start one". The skill has its own Planny pose and a Help entry.
|
||||
@@ -244,7 +252,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web-console**: six new starter templates, each slotted into every role's order. **Refactor** (Plan, Quick Task) asks what behaviour must not change. **Performance problem** (Plan, Quick Task) asks for today's number and the target. **Dependency upgrade** (Quick Task) asks for the known breaking changes. **Spike** (Pathfinder) is a time-boxed question with an "answered when". **Integration** (Pathfinder, Plan) covers the other side's auth and limits and what happens when it fails. **Data migration** (Plan) asks for a rollback plan. Pathfinder now offers 8 templates, Plan 10 and Quick Task 10, 19 in all.
|
||||
- **web-console**: six new starter templates, each slotted into every role's order. **Refactor** (Plan, Quick Task) asks what behavior must not change. **Performance problem** (Plan, Quick Task) asks for today's number and the target. **Dependency upgrade** (Quick Task) asks for the known breaking changes. **Spike** (Pathfinder) is a time-boxed question with an "answered when". **Integration** (Pathfinder, Plan) covers the other side's auth and limits and what happens when it fails. **Data migration** (Plan) asks for a rollback plan. Pathfinder now offers 8 templates, Plan 10 and Quick Task 10, 19 in all.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
@@ -336,7 +344,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **review**: with no `main` or `master` and no `--base`, `review-scope.mjs` now stops with `no-base` instead of quietly counting only uncommitted changes.
|
||||
- **commit-msg.mjs**: the add step is `git add -- <paths>`, paths starting with `@` or `-` are quoted, and subjects with `\`, `!` or curly quotes are refused. The output also carries `add` and `commit` separately for Windows PowerShell 5.1, which has no `&&`.
|
||||
- **specs.mjs**: `mark` reads a Status line written as `Status:` or `**Status**:` too, and warns when a phase file has none; a path that is not a folder directly under `specs/` is refused (`not-a-spec`).
|
||||
- **pathfinder**: the map header carries `**Next NN:**`, so a deleted question's number is never handed out again. `claim`, `resolve` and `rule-out` honour `--dry-run`. Notes indented under a map row survive a marker change. Research questions are fired unclaimed; the one-claim rule is for the questions a person works through.
|
||||
- **pathfinder**: the map header carries `**Next NN:**`, so a deleted question's number is never handed out again. `claim`, `resolve` and `rule-out` honor `--dry-run`. Notes indented under a map row survive a marker change. Research questions are fired unclaimed; the one-claim rule is for the questions a person works through.
|
||||
- **finalize**: `feedback-payload.mjs` counts the same phase files `specs.mjs` does, `submit` refuses an oversize URL when `gh` is unavailable (`oversize`), and a bare spec name present in both `specs/` and `specs--completed/` is refused as ambiguous.
|
||||
- Every script was checked against real specs and Pathfinder maps in other repositories and by four independent reviews; each issue found has a regression test.
|
||||
|
||||
@@ -346,7 +354,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **web-console**: when the agent stops checking in, the status line and Help now say to type **continue** in an idle terminal so it picks your answers up.
|
||||
- **web-console**: `wait` exit 10 now carries a `next` instruction (relay one line, then wait again), and `console.md` opens with the one rule that keeps the page alive: every turn ends on a `wait` call, never on text.
|
||||
- **web-console**: a finished quick task offers **Back to the dashboard** as well as **Review it now**, so the finished screen is never a dead end.
|
||||
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centred and in front of other windows instead of behind the terminal.
|
||||
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centered and in front of other windows instead of behind the terminal.
|
||||
- **Launcher**: before asking which CLI to use, `plan2code` says what it is about to do and that running `/plan2code` inside your agent works too.
|
||||
- **web-console**: the session meter now weighs the work a session actually did instead of a flat amount per step. A built phase scores one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review, so a twelve-task phase weighs four times a three-task one; the agent reports the count as `run.tasks`. Every 2 questions you answer on the page add a point to the skill you answered them in, so a long back-and-forth in Plan or Pathfinder counts for more than a short one. Each Pathfinder research question adds 1 through a new `pathfinder-research` event, since research fills the context with nobody answering anything. The levels move to match: yellow from 5 points, red from 10, and the ring is full at 15.
|
||||
|
||||
@@ -372,7 +380,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **`plan2code-3-implement-review`**: a quality-gated Step 3 that implements one phase, runs a focused review and the selected fixes before sign-off, and marks the phase complete only after the reviewed result is approved. Step 2's hand-off now offers it first, with `/plan2code-3-implement` as the review-free alternative.
|
||||
- **`--web` flag**: `/plan2code-1-plan --web plan a lunch voting app` opens the console without asking. Every next-step command the workflow prints (resume footers, NEXT STEP lines, the loop's completion banner) now carries `--web`.
|
||||
- **Console pages for builds and reviews**: a build shows the current task, a task-count progress bar and the phase's task list ticking as tasks land. After an approved phase or a finished quick task, **Review it now** runs `/plan2code-review` on the page, with *Which to fix* presets for critical-and-warnings or everything.
|
||||
- **Console conveniences**: nine question shapes with live validation and drag-to-reorder phases; drafts that survive a closed tab, reload, server restart or agent crash; an **Ask** tab for quick questions the agent answers at its next check-in (file edits need approval); image and document attachments; a read-only **Overview** tab; a **Workspace** of extra read-only folders addressed as `@name`; a green / yellow / red **session meter**; a **Role** preference that orders starter templates; nineteen highlight colours, light / dark themes and card widths; audio cues with per-event toggles; and a 16-topic Help dialog.
|
||||
- **Console conveniences**: nine question shapes with live validation and drag-to-reorder phases; drafts that survive a closed tab, reload, server restart or agent crash; an **Ask** tab for quick questions the agent answers at its next check-in (file edits need approval); image and document attachments; a read-only **Overview** tab; a **Workspace** of extra read-only folders addressed as `@name`; a green / yellow / red **session meter**; a **Role** preference that orders starter templates; nineteen highlight colors, light / dark themes and card widths; audio cues with per-event toggles; and a 16-topic Help dialog.
|
||||
- **Planny in the console**: drawn in SVG in his own dock above the question list, where he carries the page's state: his star lights and he waves when it is your turn, the star turns and he walks on the spot while the agent works, it goes green when all is caught up, he shows no arms when the agent is not answering, and he fades with his star shut when disconnected. He flies through a starfield while the agent thinks, wakes up on a fresh dashboard, and acts out each skill on its starting screen, arms holding that step's prop. The tab icon adds a busy, ready or attention bar, and the desktop shortcut uses him too.
|
||||
- **Tests**: `scripts/test-web-console.mjs` and `scripts/test-launcher.mjs` (run by `node --test`), `scripts/parse-check.mjs` (every shipped browser module parses as an ES module) and `scripts/check-skill-table.mjs` (the dashboard's "What each skill reads and writes" table matches the skills), all wired into `npm test`. `scripts/bench-web-console.mjs` measures time to first paint.
|
||||
- **install.js**: an animated progress indicator during the two long install phases, so the installer no longer looks hung.
|
||||
@@ -462,7 +470,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **`src/plan2code-0-pathfinder.md` recompressed** to absorb the new `## Backend` section within the 11,000-character workflow-file limit — duplication between the orchestrator and its reference files was removed (the local layout and marker legend now live only in `questions.md`; Form A/B footer detail only in `trail.md`), and step text tightened. No behaviour was dropped.
|
||||
- **`src/plan2code-0-pathfinder.md` recompressed** to absorb the new `## Backend` section within the 11,000-character workflow-file limit — duplication between the orchestrator and its reference files was removed (the local layout and marker legend now live only in `questions.md`; Form A/B footer detail only in `trail.md`), and step text tightened. No behavior was dropped.
|
||||
|
||||
## v2.0.0
|
||||
|
||||
@@ -472,7 +480,7 @@ Ports upstream v1.17.0 and v2.0.0 into Plan2Code.
|
||||
|
||||
- **Gemini CLI is no longer an install target.** The `.gemini/commands/*.toml` surface is removed, along with the build-time machinery it required: `generateTomlContent()`, `writeTomlToDestination()`, `inlineReferenceContent()`, and the `dest.type === 'toml'` branch in `syncPrompts()`. Every remaining target resolves `Read references/*.md` directives at runtime, so reference content no longer needs inlining at build time.
|
||||
|
||||
**Uninstall still cleans up Gemini files.** The `.gemini/commands` entry is deliberately retained in the uninstall target list (labelled `Gemini CLI (legacy — uninstall only)`) behind a new `uninstallOnly` flag, so `.toml` files written by v1.x installs can still be removed. Do not add it back to `LOCAL_DESTINATIONS` / `GLOBAL_DESTINATIONS`.
|
||||
**Uninstall still cleans up Gemini files.** The `.gemini/commands` entry is deliberately retained in the uninstall target list (labeled `Gemini CLI (legacy — uninstall only)`) behind a new `uninstallOnly` flag, so `.toml` files written by v1.x installs can still be removed. Do not add it back to `LOCAL_DESTINATIONS` / `GLOBAL_DESTINATIONS`.
|
||||
|
||||
All other platforms are unaffected — Claude Code (skills *and* commands), Cursor, Windsurf, Continue, Codeium, GitHub Copilot, VS Code Copilot, Pi, Crush, Amp, Devin, OpenCode, and Zed all install exactly as before.
|
||||
|
||||
@@ -502,7 +510,7 @@ Ports upstream v1.17.0 and v2.0.0 into Plan2Code.
|
||||
- **Docs site and README redesigned** around an "airmail" postcard theme — a fixed four-sided airmail-chevron page frame, sticky header, and the workflow presented as six posted letters, with Pathfinder and the optional Review step both surfaced. Adds a postage-stamp favicon set (`favicon.svg` / `.ico` / `.png` / `apple-touch-icon.png`) and a new README banner; removes three orphaned images (`desk.jpg`, `install-script.jpg`, `plan2code.jpg`).
|
||||
- **`/plan2code-4-finalize` archives `pathfinder/` with the spec** — STEP 6 now names `pathfinder/` in the move list and no longer describes the cleanup target as "research or scratch files," wording that pointed an agent straight at `pathfinder/questions/`. The map is the rationale record behind the plan, in the same class as `PLAN-CONVERSATION-*.md`.
|
||||
- **`/plan2code-1b-revise-plan` no longer deletes `pathfinder/`** — its Step 6 cleanup had the same "research or scratch files" wording.
|
||||
- **`/plan2code-quick-task` is no longer labelled "Step 0"** — pathfinder now owns step 0, and quick-task was never a pipeline step. It registers as a utility (like `init`, `review`, and `handoff`), so its generated description reads `Plan2Code Quick Task: Quick Task Mode`. Filename, skill name, and command path are unchanged.
|
||||
- **`/plan2code-quick-task` is no longer labeled "Step 0"** — pathfinder now owns step 0, and quick-task was never a pipeline step. It registers as a utility (like `init`, `review`, and `handoff`), so its generated description reads `Plan2Code Quick Task: Quick Task Mode`. Filename, skill name, and command path are unchanged.
|
||||
- **`/plan2code-handoff` asks where to save** — the OS temp directory is now the default, with `./handoffs/` or any other path available on request. Adds a spec-awareness section: when the session worked inside `specs/<feature>/`, the handoff cites the in-progress `phase-X.md` and its actual checkbox state rather than relying on conversation memory.
|
||||
- **`/plan2code-init-update` Step 7 offloaded to a reference file** — the AI Agent File Sync detail moves to `plan2code-init-update-references/ai-agent-file-sync.md` with an inline fallback. The `CLAUDE.md` MANDATORY-FIRST-STEP template is unchanged.
|
||||
- **`/plan2code-review` Session End offloaded to a reference file** — next-step routing moves to `plan2code-review-references/session-end.md` with an inline fallback.
|
||||
|
||||
@@ -88,6 +88,23 @@ Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permiss
|
||||
which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Using another agent CLI, or none yet</summary>
|
||||
|
||||
Plan2Code runs inside an AI coding agent CLI. If `plan2code` finds none of Claude Code, Devin or Codex on
|
||||
your `PATH`, it says so and prints each one's install command and official page, then exits; the desktop app
|
||||
shows the same help in a panel with an **Install page** link per agent and a **Check again** button, so you
|
||||
can install one and carry on without restarting.
|
||||
|
||||
To use a different agent CLI, open the web console's **User Preferences → Agents** and add it: a name, the
|
||||
command, and (optionally) its arguments, the start prompt, arguments for skipping permission prompts, and
|
||||
how it takes a model. Custom agents are saved in `~/.plan2code/agents.json` and used by both the
|
||||
`plan2code` command (listed after the built-ins; `--cli <id>` picks one) and the desktop app's picker. The
|
||||
`/plan2code` start prompt only does something in an agent that loads the installed Plan2Code skills; for
|
||||
any other, leave the start prompt blank and start a skill yourself. Details in
|
||||
[.readme/web-console.md](.readme/web-console.md#agents-and-the-desktop-app-in-user-preferences).
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>About the desktop app</summary>
|
||||
|
||||
@@ -395,7 +412,7 @@ console or the terminal; add `--web` to skip the question and go straight to the
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**The skills aren't recognised.** Re-run the installer and restart your AI tool. Confirm the global
|
||||
**The skills aren't recognized.** Re-run the installer and restart your AI tool. Confirm the global
|
||||
install with `npx skills list -g`. For a project install, check the generated directories aren't
|
||||
gitignored.
|
||||
|
||||
|
||||
+21
-4
@@ -65,15 +65,32 @@ Three things keep today's terminal flow:
|
||||
The first time the app opens on a folder, a checklist confirms Node, the agent CLI, the project
|
||||
folder and the skills version before anything else shows; a later launch skips straight past it.
|
||||
|
||||
A **launch card** then asks which agent (Claude, Devin or Codex), model and effort (Claude and Codex
|
||||
only) to start on. Permission checks off is its own tick, on by default (see below; New Session
|
||||
keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of
|
||||
just being greyed out. The card is skipped when the launcher already passed an agent to start.
|
||||
A **launch card** then asks which agent, model and effort (Claude and Codex only) to start on. The
|
||||
picker lists Claude Code, Devin and Codex, then any custom agents you added in the web console's
|
||||
**User Preferences → Agents** (saved in `~/.plan2code/agents.json`, shared with the `plan2code`
|
||||
command), and starts on one that is actually installed, so a machine with only Devin or Codex is ready
|
||||
to go. Permission checks off is its own tick, on by default (see below; New Session keeps whatever
|
||||
you picked, and reuses the same agent); a CLI the app cannot find is named, with how to install it,
|
||||
instead of just being grayed out. The card is skipped when the launcher already passed an agent to
|
||||
start.
|
||||
|
||||
With no agent installed at all, the checklist and the launch card explain what an agent CLI is and
|
||||
show each built-in's install command with an **Install page** link. Install one (or add a custom
|
||||
agent) and press **Check again**: the app finds it without a restart.
|
||||
|
||||
The window's own title (and so its taskbar entry) reads **Plan2Code - <folder name>** once a
|
||||
project is open, so two or more windows on different projects read apart without opening each one
|
||||
to check.
|
||||
|
||||
The taskbar entry also shows when Plan2Code needs you, the same states as the console's tab icon in
|
||||
a browser. On Windows a green dot means it is your move and a red dot means it needs attention, with
|
||||
one short burst of flashes when the window is not focused; on macOS the dock shows a red `!` badge on
|
||||
needs attention and bounces once; on Linux a count badge appears where the desktop supports it. There
|
||||
is no dot while the agent is busy or the step is finished, and it clears when the agent ends or the
|
||||
page reloads. Turn it off with **Show on the taskbar when Plan2Code needs me** under **User
|
||||
Preferences → Desktop app** (shown only inside the app). The per-system details are in
|
||||
[plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar).
|
||||
|
||||
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
|
||||
**Change project**; **New Session**, whenever an agent exists; the agent's own menu, with a dot for its
|
||||
state, an amber **checks off** badge while permission checks are off, and **Change agent** once it has
|
||||
|
||||
+10
-4
@@ -191,7 +191,10 @@ const SOURCE_PROMPTS = [
|
||||
displayName: 'Planning Mode',
|
||||
description: 'Requirements analysis and architecture design',
|
||||
scripts: ['specs.mjs'],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-1b-revise-plan.md',
|
||||
@@ -200,7 +203,10 @@ const SOURCE_PROMPTS = [
|
||||
displayName: 'Revision Mode',
|
||||
description: 'Modify specs mid-implementation when requirements change',
|
||||
scripts: ['specs.mjs'],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-2-document.md',
|
||||
@@ -1229,7 +1235,7 @@ function runInteractive() {
|
||||
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : statusLineResult !== 0 ? statusLineResult : launcherResult;
|
||||
process.exit(exitCode);
|
||||
} else {
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELLED${COLORS.RESET}\n`);
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELED${COLORS.RESET}\n`);
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
}
|
||||
@@ -1316,7 +1322,7 @@ function runInteractive() {
|
||||
|
||||
// Q — exit
|
||||
if (input === 'Q') {
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELLED${COLORS.RESET}\n`);
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.WARNING} CANCELED${COLORS.RESET}\n`);
|
||||
rl.close();
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
+1
-1
@@ -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 --test-concurrency=8 scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
"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 --test-concurrency=8 scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0",
|
||||
|
||||
@@ -4,6 +4,22 @@ The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal pane
|
||||
|
||||
The app is optional. The Node web console and the skills never depend on it, so running `/plan2code` inside an agent with no app works exactly as before.
|
||||
|
||||
## Agents and the taskbar
|
||||
|
||||
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. Custom agents offer their own models, and `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
|
||||
|
||||
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
|
||||
|
||||
**Taskbar signal.** The console page tells the app when it is busy, your move, or needs attention (the same states as its tab icon), and the app shows it:
|
||||
|
||||
| System | Your move | Needs attention |
|
||||
|---|---|---|
|
||||
| Windows | green dot on the taskbar button, and one short burst of flashes when the window is not focused (the button then stays lit until focused) | red dot, and the same burst when not focused |
|
||||
| macOS | no badge (the system badge cannot be green), one bounce when not focused | red `!` dock badge, and one bounce when not focused |
|
||||
| Linux | the urgency hint when not focused | a count badge of 1 where the desktop supports it, and the urgency hint |
|
||||
|
||||
There is no dot while busy or finished. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|
||||
@@ -73,7 +73,7 @@ file directly after checking it against the release's checksum list.
|
||||
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
|
||||
console frame and the terminal included) or Escape, and are not cut off by the bar
|
||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
||||
picker opens; cancelling the picker leaves the running agent and its project untouched
|
||||
picker opens; canceling the picker leaves the running agent and its project untouched
|
||||
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
|
||||
on the launch card (or the checklist, if its own first run has not passed yet)
|
||||
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
|
||||
@@ -109,6 +109,20 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
|
||||
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
||||
|
||||
## Agents and the taskbar (each system)
|
||||
|
||||
- [ ] A custom agent added in the console's User Preferences → Agents (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments
|
||||
- [ ] With no agent CLI on `PATH` and no custom agent, the first-run checklist and the launch card show the explainer with each install command and an **Install page** link, and Start is off
|
||||
- [ ] Each **Install page** link opens the right page in the default browser (Claude Code, Devin, Codex)
|
||||
- [ ] Install an agent (or add a custom one), press **Check again**: it appears and Start turns on without restarting the app
|
||||
- [ ] With only one agent installed and nothing remembered, the launch card starts on that agent, not Claude Code
|
||||
- [ ] Windows: the taskbar button shows a green dot when it is your move and a red dot when Plan2Code needs attention, and no dot while the agent is busy or after it ends
|
||||
- [ ] Windows: with the window unfocused, the button gives one short burst of flashes when it becomes your move or needs attention (not again on a repeat) and stays lit until the window gets focus
|
||||
- [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background
|
||||
- [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused
|
||||
- [ ] Reloading the window, or ending the agent, clears the dot
|
||||
- [ ] User Preferences → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app
|
||||
|
||||
## Standalone path
|
||||
|
||||
- [ ] `/plan2code` typed inside an agent with the app closed opens the dashboard exactly as before
|
||||
|
||||
@@ -139,7 +139,7 @@ pub fn find_on_path(program: &str, path_var: &str) -> Option<PathBuf> {
|
||||
pub fn installed_at(kind: AgentKind) -> Option<PathBuf> {
|
||||
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
|
||||
let program = bin.unwrap_or_else(|| kind.program_name().to_string());
|
||||
find_on_path(&program, crate::node_check::resolved_path())
|
||||
find_on_path(&program, &crate::node_check::resolved_path())
|
||||
}
|
||||
|
||||
/// Whether `kind`'s CLI can be run at all.
|
||||
@@ -244,7 +244,7 @@ fn launch_spec_with(
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
// directories (Task 9.9): the agent CLI itself, and anything it shells
|
||||
// out to, needs a PATH that finds them anyway.
|
||||
let env = vec![("PATH".to_string(), crate::node_check::resolved_path().to_string())];
|
||||
let env = vec![("PATH".to_string(), crate::node_check::resolved_path())];
|
||||
LaunchSpec { program: program.to_string(), args, env, cwd }
|
||||
}
|
||||
|
||||
@@ -546,7 +546,7 @@ impl Agent {
|
||||
Agent::Custom(agent) => {
|
||||
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
|
||||
let command = bin.as_deref().unwrap_or(&agent.command);
|
||||
resolve_command(command, crate::node_check::resolved_path())
|
||||
resolve_command(command, &crate::node_check::resolved_path())
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -566,9 +566,10 @@ pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option<Agent> {
|
||||
agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom)
|
||||
}
|
||||
|
||||
/// Every custom agent in `~/.plan2code/agents.json`, read afresh.
|
||||
pub fn custom_agents() -> Vec<CustomAgent> {
|
||||
agents_file().map(|file| load_custom_agents(&file).0).unwrap_or_default()
|
||||
/// Every custom agent in `~/.plan2code/agents.json`, read afresh, with the
|
||||
/// warnings about anything in the file that was skipped.
|
||||
pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
|
||||
agents_file().map(|file| load_custom_agents(&file)).unwrap_or_default()
|
||||
}
|
||||
|
||||
fn clean_command(command: &str) -> &str {
|
||||
@@ -644,7 +645,7 @@ pub fn agent_launch_spec(
|
||||
model,
|
||||
mode,
|
||||
prompt,
|
||||
crate::node_check::resolved_path(),
|
||||
&crate::node_check::resolved_path(),
|
||||
cfg!(windows),
|
||||
)
|
||||
}
|
||||
@@ -668,6 +669,7 @@ fn custom_launch_spec(
|
||||
let mut path = base_path.to_string();
|
||||
let mut program =
|
||||
resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned());
|
||||
let mut extra_env = Vec::new();
|
||||
if windows {
|
||||
let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) {
|
||||
@@ -680,13 +682,36 @@ fn custom_launch_spec(
|
||||
path = format!("{};{}", dir.to_string_lossy(), base_path);
|
||||
}
|
||||
}
|
||||
let mut wrapped = vec!["/c".to_string(), file_name];
|
||||
wrapped.append(&mut args);
|
||||
args = wrapped;
|
||||
// The pseudo-terminal quotes only arguments with a space or a quote,
|
||||
// so `cmd` would read `&`, `|` or `%` in the rest itself. The line is
|
||||
// quoted as the launcher's `quoteForCmd` does and handed over in a
|
||||
// variable: `cmd` expands it once and then parses it, so its quotes
|
||||
// hold and a `%` inside it is not expanded again.
|
||||
let line: Vec<String> = std::iter::once(file_name).chain(args).map(|arg| quote_for_cmd(&arg)).collect();
|
||||
extra_env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
|
||||
// `cmd` looks in the current folder (the project) before PATH: a
|
||||
// same-named file there must not run in the agent's place.
|
||||
extra_env.push(("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
|
||||
args = vec!["/d".to_string(), "/c".to_string(), format!("%{CMD_LINE_ENV}%")];
|
||||
program = "cmd".to_string();
|
||||
}
|
||||
}
|
||||
LaunchSpec { program, args, env: vec![("PATH".to_string(), path)], cwd: folder.to_path_buf() }
|
||||
let mut env = vec![("PATH".to_string(), path)];
|
||||
env.append(&mut extra_env);
|
||||
LaunchSpec { program, args, env, cwd: folder.to_path_buf() }
|
||||
}
|
||||
|
||||
/// The variable a custom `.cmd` or `.bat` agent's command line reaches `cmd` in.
|
||||
const CMD_LINE_ENV: &str = "PLAN2CODE_AGENT_LINE";
|
||||
|
||||
/// One argument of a `cmd` line, quoted when `cmd` would otherwise read it: the
|
||||
/// launcher's `quoteForCmd`.
|
||||
fn quote_for_cmd(arg: &str) -> String {
|
||||
let special = |c: char| c.is_whitespace() || "\"&|<>^%!()".contains(c);
|
||||
if !arg.is_empty() && !arg.chars().any(special) {
|
||||
return arg.to_string();
|
||||
}
|
||||
format!("\"{}\"", arg.replace('"', "\"\""))
|
||||
}
|
||||
|
||||
/// The page a built-in agent installs from; any other id is an error.
|
||||
@@ -1013,26 +1038,55 @@ mod tests {
|
||||
let found = Path::new("C:\\with space").join("goose.cmd");
|
||||
let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!(spec.program, "cmd");
|
||||
assert_eq!(spec.args, ["/c", "goose.cmd", "/p"]);
|
||||
assert_eq!(spec.args, ["/d", "/c", "%PLAN2CODE_AGENT_LINE%"]);
|
||||
assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy()));
|
||||
assert_eq!(spec.env[1], ("PLAN2CODE_AGENT_LINE".to_string(), "goose.cmd /p".to_string()));
|
||||
assert_eq!(spec.env[2], ("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
|
||||
// A bare name keeps the plain PATH.
|
||||
let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_line_quotes_what_cmd_would_read_as_the_launcher_does() {
|
||||
assert_eq!(quote_for_cmd("--yes"), "--yes");
|
||||
assert_eq!(quote_for_cmd(""), "\"\"");
|
||||
assert_eq!(quote_for_cmd("a|b"), "\"a|b\"");
|
||||
assert_eq!(quote_for_cmd("%X%"), "\"%X%\"");
|
||||
assert_eq!(quote_for_cmd("say \"hi\""), "\"say \"\"hi\"\"\"");
|
||||
let mut agent = goose();
|
||||
agent.args = vec!["--filter=a|b".to_string(), "{prompt}".to_string()];
|
||||
let found = Path::new("C:\\tools").join("goose.cmd");
|
||||
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p & x", "BASE", true);
|
||||
assert_eq!(spec.env[1].1, "goose.cmd \"--filter=a|b\" \"/p & x\"");
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn a_full_path_cmd_in_a_spaced_folder_resolves_and_wraps() {
|
||||
let dir = temp_dir("spaced").join("with space");
|
||||
fn a_full_path_cmd_in_a_spaced_folder_runs_with_its_arguments_intact_and_not_a_project_copy() {
|
||||
let root = temp_dir("spaced");
|
||||
let dir = root.join("with space");
|
||||
let project = root.join("project");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("goose.cmd"), "@echo off").unwrap();
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::fs::write(dir.join("goose.cmd"), "@echo off\r\necho REAL [%1] [%2]\r\n").unwrap();
|
||||
// A same-named file in the project folder must not run instead.
|
||||
std::fs::write(project.join("goose.cmd"), "@echo off\r\necho DECOY\r\n").unwrap();
|
||||
let mut agent = goose();
|
||||
agent.command = dir.join("goose.cmd").to_string_lossy().into_owned();
|
||||
agent.args = vec!["a|b".to_string(), "%PATH%".to_string()];
|
||||
let found = Agent::Custom(agent.clone()).installed_at().expect("resolves");
|
||||
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!((spec.program.as_str(), spec.args[1].as_str()), ("cmd", "goose.cmd"));
|
||||
assert!(spec.env[0].1.starts_with(&dir.to_string_lossy().to_string()));
|
||||
let _ = std::fs::remove_dir_all(dir.parent().unwrap());
|
||||
let spec = custom_launch_spec(&agent, Some(&found), &project, None, PermissionMode::Checked, "", &std::env::var("PATH").unwrap_or_default(), true);
|
||||
let mut command = std::process::Command::new(&spec.program);
|
||||
// Some shells already set the switch the spec sets; start without it.
|
||||
command.args(&spec.args).current_dir(&spec.cwd).env_remove("NoDefaultCurrentDirectoryInExePath");
|
||||
for (key, value) in &spec.env {
|
||||
command.env(key, value);
|
||||
}
|
||||
let out = command.output().expect("cmd runs");
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
assert_eq!(text.trim(), "REAL [\"a|b\"] [\"%PATH%\"]", "{text}");
|
||||
let _ = std::fs::remove_dir_all(&root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -0,0 +1,234 @@
|
||||
//! The taskbar entry's attention signal. It decides which of four states the
|
||||
//! desktop app is in (busy, ready, attention, plain), which badge the platform
|
||||
//! shows for that state, whether a change into a state that wants the person
|
||||
//! should flash the window, and the pixels of the colored dot. The states and
|
||||
//! the dot colors mirror the web console's favicon. Knows nothing about Tauri.
|
||||
//! The caller turns these decisions into calls on the window.
|
||||
|
||||
/// What Plan2Code is doing, as the web console's favicon shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Signal {
|
||||
Busy,
|
||||
Ready,
|
||||
Attention,
|
||||
Plain,
|
||||
}
|
||||
|
||||
/// The two dot colors the taskbar badge can show.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum DotColor {
|
||||
Green,
|
||||
Red,
|
||||
}
|
||||
|
||||
/// The badge a platform shows on the taskbar entry.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Badge {
|
||||
None,
|
||||
Dot(DotColor),
|
||||
Label(&'static str),
|
||||
Count(i64),
|
||||
}
|
||||
|
||||
/// The default size, in pixels, of the square dot image.
|
||||
pub const DOT_SIZE: u32 = 16;
|
||||
|
||||
const GREEN_HEX: &str = "#22c55e";
|
||||
const RED_HEX: &str = "#e5484d";
|
||||
const RING_HEX: &str = "#3b332c";
|
||||
|
||||
impl Signal {
|
||||
/// The signal named by a favicon state id ("busy", "ready", "attention"
|
||||
/// or "plain"). Any other text is `None`.
|
||||
pub fn from_id(id: &str) -> Option<Signal> {
|
||||
match id {
|
||||
"busy" => Some(Signal::Busy),
|
||||
"ready" => Some(Signal::Ready),
|
||||
"attention" => Some(Signal::Attention),
|
||||
"plain" => Some(Signal::Plain),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The badge for `signal` on the platform named by `os` (the value of
|
||||
/// `std::env::consts::OS`). When the badge is turned off, there is none.
|
||||
/// Windows shows a dot, macOS a "!" label and Linux a count of 1, and only
|
||||
/// for the states that want the person.
|
||||
pub fn badge_for(signal: Signal, os: &str, enabled: bool) -> Badge {
|
||||
if !enabled {
|
||||
return Badge::None;
|
||||
}
|
||||
match (os, signal) {
|
||||
("windows", Signal::Ready) => Badge::Dot(DotColor::Green),
|
||||
("windows", Signal::Attention) => Badge::Dot(DotColor::Red),
|
||||
("macos", Signal::Attention) => Badge::Label("!"),
|
||||
("linux", Signal::Attention) => Badge::Count(1),
|
||||
_ => Badge::None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether the window should flash. It does so only when flashing is on, the
|
||||
/// window is not focused, and the signal just changed into Ready or Attention.
|
||||
/// A repeat of the same signal does not flash again.
|
||||
pub fn should_flash(prev: Option<Signal>, next: Signal, focused: bool, enabled: bool) -> bool {
|
||||
enabled && !focused && matches!(next, Signal::Ready | Signal::Attention) && prev != Some(next)
|
||||
}
|
||||
|
||||
/// The dot as RGBA bytes, row by row: a filled, anti-aliased circle with a
|
||||
/// 1 px dark ring at its edge, on a transparent square of `size` pixels. The
|
||||
/// result is `size * size * 4` bytes long, with straight (not premultiplied)
|
||||
/// alpha.
|
||||
pub fn dot_rgba(color: DotColor, size: u32) -> Vec<u8> {
|
||||
let fill = parse_hex(match color {
|
||||
DotColor::Green => GREEN_HEX,
|
||||
DotColor::Red => RED_HEX,
|
||||
});
|
||||
let ring = parse_hex(RING_HEX);
|
||||
let n = size as usize;
|
||||
let mut out = vec![0u8; n * n * 4];
|
||||
let center = size as f32 / 2.0;
|
||||
let radius = center - 0.5;
|
||||
for y in 0..n {
|
||||
for x in 0..n {
|
||||
// Distance from the pixel's center to the circle's center.
|
||||
let dx = x as f32 + 0.5 - center;
|
||||
let dy = y as f32 + 0.5 - center;
|
||||
let distance = (dx * dx + dy * dy).sqrt();
|
||||
let coverage = (radius + 0.5 - distance).clamp(0.0, 1.0);
|
||||
let rgb = if distance > radius - 1.0 { ring } else { fill };
|
||||
let alpha = (coverage * 255.0).round() as u8;
|
||||
let i = (y * n + x) * 4;
|
||||
out[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The three bytes of a `#rrggbb` color. A malformed pair reads as 0.
|
||||
fn parse_hex(hex: &str) -> [u8; 3] {
|
||||
let digits = hex.strip_prefix('#').unwrap_or(hex);
|
||||
let byte = |i: usize| {
|
||||
digits
|
||||
.get(i..i + 2)
|
||||
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
|
||||
.unwrap_or(0)
|
||||
};
|
||||
[byte(0), byte(2), byte(4)]
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SIGNALS: [Signal; 4] = [Signal::Busy, Signal::Ready, Signal::Attention, Signal::Plain];
|
||||
|
||||
fn pixel(buf: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = ((y * size + x) * 4) as usize;
|
||||
[buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_badge_follows_the_platform_table() {
|
||||
let table: [(Signal, &str, Badge); 16] = [
|
||||
(Signal::Busy, "windows", Badge::None),
|
||||
(Signal::Ready, "windows", Badge::Dot(DotColor::Green)),
|
||||
(Signal::Attention, "windows", Badge::Dot(DotColor::Red)),
|
||||
(Signal::Plain, "windows", Badge::None),
|
||||
(Signal::Busy, "macos", Badge::None),
|
||||
(Signal::Ready, "macos", Badge::None),
|
||||
(Signal::Attention, "macos", Badge::Label("!")),
|
||||
(Signal::Plain, "macos", Badge::None),
|
||||
(Signal::Busy, "linux", Badge::None),
|
||||
(Signal::Ready, "linux", Badge::None),
|
||||
(Signal::Attention, "linux", Badge::Count(1)),
|
||||
(Signal::Plain, "linux", Badge::None),
|
||||
(Signal::Busy, "freebsd", Badge::None),
|
||||
(Signal::Ready, "freebsd", Badge::None),
|
||||
(Signal::Attention, "freebsd", Badge::None),
|
||||
(Signal::Plain, "freebsd", Badge::None),
|
||||
];
|
||||
for (signal, os, want) in table {
|
||||
assert_eq!(badge_for(signal, os, true), want, "{signal:?} on {os}, enabled");
|
||||
assert_eq!(badge_for(signal, os, false), Badge::None, "{signal:?} on {os}, disabled");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn from_id_reads_the_four_words_and_refuses_the_rest() {
|
||||
assert_eq!(Signal::from_id("busy"), Some(Signal::Busy));
|
||||
assert_eq!(Signal::from_id("ready"), Some(Signal::Ready));
|
||||
assert_eq!(Signal::from_id("attention"), Some(Signal::Attention));
|
||||
assert_eq!(Signal::from_id("plain"), Some(Signal::Plain));
|
||||
assert_eq!(Signal::from_id("sleeping"), None);
|
||||
assert_eq!(Signal::from_id("Ready"), None, "the ids are lowercase");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_change_into_ready_or_attention_flashes_when_unfocused() {
|
||||
assert!(should_flash(Some(Signal::Busy), Signal::Ready, false, true));
|
||||
assert!(should_flash(None, Signal::Attention, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_while_the_window_is_focused() {
|
||||
assert!(!should_flash(Some(Signal::Busy), Signal::Ready, true, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_for_a_repeat_of_the_same_signal() {
|
||||
assert!(!should_flash(Some(Signal::Ready), Signal::Ready, false, true));
|
||||
assert!(!should_flash(Some(Signal::Attention), Signal::Attention, false, true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_for_busy_or_plain() {
|
||||
for prev in [None, Some(Signal::Ready), Some(Signal::Attention)] {
|
||||
assert!(!should_flash(prev, Signal::Busy, false, true), "busy from {prev:?}");
|
||||
assert!(!should_flash(prev, Signal::Plain, false, true), "plain from {prev:?}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_when_flashing_is_turned_off() {
|
||||
for signal in SIGNALS.iter().copied() {
|
||||
assert!(!should_flash(Some(Signal::Busy), signal, false, false), "{signal:?} while disabled");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parse_hex_reads_the_byte_pairs() {
|
||||
assert_eq!(parse_hex("#22c55e"), [0x22, 0xc5, 0x5e]);
|
||||
assert_eq!(parse_hex("e5484d"), [0xe5, 0x48, 0x4d]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_green_dot_is_a_transparent_square_with_a_filled_middle() {
|
||||
let size = DOT_SIZE;
|
||||
let buf = dot_rgba(DotColor::Green, size);
|
||||
assert_eq!(buf.len(), (size * size * 4) as usize);
|
||||
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
|
||||
let center = pixel(&buf, size, 8, 8);
|
||||
assert_eq!(center[3], 255, "the middle is opaque");
|
||||
assert_eq!(¢er[..3], &parse_hex(GREEN_HEX)[..], "the middle is the green fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_red_dot_is_a_transparent_square_with_a_filled_middle() {
|
||||
let size = DOT_SIZE;
|
||||
let buf = dot_rgba(DotColor::Red, size);
|
||||
assert_eq!(buf.len(), (size * size * 4) as usize);
|
||||
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
|
||||
let center = pixel(&buf, size, 8, 8);
|
||||
assert_eq!(center[3], 255, "the middle is opaque");
|
||||
assert_eq!(¢er[..3], &parse_hex(RED_HEX)[..], "the middle is the red fill");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_colors_match_the_web_console_favicon() {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../src/web-console/public/favicon.js");
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
assert!(text.contains(&format!("ready: \"{GREEN_HEX}\"")), "ready color in favicon.js");
|
||||
assert!(text.contains(&format!("attention: \"{RED_HEX}\"")), "attention color in favicon.js");
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
pub mod agent_manager;
|
||||
pub mod agents;
|
||||
pub mod announce;
|
||||
pub mod attention;
|
||||
pub mod brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod handoff;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
// Hide the extra console window on Windows release builds.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
|
||||
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
|
||||
use plan2code_app_lib::attention::{self, Badge, Signal};
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, session_on_disk, ConsoleSupervisor};
|
||||
use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
@@ -37,6 +38,24 @@ struct AppState {
|
||||
// (Task 9.9): the first-run checklist's Node row names both.
|
||||
node_version: Option<String>,
|
||||
node_binary: Option<String>,
|
||||
// What the taskbar entry last said, and whether it may say anything.
|
||||
attention: Mutex<AttentionState>,
|
||||
// The app itself, once it is set up: the agent's sink clears the taskbar
|
||||
// through it when the agent ends.
|
||||
app: Arc<OnceLock<tauri::AppHandle>>,
|
||||
}
|
||||
|
||||
// The console page's last state as the taskbar shows it (attention.rs), and
|
||||
// the Desktop app switch, `taskbarSignal` in app.json.
|
||||
struct AttentionState {
|
||||
last: Option<Signal>,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
impl Default for AttentionState {
|
||||
fn default() -> Self {
|
||||
AttentionState { last: None, enabled: true }
|
||||
}
|
||||
}
|
||||
|
||||
// The operating system and, on Windows, the build number xterm needs for ConPTY.
|
||||
@@ -47,9 +66,15 @@ fn platform_info() -> serde_json::Value {
|
||||
}
|
||||
|
||||
// What the launch card offers per agent: whether its CLI is on PATH (else how
|
||||
// to install it), and whether it takes its own reasoning effort.
|
||||
// to install it), and whether it takes its own reasoning effort; plus the
|
||||
// warnings about agents.json.
|
||||
#[tauri::command]
|
||||
fn agent_availability() -> serde_json::Value {
|
||||
fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
|
||||
// "Check again" also works the PATH out again, so a CLI whose installer
|
||||
// added a new folder to it is found without restarting the app.
|
||||
if refresh == Some(true) {
|
||||
node_check::refresh_path();
|
||||
}
|
||||
// Built-ins first, then the custom agents, read afresh on every call so
|
||||
// "Check again" sees a change to agents.json.
|
||||
let mut entries: Vec<_> = AgentKind::ALL
|
||||
@@ -70,7 +95,8 @@ fn agent_availability() -> serde_json::Value {
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
for custom in agents::custom_agents() {
|
||||
let (customs, warnings) = agents::custom_agents();
|
||||
for custom in customs {
|
||||
let at = Agent::Custom(custom.clone()).installed_at();
|
||||
entries.push(serde_json::json!({
|
||||
"id": custom.id,
|
||||
@@ -84,7 +110,9 @@ fn agent_availability() -> serde_json::Value {
|
||||
"models": custom.models,
|
||||
}));
|
||||
}
|
||||
serde_json::json!(entries)
|
||||
// What was skipped in agents.json, so a custom agent that vanished from
|
||||
// the picker is explained, as the launcher and the console do.
|
||||
serde_json::json!({ "agents": entries, "warnings": warnings })
|
||||
}
|
||||
|
||||
// Opens a built-in agent install page in the default browser. Any other id
|
||||
@@ -130,9 +158,15 @@ fn windows_build() -> Option<u32> {
|
||||
}
|
||||
|
||||
// Sends the agent's output as raw bytes and its state changes as JSON, on the
|
||||
// page's latest channel. Nothing is sent while no page has registered one.
|
||||
fn page_sink(page: PageChannel) -> Sink {
|
||||
// page's latest channel. Nothing is sent while no page has registered one. An
|
||||
// agent that ends takes the taskbar's dot with it, page or no page.
|
||||
fn page_sink(page: PageChannel, app: Arc<OnceLock<tauri::AppHandle>>) -> Sink {
|
||||
Arc::new(move |event| {
|
||||
if let AgentEvent::State(snapshot) = &event {
|
||||
if let (AgentState::Ended { .. }, Some(app)) = (&snapshot.state, app.get()) {
|
||||
clear_attention(app);
|
||||
}
|
||||
}
|
||||
let Ok(guard) = page.lock() else { return };
|
||||
let Some(channel) = guard.as_ref() else { return };
|
||||
let body = match event {
|
||||
@@ -162,7 +196,7 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||
return Ok(Arc::clone(agent));
|
||||
}
|
||||
}
|
||||
let sink = page_sink(Arc::clone(&state.page));
|
||||
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app));
|
||||
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||
agent.set_before_fresh(before_fresh_hook(state));
|
||||
*guard = Some(Arc::clone(&agent));
|
||||
@@ -361,6 +395,99 @@ fn quit_app(app: &tauri::AppHandle) {
|
||||
app.exit(0);
|
||||
}
|
||||
|
||||
// The console page's state, told on every change (`attention` from the page):
|
||||
// the taskbar's dot for this system, and one flash on a change into the
|
||||
// person's move or needs attention while the window is not focused. An
|
||||
// unknown word does nothing.
|
||||
#[tauri::command]
|
||||
fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) {
|
||||
let Some(next) = Signal::from_id(&signal) else { return };
|
||||
let Some(window) = app.get_webview_window("main") else { return };
|
||||
let (prev, enabled) = {
|
||||
let Ok(mut guard) = state.attention.lock() else { return };
|
||||
(guard.last.replace(next), guard.enabled)
|
||||
};
|
||||
apply_badge(&window, attention::badge_for(next, std::env::consts::OS, enabled));
|
||||
if attention::should_flash(prev, next, window.is_focused().unwrap_or(true), enabled) {
|
||||
let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational));
|
||||
}
|
||||
}
|
||||
|
||||
// The one place a badge reaches the window, in each system's own form. A call
|
||||
// that fails changes nothing else: the taskbar is a hint, never a blocker.
|
||||
#[cfg_attr(not(any(target_os = "windows", target_os = "macos", target_os = "linux")), allow(unused_variables))]
|
||||
fn apply_badge(window: &tauri::WebviewWindow, badge: Badge) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
let icon = match badge {
|
||||
Badge::Dot(color) => Some(tauri::image::Image::new_owned(
|
||||
attention::dot_rgba(color, attention::DOT_SIZE),
|
||||
attention::DOT_SIZE,
|
||||
attention::DOT_SIZE,
|
||||
)),
|
||||
_ => None,
|
||||
};
|
||||
let _ = window.set_overlay_icon(icon);
|
||||
}
|
||||
#[cfg(target_os = "macos")]
|
||||
{
|
||||
let label = match badge {
|
||||
Badge::Label(text) => Some(text.to_string()),
|
||||
_ => None,
|
||||
};
|
||||
let _ = window.set_badge_label(label);
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
let count = match badge {
|
||||
Badge::Count(count) => Some(count),
|
||||
_ => None,
|
||||
};
|
||||
let _ = window.set_badge_count(count);
|
||||
}
|
||||
}
|
||||
|
||||
// No dot and no flash: the agent ended, the page went away, or the switch was
|
||||
// turned off. The next state the page tells starts from plain.
|
||||
fn clear_attention(app: &tauri::AppHandle) {
|
||||
if let Ok(mut guard) = app.state::<AppState>().attention.lock() {
|
||||
guard.last = Some(Signal::Plain);
|
||||
}
|
||||
let Some(window) = app.get_webview_window("main") else { return };
|
||||
apply_badge(&window, Badge::None);
|
||||
let _ = window.request_user_attention(None);
|
||||
}
|
||||
|
||||
// The app page clears it when a new page loads in the frame or none answers.
|
||||
#[tauri::command]
|
||||
fn clear_attention_cmd(app: tauri::AppHandle) {
|
||||
clear_attention(&app);
|
||||
}
|
||||
|
||||
// The Desktop app switch in the console's User Preferences (`taskbar` from the
|
||||
// page). Off clears the dot and stops flashes; on shows the dot for the state
|
||||
// the page last told at once, since the page only tells it again on a change.
|
||||
// Either way the last state is kept. Saved in the app's own app.json, never
|
||||
// in the console's files.
|
||||
#[tauri::command]
|
||||
fn set_taskbar_signal(app: tauri::AppHandle, state: State<'_, AppState>, on: bool) -> Result<(), String> {
|
||||
let saved = settings::settings_file()
|
||||
.ok_or_else(|| "no home folder found".to_string())
|
||||
.and_then(|file| settings::save_taskbar_signal(&file, on));
|
||||
let last = {
|
||||
let Ok(mut guard) = state.attention.lock() else { return saved };
|
||||
guard.enabled = on;
|
||||
guard.last.unwrap_or(Signal::Plain)
|
||||
};
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
apply_badge(&window, attention::badge_for(last, std::env::consts::OS, on));
|
||||
if !on {
|
||||
let _ = window.request_user_attention(None);
|
||||
}
|
||||
}
|
||||
saved
|
||||
}
|
||||
|
||||
/// What the page draws its bar from: the folder (or that none is chosen yet)
|
||||
/// and the agent the picker starts on.
|
||||
#[tauri::command]
|
||||
@@ -402,6 +529,8 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
// or launch card shown.
|
||||
"autoStart": state.launch.agent,
|
||||
"termPanel": term_panel,
|
||||
// The Desktop app switch, for the page's User Preferences.
|
||||
"taskbarSignal": state.attention.lock().map_or(true, |guard| guard.enabled),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -499,7 +628,7 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
|
||||
/// the old one (its agent stopped, its console stopped) before the new
|
||||
/// folder is remembered, so `agent_for_project` and `console_start` start
|
||||
/// fresh for it rather than reusing anything from the one just left. Picking
|
||||
/// nothing (cancelled) leaves the current project untouched. One project per
|
||||
/// nothing (canceled) leaves the current project untouched. One project per
|
||||
/// window stays; this replaces it, it does not add a second.
|
||||
#[tauri::command]
|
||||
fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||
@@ -580,6 +709,10 @@ fn main() {
|
||||
launch: project::launch_choice(&args),
|
||||
node_version,
|
||||
node_binary,
|
||||
attention: Mutex::new(AttentionState {
|
||||
last: None,
|
||||
enabled: settings::settings_file().map_or(true, |file| settings::load_taskbar_signal(&file)),
|
||||
}),
|
||||
..AppState::default()
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
@@ -600,9 +733,16 @@ fn main() {
|
||||
change_project,
|
||||
console_start,
|
||||
console_status,
|
||||
console_stop
|
||||
console_stop,
|
||||
set_attention,
|
||||
clear_attention_cmd,
|
||||
set_taskbar_signal
|
||||
])
|
||||
.on_window_event(|window, event| {
|
||||
// Looking at the window is the answer to its flash.
|
||||
if let tauri::WindowEvent::Focused(true) = event {
|
||||
let _ = window.request_user_attention(None);
|
||||
}
|
||||
// Closing with an agent running asks first; "no" keeps the window open.
|
||||
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
|
||||
let app = window.app_handle().clone();
|
||||
@@ -613,6 +753,7 @@ fn main() {
|
||||
}
|
||||
})
|
||||
.setup(move |app| {
|
||||
let _ = app.state::<AppState>().app.set(app.handle().clone());
|
||||
// Pages the agent's `open` announces: the supervisor and the agent's
|
||||
// environment follow the console, and the page frame shows it.
|
||||
let handle = app.handle().clone();
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
//! `console_supervisor`, `versions` and `agents` all use it.
|
||||
|
||||
use std::process::Command;
|
||||
use std::sync::OnceLock;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub const MIN_NODE_MAJOR: u32 = 18;
|
||||
|
||||
@@ -73,30 +73,110 @@ fn login_shell_path() -> Option<String> {
|
||||
(out.status.success() && !path.is_empty()).then_some(path)
|
||||
}
|
||||
|
||||
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// The PATH every process this app spawns should run with: an explicit
|
||||
/// `--node`'s directory first, then (macOS and Linux) the login shell's own
|
||||
/// PATH, then this process's own PATH, each included only once. Resolved
|
||||
/// once per launch: none of these change while the app runs.
|
||||
pub fn resolved_path() -> &'static str {
|
||||
static PATH: OnceLock<String> = OnceLock::new();
|
||||
PATH.get_or_init(|| {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let inherited = std::env::var("PATH").unwrap_or_default();
|
||||
let mut parts = Vec::new();
|
||||
if let Some(dir) = node_override_dir(&args) {
|
||||
parts.push(dir);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if let Some(login) = login_shell_path() {
|
||||
parts.push(login);
|
||||
}
|
||||
if !inherited.is_empty() {
|
||||
parts.push(inherited);
|
||||
}
|
||||
parts.join(if cfg!(windows) { ";" } else { ":" })
|
||||
/// PATH, then this process's own PATH, each included only once. Worked out
|
||||
/// once per launch, and again only on `refresh_path`.
|
||||
pub fn resolved_path() -> String {
|
||||
let mut cached = RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner());
|
||||
cached.get_or_insert_with(|| build_path(false)).clone()
|
||||
}
|
||||
|
||||
/// Work the PATH out again, for "Check again" after an agent CLI was
|
||||
/// installed: an installer may have added a folder (the login shell's
|
||||
/// profile on macOS and Linux, the saved user or system PATH on Windows)
|
||||
/// that this process's own PATH has never had.
|
||||
pub fn refresh_path() {
|
||||
let fresh = build_path(true);
|
||||
*RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
|
||||
}
|
||||
|
||||
fn build_path(fresh: bool) -> String {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let inherited = std::env::var("PATH").unwrap_or_default();
|
||||
let mut parts = Vec::new();
|
||||
if let Some(dir) = node_override_dir(&args) {
|
||||
parts.push(dir);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if let Some(login) = login_shell_path() {
|
||||
parts.push(login);
|
||||
}
|
||||
// At start this process's PATH already is the saved one; only a refresh
|
||||
// needs to read it again.
|
||||
#[cfg(windows)]
|
||||
if fresh {
|
||||
parts.extend(saved_windows_path());
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
let _ = fresh;
|
||||
if !inherited.is_empty() {
|
||||
parts.push(inherited);
|
||||
}
|
||||
parts.join(if cfg!(windows) { ";" } else { ":" })
|
||||
}
|
||||
|
||||
/// The system then the user PATH as saved in the registry, with `%NAME%`
|
||||
/// expanded: what a newly opened terminal would get.
|
||||
#[cfg(windows)]
|
||||
fn saved_windows_path() -> Vec<String> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let keys = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
|
||||
keys.iter()
|
||||
.filter_map(|key| {
|
||||
let out = Command::new("reg")
|
||||
.args(["query", key, "/v", "Path"])
|
||||
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
|
||||
.output()
|
||||
.ok()?;
|
||||
let value = parse_reg_query_value(&String::from_utf8_lossy(&out.stdout))?;
|
||||
Some(expand_percent_vars(&value, |name| std::env::var(name).ok()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The value from `reg query <key> /v <name>` output: the text after the
|
||||
/// `REG_SZ` or `REG_EXPAND_SZ` column on its line.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn parse_reg_query_value(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
let (_, rest) = line.split_once("REG_EXPAND_SZ").or_else(|| line.split_once("REG_SZ"))?;
|
||||
let value = rest.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
})
|
||||
}
|
||||
|
||||
/// `%NAME%` replaced with `lookup(NAME)`; an unknown name stays as written.
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
|
||||
let mut out = String::new();
|
||||
let mut rest = text;
|
||||
while let Some(start) = rest.find('%') {
|
||||
out.push_str(&rest[..start]);
|
||||
let after = &rest[start + 1..];
|
||||
match after.find('%') {
|
||||
Some(end) if end > 0 => match lookup(&after[..end]) {
|
||||
Some(value) => {
|
||||
out.push_str(&value);
|
||||
rest = &after[end + 1..];
|
||||
}
|
||||
None => {
|
||||
out.push('%');
|
||||
rest = after;
|
||||
}
|
||||
},
|
||||
_ => {
|
||||
out.push('%');
|
||||
rest = after;
|
||||
}
|
||||
}
|
||||
}
|
||||
out.push_str(rest);
|
||||
out
|
||||
}
|
||||
|
||||
/// Where `node` actually resolves, with `resolved_path`: for the first-run
|
||||
/// checklist to name (Task 9.9), not for `check_node` itself to decide with.
|
||||
pub fn node_binary_path() -> Option<String> {
|
||||
@@ -172,4 +252,29 @@ mod tests {
|
||||
assert_eq!(node_override_dir(&args(&["--node="])), None);
|
||||
assert_eq!(node_override_dir(&args(&["--agent", "claude"])), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_saved_path_out_of_reg_query_output() {
|
||||
let out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.local\\bin;C:\\Tools\r\n\r\n";
|
||||
assert_eq!(parse_reg_query_value(out).as_deref(), Some("%USERPROFILE%\\.local\\bin;C:\\Tools"));
|
||||
let plain = "HKEY_LOCAL_MACHINE\\x\r\n Path REG_SZ C:\\Windows\r\n";
|
||||
assert_eq!(parse_reg_query_value(plain).as_deref(), Some("C:\\Windows"));
|
||||
assert_eq!(parse_reg_query_value("ERROR: The system was unable to find the specified registry key or value.\r\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_known_percent_names_and_keeps_the_rest() {
|
||||
let lookup = |name: &str| (name == "USERPROFILE").then(|| "C:\\Users\\sam".to_string());
|
||||
assert_eq!(expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup), "C:\\Users\\sam\\.local\\bin;C:\\x");
|
||||
assert_eq!(expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup), "%NOPE%\\bin;C:\\Users\\sam");
|
||||
assert_eq!(expand_percent_vars("50%", lookup), "50%");
|
||||
assert_eq!(expand_percent_vars("a%%b", lookup), "a%%b");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refresh_path_keeps_this_process_path() {
|
||||
refresh_path();
|
||||
let inherited = std::env::var("PATH").unwrap_or_default();
|
||||
assert!(resolved_path().ends_with(&inherited));
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ impl PtyHost {
|
||||
|
||||
let mut command = CommandBuilder::new(&options.program);
|
||||
command.args(&options.args);
|
||||
// What the agent CLIs expect from a terminal that can show colour.
|
||||
// What the agent CLIs expect from a terminal that can show color.
|
||||
command.env("TERM", "xterm-256color");
|
||||
command.env("COLORTERM", "truecolor");
|
||||
for (key, value) in &options.env {
|
||||
|
||||
@@ -9,6 +9,7 @@ const TERM_DOCK_KEY: &str = "termDock";
|
||||
const TERM_FRACTION_KEY: &str = "termFraction";
|
||||
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
|
||||
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
|
||||
const TASKBAR_SIGNAL_KEY: &str = "taskbarSignal";
|
||||
|
||||
/// The terminal pane's remembered shape: which edge it docks to, how much of
|
||||
/// the window it takes (a fraction, not collapsed or maximized), and whether
|
||||
@@ -100,6 +101,20 @@ pub fn save_first_run_done(file: &Path) -> Result<(), String> {
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// Whether the taskbar entry shows when Plan2Code needs the person (the
|
||||
/// Desktop app switch in the console's User Preferences). On unless the file
|
||||
/// says `false`; anything but a boolean reads as on.
|
||||
pub fn load_taskbar_signal(file: &Path) -> bool {
|
||||
read(file).get(TASKBAR_SIGNAL_KEY).and_then(|v| v.as_bool()).unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Save the switch, keeping any other key the file holds.
|
||||
pub fn save_taskbar_signal(file: &Path, on: bool) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(TASKBAR_SIGNAL_KEY.to_string(), serde_json::Value::Bool(on));
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
@@ -187,6 +202,21 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_taskbar_signal_is_on_until_it_is_switched_off() {
|
||||
assert!(load_taskbar_signal(&temp_file("taskbar-missing")));
|
||||
let file = temp_file("taskbar");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1, "taskbarSignal": "no"}"#).unwrap();
|
||||
assert!(load_taskbar_signal(&file), "not a boolean reads as on");
|
||||
save_taskbar_signal(&file, false).unwrap();
|
||||
assert!(!load_taskbar_signal(&file));
|
||||
save_taskbar_signal(&file, true).unwrap();
|
||||
assert!(load_taskbar_signal(&file));
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_dock_or_out_of_range_fraction_on_disk_reads_as_the_default() {
|
||||
let file = temp_file("term-bad-load");
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, Once};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
|
||||
use plan2code_app_lib::agents::{Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
|
||||
use plan2code_app_lib::agents::{agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
|
||||
|
||||
mod common;
|
||||
use common::process_alive;
|
||||
@@ -299,3 +299,22 @@ fn an_agent_with_no_signal_set_gets_none() {
|
||||
assert!(!h.seen.contains("ENV PLAN2CODE_IN_APP=1"));
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
|
||||
let mut h = Harness::new();
|
||||
// Its command is nowhere on PATH: the override replaces it, as for a built-in.
|
||||
let (mut agents, warnings) = parse_agents_file(r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let goose = Agent::Custom(agents.remove(0));
|
||||
let spec = agent_launch_spec(&goose, &std::env::temp_dir(), Some("m"), None, PermissionMode::Bypass, "/plan2code");
|
||||
assert_eq!(PathBuf::from(&spec.program), common::fake_agent());
|
||||
assert!(spec.args.is_empty());
|
||||
h.manager.start(goose, None, None, PermissionMode::Checked, None).expect("start the custom agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()));
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()), "restart must keep the custom agent");
|
||||
h.manager.stop();
|
||||
}
|
||||
+37
-7
@@ -2,7 +2,7 @@
|
||||
// agent's terminal panel docked at the bottom with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor } from './meter.js';
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
@@ -26,6 +26,7 @@ const barRowEl = document.getElementById('bar-row');
|
||||
const launchCard = document.getElementById('launch-card');
|
||||
const launchAgentEl = document.getElementById('launch-agent');
|
||||
const launchMissingEl = document.getElementById('launch-missing');
|
||||
const launchWarningEl = document.getElementById('launch-agents-warning');
|
||||
const launchModelEl = document.getElementById('launch-model');
|
||||
const launchModelListEl = document.getElementById('launch-model-list');
|
||||
const launchEffortRow = document.getElementById('launch-effort-row');
|
||||
@@ -267,14 +268,21 @@ function confirmRestart(onYes) {
|
||||
// keeps the order Rust sent (built-ins, then custom agents); the map is by id.
|
||||
let agentList = [];
|
||||
let agentAvailability = {};
|
||||
// What was skipped in agents.json, shown under the picker.
|
||||
let agentWarnings = [];
|
||||
|
||||
async function loadAgentAvailability() {
|
||||
// `refresh` (Check again) also has the app work its PATH out again, so a CLI
|
||||
// whose installer added a new folder is found without a restart.
|
||||
async function loadAgentAvailability(refresh = false) {
|
||||
try {
|
||||
agentList = await invoke('agent_availability');
|
||||
const result = await invoke('agent_availability', { refresh });
|
||||
agentList = result.agents || [];
|
||||
agentWarnings = result.warnings || [];
|
||||
agentAvailability = Object.fromEntries(agentList.map((entry) => [entry.id, entry]));
|
||||
} catch {
|
||||
// Nothing to show is not a reason to block the card: Start just tries it.
|
||||
agentList = [];
|
||||
agentWarnings = [];
|
||||
agentAvailability = {};
|
||||
}
|
||||
}
|
||||
@@ -346,7 +354,7 @@ function noAgentExplainer() {
|
||||
// Re-read the agents from disk (a CLI installed or a custom agent added since),
|
||||
// then redraw whatever shows them and pick the default again.
|
||||
async function checkAgentsAgain() {
|
||||
await loadAgentAvailability();
|
||||
await loadAgentAvailability(true);
|
||||
applyDefaultAgent((appState && appState.lastAgent) || launchAgentEl.value);
|
||||
if (!firstRunEl.hidden && appState) renderFirstRun(appState);
|
||||
}
|
||||
@@ -371,6 +379,8 @@ function refreshLaunchCard() {
|
||||
}
|
||||
}
|
||||
}
|
||||
launchWarningEl.hidden = agentWarnings.length === 0;
|
||||
launchWarningEl.textContent = agentWarnings.map((warning) => `agents.json: ${warning}`).join('\n');
|
||||
// A custom agent has no separate effort, and offers its models as
|
||||
// suggestions in the (still free-text) model field.
|
||||
launchModelListEl.replaceChildren();
|
||||
@@ -626,13 +636,20 @@ let consoleKnown = false;
|
||||
function loadFrame(url) {
|
||||
currentUrl = url;
|
||||
frameReady = false;
|
||||
// The page going away takes its taskbar dot with it; the new one tells its own.
|
||||
clearAttention();
|
||||
clearTimeout(helloTimer);
|
||||
helloTimer = setTimeout(onNoHello, HELLO_WAIT_MS);
|
||||
frame.src = url;
|
||||
}
|
||||
|
||||
function clearAttention() {
|
||||
invoke('clear_attention_cmd').catch(() => {});
|
||||
}
|
||||
|
||||
// What the console page may ask of this window. Each is a named request with
|
||||
// no free text, so the page can never type anything but "continue".
|
||||
// no free text, so the page can never type anything but "continue", and the
|
||||
// taskbar's two take only their fixed words and a boolean (meter.js).
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.source !== frame.contentWindow) return;
|
||||
const kind = event.data && event.data.plan2code;
|
||||
@@ -640,6 +657,17 @@ window.addEventListener('message', (event) => {
|
||||
frameReady = true;
|
||||
clearTimeout(helloTimer);
|
||||
hideState();
|
||||
// The Desktop app switch in its User Preferences shows what app.json holds.
|
||||
const on = !appState || appState.taskbarSignal !== false;
|
||||
event.source.postMessage({ plan2code: 'taskbar-state', on }, '*');
|
||||
} else if (kind === 'attention') {
|
||||
const signal = attentionSignal(event.data);
|
||||
if (signal) invoke('set_attention', { signal }).catch(() => {});
|
||||
} else if (kind === 'taskbar') {
|
||||
const on = taskbarSwitch(event.data);
|
||||
if (on === null) return;
|
||||
if (appState) appState.taskbarSignal = on;
|
||||
invoke('set_taskbar_signal', { on }).catch(() => {});
|
||||
} else if (kind === 'agent-continue') {
|
||||
typeContinue();
|
||||
} else if (kind === 'new-session') {
|
||||
@@ -697,6 +725,8 @@ try {
|
||||
// No hello in time: ask the console why, and say so with a way forward.
|
||||
async function onNoHello() {
|
||||
if (frameReady || !consoleKnown || restarting) return;
|
||||
// A page that does not answer cannot say it is done needing the person.
|
||||
clearAttention();
|
||||
let status = null;
|
||||
try {
|
||||
status = await invoke('console_status');
|
||||
@@ -901,7 +931,7 @@ function setProjectDir(dir) {
|
||||
// checklist both need it once a folder lands, after the fact.
|
||||
let appState = null;
|
||||
|
||||
// Opens the OS folder picker. A cancelled pick (or a failed one) lands on the
|
||||
// Opens the OS folder picker. A canceled pick (or a failed one) lands on the
|
||||
// "No project folder chosen" state with a button that tries again.
|
||||
async function pickFolder() {
|
||||
try {
|
||||
@@ -930,7 +960,7 @@ function afterProjectKnown() {
|
||||
|
||||
// Switches to a folder picked fresh: the Rust side tears the old project's
|
||||
// agent and console down before the new one is remembered, so nothing from
|
||||
// it carries over. Picking nothing (cancelled) leaves the current project as
|
||||
// it carries over. Picking nothing (canceled) leaves the current project as
|
||||
// it was.
|
||||
async function doChangeProject() {
|
||||
showState('Choose the new project folder...');
|
||||
|
||||
@@ -89,7 +89,7 @@
|
||||
#dashboard-state[hidden] { display: none; }
|
||||
#dashboard-state-text { margin: 0; max-width: 60ch; overflow-wrap: anywhere; color: #bbb; }
|
||||
#dashboard-state-planny[hidden] { display: none; }
|
||||
/* Drawn and coloured like the console's own Planny (styles/planny.css):
|
||||
/* Drawn and colored like the console's own Planny (styles/planny.css):
|
||||
an outlined shell, the star eye, a lip of a smile, round hands. */
|
||||
#dashboard-state-planny { width: 104px; height: auto; overflow: visible; }
|
||||
#dashboard-state-planny :is(.ps-shell, .ps-smile, .ps-arm path, .ps-mug, .ps-handle) {
|
||||
@@ -146,6 +146,8 @@
|
||||
}
|
||||
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#launch-missing code { color: #ddd; }
|
||||
#launch-agents-warning { margin: 0; font-size: 12px; color: #d7ba7d; white-space: pre-line; }
|
||||
#launch-agents-warning[hidden] { display: none; }
|
||||
.agent-explainer { margin: 0; font-size: 12px; line-height: 1.5; }
|
||||
.agent-explainer ul { margin: 4px 0; padding-left: 18px; }
|
||||
.agent-explainer code { color: #ddd; }
|
||||
@@ -296,6 +298,7 @@
|
||||
<option value="codex">Codex</option>
|
||||
</select>
|
||||
<p id="launch-missing" hidden></p>
|
||||
<p id="launch-agents-warning" hidden></p>
|
||||
<label for="launch-model">Model</label>
|
||||
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off" list="launch-model-list">
|
||||
<datalist id="launch-model-list"></datalist>
|
||||
|
||||
@@ -31,7 +31,9 @@ export function continueKeys(kind) {
|
||||
* (built-ins first, then custom agents): the remembered id when it is
|
||||
* installed, else the first installed built-in, else the first installed
|
||||
* custom agent, else the remembered id or the first entry, so the card's
|
||||
* missing-agent line explains what is wrong instead of picking silently.
|
||||
* missing-agent line explains what is wrong instead of picking silently. A
|
||||
* remembered id the list no longer has (a custom agent deleted since) is not
|
||||
* kept, since the picker could not show it; with no list at all it is.
|
||||
*/
|
||||
export function pickDefaultAgent(availability, remembered) {
|
||||
const list = Array.isArray(availability) ? availability : [];
|
||||
@@ -41,7 +43,7 @@ export function pickDefaultAgent(availability, remembered) {
|
||||
if (builtIn) return builtIn.id;
|
||||
const custom = list.find((a) => a.installed && a.custom);
|
||||
if (custom) return custom.id;
|
||||
if (remembered) return remembered;
|
||||
if (remembered && (rememberedEntry || list.length === 0)) return remembered;
|
||||
return list.length > 0 ? list[0].id : null;
|
||||
}
|
||||
|
||||
@@ -143,3 +145,21 @@ function lastSegment(dir) {
|
||||
.filter(Boolean)
|
||||
.pop();
|
||||
}
|
||||
|
||||
/**
|
||||
* The console page's taskbar messages, checked here before anything reaches
|
||||
* the app (attention.rs decides what they mean). `attention` carries one of
|
||||
* the four states the page's favicon has; `taskbar` carries the Desktop app
|
||||
* switch as a boolean. Anything else is null, and nothing is forwarded.
|
||||
*/
|
||||
export const ATTENTION_STATES = Object.freeze(['busy', 'ready', 'attention', 'plain']);
|
||||
|
||||
export function attentionSignal(data) {
|
||||
const state = data && data.state;
|
||||
return ATTENTION_STATES.includes(state) ? state : null;
|
||||
}
|
||||
|
||||
export function taskbarSwitch(data) {
|
||||
const on = data && data.on;
|
||||
return typeof on === 'boolean' ? on : null;
|
||||
}
|
||||
@@ -106,7 +106,7 @@ export class Controller {
|
||||
clearInterval(elapsedInterval);
|
||||
spinner.stop();
|
||||
|
||||
// Cancelled or interrupted — return immediately, don't retry
|
||||
// Canceled or interrupted — return immediately, don't retry
|
||||
if (result.cancelled || this.interrupted) {
|
||||
return result;
|
||||
}
|
||||
@@ -268,9 +268,9 @@ export class Controller {
|
||||
|
||||
const result = retryResult;
|
||||
|
||||
// Check if cancelled
|
||||
// Check if canceled
|
||||
if (result.cancelled || this.interrupted) {
|
||||
logger.info('Agent process cancelled');
|
||||
logger.info('Agent process canceled');
|
||||
|
||||
const entry: IterationLogEntry = {
|
||||
iteration: iterNum,
|
||||
|
||||
@@ -43,7 +43,7 @@ const CWD = path.resolve(args.cwd || ROOT);
|
||||
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-bench-"));
|
||||
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||
// A fresh cached failure: the boot-time release check stays off the network,
|
||||
// so a slow GitHub never colours the timings.
|
||||
// so a slow GitHub never colors the timings.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
// Resolves at the first stdout line carrying a url, and again at exit.
|
||||
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
@@ -258,3 +258,43 @@ test("pickDefaultAgent with nothing installed returns the remembered id, else th
|
||||
assert.equal(pickDefaultAgent(none, null), "claude");
|
||||
assert.equal(pickDefaultAgent([], null), null);
|
||||
});
|
||||
|
||||
test("pickDefaultAgent drops a remembered id the list no longer has, unless there is no list at all", () => {
|
||||
const none = AVAIL([["claude", false], ["devin", false], ["codex", false]]);
|
||||
// A custom agent deleted since: the picker could not show it, so the first entry it can.
|
||||
assert.equal(pickDefaultAgent(none, "gone"), "claude");
|
||||
// The availability check failed: the fixed options are on the card, the remembered id stands.
|
||||
assert.equal(pickDefaultAgent([], "devin"), "devin");
|
||||
});
|
||||
|
||||
test("the launch card shows agents.json warnings, and Check again asks for a fresh PATH", () => {
|
||||
assert.match(INDEX_HTML, /<p id="launch-agents-warning" hidden><\/p>/);
|
||||
assert.match(APP_JS, /invoke\('agent_availability', \{ refresh \}\)/);
|
||||
assert.match(APP_JS, /async function checkAgentsAgain\(\) \{\n await loadAgentAvailability\(true\);/);
|
||||
});
|
||||
|
||||
// The console page's taskbar messages reach the app only as one of four fixed
|
||||
// words or a boolean (attention.rs decides what they mean); app.js forwards
|
||||
// them through these checks and nothing else.
|
||||
test("attentionSignal passes only the four favicon states, and taskbarSwitch only a boolean", () => {
|
||||
for (const state of ["busy", "ready", "attention", "plain"]) {
|
||||
assert.equal(attentionSignal({ plan2code: "attention", state }), state);
|
||||
}
|
||||
for (const data of [{ state: "Ready" }, { state: "urgent" }, { state: "" }, { state: 1 }, {}, null, undefined]) {
|
||||
assert.equal(attentionSignal(data), null, `${JSON.stringify(data)} is not forwarded`);
|
||||
}
|
||||
assert.equal(taskbarSwitch({ on: true }), true);
|
||||
assert.equal(taskbarSwitch({ on: false }), false);
|
||||
for (const data of [{ on: "false" }, { on: 0 }, { on: null }, {}, null]) {
|
||||
assert.equal(taskbarSwitch(data), null, `${JSON.stringify(data)} is not forwarded`);
|
||||
}
|
||||
});
|
||||
|
||||
test("app.js forwards attention and taskbar through those checks, and clears the dot on a new frame and a lost hello", () => {
|
||||
assert.match(APP_JS, /const signal = attentionSignal\(event\.data\);\s+if \(signal\) invoke\('set_attention', \{ signal \}\)/);
|
||||
assert.match(APP_JS, /const on = taskbarSwitch\(event\.data\);\s+if \(on === null\) return;/);
|
||||
assert.match(APP_JS, /invoke\('set_taskbar_signal', \{ on \}\)/);
|
||||
assert.match(APP_JS, /function loadFrame\(url\) \{[^}]*clearAttention\(\);[^}]*frame\.src = url;/);
|
||||
assert.match(APP_JS, /async function onNoHello\(\) \{\s+if \(frameReady \|\| !consoleKnown \|\| restarting\) return;[\s\S]{0,120}clearAttention\(\);/);
|
||||
assert.match(APP_JS, /plan2code: 'taskbar-state', on/, "the page hears the saved switch on its hello");
|
||||
});
|
||||
@@ -23,7 +23,7 @@ test("playwright-core is pinned exactly in the root devDependencies", () => {
|
||||
// A fake file system holding only `present`.
|
||||
const only = (...present) => (p) => present.includes(p);
|
||||
|
||||
test("findBrowser picks Chrome, then Edge, and honours PLAN2CODE_TEST_BROWSER", async () => {
|
||||
test("findBrowser picks Chrome, then Edge, and honors PLAN2CODE_TEST_BROWSER", async () => {
|
||||
const { findBrowser, BROWSER_PATHS } = await import("./browser.mjs");
|
||||
const chrome = BROWSER_PATHS.chrome[0];
|
||||
const edge = BROWSER_PATHS.msedge[0];
|
||||
|
||||
@@ -704,6 +704,31 @@ test("launcher agents: the model menu is the agent's own models, with no shipped
|
||||
assert.deepEqual(cli.args(["--model=m2", "-x"]), ["--yes", "/plan2code", "--model", "m2", "--bypass", "-x"]);
|
||||
});
|
||||
|
||||
test("launcher agents: the menu lists the built-ins found first, then the custom agents that resolve", (t) => {
|
||||
const box = sandbox(["goose", "codex", "claude"]);
|
||||
t.after(box.cleanup);
|
||||
const file = writeAgents(box, { schema: 1, agents: [GOOSE, { id: "ghost", name: "Ghost", command: "ghost-cmd" }] });
|
||||
const { customClis, runnableClis } = require(LAUNCHER);
|
||||
const realPath = process.env.PATH;
|
||||
process.env.PATH = path.join(box.dir, "bin");
|
||||
t.after(() => {
|
||||
process.env.PATH = realPath;
|
||||
});
|
||||
const { installed, missing } = runnableClis(customClis(file, false));
|
||||
assert.deepEqual(installed.map((cli) => cli.id), ["claude", "codex", "goose"]);
|
||||
assert.deepEqual(missing.map((cli) => cli.id), ["ghost"]);
|
||||
});
|
||||
|
||||
test("launcher agents: with no terminal to ask, a custom agent's model line names its own default", (t) => {
|
||||
const box = sandbox(["goose"]);
|
||||
t.after(box.cleanup);
|
||||
writeAgents(box, goose());
|
||||
const result = box.run(["--cli", "goose"]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Goose will start with its own default model\. To pick one, run `plan2code --model <id>`\./);
|
||||
assert.doesNotMatch(result.stdout, /last used/);
|
||||
});
|
||||
|
||||
test("launcher agents: a custom agent whose command is not found is left out and named when nothing can run", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
@@ -769,13 +794,17 @@ test("launcher agents: a full-path command starts, and on Windows a .cmd in a fo
|
||||
if (IS_WINDOWS) {
|
||||
file = path.join(spaced, "spaced.cmd");
|
||||
fs.writeFileSync(file, `@"${process.execPath}" "${recorder}" spaced %*\r\n`);
|
||||
// A same-named file in the project folder (the launcher's cwd) must not run instead.
|
||||
fs.writeFileSync(path.join(box.dir, "spaced.cmd"), `@"${process.execPath}" "${recorder}" decoy %*\r\n`);
|
||||
} else {
|
||||
file = path.join(spaced, "spaced");
|
||||
fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${recorder}" spaced "$@"\n`);
|
||||
fs.chmodSync(file, 0o755);
|
||||
}
|
||||
writeAgents(box, { schema: 1, agents: [{ id: "spaced", name: "Spaced", command: file, args: ["{prompt}"] }] });
|
||||
const result = box.run(["--cli", "spaced", "--note", "a b"]);
|
||||
// Some shells already set the switch the launcher sets; the run starts without it.
|
||||
const result = box.run(["--cli", "spaced", "--note", "a b"], { NoDefaultCurrentDirectoryInExePath: undefined });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.argsOf("spaced"), ["/plan2code", "--note", "a b"]);
|
||||
assert.equal(box.argsOf("decoy"), null);
|
||||
});
|
||||
@@ -378,7 +378,7 @@ test("pathfinder brief-data: calendar dates only, no future since, no NNs or lin
|
||||
|
||||
/* ===================================================== review-fix regressions */
|
||||
|
||||
test("pathfinder: claim, resolve and rule-out honour --dry-run", () => {
|
||||
test("pathfinder: claim, resolve and rule-out honor --dry-run", () => {
|
||||
const { root, pf } = mapFixture();
|
||||
const P = (...a) => runScript("plan2code-0-pathfinder", "pathfinder.mjs", [...a, "--root", root]);
|
||||
P("reconcile", "audit-export");
|
||||
|
||||
@@ -158,7 +158,7 @@ test("specs status: checklist formats, groups, task markers, numbering, totals,
|
||||
[3, "Web UI", "pending"],
|
||||
[4, "Docs", "pending"],
|
||||
]);
|
||||
assert.deepEqual(j.parallelGroups.map((g) => [g.id, g.phases]), [["A", [3, 4]]], "a group labelled sequential is not a parallel group");
|
||||
assert.deepEqual(j.parallelGroups.map((g) => [g.id, g.phases]), [["A", [3, 4]]], "a group labeled sequential is not a parallel group");
|
||||
assert.deepEqual(j.totals, { total: 11, complete: 4, assumed: 1, pending: 5, "in-progress": 0, blocked: 1, unknown: 0, completed: 5, incomplete: 5 });
|
||||
assert.equal(j.completionPercent, 45);
|
||||
assert.equal(j.phases[0].tasks.total, 3, "a named testing task (1.T) counts");
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
// The project writes US English: docs, comments, prompts, UI text, test names.
|
||||
// A rule in prose was missed once ("colours" slipped into a reply and ~100
|
||||
// files carried UK spellings), so this keeps it.
|
||||
// Run with: node --test scripts/test-us-english.mjs
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const SELF = "scripts/test-us-english.mjs";
|
||||
|
||||
// Tracked text files. Vendored code stays as shipped, and binaries have no words.
|
||||
const SKIP = /(^|\/)(node_modules|dist|target|vendor)\/|package-lock\.json$|\.(png|jpe?g|gif|ico|icns|mp3|wav|woff2?|ttf|lock)$/i;
|
||||
|
||||
// UK spellings with a clear US form. Whole words, any case.
|
||||
const UK = new RegExp(
|
||||
"\\b(" +
|
||||
[
|
||||
"colour\\w*", "grey\\w*", "behaviour\\w*", "centre[sd]?", "centred", "cancell(?:ed|ing)", "labell(?:ed|ing)",
|
||||
"relabell\\w*", "travell(?:ed|ing|er)", "judgement", "neighbour\\w*", "honour\\w*", "favour\\w*", "licence",
|
||||
"defence", "offence", "whilst", "amongst", "artefacts?", "catalogue[sd]?",
|
||||
"analys(?:e|ed|ing)", "(?:organ|recogn|normal|summar|sanit|optim|final|initial|serial|custom|priorit|minim|maxim|util|canonical|material|stabil|anonym|synchron|standard|categor|author|visual|emphas|apolog|special|character|central|random|token|local|capital|critic|memor|synthes|real)is(?:e|es|ed|ing|ation|ations|er|ers|able)",
|
||||
].join("|") +
|
||||
")\\b",
|
||||
"gi"
|
||||
);
|
||||
|
||||
// Names that keep the UK spelling because they are data contracts read in
|
||||
// several places (see Code Style in .agents-docs/AGENTS-code-style.md), plus
|
||||
// HTML's own attribute. Removed before the scan.
|
||||
const CONTRACTS = [
|
||||
/aria-labelledby/g,
|
||||
/\.greyed\b/g,
|
||||
/\bgreyed(?=\s*:)/g,
|
||||
/\bconst greyed\b/g,
|
||||
/\bgreyed(?=, card)/g,
|
||||
/^\/\/\s+greyed\b/gm,
|
||||
/\bcancelled(?=\s*:)/g,
|
||||
/\.cancelled\b/g,
|
||||
/"cancelled"/g,
|
||||
/\bconst cancelled\b/g,
|
||||
/\bcancelled(?=\.[a-z])/g,
|
||||
];
|
||||
|
||||
function trackedTextFiles() {
|
||||
const r = spawnSync("git", ["ls-files"], { cwd: ROOT, encoding: "utf8" });
|
||||
assert.equal(r.status, 0, r.stderr);
|
||||
return r.stdout.split("\n").filter((f) => f && f !== SELF && !SKIP.test(f));
|
||||
}
|
||||
|
||||
test("tracked text is written in US English", () => {
|
||||
const found = [];
|
||||
for (const rel of trackedTextFiles()) {
|
||||
let text;
|
||||
try {
|
||||
text = fs.readFileSync(path.join(ROOT, rel), "utf8");
|
||||
} catch {
|
||||
continue; // listed but deleted in the working tree
|
||||
}
|
||||
for (const re of CONTRACTS) text = text.replace(re, "");
|
||||
text.split("\n").forEach((line, i) => {
|
||||
for (const m of line.matchAll(UK)) found.push(`${rel}:${i + 1}: ${m[0]}`);
|
||||
});
|
||||
}
|
||||
assert.deepEqual(found, [], `UK spellings (use the US form, e.g. color, gray, behavior, canceled, -ize):\n${found.join("\n")}`);
|
||||
});
|
||||
@@ -247,7 +247,7 @@ test("nextAbout: pick sets about, drop and sent clear it, the old Ask events do
|
||||
assert.equal(JSON.stringify(picked), before, "prev is never mutated");
|
||||
});
|
||||
|
||||
test("nextAbout: an old { about, frozen, dropped } tracker normalises to the new shape", () => {
|
||||
test("nextAbout: an old { about, frozen, dropped } tracker normalizes to the new shape", () => {
|
||||
const old = { about: CARD_Q1, frozen: true, dropped: false };
|
||||
assert.deepEqual(nextAbout(old, { type: "leave-ask" }), { history: [], about: CARD_Q1 });
|
||||
assert.deepEqual(nextAbout({ frozen: false, dropped: true }, {}), { history: [], about: null });
|
||||
|
||||
@@ -190,7 +190,7 @@ test("two sessions keep their own cookies: each server reads only the one named
|
||||
// state.json has two writers, `post` and the server's /submit. Both are held
|
||||
// at the lock here until each has read nothing yet, then let go together:
|
||||
// whichever writes second must be building on the first one's write.
|
||||
test("a post and a submit that overlap both survive: the state lock serialises them", async () => {
|
||||
test("a post and a submit that overlap both survive: the state lock serializes them", async () => {
|
||||
const s = openSession();
|
||||
try {
|
||||
const lock = path.join(s.session, STATE_LOCK_FILE);
|
||||
|
||||
@@ -368,7 +368,7 @@ test("git board view: no control leaks the busy lock, in any state, mode, tab or
|
||||
assert.ok(["nav", "action", "done"].includes(gate), `${where}: "${words(c)}" (${c.tag}) has no data-gate`);
|
||||
const own = c.attrs["data-own"] === "true";
|
||||
if (!controlAllowed(mode, gate)) assert.ok(isOff(c), `${where}: "${words(c)}" is live while busy`);
|
||||
else assert.equal(isOff(c), own, `${where}: "${words(c)}" is ${isOff(c) ? "greyed with no reason of its own" : "live despite its own reason"}`);
|
||||
else assert.equal(isOff(c), own, `${where}: "${words(c)}" is ${isOff(c) ? "grayed with no reason of its own" : "live despite its own reason"}`);
|
||||
checked++;
|
||||
}
|
||||
const done = all.filter((c) => c.textContent === "Done with git");
|
||||
@@ -512,7 +512,7 @@ test("git board host: the host draws the board only through drawGitBoard, and th
|
||||
|
||||
// The commit table's ticks and the click that re-seeds them are page tests now
|
||||
// ("the commit table keeps the person's ticks across an agent post, and a click
|
||||
// re-seeds them" and its neighbours in test-web-console-page-git.mjs).
|
||||
// re-seeds them" and its neighbors in test-web-console-page-git.mjs).
|
||||
|
||||
test("git board docs: the agent prose, Help topic and readme describe the tabbed board", () => {
|
||||
const read = (p) => fs.readFileSync(new URL(p, import.meta.url), "utf8");
|
||||
|
||||
@@ -281,7 +281,7 @@ test("git: commits on a run go only with git-commits, as a whole number", () =>
|
||||
}
|
||||
});
|
||||
|
||||
test("git: the Git card is never greyed, and its resume command is /plan2code-git", () => {
|
||||
test("git: the Git card is never grayed, and its resume command is /plan2code-git", () => {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git");
|
||||
assert.equal(entry.workflow, "git");
|
||||
assert.deepEqual(cardAvailability(entry, { hasAgents: true, isGit: false }, null), { on: true, note: GIT_INIT_NOTE });
|
||||
|
||||
@@ -24,7 +24,7 @@ test("another console's cookie beside ours does not lock this one out", async ()
|
||||
const theirsOnly = await fetch(s.base + "/state", { headers: { cookie: other } });
|
||||
assert.equal(theirsOnly.status, 403);
|
||||
await theirsOnly.arrayBuffer();
|
||||
// The old shared name is no longer honoured.
|
||||
// The old shared name is no longer honored.
|
||||
const legacy = await fetch(s.base + "/state", { headers: { cookie: `p2c_console=${token}` } });
|
||||
assert.equal(legacy.status, 403);
|
||||
await legacy.arrayBuffer();
|
||||
|
||||
@@ -10,7 +10,8 @@ import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
import { CONSOLE_CLI, ENV, HOME, cli } from "./web-console-test-helpers.mjs";
|
||||
import { CONSOLE_CLI, ENV, HOME, cli, until } from "./web-console-test-helpers.mjs";
|
||||
import { openSession, pageSuite } from "./page-test-helpers.mjs";
|
||||
import { announcePage, inAppSignal } from "../src/web-console/in-app.mjs";
|
||||
|
||||
// A stand-in for the app's announce endpoint: records every POST it accepts.
|
||||
@@ -268,3 +269,65 @@ test("with nothing shown in the window yet, open makes the first session and ann
|
||||
app.close();
|
||||
}
|
||||
});
|
||||
|
||||
// The page inside the app's frame: the taskbar's two messages. Driven in a
|
||||
// real browser (page-test-helpers.mjs), with a parent that keeps every
|
||||
// message posted to it.
|
||||
const pages = pageSuite(test);
|
||||
const FAKE_APP_FRAME = () => {
|
||||
window.__toApp = [];
|
||||
Object.defineProperty(window, "parent", { configurable: true, get: () => ({ postMessage: (m) => window.__toApp.push(m) }) });
|
||||
};
|
||||
const toApp = (s, kind) => s.page.evaluate((k) => window.__toApp.filter((m) => m.plan2code === k), kind);
|
||||
const ASKING = { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } };
|
||||
|
||||
test("framed, the page tells the app its state once per change, never on a redraw, and plain when it goes away", async (t) => {
|
||||
const s = await openSession(await pages.browser(), { t, workflow: "implement", clock: true, payload: ASKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
|
||||
await until(async () => (await toApp(s, "attention")).length >= 1, 5000);
|
||||
assert.deepEqual((await toApp(s, "attention")).at(-1), { plan2code: "attention", state: "ready" }, "a question waiting is the person's move, as a named request");
|
||||
const before = (await toApp(s, "attention")).length;
|
||||
await s.page.clock.fastForward(5_000);
|
||||
assert.equal((await toApp(s, "attention")).length, before, "the status line's tick redraws without telling the app again");
|
||||
|
||||
s.post({ settle: true, items: [{ id: "q1", status: "answered", answer: { text: "x" } }], agent: { status: "working", activity: "Task 1 of 2" } });
|
||||
await until(async () => (await toApp(s, "attention")).at(-1).state !== "ready", 5000);
|
||||
const states = (await toApp(s, "attention")).map((m) => m.state);
|
||||
assert.ok(states.every((state) => ["busy", "ready", "attention", "plain"].includes(state)), states.join(", "));
|
||||
assert.ok(states.every((state, i) => i === 0 || state !== states[i - 1]), `no state is told twice in a row: ${states.join(", ")}`);
|
||||
|
||||
await s.page.evaluate(() => dispatchEvent(new Event("pagehide")));
|
||||
assert.deepEqual((await toApp(s, "attention")).at(-1), { plan2code: "attention", state: "plain" });
|
||||
});
|
||||
|
||||
test("the Desktop app group shows only in the app's frame, reflects the app's saved switch and tells the app when it changes", async (t) => {
|
||||
const browser = await pages.browser();
|
||||
const plain = await openSession(browser, { t, workflow: "implement", payload: ASKING });
|
||||
await plain.page.locator("#btn-looks").click();
|
||||
assert.equal(await plain.page.locator("#looks-desktop").isVisible(), false, "not in a browser tab");
|
||||
|
||||
const s = await openSession(browser, { t, workflow: "implement", payload: ASKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
|
||||
await s.page.locator("#btn-looks").click();
|
||||
const box = s.page.locator("#looks-taskbar");
|
||||
assert.ok(await s.page.locator("#looks-desktop").isVisible(), "shown inside the app");
|
||||
assert.ok(await box.isChecked(), "on until the app says otherwise");
|
||||
|
||||
// The app's answer to the page's hello, from a real window standing in as
|
||||
// the parent. The same answer from anywhere else is ignored.
|
||||
await s.page.evaluate(() => {
|
||||
const frame = document.createElement("iframe");
|
||||
document.body.append(frame);
|
||||
const app = frame.contentWindow;
|
||||
app.postMessage = (m) => window.__toApp.push(m);
|
||||
Object.defineProperty(window, "parent", { configurable: true, get: () => app });
|
||||
window.__app = app;
|
||||
dispatchEvent(new MessageEvent("message", { data: { plan2code: "taskbar-state", on: false }, source: window }));
|
||||
});
|
||||
assert.equal(await box.isChecked(), true, "a taskbar-state from anywhere but the parent changes nothing");
|
||||
await s.page.evaluate(() => {
|
||||
dispatchEvent(new MessageEvent("message", { data: { plan2code: "taskbar-state", on: false }, source: window.__app }));
|
||||
});
|
||||
assert.equal(await box.isChecked(), false, "the parent's saved value");
|
||||
|
||||
await box.check();
|
||||
assert.deepEqual(await toApp(s, "taskbar"), [{ plan2code: "taskbar", on: true }], "a named request with one boolean");
|
||||
});
|
||||
@@ -87,7 +87,7 @@ import {
|
||||
nextOpenAfter,
|
||||
} from "../src/web-console/public/answers.js";
|
||||
import { chatView } from "../src/web-console/public/chat.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT } from "../src/web-console/public/palette.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, RETIRED_ACCENTS, accentId } from "../src/web-console/public/palette.js";
|
||||
import {
|
||||
needsRoleNudge,
|
||||
normalizeRole,
|
||||
@@ -665,7 +665,8 @@ const contrast = (a, b) => {
|
||||
|
||||
test("every highlight color is readable in both themes", () => {
|
||||
const panel = { light: "#ffffff", dark: "#201d1a" };
|
||||
assert.ok(Object.keys(ACCENTS).length >= 32);
|
||||
// Nineteen a row in the wide Preferences dialog, two rows at most.
|
||||
assert.ok(Object.keys(ACCENTS).length >= 32 && Object.keys(ACCENTS).length <= 38);
|
||||
assert.ok(ACCENTS[DEFAULT_ACCENT], "the default must be in the list");
|
||||
const names = new Set();
|
||||
for (const [id, a] of Object.entries(ACCENTS)) {
|
||||
@@ -681,11 +682,22 @@ test("every highlight color is readable in both themes", () => {
|
||||
}
|
||||
});
|
||||
|
||||
test("a retired highlight color keeps its closest twin, an unknown one the default", () => {
|
||||
for (const [old, now] of Object.entries(RETIRED_ACCENTS)) {
|
||||
assert.ok(!ACCENTS[old], `${old} is retired, so it is not offered`);
|
||||
assert.ok(ACCENTS[now], `${old} maps to ${now}, which must exist`);
|
||||
assert.equal(accentId(old), now);
|
||||
}
|
||||
assert.equal(accentId("violet"), "violet");
|
||||
assert.equal(accentId("nope"), DEFAULT_ACCENT);
|
||||
assert.equal(accentId(undefined), DEFAULT_ACCENT);
|
||||
});
|
||||
|
||||
/* ------------------------------------------------- the spec-aware dashboard */
|
||||
|
||||
// The console scans the repo itself, so the states the picker shows have to
|
||||
// be read off real folder shapes — a fixture per stage, then the matrix that
|
||||
// turns a stage into lit or greyed cards.
|
||||
// turns a stage into lit or grayed cards.
|
||||
function fakeSpec(root, name, files) {
|
||||
const dir = path.join(root, "specs", name);
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
@@ -847,7 +859,7 @@ test("a delete is a session action naming the folder, and its reply says it is f
|
||||
assert.equal(deleteSummary({ ...spec, detail: "" }).stage, SPEC_STATE_LABELS.building);
|
||||
});
|
||||
|
||||
test("a fixed bug says so once: on its chip, in the delete dialog and on its greyed cards", () => {
|
||||
test("a fixed bug says so once: on its chip, in the delete dialog and on its grayed cards", () => {
|
||||
const fixed = { dir: "specs/old-bug", name: "old-bug", state: "fixed", detail: "bug fixed", files: 1, touched: 1 };
|
||||
assert.equal(deleteSummary(fixed).stage, "Bug fixed");
|
||||
const building = { dir: "specs/lunch-vote", name: "lunch-vote", state: "building", detail: "1 of 2 tasks done" };
|
||||
@@ -984,7 +996,7 @@ test("the Git card stays clickable outside a repository and says what happens",
|
||||
assert.equal(cardPresentation(entry, withSpec, withSpec.specs[0], menu).detail, "Two changes ready");
|
||||
});
|
||||
|
||||
test("the Git card is never greyed", () => {
|
||||
test("the Git card is never grayed", () => {
|
||||
const entry = SKILL_CATALOG.find((e) => e.skill === "plan2code-git");
|
||||
const clean = cardAvailability(entry, { hasAgents: true, isGit: true, pending: 0 }, null);
|
||||
assert.equal(clean.on, true);
|
||||
@@ -1191,7 +1203,7 @@ test("the dashboard matrix lights only the cards a spec state allows", () => {
|
||||
assert.ok(!cardAvailability(entry("plan2code-quick-task"), scan, sel("fixed")).next);
|
||||
assert.equal(launchTarget(entry("plan2code-quick-task"), sel("fixed")), null);
|
||||
|
||||
// A greyed card always says why, and a selected spec's next step is marked.
|
||||
// A grayed card always says why, and a selected spec's next step is marked.
|
||||
assert.ok(cardAvailability(entry("plan2code-3-implement"), scan, sel("exploring")).reason);
|
||||
assert.equal(cardAvailability(entry("plan2code-3-implement"), scan, sel("documented")).next, true);
|
||||
assert.ok(!cardAvailability(entry("plan2code-1-plan"), scan, sel("documented")).next);
|
||||
@@ -1989,18 +2001,18 @@ test("workspace cursor never moves backwards, and only changes past it are pendi
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: only the five opted-in workflows offer the switch", () => {
|
||||
for (const w of ["implement", "implement-review", "quick-task", "review", "pathfinder"]) {
|
||||
test("subagents: only the seven opted-in workflows offer the switch", () => {
|
||||
for (const w of ["implement", "implement-review", "quick-task", "review", "pathfinder", "plan", "revise-plan"]) {
|
||||
assert.equal(offered(w), true, w);
|
||||
assert.ok(defaultInstruction(w).length > 0, `${w} has a default instruction`);
|
||||
}
|
||||
for (const w of ["dashboard", "plan", "document", "init", "handoff", "constructor", "toString", undefined]) {
|
||||
for (const w of ["dashboard", "document", "finalize", "init", "handoff", "constructor", "toString", undefined]) {
|
||||
assert.equal(offered(w), false, String(w));
|
||||
assert.equal(defaultInstruction(w), "");
|
||||
}
|
||||
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 5);
|
||||
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 7);
|
||||
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3, strength: "balanced" });
|
||||
assert.equal(defaultSetting("plan").on, false, "a skill without the switch is never on");
|
||||
assert.equal(defaultSetting("document").on, false, "a skill without the switch is never on");
|
||||
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
|
||||
assert.equal(effectiveInstruction({ workflow: "review", instruction: " Mine " }), "Mine");
|
||||
});
|
||||
@@ -2041,7 +2053,7 @@ test("subagents: blockFor walks every switch transition, and never says off to a
|
||||
|
||||
assert.equal(blockFor(setting(true, 6), none).lines[0], "Subagents: on (revision 6) — a console setting, not typed by the person.", "a reset cursor re-states on");
|
||||
assert.equal(blockFor(setting(false, 6), none), null, "a reset cursor with it off: nothing");
|
||||
assert.equal(blockFor({ ...setting(true, 9), workflow: "plan" }, none), null, "a workflow that does not offer it: nothing");
|
||||
assert.equal(blockFor({ ...setting(true, 9), workflow: "document" }, none), null, "a workflow that does not offer it: nothing");
|
||||
});
|
||||
|
||||
test("subagents: the injected wording names no harness tool", () => {
|
||||
@@ -2164,10 +2176,24 @@ test("subagents: helperRows turns a reported strength and effort into one line,
|
||||
}
|
||||
for (const extra of [{}, { strength: "huge", effort: "max" }]) {
|
||||
const row = line(extra);
|
||||
for (const key of ["strengthLine", "strength", "effort"]) assert.equal(key in row, false, `${JSON.stringify(extra)}: no ${key}`);
|
||||
for (const key of ["strengthLine", "badges", "strength", "effort"]) assert.equal(key in row, false, `${JSON.stringify(extra)}: no ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: helperRows gives each reported strength and effort a badge ranked 1-3, and the session's own model rank 0", () => {
|
||||
const badges = (extra) => helperRows([{ id: "h1", title: "One", ask: "a", state: "running", ...extra }]).rows[0].badges;
|
||||
assert.deepEqual(badges({ strength: "standard", effort: "high" }), [
|
||||
{ kind: "strength", label: "Standard", level: 2 },
|
||||
{ kind: "effort", label: "High effort", level: 3 },
|
||||
]);
|
||||
assert.deepEqual(badges({ strength: "light" }), [{ kind: "strength", label: "Light", level: 1 }]);
|
||||
assert.deepEqual(badges({ strength: "strongest", effort: "low" }).map((b) => b.level), [3, 1]);
|
||||
assert.deepEqual(badges({ strength: "inherit", effort: "medium" }), [
|
||||
{ kind: "strength", label: "Session model", level: 0 },
|
||||
{ kind: "effort", label: "Medium effort", level: 2 },
|
||||
]);
|
||||
});
|
||||
|
||||
test("page: the Subagents button sits right after Write a brief, and its dialog is in the page with no inline styles or scripts", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const row = html.match(/<div class="row-left">([\s\S]*?)<\/div>\s*<div class="views-group">/);
|
||||
|
||||
@@ -310,7 +310,7 @@ test("reorderTabs needs exactly the current ids once each, and setLastTab rememb
|
||||
refusal(() => readNotepad(folder, "../x"), "no-such-tab");
|
||||
});
|
||||
|
||||
test("deleteTab: the folder goes, last moves to a neighbour, and the last tab left leaves an empty list", () => {
|
||||
test("deleteTab: the folder goes, last moves to a neighbor, and the last tab left leaves an empty list", () => {
|
||||
const folder = freshFolder();
|
||||
const [a, b, c] = ["A", "B", "C"].map((n) => createTab(folder, n).id);
|
||||
saveNote(folder, b, "bye");
|
||||
|
||||
@@ -269,6 +269,11 @@ test("the Subagents tab shows a reported helper's strength line and none for a h
|
||||
await tab.click();
|
||||
const rows = s.page.locator("#main .sa-card .sa-row");
|
||||
await rows.first().waitFor();
|
||||
assert.equal(await textOf(rows.filter({ hasText: "Read the store helpers" }).locator(".sa-strength")), "Standard, medium effort");
|
||||
const strength = rows.filter({ hasText: "Read the store helpers" }).locator(".sa-strength");
|
||||
assert.equal(await strength.getAttribute("aria-label"), "Standard, medium effort");
|
||||
const badges = strength.locator(".sa-badge");
|
||||
assert.deepEqual(await badges.allTextContents(), ["Standard", "Medium effort"]);
|
||||
assert.deepEqual(await badges.evaluateAll((els) => els.map((e) => e.className)), ["sa-badge is-strength lvl-2", "sa-badge is-effort lvl-2"]);
|
||||
assert.equal(await badges.first().locator(".sa-bars i.on").count(), 2);
|
||||
assert.equal(await rows.filter({ hasText: "Check the tests" }).locator(".sa-strength").count(), 0);
|
||||
});
|
||||
@@ -171,7 +171,7 @@ test("a sign-off card opens its document, and each verdict reaches the agent", a
|
||||
await card.getByRole("button", { name: /Read .*Completion report.* in full/ }).click();
|
||||
await s.page.getByText("Phase 3 adds the /tasks endpoints.").waitFor();
|
||||
assert.ok(await s.page.getByText("Phase 3 adds the /tasks endpoints.").isVisible(), "the report is on screen");
|
||||
// The danger verdict is marked as such: here the class is the behaviour.
|
||||
// The danger verdict is marked as such: here the class is the behavior.
|
||||
await s.page.locator("#views").getByRole("button", { name: /^Questions/ }).click();
|
||||
card = itemCard(s.page, "so1");
|
||||
assert.match(await card.getByRole("button", { name: "Throw it away" }).getAttribute("class"), /danger/);
|
||||
@@ -338,16 +338,16 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
|
||||
assert.equal(await itemCard(s.page, "q2").evaluate((el) => el.scrollTop), 0, "the new question opened part-way down");
|
||||
});
|
||||
|
||||
// The accent colour as the browser resolves it, and a button's outline colour,
|
||||
// The accent color as the browser resolves it, and a button's outline color,
|
||||
// so "wears the accent" is read off the screen, not off a class name.
|
||||
const accentOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--accent)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
const color = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
return color;
|
||||
});
|
||||
const outlineOf = (button) => button.evaluate((b) => getComputedStyle(b).borderTopColor);
|
||||
const warnOf = (page) =>
|
||||
@@ -355,9 +355,9 @@ const warnOf = (page) =>
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--warn)";
|
||||
document.body.appendChild(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
const color = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return colour;
|
||||
return color;
|
||||
});
|
||||
|
||||
// What a person sees break: the way forward on a sign-off card looks like any
|
||||
@@ -390,9 +390,9 @@ test("Skip this one and a comment box's quick answer are the same small accent b
|
||||
const quick = card.getByRole("button", { name: "No changes" });
|
||||
const look = (b) => b.evaluate((x) => { const c = getComputedStyle(x); return [c.fontSize, c.paddingTop, c.paddingLeft, c.color]; });
|
||||
assert.deepEqual(await look(skip), await look(quick), "the two chips look alike");
|
||||
const [size, , , colour] = await look(skip);
|
||||
const [size, , , color] = await look(skip);
|
||||
assert.equal(size, "12px", "small, not a full-size button");
|
||||
assert.equal(colour, await accentOf(s.page), "in the accent");
|
||||
assert.equal(color, await accentOf(s.page), "in the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: Combine phases is missing from a plan's breakdown,
|
||||
|
||||
@@ -19,7 +19,7 @@ const suite = pageSuite(test);
|
||||
// A project that is set up (AGENTS.md) with one spec holding a Plan draft.
|
||||
// A PLAN-DRAFT whose Status line says only "Draft" (no "Resume at Phase N")
|
||||
// scans as `planned`, which the picker labels "Ready to document". Plan is
|
||||
// still lit for it (only exploring, fixed and documented-or-later grey Plan
|
||||
// still lit for it (only exploring, fixed and documented-or-later gray Plan
|
||||
// out); Document is the state's own next step.
|
||||
const DRAFT_PROJECT = {
|
||||
"AGENTS.md": "# AGENTS.md\n\nA small demo project.\n",
|
||||
@@ -60,7 +60,7 @@ test("a Plan launch from the dashboard carries the picked spec, and its resume t
|
||||
|
||||
// The Plan card is lit for this spec; picking it asks to confirm.
|
||||
const planCard = main.getByRole("button").filter({ has: s.page.locator("code", { hasText: /^\/plan2code-1-plan$/ }) });
|
||||
assert.equal(await planCard.isEnabled(), true, "the Plan card is greyed for a drafted plan");
|
||||
assert.equal(await planCard.isEnabled(), true, "the Plan card is grayed for a drafted plan");
|
||||
await planCard.click();
|
||||
await main.getByRole("button", { name: "Start Plan" }).click();
|
||||
|
||||
@@ -146,7 +146,7 @@ test("a fixed bug is hidden while unavailable workflows are, dimmed when they sh
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the picker opens on the plan, not the newer fixed bug");
|
||||
assert.equal(await chipFor(main, "old-bug").count(), 0, "the fixed bug's chip is hidden while unavailable workflows are");
|
||||
|
||||
// Switched off: the chip shows, labelled and dimmed, and still not picked.
|
||||
// Switched off: the chip shows, labeled and dimmed, and still not picked.
|
||||
await hideUnavailable(main, false);
|
||||
const bug = chipFor(main, "old-bug");
|
||||
await bug.waitFor();
|
||||
@@ -180,7 +180,7 @@ test("a fixed bug's Delete asks once with no name to type, while any other spec
|
||||
|
||||
// The fixed bug: a visible Delete, its own warning, and one press sends it.
|
||||
const del = main.getByRole("button", { name: "Delete the spec old-bug" });
|
||||
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labelled button");
|
||||
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labeled button");
|
||||
await del.click({ force: true });
|
||||
await dialog.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#delete-warn")), /The bug is fixed, so this only clears the write-up/);
|
||||
@@ -203,17 +203,17 @@ const pickedChip = (main, name) => main.locator('button[aria-current="true"]', {
|
||||
|
||||
// What a person would see break: picking another target leaves the launch
|
||||
// aimed at the old spec, or the cards lit for it.
|
||||
test("picking Start from scratch instead of a spec greys Document, and a launch then carries no spec", async (t) => {
|
||||
test("picking Start from scratch instead of a spec grays Document, and a launch then carries no spec", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project: tempProject(DRAFT_PROJECT) });
|
||||
const main = await toTheMenu(s);
|
||||
const document = lightOf(main, "/plan2code-2-document");
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
assert.equal(await document.isEnabled(), true, "Document is lit for the drafted spec");
|
||||
|
||||
// From scratch there is no draft to document: the card greys.
|
||||
// From scratch there is no draft to document: the card grays.
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
assert.equal(await document.isDisabled(), true, "Document is greyed with no spec picked");
|
||||
assert.equal(await document.isDisabled(), true, "Document is grayed with no spec picked");
|
||||
assert.equal(await chipFor(main, "demo").getAttribute("aria-current"), "false");
|
||||
|
||||
// Back on the spec it is lit again; then from scratch once more to launch.
|
||||
@@ -270,7 +270,7 @@ async function openHandoffMenu(t, env) {
|
||||
// project has, or picking it still shows the skill cards beside the preview.
|
||||
test("a handoff shows as a dashed Handoff chip even with no spec, and picking it swaps the cards for a preview of four buttons", async (t) => {
|
||||
const { main, chip } = await openHandoffMenu(t);
|
||||
assert.match(await textOf(chip), /Handoff/i, "the chip is labelled Handoff");
|
||||
assert.match(await textOf(chip), /Handoff/i, "the chip is labeled Handoff");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "false", "a handoff is offered, not picked for you");
|
||||
assert.equal(await chip.evaluate((b) => getComputedStyle(b).borderTopStyle), "dashed", "the chip's border is dashed");
|
||||
assert.ok(await lightOf(main, "/plan2code-1-plan").isVisible(), "the cards show before a handoff is picked");
|
||||
|
||||
@@ -301,7 +301,7 @@ test("the editor follows the console's light and dark themes", async (t) => {
|
||||
await openNotepad(s);
|
||||
await setDoc(s, "# Heading\n\nText");
|
||||
await s.page.locator("#notepad-editor .cm-h1").waitFor();
|
||||
const colours = (theme) =>
|
||||
const colors = (theme) =>
|
||||
s.page.evaluate((th) => {
|
||||
document.documentElement.setAttribute("data-theme", th);
|
||||
const root = getComputedStyle(document.documentElement);
|
||||
@@ -325,13 +325,13 @@ test("the editor follows the console's light and dark themes", async (t) => {
|
||||
background: getComputedStyle(shadow.querySelector(".cm-editor")).backgroundColor,
|
||||
};
|
||||
}, theme);
|
||||
const light = await colours("light");
|
||||
const dark = await colours("dark");
|
||||
const light = await colors("light");
|
||||
const dark = await colors("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.equal(c.heading, c.accent, `${name}: headings in the highlight color`);
|
||||
assert.equal(c.caret, c.accent, `${name}: the caret in the highlight color`);
|
||||
assert.equal(c.background, c.panel, `${name}: the editor on the panel color`);
|
||||
}
|
||||
assert.notEqual(light.text, dark.text, "the two themes differ");
|
||||
assert.notEqual(light.background, dark.background);
|
||||
@@ -706,7 +706,7 @@ test("Delete asks twice, Escape backs out of either, and only the second confirm
|
||||
await panel.waitFor({ state: "hidden" });
|
||||
assert.equal(fs.existsSync(folder), true);
|
||||
|
||||
// Both confirms: gone, with its folder, and the neighbour is shown.
|
||||
// Both confirms: gone, with its folder, and the neighbor is shown.
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await s.page.click("#notepad-delete-go");
|
||||
@@ -714,7 +714,7 @@ test("Delete asks twice, Escape backs out of either, and only the second confirm
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
assert.deepEqual(await selectedName(s), ["Notes"]);
|
||||
assert.equal(await shows(s, "keep me"), "keep me");
|
||||
assert.equal(listTabs(s.project).last, idOf(s, "Notes"), "the neighbour became the last tab");
|
||||
assert.equal(listTabs(s.project).last, idOf(s, "Notes"), "the neighbor became the last tab");
|
||||
|
||||
// Delete the last tab: the empty state, with the focus on its button.
|
||||
await s.page.click(X_SELECTED);
|
||||
@@ -808,7 +808,7 @@ test("when the tab after a delete cannot be loaded, the deleted text is not left
|
||||
await typeInto(s, "doomed text");
|
||||
const ideas = idOf(s, "Ideas");
|
||||
await until(() => readNotepad(s.project, ideas).text === "doomed text", 4000);
|
||||
// The neighbour's read fails, as if the connection dropped right after the delete.
|
||||
// The neighbor's read fails, as if the connection dropped right after the delete.
|
||||
await s.page.route("**/notepad?tab=*", (route) => route.abort());
|
||||
await s.page.click(X_SELECTED);
|
||||
await s.page.click("#notepad-delete-go");
|
||||
@@ -836,8 +836,8 @@ 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) =>
|
||||
// decode, one color per call so the pictures differ.
|
||||
const pngBase64 = (s, color) =>
|
||||
s.page.evaluate(async (fill) => {
|
||||
const c = document.createElement("canvas");
|
||||
c.width = 320;
|
||||
@@ -849,13 +849,13 @@ const pngBase64 = (s, colour) =>
|
||||
let bin = "";
|
||||
for (const b of new Uint8Array(await blob.arrayBuffer())) bin += String.fromCharCode(b);
|
||||
return btoa(bin);
|
||||
}, colour);
|
||||
}, color);
|
||||
|
||||
const pngFile = async (s, colour, name = "shot.png") => ({ name, mimeType: "image/png", buffer: Buffer.from(await pngBase64(s, colour), "base64") });
|
||||
const pngFile = async (s, color, name = "shot.png") => ({ name, mimeType: "image/png", buffer: Buffer.from(await pngBase64(s, color), "base64") });
|
||||
|
||||
async function addViaButton(s, colour) {
|
||||
async function addViaButton(s, color) {
|
||||
const before = stored(s).length;
|
||||
await s.page.setInputFiles("#notepad-file", await pngFile(s, colour));
|
||||
await s.page.setInputFiles("#notepad-file", await pngFile(s, color));
|
||||
await until(() => stored(s).length === before + 1 && filesOf(s, stored(s).at(-1).id).every(Boolean), 5000);
|
||||
await readyCount(s, before + 1);
|
||||
}
|
||||
@@ -863,7 +863,7 @@ async function addViaButton(s, colour) {
|
||||
// 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) =>
|
||||
const sendPicture = (s, kind, color) =>
|
||||
s.page.evaluate(
|
||||
async ({ kind, fill }) => {
|
||||
const c = document.createElement("canvas");
|
||||
@@ -882,7 +882,7 @@ const sendPicture = (s, kind, colour) =>
|
||||
ta.dispatchEvent(new DragEvent("drop", { dataTransfer: dt, bubbles: true, cancelable: true, composed: true }));
|
||||
return lit;
|
||||
},
|
||||
{ kind, fill: colour },
|
||||
{ kind, fill: color },
|
||||
);
|
||||
|
||||
test("Add image, paste and drop each add a thumbnail whose files are on disk and which survives closing", async (t) => {
|
||||
@@ -963,7 +963,7 @@ test("the X asks first: Keep keeps the picture, Delete removes both its files",
|
||||
test("the preview opens at the clicked picture, steps and wraps, and Esc closes it before the Notebook", 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);
|
||||
for (const color of ["#c33", "#3c3", "#33c"]) await addViaButton(s, color);
|
||||
const urls = stored(s).map((img) => img.url);
|
||||
const shown = () =>
|
||||
s.page.evaluate(() => ({
|
||||
|
||||
@@ -164,7 +164,7 @@ test("Continue here is hidden once the session meter is red, and the command and
|
||||
// Under the desktop app (PLAN2CODE_IN_APP=1) the fresh-session advice in the
|
||||
// meter's popover and the dashboard's red banner must point at the app's own
|
||||
// New Session, never a command to copy into a terminal that is not there:
|
||||
// the popover's is a button filled with the user's highlight colour.
|
||||
// the popover's is a button filled with the user's highlight color.
|
||||
test("under the app, the meter popover and the dashboard's red banner point at New Session, not a command", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
@@ -185,11 +185,11 @@ test("under the app, the meter popover and the dashboard's red banner point at N
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--accent)";
|
||||
n.append(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
const color = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return [getComputedStyle(n).backgroundColor, colour];
|
||||
return [getComputedStyle(n).backgroundColor, color];
|
||||
});
|
||||
assert.equal(fill, highlight, "filled with the user's highlight colour");
|
||||
assert.equal(fill, highlight, "filled with the user's highlight color");
|
||||
assert.equal(await fresh.locator("code").count(), 0, "no command to copy under the app");
|
||||
});
|
||||
|
||||
|
||||
@@ -671,7 +671,7 @@ test("help: the template's icons and panels match HELP_TABS in order, headed by
|
||||
}
|
||||
});
|
||||
|
||||
test("help: every diagram tab has one labelled picture, the rest none; no inline styles or scripts", () => {
|
||||
test("help: every diagram tab has one labeled picture, the rest none; no inline styles or scripts", () => {
|
||||
const tpl = helpTemplate();
|
||||
assert.doesNotMatch(tpl, /\sstyle=/);
|
||||
assert.doesNotMatch(tpl, /<script/i);
|
||||
@@ -691,7 +691,7 @@ test("help: every diagram tab has one labelled picture, the rest none; no inline
|
||||
assert.doesNotMatch(body, /<div class="help-figure"[^>]*><\/div>/, `${t.id}'s insertion point is filled`);
|
||||
if (t.id === "planny") {
|
||||
const fig = body.match(/<figure class="help-figure help-moods"[^>]*role="img"[^>]*aria-labelledby="hd-planny-title"/);
|
||||
assert.ok(fig, "the Planny moods are one labelled role=img figure");
|
||||
assert.ok(fig, "the Planny moods are one labeled role=img figure");
|
||||
const label = body.match(/id="hd-planny-title"[^>]*>([^<]*)</);
|
||||
assert.ok(label && label[1].trim(), "the moods figure's label exists and says something");
|
||||
continue;
|
||||
@@ -700,9 +700,9 @@ test("help: every diagram tab has one labelled picture, the rest none; no inline
|
||||
assert.ok(svg, `${t.id} draws an svg diagram`);
|
||||
const open = svg[0].slice(0, svg[0].indexOf(">"));
|
||||
assert.match(open, /role="img"/, `${t.id}'s diagram is an image`);
|
||||
const labelled = open.match(/aria-labelledby="([^"]+)"/);
|
||||
assert.ok(labelled, `${t.id}'s diagram is labelled`);
|
||||
for (const id of labelled[1].split(/\s+/)) {
|
||||
const labeled = open.match(/aria-labelledby="([^"]+)"/);
|
||||
assert.ok(labeled, `${t.id}'s diagram is labeled`);
|
||||
for (const id of labeled[1].split(/\s+/)) {
|
||||
const ref = svg[1].match(new RegExp(`<(title|desc) id="${id}">([\\s\\S]*?)</\\1>`));
|
||||
assert.ok(ref && ref[2].trim(), `${t.id}'s diagram has a non-empty #${id}`);
|
||||
}
|
||||
|
||||
@@ -253,7 +253,7 @@ function appJsReaders(dir) {
|
||||
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
|
||||
return oneStatement || handedToAHelper || publicPath;
|
||||
})
|
||||
.map((f) => `${f} reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it`);
|
||||
.map((f) => `${f} reads public/app.js as text: test the behavior in a page test, or read the screen file that holds it`);
|
||||
}
|
||||
|
||||
test("shape: no test in scripts/ reads public/app.js as text", () => {
|
||||
@@ -266,10 +266,10 @@ test("shape: the app.js check names the test file that reads it", () => {
|
||||
fs.writeFileSync(path.join(dir, "test-fine.mjs"), 'const r = await fetch(base + "/app.js");\nfs.appendFileSync(path.join(d, "src", "app.js"), "x");\n');
|
||||
assert.deepEqual(appJsReaders(dir), []);
|
||||
fs.writeFileSync(path.join(dir, "test-reads-it.mjs"), 'const app = fs.readFileSync(path.join(ROOT, "public", "app.js"), "utf8");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-reads-it.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
assert.deepEqual(appJsReaders(dir), ["test-reads-it.mjs reads public/app.js as text: test the behavior in a page test, or read the screen file that holds it"]);
|
||||
fs.rmSync(path.join(dir, "test-reads-it.mjs"));
|
||||
fs.writeFileSync(path.join(dir, "test-alias.mjs"), 'const web = (f) => fs.readFileSync(path.join(ROOT, "public", f), "utf8");\nconst app = web("app.js");\n');
|
||||
assert.deepEqual(appJsReaders(dir), ["test-alias.mjs reads public/app.js as text: test the behaviour in a page test, or read the screen file that holds it"]);
|
||||
assert.deepEqual(appJsReaders(dir), ["test-alias.mjs reads public/app.js as text: test the behavior in a page test, or read the screen file that holds it"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
@@ -382,7 +382,7 @@ test("Implement's card launches Implement + Review when Review is ticked", () =>
|
||||
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
|
||||
});
|
||||
|
||||
test("helper-strength.md ships in the five skills that start helpers, and in no other", () => {
|
||||
test("helper-strength.md ships in the seven skills that start helpers, and in no other", () => {
|
||||
// npm test has just built skills/; a direct run builds it so the check never reads a stale tree.
|
||||
if (process.env.npm_lifecycle_event !== "test") {
|
||||
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
|
||||
@@ -391,6 +391,8 @@ test("helper-strength.md ships in the five skills that start helpers, and in no
|
||||
const having = fs.readdirSync(built).filter((dir) => fs.existsSync(path.join(built, dir, "references", "helper-strength.md")));
|
||||
assert.deepEqual(having.sort(), [
|
||||
"plan2code-0-pathfinder",
|
||||
"plan2code-1-plan",
|
||||
"plan2code-1b-revise-plan",
|
||||
"plan2code-3-implement",
|
||||
"plan2code-3-implement-review",
|
||||
"plan2code-quick-task",
|
||||
|
||||
@@ -365,7 +365,7 @@ test("finished: any finished state is never the picker's default, not only fixed
|
||||
assert.equal(defaultSpec(specs.slice(0, 2), lookup), null, "only finished specs: start from scratch");
|
||||
assert.equal(defaultSpec(specs)?.dir, "specs/a", "the real table does not know archived, so it is in play");
|
||||
|
||||
// The cards greyed for a fixed bug give a made-up finished state the same reason.
|
||||
// The cards grayed 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 CARD_ENTRIES) {
|
||||
const fixed = cardAvailability(entry, SCAN, { dir: "specs/b", name: "b", state: "fixed" });
|
||||
@@ -463,12 +463,12 @@ test("card rules: every state still in play is taken by at least one card", () =
|
||||
assert.deepEqual(untakenStates(without, TABLE), ["no card's states take planned: add it to the skills.js entries whose card it lights"]);
|
||||
});
|
||||
|
||||
test("card rules: a card's states and greyed reasons name only real states", () => {
|
||||
test("card rules: a card's states and grayed reasons name only real states", () => {
|
||||
const known = new Set([...Object.keys(TABLE), "none"]);
|
||||
for (const sk of SKILLS) {
|
||||
if (Array.isArray(sk.states)) for (const st of sk.states) assert.ok(known.has(st), `${sk.skill} takes ${st}, which is no state`);
|
||||
for (const key of Object.keys(sk.greyed || {})) assert.ok(key === "default" || key === "finished" || known.has(key), `${sk.skill}'s greyed names ${key}, which is no state`);
|
||||
if (Array.isArray(sk.states) && sk.card) assert.ok(sk.greyed && sk.greyed.default, `${sk.skill} has a default greyed reason`);
|
||||
for (const key of Object.keys(sk.greyed || {})) assert.ok(key === "default" || key === "finished" || known.has(key), `${sk.skill}'s grayed names ${key}, which is no state`);
|
||||
if (Array.isArray(sk.states) && sk.card) assert.ok(sk.greyed && sk.greyed.default, `${sk.skill} has a default grayed reason`);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -718,10 +718,10 @@ test("a card with a note box over the git board flows at its own height, never s
|
||||
|
||||
test("a card and its pager in the git board's card slot fill the board's width, never shrink to their content", () => {
|
||||
const css = joinedCss();
|
||||
// .card and .pager centre with auto inline margins; in the slot's grid those
|
||||
// .card and .pager center with auto inline margins; in the slot's grid those
|
||||
// would shrink a short confirm, and the pager under it, to fit their content.
|
||||
assert.match(css, /\.card\s*\{[^}]*margin:\s*0 auto/, "the base card still centres outside the board");
|
||||
assert.match(css, /\.pager\s*\{[^}]*margin:\s*0 auto/, "the base pager still centres outside the board");
|
||||
assert.match(css, /\.card\s*\{[^}]*margin:\s*0 auto/, "the base card still centers outside the board");
|
||||
assert.match(css, /\.pager\s*\{[^}]*margin:\s*0 auto/, "the base pager still centers outside the board");
|
||||
assert.match(css, /\.git-cards > \.card,\s*\.git-cards > \.pager\s*\{\s*margin:\s*0;\s*\}/, "the card slot drops the auto margins for both");
|
||||
});
|
||||
|
||||
|
||||
@@ -243,12 +243,12 @@ test("subagents: a save that matches this session still becomes the project's se
|
||||
});
|
||||
|
||||
test("subagents: a workflow without the switch refuses it, bad bodies name the field, and an older copy's open hides it", async () => {
|
||||
const plan = subagentsSession({ workflow: "plan" });
|
||||
const doc = subagentsSession({ workflow: "document" });
|
||||
const s = subagentsSession();
|
||||
try {
|
||||
assert.deepEqual(await setSubagents(plan, ON3), { status: 400, body: { error: "not-offered" } });
|
||||
assert.equal((await frameSubagents(plan)).offered, false);
|
||||
assert.equal("subagents" in (await submitAndWait(plan)).json, false);
|
||||
assert.deepEqual(await setSubagents(doc, ON3), { status: 400, body: { error: "not-offered" } });
|
||||
assert.equal((await frameSubagents(doc)).offered, false);
|
||||
assert.equal("subagents" in (await submitAndWait(doc)).json, false);
|
||||
|
||||
assert.deepEqual(await setSubagents(s, { ...ON3, max: 0 }), { status: 400, body: { error: "max" } });
|
||||
assert.deepEqual(await setSubagents(s, { ...ON3, max: 21 }), { status: 400, body: { error: "max" } });
|
||||
@@ -268,7 +268,7 @@ test("subagents: a workflow without the switch refuses it, bad bodies name the f
|
||||
fs.rmSync(path.join(s.session, "subagents-setting.json"), { force: true });
|
||||
assert.equal("subagents" in (await submitAndWait(s)).json, false);
|
||||
} finally {
|
||||
cli(["stop", "--session", plan.sid]);
|
||||
cli(["stop", "--session", doc.sid]);
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -251,7 +251,7 @@ test("workspace: the original can be renamed and described but never removed; ot
|
||||
}
|
||||
});
|
||||
|
||||
test("workspace: browse returns the picked folder, or cancelled, and is hidden when the session looks remote", async () => {
|
||||
test("workspace: browse returns the picked folder, or canceled, and is hidden when the session looks remote", async () => {
|
||||
const picked = tempFolder();
|
||||
const echo = consoleSession(["--workflow", "plan"], { env: { PLAN2CODE_PICKER_ECHO: picked } });
|
||||
const cancel = consoleSession(["--workflow", "plan"], { env: { PLAN2CODE_PICKER_ECHO: "-" } });
|
||||
|
||||
@@ -35,7 +35,7 @@ export const VERSIONS = Object.freeze({
|
||||
});
|
||||
|
||||
export const HEADER =
|
||||
"/* CodeMirror 6 (state, view, language, commands, lang-markdown), MIT licence, (c) Marijn Haverbeke and others.\n" +
|
||||
"/* CodeMirror 6 (state, view, language, commands, lang-markdown), MIT license, (c) Marijn Haverbeke and others.\n" +
|
||||
" * https://codemirror.net/ . Bundled by scripts/vendor-codemirror.mjs; do not edit by hand.\n" +
|
||||
" * Versions: " +
|
||||
Object.entries(VERSIONS)
|
||||
|
||||
@@ -11,7 +11,7 @@
|
||||
//
|
||||
// PLAN2CODE_PICKER_ECHO (tests only, beside PLAN2CODE_NO_BROWSER): when set
|
||||
// in the server's environment, /workspace/browse returns it as the picked
|
||||
// folder instead of opening a picker, and "-" as a cancelled one.
|
||||
// folder instead of opening a picker, and "-" as a canceled one.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
@@ -26,7 +26,7 @@ import { readChat } from "../src/web-console/inbox.mjs";
|
||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
|
||||
// Canonicalised the same way server.mjs canonicalises a session dir (DIR,
|
||||
// Canonicalized the same way server.mjs canonicalizes a session dir (DIR,
|
||||
// server.mjs): on a machine whose %TEMP% itself resolves through an 8.3
|
||||
// short name (seen in the wild on Windows), a server started later writes
|
||||
// `state.worktree` in its realpath'd form, while anything in a test that
|
||||
|
||||
+31
-12
@@ -632,13 +632,10 @@ function announceCli(cli) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose the CLI from those installed: the `--cli` pick, the only one installed, or a numbered
|
||||
* menu defaulting to the last pick. Returns `{ cli }` with its resolved `path`, or `{ code }` (the
|
||||
* exit code) after printing why none can be used.
|
||||
* The CLIs that can run, in menu order (the built-ins found on PATH, then the custom agents whose
|
||||
* command resolves), and the custom agents left out because theirs does not.
|
||||
*/
|
||||
async function chooseCli(requested) {
|
||||
const customs = customClis();
|
||||
const all = [...CLIS, ...customs];
|
||||
function runnableClis(customs) {
|
||||
const installed = CLIS.map((cli) => ({ ...cli, path: findOnPath(cli.id) })).filter((cli) => cli.path);
|
||||
// A custom agent whose command does not resolve is left out of the menu and named when nothing can run.
|
||||
const missing = [];
|
||||
@@ -647,6 +644,18 @@ async function chooseCli(requested) {
|
||||
if (found) installed.push({ ...cli, ...found });
|
||||
else missing.push(cli);
|
||||
}
|
||||
return { installed, missing };
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose the CLI from those installed: the `--cli` pick, the only one installed, or a numbered
|
||||
* menu defaulting to the last pick. Returns `{ cli }` with its resolved `path`, or `{ code }` (the
|
||||
* exit code) after printing why none can be used.
|
||||
*/
|
||||
async function chooseCli(requested) {
|
||||
const customs = customClis();
|
||||
const all = [...CLIS, ...customs];
|
||||
const { installed, missing } = runnableClis(customs);
|
||||
|
||||
if (requested !== undefined) {
|
||||
const known = all.find((cli) => cli.id === requested);
|
||||
@@ -743,13 +752,20 @@ function listModels(cli) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask which model to run: a numbered list with Enter keeping the model the CLI last used.
|
||||
* Ask which model to run: a numbered list with Enter keeping the model the CLI last used (a
|
||||
* custom agent: its own default).
|
||||
* A pick appends `--model <id>` to `extraArgs`. Without an interactive terminal there is
|
||||
* nobody to ask, so it just says which model will be used, as it always has.
|
||||
*/
|
||||
async function chooseModel(cli, extraArgs) {
|
||||
if (cli.custom && !listModels(cli).length) return;
|
||||
// A custom agent has no last-used model to keep: left alone it starts on its own default.
|
||||
const keep = cli.custom ? 'its own default model' : 'the last-used model';
|
||||
if (!process.stdin.isTTY) {
|
||||
if (cli.custom) {
|
||||
console.log(`${cli.label} will start with its own default model. To pick one, run \`plan2code --model <id>\`.`);
|
||||
return;
|
||||
}
|
||||
console.log(`${cli.label} will use the model you last used in it. To use a different model, open`);
|
||||
console.log(`\`${cli.id}\` on its own and switch model there, or run \`plan2code --model <name>\`.`);
|
||||
return;
|
||||
@@ -773,7 +789,7 @@ async function chooseModel(cli, extraArgs) {
|
||||
models.forEach((model, i) => console.log(!model.label ? ` ${c.cyan(`${i + 1})`)} ${model.id}` : ` ${c.cyan(`${i + 1})`)} ${model.id} — ${model.label}`));
|
||||
}
|
||||
for (;;) {
|
||||
const answer = (await ask(`Choice ${c.green('[keep last used]')}: `)).trim().toLowerCase();
|
||||
const answer = (await ask(`Choice ${c.green(cli.custom ? '[default]' : '[keep last used]')}: `)).trim().toLowerCase();
|
||||
if (!answer) return;
|
||||
const byNumber = models[Number(answer) - 1];
|
||||
const byName = models.find((model) => model.id === answer || model.label.toLowerCase() === answer);
|
||||
@@ -782,7 +798,7 @@ async function chooseModel(cli, extraArgs) {
|
||||
extraArgs.push('--model', model.id);
|
||||
return;
|
||||
}
|
||||
console.log(c.yellow(`Type a number from 1 to ${models.length}, a model name, or press Enter to keep the last-used model.`));
|
||||
console.log(c.yellow(`Type a number from 1 to ${models.length}, a model name, or press Enter to keep ${keep}.`));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -946,7 +962,7 @@ async function confirmProject(cwd) {
|
||||
|
||||
/**
|
||||
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
||||
* Returns the folder, or null when the person cancelled.
|
||||
* Returns the folder, or null when the person canceled.
|
||||
*/
|
||||
async function pickFolder() {
|
||||
const start = readLastFolder();
|
||||
@@ -962,7 +978,7 @@ async function pickFolder() {
|
||||
windowsHide: true,
|
||||
});
|
||||
const folder = (result.stdout || '').trim();
|
||||
// Pickers exit 0 or 1 with nothing printed when cancelled; anything else means the picker
|
||||
// Pickers exit 0 or 1 with nothing printed when canceled; anything else means the picker
|
||||
// itself failed, so fall through to the typed prompt rather than giving up.
|
||||
if (!result.error && folder && result.status === 0) return path.resolve(folder);
|
||||
if (!result.error && !folder && (result.status === 0 || result.status === 1)) return null;
|
||||
@@ -1013,6 +1029,9 @@ function spawnCommand(file, args, options) {
|
||||
// Windows env names are case-insensitive and the copy keeps the original spelling (Path).
|
||||
const pathKey = Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'PATH';
|
||||
env[pathKey] = path.dirname(file) + path.delimiter + (env[pathKey] || '');
|
||||
// cmd looks in the current folder (the project) before PATH: a same-named
|
||||
// file there must not run in the agent's place.
|
||||
env.NoDefaultCurrentDirectoryInExePath = '1';
|
||||
return spawn(shell, ['/d', '/s', '/c', `"${[path.basename(file), ...args].map(quoteForCmd).join(' ')}"`], {
|
||||
...spawnOptions,
|
||||
env,
|
||||
@@ -1161,4 +1180,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { normalizeAgents, buildArgs, customClis, resolveCustomCommand, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
|
||||
module.exports = { normalizeAgents, buildArgs, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
|
||||
@@ -1,9 +1,9 @@
|
||||
# Chart Playbook
|
||||
> Part of plan2code-0-pathfinder — loaded at the top of MODE A (Chart). Expands the numbered Chart steps.
|
||||
>
|
||||
> **Backend note.** Steps 0, 2, and 4 — the gates and the grills — are identical either way, and so is every judgement call below (fog vs question, in scope vs out, the destination test). What differs is where Steps 3 and 5-7 put the bytes: on `**Backend:** github`, `github-issues.md` overrides the `map.md` and question-file templates here, the single-pass rule under *Step 6: Numbering and dependency order*, and the timing of the recon. Read it alongside this file, not instead of it.
|
||||
> **Backend note.** Steps 0, 2, and 4 — the gates and the grills — are identical either way, and so is every judgment call below (fog vs question, in scope vs out, the destination test). What differs is where Steps 3 and 5-7 put the bytes: on `**Backend:** github`, `github-issues.md` overrides the `map.md` and question-file templates here, the single-pass rule under *Step 6: Numbering and dependency order*, and the timing of the recon. Read it alongside this file, not instead of it.
|
||||
|
||||
Charting produces a map and a set of question files. It resolves nothing by hand. Every judgement below serves one goal: put a sharp question on the map for everything you can phrase now, and leave everything else honestly in the fog.
|
||||
Charting produces a map and a set of question files. It resolves nothing by hand. Every judgment below serves one goal: put a sharp question on the map for everything you can phrase now, and leave everything else honestly in the fog.
|
||||
|
||||
---
|
||||
|
||||
@@ -33,7 +33,7 @@ This gate and the Step 4 no-fog off-ramp are the same instinct at two moments: t
|
||||
|
||||
## Step 2: The destination grill
|
||||
|
||||
The destination is settled **first** because it fixes scope. Every later judgement — is this a question or fog, is this in scope or past the edge, is this map cleared — is measured against it. A vague destination makes all three unanswerable, and you will spend the rest of the map arguing about boundaries instead of decisions.
|
||||
The destination is settled **first** because it fixes scope. Every later judgment — is this a question or fog, is this in scope or past the edge, is this map cleared — is measured against it. A vague destination makes all three unanswerable, and you will spend the rest of the map arguing about boundaries instead of decisions.
|
||||
|
||||
A destination is **one or two lines** describing what exists when the map clears. It is not a feature description. It is not a value proposition. It names the artifact and draws the edge.
|
||||
|
||||
@@ -50,7 +50,7 @@ Recommend an answer with each probe — the human corrects faster than they comp
|
||||
|
||||
Two round trips, not six. Three probes each — exactly the cap, so neither batch needs splitting.
|
||||
|
||||
Batch 2 bends the independence test on purpose. The arrival signal (5) can shift under the smallest arrival (4), so strictly it should be held back — but holding it costs a third round trip to catch a conflict that is rare and cheap to spot. The trade is to send them together and reconcile at the recap: if the smallest arrival comes back materially smaller than the artifact you were told about, re-check the arrival signal against it before writing the destination. A knowing trade here, not a licence to batch dependent probes elsewhere.
|
||||
Batch 2 bends the independence test on purpose. The arrival signal (5) can shift under the smallest arrival (4), so strictly it should be held back — but holding it costs a third round trip to catch a conflict that is rare and cheap to spot. The trade is to send them together and reconcile at the recap: if the smallest arrival comes back materially smaller than the artifact you were told about, re-check the arrival signal against it before writing the destination. A knowing trade here, not a license to batch dependent probes elsewhere.
|
||||
|
||||
**Both batches go through the structured question tool.** Give each probe genuine candidate options with trade-offs and a recommendation; the built-in `Other` path is where the human composes the actor, a further feature to leave out, the arrival signal, or forcing-function detail in their own words. A clicked option is not written verbatim as the destination — the recap-confirmation tool call turns all six answers into the agreed one-or-two-line destination before disk write.
|
||||
|
||||
@@ -141,7 +141,7 @@ Recon is `legwork · AFK` — you do it alone, and you write it down **already r
|
||||
|
||||
Two disciplines keep this file useful:
|
||||
|
||||
- **Verify behaviour against actual code, never against a filename.** A file called `auditLogger.ts` may log nothing.
|
||||
- **Verify behavior against actual code, never against a filename.** A file called `auditLogger.ts` may log nothing.
|
||||
- **Scope the recon to the destination.** A recon of the whole repo is unreadable and stale in a week. If a subtree cannot plausibly be touched by the destination, say so in one line and move on.
|
||||
|
||||
Record what you could **not** determine as an explicit gap. Gaps at recon time are often the first real fog bullets.
|
||||
@@ -257,7 +257,7 @@ The destination grill went **deep on one thing**. This grill goes **wide on ever
|
||||
|
||||
**You are not resolving anything here.** You are taking inventory. The instant an answer feels satisfying, you are probably going deep.
|
||||
|
||||
### Recognising that you have gone deep
|
||||
### Recognizing that you have gone deep
|
||||
|
||||
Watch for these. Any one of them means stop and pull back:
|
||||
|
||||
@@ -312,7 +312,7 @@ Record each answer as one line in your working notes with an area label. At the
|
||||
|
||||
## The fog-vs-question test
|
||||
|
||||
This is the single most important judgement in the skill. Get it wrong toward questions and the map fills with unanswerable stubs that block the frontier. Get it wrong toward fog and the map has nothing takeable on it.
|
||||
This is the single most important judgment in the skill. Get it wrong toward questions and the map fills with unanswerable stubs that block the frontier. Get it wrong toward fog and the map has nothing takeable on it.
|
||||
|
||||
> **The test is whether you can STATE the question precisely now — not whether you can ANSWER it now.**
|
||||
|
||||
@@ -446,7 +446,7 @@ plan, not at shipped code. Continuous streaming to external systems is not on th
|
||||
- Questions are put to the human in plain English. Technical terms only where the term is the decision.
|
||||
- HITL questions are answered by the human in their own words. Never self-answered.
|
||||
- No new runtime dependency is assumed without a `research` question backing it.
|
||||
- Compliance language is reviewed by Dana before anything user-facing is finalised.
|
||||
- Compliance language is reviewed by Dana before anything user-facing is finalized.
|
||||
- Sketches are throwaway and live only under `pathfinder/sketch-NN/`.
|
||||
|
||||
## Glossary
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
>
|
||||
> **Local-file maps never load this file.** If `## Ground rules` says `**Backend:** local`, close it and use `questions.md`.
|
||||
|
||||
Everything the skill says about *judgement* is unchanged by the backend: the fog-vs-question test, the destination grill, one question at a time, the decide-menu-checkpoint cadence, HITL is never self-answered, the Clearing Gate rubric. This file changes only *where the bytes go*.
|
||||
Everything the skill says about *judgment* is unchanged by the backend: the fog-vs-question test, the destination grill, one question at a time, the decide-menu-checkpoint cadence, HITL is never self-answered, the Clearing Gate rubric. This file changes only *where the bytes go*.
|
||||
|
||||
---
|
||||
|
||||
@@ -17,13 +17,13 @@ A map on GitHub Issues buys three things local files cannot:
|
||||
| | Local files | GitHub Issues |
|
||||
|---|---|---|
|
||||
| Visibility | One machine, one person | Anyone with repo access, in a UI they already have open |
|
||||
| Blocking | A `Blocked by:` line only an agent reads | Native issue dependencies — GitHub greys out blocked issues in its own UI |
|
||||
| Blocking | A `Blocked by:` line only an agent reads | Native issue dependencies — GitHub grays out blocked issues in its own UI |
|
||||
| Concurrency | One session at a time by construction | Several people can work unblocked questions at once; the assignee is a real lock |
|
||||
|
||||
It costs three things too, and the human must know all three before they pick it:
|
||||
|
||||
1. **Issues on a public repo are public.** The destination, the rejected alternatives, the codebase recon, the technical debt in the blast radius — all of it is world-readable the moment it is written. Never chart to a public repo's tracker anything that would embarrass the project or leak a customer.
|
||||
2. **It writes to shared state.** A local map costs nothing to abandon. Twelve stale issues labelled `pathfinder:grill-hitl` on a team's tracker is litter someone has to clean.
|
||||
2. **It writes to shared state.** A local map costs nothing to abandon. Twelve stale issues labeled `pathfinder:grill-hitl` on a team's tracker is litter someone has to clean.
|
||||
3. **It needs `gh`, auth, and issues enabled.** More that can break, in a step whose whole job is to remove friction.
|
||||
|
||||
---
|
||||
@@ -69,7 +69,7 @@ This is the whole mapping. Everything below expands a row.
|
||||
|
||||
| Local file model | GitHub Issues model |
|
||||
|---|---|
|
||||
| `specs/<idea>/pathfinder/map.md` | One issue, labelled `pathfinder:map`, titled `Map: <idea>` |
|
||||
| `specs/<idea>/pathfinder/map.md` | One issue, labeled `pathfinder:map`, titled `Map: <idea>` |
|
||||
| `questions/NN-<slug>.md` | A **sub-issue** of the map, titled with the question name |
|
||||
| `NN` ordering | The map's sub-issue order — the order they were created, which is dependency order |
|
||||
| `## Question` in the file | The issue body |
|
||||
@@ -79,7 +79,7 @@ This is the whole mapping. Everything below expands a row.
|
||||
| `State: open` | Issue open, **no assignee** |
|
||||
| `State: claimed` | Issue open, **assigned** |
|
||||
| `State: resolved` | Issue **closed as completed**, with an `## Answer` comment |
|
||||
| `State: out-of-scope` | Issue **closed as not planned**, labelled `pathfinder:out-of-scope`, no `## Answer` |
|
||||
| `State: out-of-scope` | Issue **closed as not planned**, labeled `pathfinder:out-of-scope`, no `## Answer` |
|
||||
| `Blocked by: 02, 04` | Native issue dependencies (`dependencies/blocked_by`) |
|
||||
| `Locked: yes` | The `pathfinder:locked` label |
|
||||
| `Claimed: <timestamp>` | GitHub's own assignment event in the timeline |
|
||||
@@ -221,7 +221,7 @@ gh api --method POST repos/<owner>/<repo>/issues/<blocked-number>/dependencies/b
|
||||
|
||||
**The database id is the single most common failure in this backend.** `gh api repos/o/r/issues/42 --jq .id` returns something like `2716143027`. The `42` is the *number*; `I_kwDO...` is the *node id*. The node id is rejected outright. The *number* is worse: a small integer like `42` is itself a perfectly valid database id — of some unrelated issue created years ago — so the call can succeed and silently attach the wrong thing. Fetch `.id` for every issue you are about to reference, and never hand-assemble one.
|
||||
|
||||
Charting still writes `00-codebase-context`'s equivalent — the Step 3 recon you held. Create it **first**, labelled `pathfinder:legwork-afk`, post the recon as an `## Answer` comment, and close it as completed in the same pass. It is resolved on arrival, exactly as in local mode, and it is what the handoff's `## System Context` is built from.
|
||||
Charting still writes `00-codebase-context`'s equivalent — the Step 3 recon you held. Create it **first**, labeled `pathfinder:legwork-afk`, post the recon as an `## Answer` comment, and close it as completed in the same pass. It is resolved on arrival, exactly as in local mode, and it is what the handoff's `## System Context` is built from.
|
||||
|
||||
### If the endpoints are unavailable
|
||||
|
||||
@@ -384,7 +384,7 @@ Research subagents work the same way with one substitution: the brief carries th
|
||||
|
||||
Identical in shape; the inputs come from the query instead of the checklist.
|
||||
|
||||
- **Heading** — `🧭 <idea> · <Status> · <closed>/<total> cleared`, where `<total>` excludes anything labelled `pathfinder:out-of-scope`.
|
||||
- **Heading** — `🧭 <idea> · <Status> · <closed>/<total> cleared`, where `<total>` excludes anything labeled `pathfinder:out-of-scope`.
|
||||
- **Glyph order** — sub-issue order, the same order Chart Step 6 created them in.
|
||||
- **Glyphs** — `●` closed as completed · `◉` open and assigned to you · `○` open, unassigned, unblocked · `⊘` open with `blocked_by > 0` · `⊝` closed as not planned.
|
||||
- **Named legend** — names, never `#numbers`. `(blocked:<name>)` names the blocker rather than numbering it, since there is no stable `NN` to point at.
|
||||
|
||||
@@ -112,13 +112,13 @@ The primary channel. One question object per probe, up to three in a single call
|
||||
|
||||
- **Header** — the decision in two or three plain words (`Export format`, `Size cap`). Not a type, not a marker, not a number.
|
||||
- **Question** — the probe, with its why-it-matters. This is prose and it is not rationed; the same sentences you would have written in a Q block go here.
|
||||
- **Options** — the genuine alternatives, each described by its trade-off, with the recommended one named as such in its description. Two to four; the free-text escape hatch covers the rest. Label plainly, then let the description carry the precise term: `One file per message` labelling the `.eml`-in-a-ZIP option, with `.eml` named in the description.
|
||||
- **Options** — the genuine alternatives, each described by its trade-off, with the recommended one named as such in its description. Two to four; the free-text escape hatch covers the rest. Label plainly, then let the description carry the precise term: `One file per message` labeling the `.eml`-in-a-ZIP option, with `.eml` named in the description.
|
||||
|
||||
A short *label* is not a short *decision*. The label is a handle — `Fixed tick count` — and the description carries the trade-off that makes it choosable. A label bundling several independent answers is a probe that wants splitting.
|
||||
|
||||
**A click is a decision, not a sentence.** The HITL rule wants an `## Answer` traceable to something the human actually said, and a selected option label is thin evidence on its own. What makes tool-delivered answers legitimate is the recap turn in *Landing the grill* — you play the choices back in the tool's question text and they confirm or correct in their own words. Never skip the recap on the grounds that the tool already captured the answer; the tool captured the *pick*, and the recap captures the *agreement*.
|
||||
|
||||
**If a reply comes back thinner than the decision** — a bare click on something you now realise carries weight — do not paper over it. Fold the why into the recap turn as one more probe before writing the `## Answer`.
|
||||
**If a reply comes back thinner than the decision** — a bare click on something you now realize carries weight — do not paper over it. Fold the why into the recap turn as one more probe before writing the `## Answer`.
|
||||
|
||||
#### Numbered Q blocks
|
||||
|
||||
|
||||
@@ -102,7 +102,7 @@ Pathfinder writes `specs/<idea>/PLAN-DRAFT-<YYYYMMDD>.md` with the header line:
|
||||
|
||||
`**Status:** Phase 3 Complete - Resume at Phase 4`
|
||||
|
||||
`/plan2code-1-plan` **already recognises that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
|
||||
`/plan2code-1-plan` **already recognizes that exact string.** Its "Check for Existing Progress" block, which runs before Phase 1, reads:
|
||||
|
||||
`- Status "Phase 3 Complete - Resume at Phase 4": Resume at Phase 4`
|
||||
|
||||
@@ -128,7 +128,7 @@ Everything in the draft traces to something on the map. Nothing is invented at h
|
||||
| `## Destination` | Section 1 Executive Summary (2-3 sentences, present tense) and Section 7 Success Criteria (the destination restated as checkable outcomes) |
|
||||
| Resolved `grill` answers describing behavior | Section 2.1 Functional Requirements, one `FR-N` per decided behavior |
|
||||
| Resolved `grill` answers describing performance, security, scale, operability | Section 2.2 Non-Functional Requirements, one `NFR-N` each |
|
||||
| `## Out of scope` | Section 2.3 Out of Scope — copied line for line, wording and order intact. The ONLY permitted change is the link prefix: `./questions/` becomes `./pathfinder/questions/`, because the draft sits one level above the map. Do not re-word, re-order, or summarise; a re-worded scope boundary is a re-litigated one. |
|
||||
| `## Out of scope` | Section 2.3 Out of Scope — copied line for line, wording and order intact. The ONLY permitted change is the link prefix: `./questions/` becomes `./pathfinder/questions/`, because the draft sits one level above the map. Do not re-word, re-order, or summarize; a re-worded scope boundary is a re-litigated one. |
|
||||
| The testing-posture question's answer | Section 2.4 Testing Strategy table (Types / Phase Testing / Coverage) |
|
||||
| Resolved `research` answers and their `## Evidence` | Section 3 Tech Stack — the cited source becomes the Justification cell |
|
||||
| `questions/00-codebase-context.md` | The `## System Context` section, and the components table in 4.3 |
|
||||
@@ -211,7 +211,7 @@ next run rather than truncating.
|
||||
| Entry points to change | `AuditExportJob`, registered in `HangfireStartup.ConfigureRecurringJobs()` | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
|
||||
| Existing patterns to follow | Jobs resolve tenant scope via `ITenantScopeFactory`; no job reads config directly | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
|
||||
| Integration surfaces | S3 (customer-owned), Hangfire scheduler, `TenantConfigStore` | [Destination auth](./pathfinder/questions/03-destination-auth.md), [Scheduling model](./pathfinder/questions/02-scheduling-model.md) |
|
||||
| Technical debt in the path | `AuditQuery` materialises full result sets; streaming reader needed before FR-1 | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
|
||||
| Technical debt in the path | `AuditQuery` materializes full result sets; streaming reader needed before FR-1 | [Codebase context](./pathfinder/questions/00-codebase-context.md) |
|
||||
| System boundaries | Read-only against the audit store; writes only to customer buckets and the run-log table | [Retention and replay](./pathfinder/questions/04-retention-and-replay.md) |
|
||||
| Conventions in force | `AGENTS.md` present and read; its logging and DI conventions govern | `pathfinder/map.md` ## Ground rules |
|
||||
|
||||
@@ -280,7 +280,7 @@ Manifest sequence numbers are per tenant, monotonic, and reused on replay.
|
||||
| Cross-account role assumption is unexercised in this codebase | Medium | High | Spike `S3RoleAssumer` against a second AWS account before any other component |
|
||||
| A tenant exceeds the daily ceiling indefinitely | Medium | Medium | Spill oldest-first plus a three-run alarm — [Overflow behavior](./pathfinder/questions/08-overflow-behavior.md) |
|
||||
| Partial objects visible after a failed run | Low | High | Upload to a run-scoped prefix, publish the manifest last — the manifest is the commit point |
|
||||
| `AuditQuery` materialises full result sets | High | High | Streaming reader is a prerequisite, not an optimisation |
|
||||
| `AuditQuery` materializes full result sets | High | High | Streaming reader is a prerequisite, not an optimization |
|
||||
| Customer revokes the role mid-run | Low | Medium | Fail the run whole; replay window covers recovery |
|
||||
|
||||
## 7. Success Criteria
|
||||
@@ -335,7 +335,7 @@ Ruled out of scope: [Failure notification](./pathfinder/questions/07-failure-not
|
||||
|
||||
**No scrapable confidence numbers anywhere in the file.** Write the confidence as `Requirements-clarity 22/25 · Feasibility-technical 21/25 · Integration-points 23/25 · Risk-assessment 20/25` — hyphenated dimension labels, sub-scores over 25, no total, no percent sign.
|
||||
|
||||
The reason is exact. When a PLAN-DRAFT carries no `METRICS_JSON` comment, the metrics collector falls back to scraping it by regex: an overall-confidence pattern that requires a literal `%`, and four breakdown patterns that match a bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed directly by whitespace, a colon, or a pipe and then digits. **The breakdown patterns do not require a percent sign.** A pathfinder-written draft always lacks that comment until `/plan2code-1-plan` Phase 7 appends one, so both the percent sign *and* the bare dimension words have to be kept off the page — otherwise the pipeline records a planning-step confidence that no planning step ever produced. The hyphen in `Requirements-clarity` breaks the match; a table row reading `| Requirements | 11 |` does not, which is why the Scope Assessment row is labelled `Requirements decided`.
|
||||
The reason is exact. When a PLAN-DRAFT carries no `METRICS_JSON` comment, the metrics collector falls back to scraping it by regex: an overall-confidence pattern that requires a literal `%`, and four breakdown patterns that match a bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed directly by whitespace, a colon, or a pipe and then digits. **The breakdown patterns do not require a percent sign.** A pathfinder-written draft always lacks that comment until `/plan2code-1-plan` Phase 7 appends one, so both the percent sign *and* the bare dimension words have to be kept off the page — otherwise the pipeline records a planning-step confidence that no planning step ever produced. The hyphen in `Requirements-clarity` breaks the match; a table row reading `| Requirements | 11 |` does not, which is why the Scope Assessment row is labeled `Requirements decided`.
|
||||
|
||||
**The `**Next:**` footer must ship with both bullets.** Pathfinder cannot edit the planning skill, so those two instructions travel inside the artifact:
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ One idea per session, so there is only ever one trail.
|
||||
Confidence: solid, but Risk is borderline.
|
||||
|
||||
WAITING ON YOU · answer here, in this conversation:
|
||||
Q2 Ceiling behaviour past the cap (re-ask) · Q3 Who sees the truncation warning
|
||||
Q2 Ceiling behavior past the cap (re-ask) · Q3 Who sees the truncation warning
|
||||
```
|
||||
|
||||
- The heading counts resolved questions over every question except out-of-scope ones.
|
||||
|
||||
@@ -1097,31 +1097,31 @@ async function cmdLint(loc) {
|
||||
if (b === q.nn) add("error", q.path, "is blocked by itself");
|
||||
}
|
||||
}
|
||||
// Cycles in Blocked by: a three-colour depth-first search (grey = on the
|
||||
// Cycles in Blocked by: a three-color depth-first search (gray = on the
|
||||
// current path, black = fully explored), so each question is explored once
|
||||
// however densely the questions block each other. Every back edge is a
|
||||
// cycle, reported once, against the question it starts from.
|
||||
const reported = new Set();
|
||||
const colour = new Map();
|
||||
const color = new Map();
|
||||
const pathStack = [];
|
||||
const visit = (nn) => {
|
||||
colour.set(nn, "grey");
|
||||
color.set(nn, "gray");
|
||||
pathStack.push(nn);
|
||||
for (const b of byNN.get(nn).blockedBy) {
|
||||
if (!byNN.has(b)) continue;
|
||||
if (colour.get(b) === "grey") {
|
||||
if (color.get(b) === "gray") {
|
||||
const c = [...pathStack.slice(pathStack.indexOf(b)), b];
|
||||
const key = [...new Set(c)].sort().join(",");
|
||||
if (!reported.has(key)) {
|
||||
reported.add(key);
|
||||
add("error", byNN.get(b).path, `Blocked by: cycle ${c.join(" -> ")}; a cycle is one decision phrased twice (merge them or drop an edge)`);
|
||||
}
|
||||
} else if (!colour.has(b)) visit(b);
|
||||
} else if (!color.has(b)) visit(b);
|
||||
}
|
||||
pathStack.pop();
|
||||
colour.set(nn, "black");
|
||||
color.set(nn, "black");
|
||||
};
|
||||
for (const q of questions) if (!colour.has(q.nn)) visit(q.nn);
|
||||
for (const q of questions) if (!color.has(q.nn)) visit(q.nn);
|
||||
// Scraper bait in the files the collector or a reader treats as planning output.
|
||||
const baitFiles = [loc.mapPath, ...walk(path.join(loc.pf, "briefs"))];
|
||||
for (const n of fs.existsSync(loc.ideaDir) ? fs.readdirSync(loc.ideaDir) : []) {
|
||||
|
||||
@@ -23,7 +23,7 @@ The map lives in ONE of two places — the human's pick at Chart Step 1, never y
|
||||
|
||||
Read references/github-issues.md — REQUIRED on `github`, skip on `local`.
|
||||
|
||||
> Fallback: map = a `pathfinder:map` issue titled `Map: <idea>`; questions = its sub-issues, labelled `pathfinder:<type>-<mode>`; blocking = native dependencies; claim = assign `@me`; resolve = `## Answer` comment, then close.
|
||||
> Fallback: map = a `pathfinder:map` issue titled `Map: <idea>`; questions = its sub-issues, labeled `pathfinder:<type>-<mode>`; blocking = native dependencies; claim = assign `@me`; resolve = `## Answer` comment, then close.
|
||||
|
||||
Recorded as the first `## Ground rules` bullet (`**Backend:** local|github`), never re-asked or switched. Either way the PLAN-DRAFT lands in local `specs/<idea>/` — downstream steps read files, not issues.
|
||||
|
||||
|
||||
@@ -43,6 +43,16 @@ Check if `./AGENTS.md` exists:
|
||||
- NEVER write implementation code; keep responses conceptual, detailed specs belong in the final PLAN-DRAFT only
|
||||
- If no file access, output content in code blocks with file path headers
|
||||
|
||||
## Helpers
|
||||
|
||||
When your tool can start helpers (subagents) and they are not switched off for this run (on the web console a `Subagents:` block says which, console-subagents.md), hand them the work whose answer does not hang on the conversation still to come:
|
||||
- **Phase 1:** reading each file, folder or reference the person names, and the domain research; one source per helper.
|
||||
- **Phase 2:** mapping separate areas of the codebase, one area per helper (structure, one component's real behavior, one integration point). Each returns facts with `file:line`, never a design.
|
||||
- **Phase 4:** evidence on each open tech choice (current version, upkeep, fit with the stack); the recommendation stays yours.
|
||||
- **Phase 7, step 3:** one fresh helper, briefed only with the PLAN-CONVERSATION and the PLAN-DRAFT, lists the gaps between them; confirm each yourself before you add it.
|
||||
|
||||
Keep with you: every question, confidence score, decision and sign-off, Phases 3, 5 and 6, and the writing of the PLAN-DRAFT (its sections cross-reference each other and rest on decisions only this session holds). Pick each helper's strength and effort from references/helper-strength.md. Every helper reports back before that phase's sign-off. No helpers? Do the same work yourself.
|
||||
|
||||
---
|
||||
|
||||
### Check for Existing Progress
|
||||
|
||||
@@ -31,6 +31,14 @@ The FIRST thing you do, before anything else in this file — before Step 1, bef
|
||||
- `node "<S>/specs.mjs" status <spec>`: phases, task counts by marker, `checks`, `pending`.
|
||||
- `node "<S>/specs.mjs" mark <spec> --phase <N> --to open`: re-open a completed phase in overview.md.
|
||||
|
||||
## Helpers
|
||||
|
||||
When your tool can start helpers (subagents) and they are not switched off for this run (on the web console a `Subagents:` block says which, console-subagents.md):
|
||||
- **Steps 1 and 2, read-only lookups:** the code behind each affected task (its functions and files as they stand now, for Step 3's code references), and the code behind completed tasks the change could undo, so **Completed Work at Risk** rests on evidence. One area per helper.
|
||||
- **Step 3, only after approval, when the revision touches 3 or more phase files:** one helper per `phase-X.md` whose edits the approved plan spells out. Run `mark` for every re-opened phase before starting them, since it rewrites that phase file too. Its brief carries that file's approved changes, the `🔄 REVISED` / `🆕 ADDED` formats, and the rule that it edits that one file under `specs/` and nothing else.
|
||||
|
||||
Keep with you: every question, the Step 2 approval, overview.md (`mark`, Revision History), the waiting brief's line, dependencies and numbering across phases, and Steps 4 to 6. Re-read every file a helper edited against the approved plan before Step 4. Strength and effort per references/helper-strength.md. No helpers? Do the same work yourself.
|
||||
|
||||
## Required Context
|
||||
|
||||
Find the spec with `specs.mjs list`, then request these files if not provided:
|
||||
|
||||
@@ -164,7 +164,7 @@ Use kebab-case for feature name (e.g., `user-authentication`).
|
||||
- "Run after each phase": Add testing task block at end of EVERY phase
|
||||
- "Dedicated phase only": Create final Phase N: Testing
|
||||
- "None" or empty: Omit testing tasks
|
||||
- `| Approach | Test first |` in 2.4: in every phase, order each task's test before its code and put a plain sub-bullet ` - Test: <where the test drives the behaviour>` directly under the task line (no checkbox, so the loop's task count is unchanged), for example `` - Test: through `POST /votes` ``
|
||||
- `| Approach | Test first |` in 2.4: in every phase, order each task's test before its code and put a plain sub-bullet ` - Test: <where the test drives the behavior>` directly under the task line (no checkbox, so the loop's task count is unchanged), for example `` - Test: through `POST /votes` ``
|
||||
|
||||
**Small Projects (1-2 phases):** Combine sections, still create separate overview.md and phase-1.md. Note: "Small project - phases combined"
|
||||
|
||||
|
||||
@@ -26,7 +26,7 @@ The FIRST thing you do, before anything else in this file — before reading a s
|
||||
- Run tests ONLY if a phase task or a task's `Test:` line lists them
|
||||
- Do NOT run git commands - provide commit instructions for user
|
||||
- Flag blockers clearly - never skip silently
|
||||
- Read `references/building-habits.md` when a bug or unexpected failing test turns up, before any task in a Test first phase (its tasks carry `Test:` lines), and before any task that changes no behaviour; follow it.
|
||||
- Read `references/building-habits.md` when a bug or unexpected failing test turns up, before any task in a Test first phase (its tasks carry `Test:` lines), and before any task that changes no behavior; follow it.
|
||||
- No file tools: output contents in code blocks with a file path header; no filesystem: ask the user to paste file contents
|
||||
|
||||
## Required Context
|
||||
|
||||
@@ -71,7 +71,7 @@ A reproduction written as a new test inside the project is offered, never assume
|
||||
### Step 3: Narrow
|
||||
|
||||
- **A known-good version exists** (it worked before): `git bisect` with the reproduction as the check, in a throwaway worktree (`git worktree add <tmp> HEAD`, removed at the end) so the person's checkout never moves; in place only on a clean tree, with `git bisect reset` before you finish. Then read the commit it lands on.
|
||||
- **Otherwise:** read the code path from the entry point the reproduction hits to where the wrong value or behaviour first appears.
|
||||
- **Otherwise:** read the code path from the entry point the reproduction hits to where the wrong value or behavior first appears.
|
||||
- Temporary logging only outside the source tree, or reverted at once.
|
||||
|
||||
Stop when you can name the line where right turns into wrong.
|
||||
|
||||
@@ -59,7 +59,7 @@ On the console the page draws the board itself from `state.git`; you never post
|
||||
|
||||
1. Post an `activity` line ("Pulling from origin…"); collecting the click already set the page to working.
|
||||
2. Run `git.mjs plan <op>` with the action's fields as flags.
|
||||
3. With `ask: true`: a `confirm` becomes a `confirm` card, posted verbatim (`danger` and `consequences` as given; `files` as a `[{ path, state }]` table where the plan names files). A `card` of kind `switch`, `dirty` or `remote` becomes a `choice` card with exactly its `options`, labelled **Switch and bring them** (`bring`), **Commit first** (`commit-first`) and **Cancel** (`cancel`), or for `remote` one option per remote with `preset` recommended; put git's `reason` in `body` when given. Then wait for the answer. A `remote` pick plans `publish --remote <it>` again and asks its `confirm`.
|
||||
3. With `ask: true`: a `confirm` becomes a `confirm` card, posted verbatim (`danger` and `consequences` as given; `files` as a `[{ path, state }]` table where the plan names files). A `card` of kind `switch`, `dirty` or `remote` becomes a `choice` card with exactly its `options`, labeled **Switch and bring them** (`bring`), **Commit first** (`commit-first`) and **Cancel** (`cancel`), or for `remote` one option per remote with `preset` recommended; put git's `reason` in `body` when given. Then wait for the answer. A `remote` pick plans `publish --remote <it>` again and asks its `confirm`.
|
||||
4. Run the command(s).
|
||||
5. In ONE post: `{ "reread": true }`, the `git-result` notice (one line: what happened, with short hashes, and after a push or publish the link from `pr-url`), `board: { describe }` when changes remain (a short kebab-case description of them, for the Create prompt), posted with `--wait`.
|
||||
|
||||
@@ -74,7 +74,7 @@ On a non-zero exit, save git's stderr to the session folder, run `classify-error
|
||||
- **commit** commits only the paths in `files`. With `ignore[]`, first propose those `.gitignore` lines as a doc plus a `review` card (approve / change), write them on approve, and add `.gitignore` to the commit.
|
||||
- **abort**, **continue**: `plan abort` / `plan continue`, then `reread`.
|
||||
- **pr-host**: the server already saved the answer; post `reread` only.
|
||||
- **done** (Done with git): Session End; a card of yours still open is cancelled first (notes/git.md).
|
||||
- **done** (Done with git): Session End; a card of yours still open is canceled first (notes/git.md).
|
||||
- Deleting a branch on the remote is never offered and never run.
|
||||
|
||||
## Conflict help
|
||||
|
||||
@@ -71,7 +71,7 @@ The `Failure log` section below is a recording of mistakes made by previous AI A
|
||||
|
||||
When you make a mistake, get corrected, or discover something about this codebase that wasn't written down:
|
||||
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behaviour.
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behavior.
|
||||
2. Keep it specific to this repo. General advice belongs nowhere.
|
||||
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
|
||||
4. Include the change in the same commit and mention it in your summary.
|
||||
@@ -156,7 +156,7 @@ Present the user with update options:
|
||||
| Testing | Commands? Fixtures? Mocking? |
|
||||
| Environment | Local/CI/deploy? Env vars/files? |
|
||||
| Rules | Project-wide or specific? Why? |
|
||||
| Failure Log | What went wrong? Correct behaviour (imperative, one line)? Merge into an entry on the same topic if one exists; over 17 entries, propose what to prune (rule 7). |
|
||||
| Failure Log | What went wrong? Correct behavior (imperative, one line)? Merge into an entry on the same topic if one exists; over 17 entries, propose what to prune (rule 7). |
|
||||
| Other | "Tell me what to add." |
|
||||
| Sync & Maintain | Scope: all surfaces or specific? Then follow the Sync & Maintain section. |
|
||||
| Review | Per section: "Still accurate?" |
|
||||
|
||||
@@ -74,7 +74,7 @@ The `Failure log` section below is a recording of mistakes made by previous AI A
|
||||
|
||||
When you make a mistake, get corrected, or discover something about this codebase that wasn't written down:
|
||||
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behaviour.
|
||||
1. Add one line to the `Failure log` below, in the imperative, describing the correct behavior.
|
||||
2. Keep it specific to this repo. General advice belongs nowhere.
|
||||
3. If this fix is a workflow rather than a rule, put it in `.claude/skills/` and link it from here.
|
||||
4. Include the change in the same commit and mention it in your summary.
|
||||
|
||||
@@ -40,7 +40,7 @@ Check for `./AGENTS.md` first:
|
||||
- Standalone workflow - does NOT create spec files or feed into steps 2-4
|
||||
- Launched with a spec folder holding a `DIAGNOSIS-*.md`: read it first, as the bug's context (its cause and suggested fix are already found; re-run its reproduction before and after the fix). Once it passes, set the diagnosis `**Status:**` to `Fixed`; escalating, use that folder rather than asking for a name. Fixed, with nothing in the folder past the diagnosis (no `PLAN-CONVERSATION`, `PLAN-DRAFT`, `pathfinder/map.md` or `overview.md`)? It is done: run `node "<S>/specs.mjs" archive <spec> --dry-run` from the project root (`<S>` is `scripts/` beside this SKILL.md, `~/.agents/skills/plan2code-quick-task/scripts/` globally), show its `files`, ask "Archive it to `specs--completed/`? (yes / no)", and on yes run it without `--dry-run`. On no it stays on the dashboard as "Bug fixed".
|
||||
- Cause unclear or the fix big? Stop and suggest `/plan2code-diagnose`.
|
||||
- Read `references/building-habits.md` when the ask is a bug fix or a test fails unexpectedly, after a yes to "Write the test first?", and before a change meant to alter no behaviour; follow it.
|
||||
- Read `references/building-habits.md` when the ask is a bug fix or a test fails unexpectedly, after a yes to "Write the test first?", and before a change meant to alter no behavior; follow it.
|
||||
|
||||
```
|
||||
⋅
|
||||
@@ -52,7 +52,7 @@ Check for `./AGENTS.md` first:
|
||||
|
||||
Ask what feature the user wants, then ask follow-up questions until 100% clear. Console: that first card carries `"templates": "idea"` (console.md → The kinds).
|
||||
|
||||
**Write the test first?** Ask it with the follow-ups (or on its own if there are none) only when the change alters behaviour AND the project already has a test runner you can see (a `test` script in `package.json`, pytest config in `pytest.ini` or `pyproject.toml`, `go.mod` with `_test.go` files, or similar). Never for a pure refactor, a docs change, or a project with no runner. Console: one `confirm` card in the same batch as the other plan questions; terminal: one line in the same prompt. On yes, name the test spot in the plan's Verify section and follow the test-first habit.
|
||||
**Write the test first?** Ask it with the follow-ups (or on its own if there are none) only when the change alters behavior AND the project already has a test runner you can see (a `test` script in `package.json`, pytest config in `pytest.ini` or `pyproject.toml`, `go.mod` with `_test.go` files, or similar). Never for a pure refactor, a docs change, or a project with no runner. Console: one `confirm` card in the same batch as the other plan questions; terminal: one line in the same prompt. On yes, name the test spot in the plan's Verify section and follow the test-first habit.
|
||||
|
||||
## Scope Validation
|
||||
|
||||
|
||||
+2
-2
@@ -19,7 +19,7 @@ If `open` fails outright, fall back without drama: list the skills in the termin
|
||||
|
||||
## The menu
|
||||
|
||||
The page draws the cards itself — you never send the list. It also knows the repo already: `open` scans `AGENTS.md` and `specs/` into `state.scan` (`{ hasAgents, isGit, specs: [{ dir, name, state, detail, touched }] }`), and the picker at the top enables or greys every card from it — the spec the person picks there is the target their launch carries. What you post is your judgment on top of that:
|
||||
The page draws the cards itself — you never send the list. It also knows the repo already: `open` scans `AGENTS.md` and `specs/` into `state.scan` (`{ hasAgents, isGit, specs: [{ dir, name, state, detail, touched }] }`), and the picker at the top enables or grays every card from it — the spec the person picks there is the target their launch carries. What you post is your judgment on top of that:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
@@ -137,6 +137,6 @@ You arrive here mid-conversation after a `__dashboard` press — from a finished
|
||||
|
||||
## While it waits
|
||||
|
||||
- Bounded slices per console.md, using the longest safe slice: exit 10 → relay one line and immediately wait again — never end the turn after an arbitrary number of slices; exit 20 → `open --resume <sid>` (no `--workflow` — it stays `dashboard` until a launch overwrites it); exit 30 → they cancelled, ask in the terminal what they want.
|
||||
- Bounded slices per console.md, using the longest safe slice: exit 10 → relay one line and immediately wait again — never end the turn after an arbitrary number of slices; exit 20 → `open --resume <sid>` (no `--workflow` — it stays `dashboard` until a launch overwrites it); exit 30 → they canceled, ask in the terminal what they want.
|
||||
- A `__stop` action is the person ending the session before picking: post `finish` (a headline that says paused, `"command": "/plan2code"`) then `stop`, per console-stop.md.
|
||||
- The console keeps `agent.status` honest: collecting a pick sets `working`, and waiting on the menu sets `waiting`. Post an `activity` while a launch becomes a skill.
|
||||
@@ -15,17 +15,17 @@ When a bug is reported or turns up, or a test fails unexpectedly:
|
||||
Applies only when the phase's tasks carry `Test:` lines (the plan picked Test first), or the person said yes to "Write the test first?" in Quick Task. For each task:
|
||||
|
||||
1. Write the test at the task's named test spot (its `Test:` line, or the plan's Verify section).
|
||||
2. Run it and see it fail for the right reason: the behaviour is missing, not a typo or an import error.
|
||||
2. Run it and see it fail for the right reason: the behavior is missing, not a typo or an import error.
|
||||
3. Write the code until the test passes. Keep the change to what the test asks for.
|
||||
4. Never weaken, skip or delete a test to make it pass. If the test itself is wrong, say so and fix the test on its own.
|
||||
|
||||
## Pin behaviour first
|
||||
## Pin behavior first
|
||||
|
||||
For a task meant to change no behaviour (a restructure, a rename, a move):
|
||||
For a task meant to change no behavior (a restructure, a rename, a move):
|
||||
|
||||
1. Before touching the code, add or confirm tests that cover what the task touches.
|
||||
2. Run them and see them pass.
|
||||
3. Make the change.
|
||||
4. Run the same tests, unchanged. They must pass. A test that needs editing means behaviour changed: stop and say so.
|
||||
4. Run the same tests, unchanged. They must pass. A test that needs editing means behavior changed: stop and say so.
|
||||
|
||||
Adapted from Matt Pocock's `diagnose` and `tdd` skills and pstack's debugging playbook (both MIT).
|
||||
@@ -1,5 +1,5 @@
|
||||
# Helper Strength
|
||||
> Shared by the skills that start helpers (subagents): Pathfinder, Quick Task, Implement, Implement + Review and Review. Read it when you first start a helper in a session. Never invoked as a skill.
|
||||
> Shared by the skills that start helpers (subagents): Pathfinder, Plan, Revise Plan, Quick Task, Implement, Implement + Review and Review. Read it when you first start a helper in a session. Never invoked as a skill.
|
||||
|
||||
## The words
|
||||
|
||||
@@ -17,10 +17,12 @@ Never write a model or vendor name in a brief, a report or a file, and never inv
|
||||
| Helper's job | Strength | Effort |
|
||||
|---|---|---|
|
||||
| Lookups, reading code, checking docs, recon | light | low |
|
||||
| Revise Plan edit to one phase file, spelled out in the approved plan | light | medium |
|
||||
| Build task in 1 or 2 files, with the change spelled out in the task | light | medium |
|
||||
| Build task across several files, integration work, debugging | standard | medium |
|
||||
| Build task needing a design decision the spec leaves open | strongest (or keep it yourself) | high |
|
||||
| Pathfinder research question, sketch | standard | medium |
|
||||
| Plan's PLAN-DRAFT cross-check against the conversation | standard | medium |
|
||||
| Review analysis, focused scope | standard | high |
|
||||
| Review analysis, branch or full scope, or touching security, auth or data | strongest | high |
|
||||
|
||||
@@ -28,7 +30,7 @@ Decide from these signals: how many files the job touches, whether the task spel
|
||||
|
||||
## Floor and escalation
|
||||
|
||||
- A review helper never runs below `standard`.
|
||||
- A review helper, or Plan's PLAN-DRAFT cross-check, never runs below `standard`.
|
||||
- A retry, after a helper fails or after its work fails the phase's tests, goes one strength up and at least `medium` effort. Never retry at the same strength.
|
||||
- When a `strongest` helper fails, its task comes back to you.
|
||||
|
||||
|
||||
@@ -177,7 +177,7 @@ export function writeIfChanged(file, content) {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Normalise line endings for parsing; keep the original for writing back. */
|
||||
/** Normalize line endings for parsing; keep the original for writing back. */
|
||||
export function eol(text) {
|
||||
return text.includes("\r\n") ? "\r\n" : "\n";
|
||||
}
|
||||
|
||||
@@ -206,7 +206,7 @@ function parseGroups(overview) {
|
||||
if (cells.length < 2 || /^group$/i.test(cells[0])) continue;
|
||||
const id = plainText(cells[0]);
|
||||
const phases = phaseList(cells[1]);
|
||||
// "None", a dash, a single phase, a group its author labelled sequential
|
||||
// "None", a dash, a single phase, a group its author labeled sequential
|
||||
// ("A (sequential)"), or a Phases cell written as a chain ("1 → 2") is not
|
||||
// a parallel group.
|
||||
if (!id || /^(none|-|–|—)$/i.test(id) || /\bsequential\b/i.test(id) || /→|->|\bthen\b/i.test(cells[1]) || phases.length < 2) continue;
|
||||
|
||||
@@ -73,7 +73,7 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
in the web console"; call again), 20 = server gone (open --resume
|
||||
<sid>), 30 = cancelled. Exits 0 and 10 carry terminalLine.
|
||||
<sid>), 30 = canceled. Exits 0 and 10 carry terminalLine.
|
||||
Exit 0 may carry "chat" (Quick questions); with no card send it
|
||||
is type: "chat" and actions is empty. Exit 0 may also carry
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
|
||||
@@ -73,7 +73,7 @@ export function useCli(cli) {
|
||||
|
||||
// PLAN2CODE_CONSOLE_TRACE=1 prints where the time goes, to stderr: the
|
||||
// start path is what stands between someone and their first look at the page,
|
||||
// and it is only worth optimising with numbers in hand.
|
||||
// and it is only worth optimizing with numbers in hand.
|
||||
const TRACE = Boolean(process.env.PLAN2CODE_CONSOLE_TRACE);
|
||||
function trace(what) {
|
||||
if (TRACE) process.stderr.write(`trace ${Math.round(performance.now())}ms ${what}\n`);
|
||||
|
||||
@@ -50,9 +50,9 @@ first, and post before anything slow.
|
||||
`state.scan` is `{ hasAgents, isGit, pending, specs: [{ dir, name, state, detail, touched }], handoffs, handoffsDir }`,
|
||||
a snapshot of the last `open` (a spec created mid-session appears the next time
|
||||
the session resumes as a dashboard). `pending` is how many files a commit would
|
||||
take (`null` when git cannot say): the Git card never greys out, shows the count
|
||||
take (`null` when git cannot say): the Git card never grays out, shows the count
|
||||
when there is one, and outside a repository says Git can start one. The picker
|
||||
greys the cards that do not fit the selected spec — or hides them, while the
|
||||
grays the cards that do not fit the selected spec — or hides them, while the
|
||||
**Hide unavailable workflows** switch under it is on (the default).
|
||||
|
||||
The `menu` you post (`note`, `recommend`, `details`) describes the initially
|
||||
|
||||
@@ -4,7 +4,7 @@ Part of the web console contract (`console.md`). Read when a `Subagents:` block
|
||||
arrives, or when your workflow notes say to report helpers.
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
`review`, `pathfinder`, `plan`, `revise-plan`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, on until switched off, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
@@ -59,7 +59,7 @@ export class NotepadError extends Error {
|
||||
|
||||
/* ------------------------------------------------------------------ names */
|
||||
|
||||
// `<folder-name>-<first 12 hex of sha256(foldKey(folder))>`: recognisable in a
|
||||
// `<folder-name>-<first 12 hex of sha256(foldKey(folder))>`: recognizable 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) {
|
||||
|
||||
@@ -64,7 +64,7 @@ answer. `__git` names no question, like `__stop`.
|
||||
| `plan` says | On the page |
|
||||
| --- | --- |
|
||||
| `confirm` | A `confirm` card with its `title`, `body`, `danger` and `consequences` verbatim (the consequences end with the exact command). Where the plan names files, add them as `files: [{ "path", "state" }]`. |
|
||||
| `card.kind: "switch"` | A `choice`, "Bring your changes?": exactly the `options` given, labelled **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); the files in `body`, and `reason` when git would refuse (then there is no `bring`). `allowOther: false`. |
|
||||
| `card.kind: "switch"` | A `choice`, "Bring your changes?": exactly the `options` given, labeled **Switch and bring them** (`bring`), **Commit first** (`commit-first`), **Cancel** (`cancel`); the files in `body`, and `reason` when git would refuse (then there is no `bring`). `allowOther: false`. |
|
||||
| `card.kind: "dirty"` | The same `choice` for a pull that needs a clean tree: **Commit first** / **Cancel**, `reason` in `body`. |
|
||||
| `card.kind: "remote"` | A `choice`, "Publish to which remote?": one option per remote, `preset` recommended. Then `plan publish --remote <it>` and its `confirm`. |
|
||||
| `ask: false` | No card: run it on the click. |
|
||||
@@ -109,9 +109,9 @@ after each commit step (N commits made), and `run: { "event": "git-conflict",
|
||||
"id": "conflict-<n>" }` once per conflict help, resolved or aborted.
|
||||
|
||||
**Finishing** (`console-finish.md`). **Done with git** (`op: "done"`). A `done`
|
||||
that arrives while one of your cards is still open is the person cancelling it:
|
||||
record that card as cancelled (`{ "items": [{ "id": "<id>", "status":
|
||||
"answered", "answer": { "text": "Cancelled by Done with git" } }] }`, not
|
||||
that arrives while one of your cards is still open is the person canceling it:
|
||||
record that card as canceled (`{ "items": [{ "id": "<id>", "status":
|
||||
"answered", "answer": { "text": "Canceled by Done with git" } }] }`, not
|
||||
`settle`, which refuses a card nothing was sent to) in the same post as the
|
||||
finish, or, with nothing done, before resuming as the dashboard. Never run what
|
||||
the card was asking for. With something done this session: a `finish` with a
|
||||
|
||||
@@ -15,3 +15,8 @@ Workflow notes for `plan`, part of the web console contract (`console.md`).
|
||||
browser user is not watching.
|
||||
- The Large checkpoint finish is a pause: a headline starting "Paused", no
|
||||
`dashboard`, and `stop` at once.
|
||||
- Plan offers the Subagents switch. A `Subagents:` block may arrive on `open`
|
||||
output or a `wait` / `chat` pickup: follow `console-subagents.md` and the
|
||||
skill's Helpers section, and report each helper as `helpers`. Post a helper
|
||||
as `done` or `failed` before the sign-off it feeds, and every one before a
|
||||
`finish`. Questions, sign-offs and the PLAN-DRAFT stay with you.
|
||||
@@ -16,3 +16,11 @@ offers to execute or implement.** Pass `--spec specs/<feature>` to `open`, or
|
||||
post `specDir` once you know it. The finish command is
|
||||
`/plan2code-3-implement specs/<feature>/overview.md`; an abort's is
|
||||
`/plan2code-1b-revise-plan specs/<feature>/overview.md`.
|
||||
|
||||
Revision offers the Subagents switch. A `Subagents:` block may arrive on
|
||||
`open` output or a `wait` / `chat` pickup: follow `console-subagents.md` and
|
||||
the skill's Helpers section, and report each helper as `helpers`. Lookup
|
||||
helpers report back before the Step 2 review item goes up; phase-file helpers
|
||||
report back before the Step 4 check. Every gate stays with you, and a helper's
|
||||
`title`, `ask` and `result` follow the same rule as every label: nothing
|
||||
offers to execute or implement.
|
||||
@@ -8,7 +8,7 @@
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
/** The link to open, normalised, or null when it is not a plain http or https link. */
|
||||
/** The link to open, normalized, or null when it is not a plain http or https link. */
|
||||
export function linkToOpen(raw) {
|
||||
if (typeof raw !== "string" || raw.length > 4096) return null;
|
||||
let url;
|
||||
|
||||
@@ -249,7 +249,7 @@ export function pickerCommand(start, prompt) {
|
||||
* Show the picker and settle on what the person did: `{ path }` for a pick,
|
||||
* `{ cancelled: true }` when they closed it, `{ error }` when the picker
|
||||
* itself failed or this OS has none. Pickers exit 0 or 1 with nothing printed
|
||||
* when cancelled.
|
||||
* when canceled.
|
||||
*/
|
||||
export function pickFolder(start, prompt, { spawnImpl = spawn } = {}) {
|
||||
const picker = pickerCommand(start, prompt);
|
||||
|
||||
@@ -244,7 +244,7 @@ export function suggestionFrom(item) {
|
||||
if (!raw) return "";
|
||||
const stripped = raw.replace(EXAMPLE_LEAD, "").trim();
|
||||
if (!stripped) return "";
|
||||
// Recapitalise only when a lead-in was actually removed, and never on a
|
||||
// Recapitalize only when a lead-in was actually removed, and never on a
|
||||
// field with a shape to match: "audit-export" must not become "Audit-export".
|
||||
if (stripped !== raw && !item.pattern && /^[a-z]/.test(stripped)) {
|
||||
return stripped[0].toUpperCase() + stripped.slice(1);
|
||||
@@ -358,7 +358,7 @@ export function stopAction({ handoff } = {}) {
|
||||
* answers into the files, and a request landing then is how a question ends up
|
||||
* half recorded. `waiting` is the caller's "the agent is working or a reply is
|
||||
* owed, and it has not gone adrift" -- an agent that has stopped checking in
|
||||
* never replies, and a button greyed out forever would lock the person in. An
|
||||
* never replies, and a button grayed out forever would lock the person in. An
|
||||
* uncollected send still blocks even then, because the server takes one at a
|
||||
* time.
|
||||
*/
|
||||
@@ -665,7 +665,7 @@ export function dashNoteKind({ menu, hasMenu, onInitial, working }) {
|
||||
* availability — but its folder still goes along on a Pathfinder or Plan
|
||||
* launch, since the files may be reference docs.
|
||||
*
|
||||
* Returns { on, reason?, note?, next? } — `reason` is the one line a greyed card
|
||||
* Returns { on, reason?, note?, next? } — `reason` is the one line a grayed card
|
||||
* shows, `note` the one line a clickable card shows when there is something to
|
||||
* know before launching it, `next` marks the state's natural step. `lookup` is
|
||||
* stateFor unless a test hands in its own table.
|
||||
@@ -681,7 +681,7 @@ export function cardAvailability(entry, scan, sel, lookup = stateFor) {
|
||||
if (entry.skill === "plan2code-init") return hasAgents ? off(rule.greyed.default) : ON;
|
||||
if (entry.skill === "plan2code-init-update") return hasAgents ? ON : off(rule.greyed.default);
|
||||
if (entry.skill === "plan2code-git") {
|
||||
// Never greyed: a clean tree still has branches to switch, pull and push.
|
||||
// Never grayed: a clean tree still has branches to switch, pull and push.
|
||||
if (scan && scan.isGit === false) return { on: true, note: GIT_INIT_NOTE };
|
||||
if (scan && Number.isInteger(scan.pending) && scan.pending > 0) return { on: true, note: pendingNote(scan.pending) };
|
||||
return ON;
|
||||
|
||||
@@ -23,6 +23,19 @@ export function linkLeavesPage(href, origin) {
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && url.origin !== origin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call `handler(data)` for each `{ plan2code: kind, ... }` message the frame's
|
||||
* parent sends, and for nothing from anywhere else (another frame, the page
|
||||
* itself). The app's only answer today is `taskbar-state`.
|
||||
*/
|
||||
export function onAppMessage(kind, handler) {
|
||||
window.addEventListener("message", (event) => {
|
||||
if (!framed() || event.source !== window.parent) return;
|
||||
const data = event.data;
|
||||
if (data && typeof data === "object" && data.plan2code === kind) handler(data);
|
||||
});
|
||||
}
|
||||
|
||||
/** Post `message` to the frame's parent, as `{ plan2code: kind, ...extra }`; nothing outside a frame. */
|
||||
export function tellApp(kind, extra = {}) {
|
||||
if (!framed()) return;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
// Planny's wake-up on a freshly opened dashboard: he sits powered down centre
|
||||
// Planny's wake-up on a freshly opened dashboard: he sits powered down center
|
||||
// stage until the first click or key, gets nudged awake (he rocks side to side
|
||||
// for one snore), then about five seconds of him powering on, then a glide
|
||||
// into the rail as the menu comes in.
|
||||
@@ -68,7 +68,7 @@ export function playWake({ stage, bot, target, skipEl, stir, onStart, onGlide, o
|
||||
// between the two top-left corners and the scale is the width ratio.
|
||||
// The target's own box, not its bounding rect: the rail's Planny is
|
||||
// usually tilted mid-flight, and a tilted box measures wider than he
|
||||
// is. Centred on the rect, which the tilt barely moves.
|
||||
// is. Centered on the rect, which the tilt barely moves.
|
||||
const from = bot.getBoundingClientRect();
|
||||
const rect = target.getBoundingClientRect();
|
||||
const w = target.clientWidth || rect.width;
|
||||
|
||||
@@ -147,7 +147,7 @@ const ABOUT_HISTORY = 3;
|
||||
*
|
||||
* The tracker is `{ history, about }`; each entry and `about` are
|
||||
* `{ kind, id, label }` (`about` may be null), in the exact shape POST /chat
|
||||
* takes. An old `{ about, frozen, dropped }` tracker normalises to an empty
|
||||
* takes. An old `{ about, frozen, dropped }` tracker normalizes to an empty
|
||||
* history.
|
||||
*/
|
||||
export function nextAbout(prev, event) {
|
||||
|
||||
@@ -12,7 +12,7 @@
|
||||
// className, id, type, value, checked, disabled, textContent, placeholder,
|
||||
// title, open, href, target, rel, tabIndex. Text runs are h.el("span", null, text).
|
||||
//
|
||||
// Every button, input and select is made through control(), which greys it
|
||||
// Every button, input and select is made through control(), which grays it
|
||||
// out whenever controlAllowed(mode, role) says no and stamps data-gate with
|
||||
// its role; one disabled for a reason of the view's own also carries
|
||||
// data-own. The guard test in scripts/test-web-console-git-board.mjs holds
|
||||
@@ -64,7 +64,7 @@ function control(ctx, tag, className, label, { role = "action", onClick, onInput
|
||||
return node;
|
||||
}
|
||||
|
||||
// A copy button is a control like any other: greyed while busy.
|
||||
// A copy button is a control like any other: grayed while busy.
|
||||
function copy(ctx, text, cls, codeEl) {
|
||||
const b = ctx.h.copyButton(text, cls, codeEl);
|
||||
b.setAttribute("data-gate", "action");
|
||||
|
||||
@@ -194,7 +194,7 @@ const button = (shown, enabled, label, title) => ({ shown, enabled: shown && ena
|
||||
/**
|
||||
* Every board button as `{ shown, enabled, label, title? }`. Pull is enabled
|
||||
* only with an upstream to pull from; Push shows with an upstream, Publish
|
||||
* without one. `busy` greys everything out but Done; an operation in
|
||||
* without one. `busy` grays everything out but Done; an operation in
|
||||
* progress hides everything but Done (its banner carries Abort / Continue).
|
||||
*/
|
||||
export function boardActions(git, { busy = false } = {}) {
|
||||
|
||||
@@ -64,7 +64,7 @@
|
||||
<div id="banner" class="banner" role="status" hidden></div>
|
||||
|
||||
<!-- Planny's wake-up on a freshly opened dashboard: a large copy of the
|
||||
rail drawing that powers on centre stage, then glides into the rail.
|
||||
rail drawing that powers on center stage, then glides into the rail.
|
||||
Hidden unless boot.js is playing it; placed entirely by app.css,
|
||||
because the CSP refuses style attributes. -->
|
||||
<div class="wake" id="wake" hidden>
|
||||
@@ -97,7 +97,7 @@
|
||||
<span class="badge" id="badge">Pathfinder</span>
|
||||
<h1 id="title">Plan2Code Console</h1>
|
||||
<!-- The session meter: how much this console session has done. The
|
||||
ring fills with the points (full at 15); the colour is the
|
||||
ring fills with the points (full at 15); the color is the
|
||||
level. Hidden until a frame carries `meter`. -->
|
||||
<span class="meter-slot">
|
||||
<button
|
||||
@@ -812,7 +812,7 @@
|
||||
Four boxes in a row, each talking both ways with the next: you in
|
||||
your browser, this page, a small program on 127.0.0.1, and
|
||||
Plan2Code in your terminal. A dashed outline around all four is
|
||||
labelled "Your machine only".
|
||||
labeled "Your machine only".
|
||||
</desc>
|
||||
<defs>
|
||||
<marker id="hd-about-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto-start-reverse">
|
||||
@@ -930,7 +930,7 @@
|
||||
</li>
|
||||
<li class="help-row">
|
||||
<dl>
|
||||
<dt>You see</dt><dd><strong>Not running</strong> (Planny grey and still).</dd>
|
||||
<dt>You see</dt><dd><strong>Not running</strong> (Planny gray and still).</dd>
|
||||
<dt>Likely cause</dt><dd>Plan2Code has not checked in for a few minutes.</dd>
|
||||
<dt>Do this</dt><dd class="for-browser">Look at the terminal. If it is idle, type <code>continue</code> there.</dd><dd class="for-app">Look at the terminal panel. If it is idle, press <strong>continue</strong> in the line beside Planny, which types it there for you.</dd>
|
||||
</dl>
|
||||
@@ -998,7 +998,7 @@
|
||||
<h4>Not running, or not connected?</h4>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Not running</strong> (Planny grey and still): this page is
|
||||
<strong>Not running</strong> (Planny gray and still): this page is
|
||||
fine, but Plan2Code in the terminal has not checked in for
|
||||
<span data-fact="adriftMinutes">3</span> minutes. It may have finished
|
||||
its turn, hit an error, or be waiting on you there.
|
||||
@@ -1386,7 +1386,7 @@
|
||||
<p id="help-planny-done-text">A green star and both arms up. The session is finished. You can close the tab.</p>
|
||||
<h4>Not running</h4>
|
||||
<p>
|
||||
Grey, still, arms down out of sight. This page is fine, but Plan2Code has not checked in
|
||||
Gray, still, arms down out of sight. This page is fine, but Plan2Code has not checked in
|
||||
for <span data-fact="adriftMinutes">3</span> minutes. Anything you answer
|
||||
is still saved.
|
||||
</p>
|
||||
@@ -1762,7 +1762,7 @@
|
||||
<strong>Start from scratch</strong> for a new idea. The one you pick is
|
||||
what a step works on, and it decides which cards make sense: a spec
|
||||
that is half built has no use for Pathfinder, and a new idea cannot be
|
||||
implemented yet. Cards that do not fit are greyed out with the reason
|
||||
implemented yet. Cards that do not fit are grayed out with the reason
|
||||
why.
|
||||
</p>
|
||||
<p>
|
||||
@@ -2026,7 +2026,7 @@
|
||||
<h4>While something is running</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Everything greys out except switching tabs, searching and opening
|
||||
Everything grays out except switching tabs, searching and opening
|
||||
folds, so nothing queues up behind the running command.
|
||||
</li>
|
||||
<li>What is running shows where the next step usually sits.</li>
|
||||
@@ -2049,7 +2049,7 @@
|
||||
<strong>Done with git</strong> ends the board. If anything happened, the
|
||||
last screen lists the commits, pushes and branches created or deleted,
|
||||
with <strong>Back to the dashboard</strong>; if nothing did, the page
|
||||
goes straight back to the dashboard. It greys while a command runs and
|
||||
goes straight back to the dashboard. It grays while a command runs and
|
||||
comes back when it is done; if Plan2Code stops checking in,
|
||||
<strong>Stop session</strong> in the top bar ends the session instead.
|
||||
While a question of Plan2Code's waits, it cancels that question and
|
||||
@@ -2061,9 +2061,9 @@
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
On a build, a review, Pathfinder, Plan and Revise plan, Plan2Code
|
||||
can hand independent pieces of work to helpers (subagents) while it
|
||||
keeps the conversation with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
@@ -2423,7 +2423,7 @@
|
||||
</li>
|
||||
<li>
|
||||
<strong>Highlight color</strong>: one of
|
||||
<span data-fact="accentCount">32</span>, ocean blue to begin with. It marks
|
||||
<span data-fact="accentCount">38</span>, ocean blue to begin with. It marks
|
||||
what is yours to do, and Planny's star uses it while he works.
|
||||
</li>
|
||||
<li>
|
||||
@@ -2664,6 +2664,16 @@
|
||||
<span class="help" id="agents-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<!-- Only inside the desktop app (framed()): the app saves the switch in its own app.json. -->
|
||||
<fieldset class="modal-ranges looks-desktop" id="looks-desktop" hidden>
|
||||
<legend>Desktop app</legend>
|
||||
<label><input type="checkbox" id="looks-taskbar" checked /> <span>Show on the taskbar when Plan2Code needs me</span></label>
|
||||
<p class="help">
|
||||
Windows: a colored dot on the taskbar button (green on your move, red when it
|
||||
needs you) and a short burst of flashes. macOS: a red badge on the dock icon when it needs
|
||||
you, and a bounce. Linux: depends on your desktop.
|
||||
</p>
|
||||
</fieldset>
|
||||
</div>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
// `looks` is a live binding: every file reads the current object, and only
|
||||
// this file replaces it.
|
||||
|
||||
import { DEFAULT_ACCENT, soundPrefs, DEFAULT_CARD_WIDTH, ACCENTS, cardWidth, soundKey } from "./palette.js";
|
||||
import { DEFAULT_ACCENT, soundPrefs, DEFAULT_CARD_WIDTH, ACCENTS, accentId, cardWidth, soundKey } from "./palette.js";
|
||||
import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
|
||||
import { bootData, hooks } from "./state.js";
|
||||
import { el } from "./render.js";
|
||||
@@ -40,7 +40,7 @@ export let looksReady = false;
|
||||
|
||||
export function adoptLooks(saved) {
|
||||
looks = { ...DEFAULT_LOOKS, ...saved };
|
||||
if (!ACCENTS[looks.accent]) looks.accent = DEFAULT_LOOKS.accent;
|
||||
looks.accent = accentId(looks.accent);
|
||||
if (!["system", "light", "dark"].includes(looks.theme)) looks.theme = DEFAULT_LOOKS.theme;
|
||||
if (typeof looks.sound !== "boolean") looks.sound = DEFAULT_LOOKS.sound;
|
||||
Object.assign(looks, soundPrefs(looks));
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
// The highlight colors, as data. Kept out of app.js for one reason: app.js
|
||||
// cannot be imported outside a browser, and thirty-two colors each with four
|
||||
// cannot be imported outside a browser, and thirty-eight colors each with four
|
||||
// shades in two themes is far too many to trust to eyeballing. The test suite
|
||||
// imports this and checks every one.
|
||||
//
|
||||
@@ -19,12 +19,20 @@
|
||||
// also badge text on the soft tint). Everything after the first five was
|
||||
// found by stepping lightness until both held, not picked by eye.
|
||||
//
|
||||
// Order is the order of the picker: round the wheel, then the greys. Sixteen
|
||||
// a row, so the warm half and the greens sit on the first, the blues, purples,
|
||||
// pinks and greys on the second.
|
||||
// Order is the order of the picker: round the wheel, then the grays and Mono
|
||||
// (near-black in light, near-white in dark). Nineteen a row, so the reds,
|
||||
// browns, yellows and greens sit on the first, the blues, purples, pinks and
|
||||
// grays on the second. The pale ones (Peach, Cream, Mint, Aqua, Lavender,
|
||||
// Pink) are pastels only in dark mode: in light mode a fill has to carry a
|
||||
// white label, so they come out as deeper shades of the same hue.
|
||||
|
||||
export const ACCENTS = {
|
||||
// name fill soft ink line
|
||||
maroon: {
|
||||
name: "Maroon",
|
||||
light: ["#7c1d2d", "#fbeef1", "#ffffff", "#cea1a9"],
|
||||
dark: ["#da818f", "#321b1f", "#140b0c", "#76424b"],
|
||||
},
|
||||
crimson: {
|
||||
name: "Crimson",
|
||||
light: ["#cd1d41", "#fbe9ed", "#ffffff", "#dcaab4"],
|
||||
@@ -40,40 +48,45 @@ export const ACCENTS = {
|
||||
light: ["#c83510", "#fbede9", "#ffffff", "#dcaca0"],
|
||||
dark: ["#ef5b37", "#321f1b", "#140d0b", "#6f4237"],
|
||||
},
|
||||
rust: {
|
||||
name: "Rust",
|
||||
light: ["#ae4f2b", "#fbeee7", "#ffffff", "#dd9b7e"],
|
||||
dark: ["#e8825a", "#34211a", "#1a120e", "#8a4f36"],
|
||||
peach: {
|
||||
name: "Peach",
|
||||
light: ["#b44c2d", "#fbf2ef", "#ffffff", "#cdaca2"],
|
||||
dark: ["#f9a48b", "#32201b", "#140d0b", "#764e42"],
|
||||
},
|
||||
tangerine: {
|
||||
name: "Tangerine",
|
||||
light: ["#b15209", "#fbf1e9", "#ffffff", "#d9af8f"],
|
||||
dark: ["#f2700d", "#32251b", "#140f0b", "#664830"],
|
||||
},
|
||||
copper: {
|
||||
name: "Copper",
|
||||
light: ["#a2592f", "#f9f0eb", "#ffffff", "#cdb2a2"],
|
||||
dark: ["#cb7a4b", "#32231b", "#140e0b", "#5f493d"],
|
||||
rust: {
|
||||
name: "Rust",
|
||||
light: ["#ae4f2b", "#fbeee7", "#ffffff", "#dd9b7e"],
|
||||
dark: ["#e8825a", "#34211a", "#1a120e", "#8a4f36"],
|
||||
},
|
||||
brown: {
|
||||
name: "Brown",
|
||||
light: ["#6f472a", "#f9f4f0", "#ffffff", "#c8b5a8"],
|
||||
dark: ["#c59877", "#32241b", "#140f0b", "#765842"],
|
||||
},
|
||||
clay: {
|
||||
name: "Clay",
|
||||
light: ["#8d644c", "#f5f2f0", "#ffffff", "#bfafa6"],
|
||||
dark: ["#ba957f", "#2b2521", "#17100c", "#62544b"],
|
||||
},
|
||||
marigold: {
|
||||
name: "Marigold",
|
||||
light: ["#9a6406", "#fbf5e9", "#ffffff", "#d3b279"],
|
||||
dark: ["#f59f0a", "#32291b", "#14110b", "#5e4c2c"],
|
||||
},
|
||||
gold: {
|
||||
name: "Gold",
|
||||
light: ["#896b09", "#fbf7e9", "#ffffff", "#ccb66d"],
|
||||
dark: ["#f0bb0f", "#322c1b", "#14120b", "#584d2a"],
|
||||
},
|
||||
mustard: {
|
||||
name: "Mustard",
|
||||
light: ["#806f1b", "#fbf8ea", "#ffffff", "#c3b881"],
|
||||
dark: ["#d2b72d", "#322e1b", "#14120b", "#544e31"],
|
||||
cream: {
|
||||
name: "Cream",
|
||||
light: ["#776740", "#f8f6f2", "#ffffff", "#c0b9aa"],
|
||||
dark: ["#f1e1bc", "#322b1b", "#14110b", "#766642"],
|
||||
},
|
||||
lemon: {
|
||||
name: "Lemon",
|
||||
light: ["#7e7607", "#fcfbee", "#ffffff", "#c5bf67"],
|
||||
dark: ["#f0e442", "#32301b", "#14130b", "#767242"],
|
||||
},
|
||||
olive: {
|
||||
name: "Olive",
|
||||
@@ -90,21 +103,31 @@ export const ACCENTS = {
|
||||
light: ["#577740", "#f2f6ee", "#ffffff", "#acbca1"],
|
||||
dark: ["#79a659", "#24321b", "#0f140b", "#475140"],
|
||||
},
|
||||
forest: {
|
||||
name: "Forest",
|
||||
light: ["#216337", "#f0faf3", "#ffffff", "#9cc4a9"],
|
||||
dark: ["#6bbd86", "#1b3222", "#0b140e", "#427653"],
|
||||
},
|
||||
emerald: {
|
||||
name: "Emerald",
|
||||
light: ["#207e47", "#ebfaf1", "#ffffff", "#8ac4a2"],
|
||||
dark: ["#33cc73", "#1b3224", "#0b140f", "#345542"],
|
||||
},
|
||||
jade: {
|
||||
name: "Jade",
|
||||
light: ["#297c61", "#ecf9f4", "#ffffff", "#92c1b1"],
|
||||
dark: ["#40bf95", "#1b322a", "#0b1411", "#38544b"],
|
||||
mint: {
|
||||
name: "Mint",
|
||||
light: ["#25805a", "#effaf6", "#ffffff", "#97c4b1"],
|
||||
dark: ["#8be4bf", "#1b3228", "#0b1410", "#427660"],
|
||||
},
|
||||
teal: {
|
||||
name: "Teal",
|
||||
light: ["#0f766e", "#e2f1ef", "#ffffff", "#6fb3aa"],
|
||||
dark: ["#5ecfc0", "#14302c", "#0b1a18", "#3a7d74"],
|
||||
},
|
||||
aqua: {
|
||||
name: "Aqua",
|
||||
light: ["#177e82", "#eefbfc", "#ffffff", "#8dc6c8"],
|
||||
dark: ["#84e8eb", "#1b3132", "#0b1414", "#427476"],
|
||||
},
|
||||
cyan: {
|
||||
name: "Cyan",
|
||||
light: ["#0f798a", "#ebf7f9", "#ffffff", "#75bec9"],
|
||||
@@ -120,31 +143,31 @@ export const ACCENTS = {
|
||||
light: ["#206cc3", "#ecf2f9", "#ffffff", "#9ab4d3"],
|
||||
dark: ["#619fe5", "#1a2533", "#0c1117", "#3d5978"],
|
||||
},
|
||||
navy: {
|
||||
name: "Navy",
|
||||
light: ["#24396b", "#eef0f7", "#ffffff", "#a7b3cd"],
|
||||
dark: ["#819ad5", "#1e232f", "#0c1017", "#4a5775"],
|
||||
},
|
||||
cobalt: {
|
||||
name: "Cobalt",
|
||||
light: ["#405ce7", "#ebeef9", "#ffffff", "#a8b0dc"],
|
||||
dark: ["#7b8fef", "#191d34", "#0c0e17", "#465392"],
|
||||
},
|
||||
navy: {
|
||||
name: "Navy",
|
||||
light: ["#24396b", "#eef0f7", "#ffffff", "#a7b3cd"],
|
||||
dark: ["#819ad5", "#1e232f", "#0c1017", "#4a5775"],
|
||||
},
|
||||
indigo: {
|
||||
name: "Indigo",
|
||||
light: ["#4f46e5", "#ecebfb", "#ffffff", "#9b95ef"],
|
||||
dark: ["#a5a0ff", "#1e1d3a", "#121129", "#5f5ba8"],
|
||||
},
|
||||
lavender: {
|
||||
name: "Lavender",
|
||||
light: ["#6f61b8", "#f2f1f9", "#ffffff", "#afaac5"],
|
||||
dark: ["#b9acf6", "#1f1b32", "#0c0b14", "#4d4479"],
|
||||
},
|
||||
violet: {
|
||||
name: "Violet",
|
||||
light: ["#7f4dd5", "#f1edf8", "#ffffff", "#bbabd6"],
|
||||
dark: ["#a785e2", "#231c31", "#100c17", "#624c87"],
|
||||
},
|
||||
lilac: {
|
||||
name: "Lilac",
|
||||
light: ["#8b51b8", "#f3eff6", "#ffffff", "#beaccb"],
|
||||
dark: ["#b189cf", "#271f2d", "#130c17", "#634f73"],
|
||||
},
|
||||
orchid: {
|
||||
name: "Orchid",
|
||||
light: ["#a141b9", "#f5eef7", "#ffffff", "#c5a8cc"],
|
||||
@@ -165,6 +188,16 @@ export const ACCENTS = {
|
||||
light: ["#c42e6a", "#f8edf1", "#ffffff", "#d3a6b8"],
|
||||
dark: ["#df77a0", "#311c24", "#170c11", "#7c465b"],
|
||||
},
|
||||
pink: {
|
||||
name: "Pink",
|
||||
light: ["#b23875", "#faeff5", "#ffffff", "#caa5b8"],
|
||||
dark: ["#f7a1cc", "#321b26", "#140b0f", "#76425c"],
|
||||
},
|
||||
mauve: {
|
||||
name: "Mauve",
|
||||
light: ["#816281", "#f4f1f4", "#ffffff", "#bbafbb"],
|
||||
dark: ["#ae93ae", "#292329", "#170c17", "#5f545f"],
|
||||
},
|
||||
steel: {
|
||||
name: "Steel",
|
||||
light: ["#50737c", "#f0f3f4", "#ffffff", "#a5b5b8"],
|
||||
@@ -175,20 +208,30 @@ export const ACCENTS = {
|
||||
light: ["#5b6e88", "#f0f2f4", "#ffffff", "#acb3bc"],
|
||||
dark: ["#8e9eb4", "#23262a", "#0c1117", "#515861"],
|
||||
},
|
||||
mauve: {
|
||||
name: "Mauve",
|
||||
light: ["#816281", "#f4f1f4", "#ffffff", "#bbafbb"],
|
||||
dark: ["#ae93ae", "#292329", "#170c17", "#5f545f"],
|
||||
},
|
||||
graphite: {
|
||||
name: "Graphite",
|
||||
light: ["#4a4640", "#eeedea", "#ffffff", "#a8a196"],
|
||||
dark: ["#cfc7bb", "#2b2a28", "#161513", "#7a7369"],
|
||||
},
|
||||
mono: {
|
||||
name: "Mono",
|
||||
light: ["#1f1f1f", "#efefef", "#ffffff", "#a3a3a3"],
|
||||
dark: ["#ececec", "#2a2a2a", "#141414", "#6e6e6e"],
|
||||
},
|
||||
};
|
||||
|
||||
export const DEFAULT_ACCENT = "ocean";
|
||||
|
||||
// Colors that were merged into a near twin when the picker grew to Paint's
|
||||
// range. A looks.json saved with one keeps the closest color, not the default.
|
||||
export const RETIRED_ACCENTS = { copper: "rust", marigold: "gold", mustard: "lemon", jade: "emerald", lilac: "violet" };
|
||||
|
||||
export function accentId(value) {
|
||||
const id = String(value);
|
||||
if (Object.hasOwn(ACCENTS, id)) return id;
|
||||
return Object.hasOwn(RETIRED_ACCENTS, id) ? RETIRED_ACCENTS[id] : DEFAULT_ACCENT;
|
||||
}
|
||||
|
||||
// The card-width presets. Here for the same reason the accents are: the page
|
||||
// validates a saved `looks.width` with cardWidth(), and the server uses it to
|
||||
// paint the first-load `data-width` attribute before app.js runs. One list,
|
||||
|
||||
@@ -7,11 +7,11 @@
|
||||
// that reads and writes the user's files and holds the session cookie. Script
|
||||
// running here could post arbitrary answers back to the agent, which would then
|
||||
// act on them with the agent's full tool permissions. And the markdown is only
|
||||
// nominally agent-authored: in practice the agent is summarising a dependency
|
||||
// nominally agent-authored: in practice the agent is summarizing a dependency
|
||||
// README, a scraped page, a PR description, a log. Treat it as hostile.
|
||||
//
|
||||
// Building nodes rather than parsing a string makes injection structurally
|
||||
// impossible instead of filtered, so there is nothing for a sanitiser bypass to
|
||||
// impossible instead of filtered, so there is nothing for a sanitizer bypass to
|
||||
// bypass. `html` tokens render as visible text, on purpose.
|
||||
|
||||
import { marked } from "./vendor/marked.esm.js";
|
||||
|
||||
@@ -724,7 +724,24 @@ export function renderSubagents(main) {
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.strengthLine) item.appendChild(el("p", "sa-strength", row.strengthLine));
|
||||
if (row.strengthLine) {
|
||||
// Badges for the eye, the plain line for screen readers and the tooltip.
|
||||
const strength = el("p", "sa-strength");
|
||||
strength.setAttribute("aria-label", row.strengthLine);
|
||||
strength.title = row.strengthLine;
|
||||
for (const badge of row.badges) {
|
||||
const chip = el("span", `sa-badge is-${badge.kind} lvl-${badge.level}`);
|
||||
chip.setAttribute("aria-hidden", "true");
|
||||
if (badge.level) {
|
||||
const bars = el("span", "sa-bars");
|
||||
for (let i = 1; i <= 3; i++) bars.appendChild(el("i", i <= badge.level ? "on" : null));
|
||||
chip.appendChild(bars);
|
||||
}
|
||||
chip.appendChild(document.createTextNode(badge.label));
|
||||
strength.appendChild(chip);
|
||||
}
|
||||
item.appendChild(strength);
|
||||
}
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
|
||||
Loaded 100 of 124 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user