Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
13532737e0 | ||
|
|
ed81c2b4fc | ||
|
|
5950abb0aa | ||
|
|
03f433043e | ||
|
|
dbd31611b7 | ||
|
|
720758a7ee | ||
|
|
7973bc093b | ||
|
|
528fcaaa8e | ||
|
|
d5d8278cfe | ||
|
|
77ddcc048d | ||
|
|
7d5e78179e | ||
|
|
46f1f17261 | ||
|
|
0d569954c4 | ||
|
|
2709252daa | ||
|
|
5043b424cf | ||
|
|
dd2ab86584 | ||
|
|
78153576a9 | ||
|
|
c3ee918b62 | ||
|
|
d4d64987fe | ||
|
|
10379e3870 | ||
|
|
899b3a48d8 | ||
|
|
e67aaabdce | ||
|
|
c602dfed57 | ||
|
|
765d2b3536 | ||
|
|
b99a1a701f | ||
|
|
a2b43d1188 | ||
|
|
94063fc0a9 | ||
|
|
3e22d53bf5 | ||
|
|
7a9f56a452 | ||
|
|
37f2735294 | ||
|
|
1d146cce6f | ||
|
|
5f91fb665f | ||
|
|
4d05b4f6f6 | ||
|
|
3155298fea | ||
|
|
a4644d533b | ||
|
|
b73a4cebe7 | ||
|
|
efc96e91c2 | ||
|
|
442904e6f2 | ||
|
|
c1f41e4a82 | ||
|
|
72043e20fc | ||
|
|
bdc4decbb4 | ||
|
|
cb6468577d | ||
|
|
0de630603b | ||
|
|
26013db54f | ||
|
|
e00769b56a | ||
|
|
a5a3a81c5f | ||
|
|
681c4a4b85 | ||
|
|
7a4b7c6db8 | ||
|
|
086c735c65 | ||
|
|
d4adb53a3a |
No files matched your search
@@ -16,7 +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)
|
||||
│ │ ├── 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
|
||||
@@ -52,11 +53,12 @@ plan2code/
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
|
||||
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
|
||||
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
|
||||
│ ├── vendor-overtype.mjs # Dev-only: loads the vendored OverType in a browser and writes the CSS it would inject into `public/styles/notepad.css`, above the `/* end OverType */` marker; run it after upgrading the vendored file
|
||||
│ ├── vendor-codemirror.mjs # Dev-only: bundles the pinned CodeMirror 6 packages with esbuild into `public/vendor/codemirror.esm.js` (installed in a temp folder from `vendor-codemirror-lock.json`, never in the repo)
|
||||
│ ├── check-skill-table.mjs # src/plan2code.md "What each skill reads and writes" table vs each skill's prompt and references
|
||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||
│ ├── node-test.mjs, page-test-helpers.mjs # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()`
|
||||
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
|
||||
│ └── validate-char-count.js # Pre-commit character count validator
|
||||
@@ -92,7 +94,21 @@ plan2code/
|
||||
| `version.json` | Version metadata (name, version, description) |
|
||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
||||
| `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`) |
|
||||
| `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. 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/`)
|
||||
|
||||
@@ -108,7 +124,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 |
|
||||
@@ -189,9 +205,12 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
|
||||
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
|
||||
| `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser |
|
||||
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
|
||||
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
|
||||
| `agents.mjs` | the rules of `~/.plan2code/agents.json` (see Agents file above), console side: `normalizeAgents()` reads the file into clean entries and warnings, never throwing; `validateForSave()` checks what User Preferences sends and names the first bad entry and field; `makeId()`, `buildArgs()` (the command line from an entry) and `resolveCommand()` (where a command runs from, never running it). Served by `GET` / `POST /agents` and `POST /agents/test` in `routes.mjs` |
|
||||
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
|
||||
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
|
||||
@@ -201,6 +220,12 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
|
||||
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
|
||||
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
|
||||
| `public/activities.js` | the list of activities (`ACTIVITIES`: each game's id, title and module path) and `bestKey(id)`, the flat looks.json key for its best score (`activityBestSnake`, `activityBestGolf`); lists Snake and Mini golf, and documents the game contract including the optional `pointer(type, x, y)`, `release(name)` (a game key let go) and `lowerIsBetter`; data only, imported by the page and by Node |
|
||||
| `public/activities/snake.js` | Snake: its rules as plain exported functions and the game contract (`create({ canvas, tone, onScore })` returning `start`, `pause`, `resume`, `key`, `tick`, `resize`, `score`, `state`); it never runs a timer or listens for keys, so the Activities window drives it |
|
||||
| `public/activities/golf.js` | Mini golf: its rules and physics as plain exported functions (`newRound`, `strike`, `advance` on a fixed 4 ms sub-step, `nextHole`, `total`, `toPar`, `predictPath` for the spyglass, `moverAt`, `gateShut`), the `POWERUPS` held for the next putt (`round.held`, then `round.active` for that putt), the arcade swing (`startSwing`, `setPower`, `meterAt`, `meterZone`, `swingShot`: a ping-pong power meter, slow at the bottom and fast at the top, with a MAX band that boosts and an overswing band that shanks; a shot clock in `advance()` that starts the meter after `SHOT_CLOCK_MS` and dribbles the ball after `METER_TRIPS` trips; all on the round's own clock), the pop-up gags, and the game contract with `pointer()` (the aim follows the pointer, a press swings, a press held on a roll fast-forwards), `release()` (held arrows turn the aim, held space fast-forwards) and `lowerIsBetter`; deterministic (no `Math.random()`), a read-only `round` getter for the unit suite only |
|
||||
| `public/activities/golf-draw.js` | Mini golf's drawing: `drawCourse(ctx, view)` from a plain view `golf.js` builds, each hole in its theme's fixed palette (`pirate`, or `cave` with its darkness and glows), and `readColors(canvas)`, which reads the `--golf-*` properties `styles/activities.css` mixes from the tokens for the ball, pills and scorecard; decides nothing |
|
||||
| `public/activities/golf-decor.js` | Mini golf's scenery and props: each `decor` kind (sharks, ships, parrots, bats, torches, eyes, a dragon) on its layer, the looks of bumpers, movers and spinners, and the power-up icons; drawing only, moving with the round's clock |
|
||||
| `public/activities/golf-holes.js` | Mini golf's course, data only (no DOM, no imports): `COURSE_W`, `COURSE_H`, `FRONT_NINE` and the eighteen frozen `HOLES` (theme, quip, ground, liquid, tee, cup, outline, walls, bumpers, sand, water, slopes, bridges, spinners, tunnels, movers, gates, powerups, decor); the front nine is pirate, the back nine cave |
|
||||
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
|
||||
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
|
||||
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, into Git, or from one skill into another off a finished screen, but never out of Git or into Review); shared by `cmd-open.mjs`, `server.mjs` (its Ask reset) and `screens/core.js` |
|
||||
@@ -215,6 +240,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
|
||||
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
||||
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
|
||||
| `public/tones.js` | the activities' short Web Audio blips (`tone(name, level)` with an optional loudness from 0 to 1, `unlockTones()`; Snake's blips plus golf's `putt`, `wall`, `bump`, `cup`, `ace` (a three-note rise), `splash`, `power` (a power-up, three notes), `tunnel`, `boom` (a cannon putt), `sizzle` (lava) and `fall` (the pit), and the countdown's `count` and `go`), silent while Play sounds is off; separate from `sound.js`'s cue queue |
|
||||
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry |
|
||||
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
|
||||
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
|
||||
@@ -224,7 +250,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
|
||||
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js) |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js). Help reads right in both modes: a phrase that differs under the desktop app carries its app wording in `data-app` (swapped in by `renderAppWording()`), and a paragraph that differs is a `.for-browser` / `.for-app` sibling pair, switched by `:root.in-app` (set in `core.js` from `page.inApp`, rule in `help.css`). The older `render*Help()` functions patch a few ids the same way. `scripts/test-web-console-page-help.mjs` sweeps every topic's visible text in each mode for the other mode's wording |
|
||||
| `public/screens/looks.js` | User Preferences: looks, sounds and the launcher's model menus |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
|
||||
@@ -240,8 +266,8 @@ 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/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `public/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` (19 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build, and Activities right after Ask a quick question), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
|
||||
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
|
||||
| `public/git-board-view.js` | No DOM access of its own: `drawGitBoard(ctx)` draws the tabbed board (header, tab strip with Done with git, the card slot, step strip, Changes / Branches / Sync) from the helpers it is handed (`el`, `md`, `copyButton`), every control through one gate; `screens/git-host.js` hosts it, and `scripts/test-web-console-git-board.mjs` drives it with a recording fake `el` |
|
||||
@@ -249,14 +275,20 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
|
||||
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (`done`, `happy`); a finished screen gets no special case, so one still offering a press points and lights `ready` (the desktop app's taskbar dot follows), a stranded press is `attention`, and only all done or paused is `plain`; `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, `plan`, `revise-plan`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notepad store, the only code that names, reads, writes and removes notepads, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests): `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `readNotepad()` (never creates or writes anything), `saveNote()` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures at most, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notepad's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `IMAGE_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), `withoutStyleAttrs()` (OverType's HTML without its inline `style` attributes, which the policy refuses: a link's `anchor-name` moves to `data-anchor`), `topLevelParts()` and `changedRange()` (the styled layer cut into its top-level elements as strings, and which run of them changed) and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notepad: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one OverType editor (made on first open, after setting `OverType.stylesInjected = true`), the text read from `GET /notepad` on every open (the editor is read-only until the first read lands, so nothing typed into an empty editor is saved over the note), and autosave through `nextSave()` to `POST /notepad/text`, flushed on close and when the tab is hidden. Three things lean on OverType's internals: `buildWithoutStyleAttrs()` swaps `document.createElement` only while the editor is built, so the elements OverType makes (its preview and its link tooltip among them) get an `innerHTML` that runs `withoutStyleAttrs()`; `patchPreview()`, behind that same `innerHTML` on the preview, swaps only the lines that changed (a whole-note redraw took about 310 ms a key at 200 KB) and clears the code-fence shading OverType re-applies right after; and `linkTooltip.findAnchorElement` is pointed at `data-anchor` |
|
||||
| `public/vendor/overtype.esm.js` | OverType 2.6.1 (MIT), vendored unchanged from `https://cdn.jsdelivr.net/npm/overtype@2.6.1/dist/overtype.esm.js` (sha256 `87bc797660d2b1cf6bc13551be6fa9ffa6393a98af453293c0530d5ca4950874`): the Notepad's styled-in-place Markdown editor over a real textarea. Regenerate the CSS with `scripts/vendor-overtype.mjs` after any upgrade, then recheck what `screens/notepad.js` relies on: `updatePreview()` setting `preview.innerHTML` then calling `_applyCodeBlockBackgrounds()`, the elements `_createDOM()` and `LinkTooltip.createTooltip()` make with `document.createElement`, `_init()` reporting its first value through `onChange`, the `anchor-name` style on links and `linkTooltip.findAnchorElement()`, and `OverType.stylesInjected` |
|
||||
| `public/styles/notepad.css` | OverType's generated CSS (between its header and `/* end OverType */`, rewritten by `scripts/vendor-overtype.mjs`, since the page's `style-src 'self'` blocks the `<style>` OverType would inject), then the notepad's own rules: OverType's theme mapped onto the console's tokens, one monospace font at one size, the top bar button and the dialog |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created, sent? } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
| `public/screens/notepad.js` | the Notebook: `#btn-notepad` in the top bar on every screen (disabled while the server is gone, `renderNotepadButton()` in the render pass), `#notepad-modal`, the one CodeMirror editor (made on first open by a dynamic import of `notepad-editor.js`), the page's view of the notepad as `{ tabs, activeId }`, the name form (New tab and Rename, never `window.prompt`), the in-modal two-step delete, and autosave through `nextSave()` to `POST /notepad/text?tab=<id>`, flushed on close, when the page is hidden and before a switch. The editor stays read-only until the first read lands, so nothing typed into an empty editor is saved over a note. **Every save and every picture is bound to the tab it was made in**: `saveTab` is fixed when the change is made, a picture entry carries its `tab`, and a switch waits for the save (`settled()`), stays put with "Not saved yet, so staying on this tab." when it cannot, and drops a deleted tab's unsaved text without sending it |
|
||||
| `public/screens/activities.js` | Activities: `#btn-activities` (the die right of the megaphone), `#activities-modal`, the one frame timer (`requestAnimationFrame`, swappable with `setTickSource()` for the page tests), the keys (arrows, W/A/S/D, space, P, Esc; stopped at the dialog so none reach the page behind) and `pauseAll()`, which a new question, a finish, a hidden page, a window blur and a close all go through and which never resumes a game (it also sends a pointer game a cancel, dropping a drag). Canvas pointer events (down, move, up, cancel, with pointer capture) go to a game with `pointer()`, and key releases to a game with `release()`; a press on a paused board resumes without starting a drag. While paused, any game key or a board click resumes. Every start and play-on first counts down 3, 2, 1 (`COUNT_FROM`, 700 ms a number, `setCountdownMs()` for the page tests, which set 0 unless they test it): the game is already `running`, the frame timer just does not tick it, and game keys, overlay clicks and board presses wait, while P and Esc still pause. The picker remembers the last pick as `lastActivity`; `lowerIsBetter` games keep the lowest round as the best; the header shows the current game's best (`paintTitle()`). `renderActivities()` in the render pass compares `myTurn()` and `finish()` with the last render and shows the banner with **Go to it**. Loads each listed game once with `import()` and keeps it for the page's life; `setActivityList()` lets a test list a stub second game, which brings up the picker |
|
||||
| `public/notepad-tabs.js` | the tab bar: `createTabs({ onSwitch, onChange })` with `draw(tabs, activeId)` (`role="tab"` buttons, roving `tabindex`, arrow keys, Alt+arrows to reorder, F2 and double-click to rename, native drag and drop with an `.is-drop-before` mark that only a tab drag lights, focus kept across redraws, `#notepad-empty` and `#notepad-body` toggled) and `focusTab()`. No fetches: it calls back, and `screens/notepad.js` owns every request |
|
||||
| `public/notepad-editor.js` | the Notebook's live-preview editor on CodeMirror 6 (`makeCodeMirrorEditor(parent, { onChange, label })` returning `{ getValue, setValue, setReadOnly, focus, destroy }`). A `ViewPlugin` decorates only the lines in view from the Markdown syntax tree: heading line classes `cm-h1` to `cm-h6`, bullets drawn as a widget, the marks around bold, links, quotes and a heading hidden on every line the selection is not on. The editor sits in a shadow root (`.notepad-cm-host`), because CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, and adopts them as a constructed stylesheet inside a shadow root. `setValue()` is `setState()`: not reported through `onChange`, and the undo history is cleared (so each tab starts with a clean one) |
|
||||
| `public/notepad-editor.css` | the one stylesheet of that shadow root, linked from `notepad-editor.js` (a `<link>` inside the root, in `SERVABLE`, not in `CSS_ORDER`): heading sizes, bullets, quote, code and link looks on the console's tokens (custom properties inherit across the boundary, so both themes work). Rules that meet CodeMirror's own base theme use `div.cm-editor` for the specificity |
|
||||
| `public/vendor/codemirror.esm.js` | CodeMirror 6 (state, view, language, commands, lang-markdown, MIT), bundled into one minified ES module by `scripts/vendor-codemirror.mjs` (sha256 `4ff96d58fc1a5497eb933426bd2d160d2fb0cf490de8bb9302c304096c71c1d4`, the six top-level versions in the script and the file's header comment, everything they pull in pinned by `scripts/vendor-codemirror-lock.json` and installed with `npm ci`, so the same lock gives the same bytes). Never edited by hand: change a version in the script and run `node scripts/vendor-codemirror.mjs --update-lock` (needs npm and network; the packages install in a temp folder, never in the repo), or without the flag to rebuild from the lock |
|
||||
| `public/styles/notepad.css` | the notebook's own rules: the top bar button, the dialog, the tab bar and its tools, the name form, the delete question, the empty state and the pictures. The editor's look is `notepad-editor.css`, inside its shadow root |
|
||||
| `public/styles/activities.css` | the Activities rules: the die in the top bar, the Notebook-sized dialog, the board and its state overlay, the your-turn banner in the highlight color, the picker and the notes |
|
||||
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
|
||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||
@@ -275,17 +307,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 with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). 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 `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`.
|
||||
- **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`), `notepad:<key>` (a month-old notepad, whole; see Notepad below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **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.
|
||||
@@ -319,12 +351,12 @@ Key design points:
|
||||
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
|
||||
- **Notepad: the person's, one per folder, in `~/.plan2code/notepads/`, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads), and holds `meta.json` (`{ v, folder, created }`, written once), `note.md` and `images/<uuid>.jpg` with `<uuid>.thumb.jpg`. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. The page reaches it through six routes, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad` (`{ text, savedAt, images: [{ id, url, thumb }] }`), `POST /notepad/text` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image` and `POST /notepad/thumb?id=<uuid>` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete` (`{ id }`) and `GET /notepad/images/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`); the four POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }`. None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The CSP workaround.** OverType 2.6.1 (MIT, vendored unchanged as `public/vendor/overtype.esm.js`) adds a `<style>` element and inline `style` attributes, both of which `style-src 'self'` refuses: `screens/notepad.js` sets `OverType.stylesInjected = true` before making the one editor, OverType's own CSS ships at the top of `styles/notepad.css` (in `CSS_ORDER`, so it rides the joined stylesheet), and `withoutStyleAttrs()` strips the attributes from what OverType renders. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading OverType:** replace the vendored file from `https://cdn.jsdelivr.net/npm/overtype@<version>/dist/overtype.esm.js`, update its version and sha256 in its files-table row and the version in `HEADER` in `scripts/vendor-overtype.mjs`, run `node scripts/vendor-overtype.mjs` (needs a local Chrome or Edge; it rewrites only what sits above `/* end OverType */` and refuses a `notepad.css` without the marker), recheck the internals listed in the vendored file's row, then run the two notepad test files. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notepad for <folder>" by `screens/cleanup.js`, the key when it is missing) only when `staleNotepads()` finds the newest file in it (`newestMtime()` in `files.mjs`) `SESSION_MAX_AGE_MS` (30 days) old or more; `removeCleanup()` removes the whole folder through `removeNotepad()` (key checked against `NOTEPAD_KEY_RE`, contained in `notepadsDir()`, a link refused).
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and the agent's only when the person sends a tab.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created, sent? } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** twelve, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) `/notepad/tab/last` (`{ id }`) and `/notepad/tab/sent` (`{ id, workflow, spec? }`, `markTabSent()`: sets `sent: { workflow, spec?, at }` on the tab, replacing an earlier one; `workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`, `spec` matching `^specs/[A-Za-z0-9._-]+$`, else 400 `bad-sent`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The eleven POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` and the `cmd-*.mjs` files never import `notepads.mjs` (a source test pins it; `sessions.mjs` loads it lazily for Cleanup only, listing and removing whole notepads), so nothing in a notepad reaches `state.json` or anything `wait` prints except a tab the person sends (see **Send to a skill**). **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notLine truncated
|
||||
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 18 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 19 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
|
||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||
|
||||
@@ -362,9 +394,11 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
|
||||
| CLI | Runs |
|
||||
| --- | --- |
|
||||
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
|
||||
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
|
||||
| Codex | `codex --dangerously-bypass-approvals-and-sandbox [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
|
||||
| Claude Code | `claude /plan2code [--permission-mode bypassPermissions] [args]` |
|
||||
| Devin | `devin [--permission-mode bypass] [args] -- /plan2code` |
|
||||
| Codex | `codex [--dangerously-bypass-approvals-and-sandbox] [args] $plan2code` (Codex starts a skill with `$name`; the launch line follows Codex's documentation) |
|
||||
|
||||
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` with Yes as the default; `--keep-permissions` (never forwarded) answers no, and with no TTY on stdin the prompts are off, as before. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
|
||||
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it exits 127 and prints `SKILL_STEPS`: how to install an agent, `cd` into the project, and type `/plan2code` (`$plan2code` in Codex). An uninstalled `--cli` pick prints that CLI's own steps after its error (its install command, `cd` into the project, then `plan2code --cli <id>` or its prompt). `--cli claude` / `devin` / `codex` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=` (or, for Codex, `-m`), it asks `Which model should <CLI> use?` from `models.json` plus the user's additions, Enter keeping the model the CLI last used — Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. `plan2code update` is the one subcommand: it is never forwarded and opens no agent, it runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists. On every other start, before spawning the CLI, it prints one line when a newer release is out (`Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`), compared against `~/.plan2code/bin/version.json` and read from the console's cached release check (`~/.plan2code/console/update-check.json`); it never waits on the network, and when the cache is missing or stale it refreshes it in a detached background process so the next start knows. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin`/`codex` commands and a temp home.
|
||||
|
||||
@@ -374,7 +408,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,17 +10,18 @@
|
||||
- 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
|
||||
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number. The desktop app carries it too (`plan2code-app/src-tauri/tauri.conf.json`, `plan2code-app/package.json`, `plan2code-app/src-tauri/Cargo.toml`, and `Cargo.lock`'s `plan2code-app` entry follows the build): `node scripts/check-versions.mjs [--tag vX.Y.Z]` compares all six, and the release workflow runs it before building. It reports a mismatch today because the app is at 3.0.0 while the rest is still 2.x; it is deliberately not part of `npm test`, so bump the app's files with the release that ships v3.0.0.
|
||||
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
|
||||
- **CHANGELOG house format is not Keep a Changelog:** version headings are `## vX.Y.Z` — with a `v` prefix and **no date**. The release date is recorded only in `version.json`'s `releaseDate`. Category headings carry emoji: `### ✨ Added`, `### 🔧 Changed`, `### 🐛 Fixed`, `### 💥 Breaking`, `### 🗑️ Removed`, `### 📚 Documentation`. Older entries contain one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) — do not introduce new ones. The `.claude/skills/plan2code-changelog/` skill automates version selection and formatting; use it rather than hand-rolling an entry.
|
||||
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
|
||||
- **`.claude/skills/` is tracked:** a new repo-local skill only needs `git add` (see Architecture → Repo-Local Skills). A correction that is a workflow belongs there as a skill, linked from AGENTS.md, not as a Failure log line.
|
||||
- **Loop `.gitignore` setup:** `ensureGitignore()` runs at startup in `Controller.run()` as a pre-flight step, not just inside `createTaskCommit()`. This is critical for phase mode where the Node controller doesn't handle commits — without it, `git add -A` would stage spec files.
|
||||
- **Workflow file character limit:** All `src/plan2code-*.md` files (and the dashboard prompt `src/plan2code.md`) must be ≤ 20,000 characters (about 5k tokens, the usual Agent Skills guidance for a SKILL.md body). A husky pre-commit hook enforces this, and `plan2code-metrics` (`improver.ts`, `applier.ts`) applies the same number to proposed prompt edits, so change them together. History: 11,000 originally (headroom under Windsurf's old 12,000-char limit for platform-specific files, gone since 2.1.0's single-format build), 11,500 in 2.4.0, 20,000 in 2.4.1. The limit is now a prompt-size discipline only: the whole SKILL.md loads on every invocation while references load on demand, so situational detail still belongs in a reference file, and anything with one correct answer belongs in a script (see Skill scripts in the architecture doc).
|
||||
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure with `node scripts/validate-char-count.js` before trusting a near-limit prompt.
|
||||
- **Keep LF line endings:** `.gitattributes` pins `eol=lf` because `validate-char-count.js` counts the characters on disk, and a CRLF checkout adds about one per line to every prompt. Measure with `node scripts/validate-char-count.js` before trusting a near-limit prompt. Git never writes CRLF here, but tools do (Python writing in text mode on Windows, some editors and generators), so `scripts/fix-line-endings.mjs` puts every text file git sees back to LF: `npm run fix:eol` by hand, `--check` to only list, and it runs by itself as npm's `pretest`, in the husky pre-commit before the char count, and after every Write or Edit through the PostToolUse hook in `.claude/settings.json`. In a Python script that writes repo files, open them with `newline="\n"` (or write bytes) anyway.
|
||||
- **The pre-commit hook runs only the char-count check:** `.husky/pre-commit` is `node scripts/validate-char-count.js` alone. `skills/` drift, parse errors and test failures are caught only by `npm test`, so run it before committing. Sub-package tests are separate; see [Development Commands](./AGENTS-development-commands.md).
|
||||
- **`skills/` is generated build output (gitignored):** edit `src/` only. The installer rebuilds `skills/` on every run, so it is always up to date at install time. `npm test` runs `install.js --build-skills` so a broken `SOURCE_PROMPTS` entry or unreadable source fails CI. Never hand-edit `skills/`; `install.js --verify-skills` can diff a stale tree against `src/` when diagnosing.
|
||||
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
||||
@@ -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.
|
||||
|
||||
@@ -47,12 +47,20 @@ cd plan2code-metrics && npm install # First time setup
|
||||
cd plan2code-metrics && npm run build # Build the CLI
|
||||
cd plan2code-metrics && npm test # vitest (aggregator, community, improver)
|
||||
|
||||
# Desktop app (plan2code-app/, Rust + Tauri). CI's `app` workflow runs all three on
|
||||
# Windows, macOS and Linux and fails on any rustfmt difference or clippy warning, so run
|
||||
# them before pushing, not only cargo test (see plan2code-app/README.md "Tests").
|
||||
# First time: rustup component add rustfmt clippy (for the toolchain in rust-toolchain.toml)
|
||||
cd plan2code-app && node scripts/vendor.mjs && cargo fmt --check
|
||||
cd plan2code-app && cargo clippy --workspace --all-targets -- -D warnings
|
||||
cd plan2code-app && cargo test --workspace
|
||||
|
||||
# Plan2Code Bot (end-to-end workflow runner, Claude Agent SDK)
|
||||
cd plan2code-bot && npm install && npm run build
|
||||
cd plan2code-bot && npm test # vitest
|
||||
```
|
||||
|
||||
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in loop, metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel.
|
||||
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in loop, metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel. `npm test` runs them through `scripts/node-test.mjs`, which caps the files run at once at one per spare core (8 at most): each page test file drives a browser, and more at once than the cores can carry fails page tests at random (a flat 8 did on 3 and 4 core CI runners). Page tests (`test-web-console-page-*.mjs`) read styles and set scrolls only through `styleOf()`, `stylesOf()` and `scrollCard()` from `page-test-helpers.mjs`, which retry until the element is still on the page; `test-web-console-shape.mjs` fails a raw `locator.evaluate` that does either.
|
||||
|
||||
## Test/Dev Env Vars
|
||||
|
||||
@@ -62,7 +70,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 +152,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).
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"hooks": {
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Write|Edit|MultiEdit|NotebookEdit",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "node \"$CLAUDE_PROJECT_DIR/scripts/fix-line-endings.mjs\" --hook",
|
||||
"timeout": 30
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
name: app
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
app:
|
||||
name: app (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest, ubuntu-latest]
|
||||
defaults:
|
||||
run:
|
||||
working-directory: plan2code-app
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 20
|
||||
cache: npm
|
||||
cache-dependency-path: plan2code-app/package-lock.json
|
||||
- name: Check the versions agree
|
||||
working-directory: .
|
||||
run: node scripts/check-versions.mjs
|
||||
- name: Install the pinned Rust toolchain
|
||||
shell: bash
|
||||
# clippy and rustfmt are not part of rust-toolchain.toml's minimal profile.
|
||||
run: rustup toolchain install "$(grep channel rust-toolchain.toml | cut -d '"' -f2)" --profile minimal --component clippy --component rustfmt
|
||||
- name: Cache the Cargo registry and build output
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
plan2code-app/target
|
||||
key: cargo-${{ runner.os }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-${{ runner.os }}-
|
||||
- name: Install Linux system packages
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev xvfb
|
||||
- name: Install the app's packages
|
||||
run: npm ci
|
||||
- name: Vendor the xterm files cargo needs
|
||||
# `tauri build` runs this itself (beforeBuildCommand in tauri.conf.json); the cargo
|
||||
# steps below call straight into cargo and skip that, so they need it run by hand.
|
||||
run: node scripts/vendor.mjs
|
||||
- name: Format check
|
||||
run: cargo fmt --check
|
||||
- name: Lint
|
||||
run: cargo clippy --workspace --all-targets -- -D warnings
|
||||
- name: Test
|
||||
run: cargo test --workspace
|
||||
- name: Build
|
||||
run: cargo build --workspace
|
||||
- name: Build the app (tauri build --no-bundle)
|
||||
run: npm run tauri -- build --no-bundle
|
||||
- name: Smoke-test the built app against the fake agent
|
||||
shell: bash
|
||||
# Points the real app at tests/agent_manager.rs's fake-agent fixture (already built
|
||||
# by the "Build" step above, in target/debug) and checks the real binary comes up and
|
||||
# stays up for a few seconds instead of crashing. Linux has no display by default.
|
||||
run: |
|
||||
exe=plan2code-app
|
||||
agent=fake-agent
|
||||
if [ "${{ runner.os }}" = "Windows" ]; then exe="$exe.exe"; agent="$agent.exe"; fi
|
||||
export PLAN2CODE_APP_AGENT_BIN="$(pwd)/target/debug/$agent"
|
||||
launch=("target/release/$exe")
|
||||
if [ "${{ runner.os }}" = "Linux" ]; then launch=(xvfb-run -a "target/release/$exe"); fi
|
||||
"${launch[@]}" &
|
||||
pid=$!
|
||||
sleep 5
|
||||
if kill -0 "$pid" 2>/dev/null; then
|
||||
echo "plan2code-app is still running after 5s; smoke test passed"
|
||||
kill "$pid"
|
||||
else
|
||||
wait "$pid"
|
||||
echo "plan2code-app exited within 5s (exit code $?); smoke test failed"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
node-tests:
|
||||
name: npm test (${{ matrix.os }})
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [windows-latest, macos-latest, ubuntu-latest]
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 20
|
||||
- run: npm install
|
||||
- run: npm test
|
||||
@@ -0,0 +1,119 @@
|
||||
name: release-app
|
||||
|
||||
# Builds the desktop app on four systems when a GitHub release is published, or a v* tag is
|
||||
# pushed ahead of one, and attaches one file per system, named
|
||||
# plan2code-app-<version>-<os>-<arch>[.exe], plus one checksum file
|
||||
# (plan2code-app-<version>-SHA256SUMS.txt). install.js fetches the matching file and checks it
|
||||
# against that list. Linux ships the plain binary, not an AppImage: docs/desktop-app.md documents
|
||||
# its WebKitGTK 4.1 dependency instead. The first release is unsigned: docs/desktop-app.md says
|
||||
# how to allow it.
|
||||
|
||||
on:
|
||||
release:
|
||||
types: [published]
|
||||
push:
|
||||
tags: ['v*']
|
||||
|
||||
permissions:
|
||||
contents: write
|
||||
|
||||
jobs:
|
||||
build:
|
||||
name: build (${{ matrix.label }})
|
||||
runs-on: ${{ matrix.runner }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- { runner: windows-latest, label: windows-x64, built: plan2code-app.exe, suffix: .exe }
|
||||
- { runner: macos-latest, label: macos-arm64, built: plan2code-app, suffix: '' }
|
||||
- { runner: macos-15-intel, label: macos-x64, built: plan2code-app, suffix: '' }
|
||||
- { runner: ubuntu-latest, label: linux-x64, built: plan2code-app, suffix: '' }
|
||||
defaults:
|
||||
run:
|
||||
shell: bash
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/setup-node@v4.4.0
|
||||
with:
|
||||
node-version: 22
|
||||
cache: npm
|
||||
cache-dependency-path: plan2code-app/package-lock.json
|
||||
- name: Check the versions agree with the release tag
|
||||
env:
|
||||
TAG: ${{ github.event.release.tag_name || github.ref_name }}
|
||||
run: node scripts/check-versions.mjs --tag "$TAG"
|
||||
- name: Install the pinned Rust toolchain
|
||||
working-directory: plan2code-app
|
||||
run: rustup toolchain install "$(grep channel rust-toolchain.toml | cut -d '"' -f2)" --profile minimal
|
||||
- name: Cache the Cargo registry and build output
|
||||
uses: actions/cache@v6.1.0
|
||||
with:
|
||||
path: |
|
||||
~/.cargo/registry
|
||||
~/.cargo/git
|
||||
plan2code-app/target
|
||||
key: cargo-release-${{ matrix.label }}-${{ hashFiles('plan2code-app/Cargo.lock') }}
|
||||
restore-keys: |
|
||||
cargo-release-${{ matrix.label }}-
|
||||
- name: Install Linux system packages
|
||||
if: runner.os == 'Linux'
|
||||
run: |
|
||||
sudo apt-get update
|
||||
sudo apt-get install -y libwebkit2gtk-4.1-dev build-essential libxdo-dev libssl-dev libayatana-appindicator3-dev librsvg2-dev
|
||||
- name: Install the app's packages
|
||||
working-directory: plan2code-app
|
||||
run: npm ci
|
||||
# One plain executable per system: the web page is built into it, so it needs no installer.
|
||||
- name: Build
|
||||
working-directory: plan2code-app
|
||||
run: npm run tauri -- build --no-bundle
|
||||
- name: Name the file
|
||||
run: |
|
||||
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
|
||||
mkdir -p dist
|
||||
cp "plan2code-app/target/release/${{ matrix.built }}" "dist/plan2code-app-${VERSION}-${{ matrix.label }}${{ matrix.suffix }}"
|
||||
- uses: actions/upload-artifact@v4.6.2
|
||||
with:
|
||||
name: app-${{ matrix.label }}
|
||||
path: dist/*
|
||||
if-no-files-found: error
|
||||
|
||||
publish:
|
||||
name: attach to the release
|
||||
needs: build
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
GH_TOKEN: ${{ github.token }}
|
||||
TAG: ${{ github.event.release.tag_name || github.ref_name }}
|
||||
steps:
|
||||
- uses: actions/checkout@v4.2.2
|
||||
- uses: actions/download-artifact@v4.3.0
|
||||
with:
|
||||
path: dist
|
||||
pattern: app-*
|
||||
merge-multiple: true
|
||||
- name: Verify every system's file is here
|
||||
run: |
|
||||
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
|
||||
cd dist
|
||||
missing=0
|
||||
for name in "plan2code-app-${VERSION}-windows-x64.exe" "plan2code-app-${VERSION}-macos-arm64" "plan2code-app-${VERSION}-macos-x64" "plan2code-app-${VERSION}-linux-x64"; do
|
||||
if [ ! -f "$name" ]; then
|
||||
echo "::error::missing release asset $name"
|
||||
missing=1
|
||||
fi
|
||||
done
|
||||
[ "$missing" -eq 0 ]
|
||||
- name: Write the checksum file
|
||||
run: |
|
||||
VERSION="$(node -p "require('./plan2code-app/src-tauri/tauri.conf.json').version")"
|
||||
cd dist
|
||||
sha256sum plan2code-app-* > "plan2code-app-${VERSION}-SHA256SUMS.txt"
|
||||
cat "plan2code-app-${VERSION}-SHA256SUMS.txt"
|
||||
- name: Make sure the release exists
|
||||
# A tag push alone names no release; create one (same tag, generated notes) so the
|
||||
# upload below always has somewhere to go, whichever trigger ran it.
|
||||
run: gh release view "$TAG" || gh release create "$TAG" --title "$TAG" --generate-notes
|
||||
- name: Attach to the release
|
||||
run: gh release upload "$TAG" dist/* --clobber
|
||||
@@ -13,7 +13,7 @@ nul
|
||||
.cognition/
|
||||
handoffs/
|
||||
node_modules/
|
||||
package-lock.json
|
||||
/package-lock.json
|
||||
SYNC.md
|
||||
|
||||
# Generated by install.js/`npm run build:skills` from src/, regenerated on
|
||||
@@ -24,3 +24,8 @@ SYNC.md
|
||||
# Throwaway design prototypes (ai-assist-prototype). The decision they
|
||||
# recorded lives in the code and the CHANGELOG; the files stay local.
|
||||
prototypes/
|
||||
|
||||
# The Tauri app (plan2code-app/)
|
||||
plan2code-app/target/
|
||||
plan2code-app/src-tauri/gen/
|
||||
plan2code-app/ui/vendor/
|
||||
@@ -1 +1,2 @@
|
||||
node scripts/fix-line-endings.mjs
|
||||
node scripts/validate-char-count.js
|
||||
@@ -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 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. On the dashboard, a spec with no overview gets a **Map** tab (`?file=map`, `pathfinder/map.md`) and a **Plan draft** tab (`?file=draft`, the live `PLAN-DRAFT-*.md`) in its place, each while its file exists, fetched and drawn the same way; away from the dashboard only the overview is read, since a session's own map or draft is the work already in front of it. 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 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.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -129,7 +129,10 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
spec that has an `overview.md`, an **Overview** tab shows it — read-only,
|
||||
and read fresh from disk each time you open the tab, so an edit shows up
|
||||
straight away. No file, no tab. On the dashboard it follows the spec picked
|
||||
at the top, and disappears for *start from scratch*.
|
||||
at the top, and disappears for *start from scratch*. A picked spec that is
|
||||
not documented yet shows its **Map** (`pathfinder/map.md`) and its
|
||||
**Plan draft** (the live `PLAN-DRAFT-*.md`) as tabs instead, each when it
|
||||
exists.
|
||||
- **Where you are, at the bottom.** The footer names the folder the session
|
||||
was launched from and its git branch (`plan2code · feature/…`), muted in
|
||||
the middle. Click it to open the Workspace dialog (see *Your workspace*).
|
||||
@@ -146,8 +149,9 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
- **Files in your notes.** Show instead of describe: attach a screenshot, a
|
||||
photo or a document to any note or quick question (see *Attachments in notes
|
||||
and questions* below).
|
||||
- **A notepad of your own.** One per project folder, for jottings and
|
||||
screenshots that are yours, not the agent's (see *Your notepad* below).
|
||||
- **A notebook of your own.** One per project folder, in named tabs, for
|
||||
jottings and screenshots that are yours, not the agent's (see *Your notebook*
|
||||
below).
|
||||
- **A nudge when it might be waiting on you.** Your agent may stop in the
|
||||
terminal to ask permission for something, and the page cannot see that. So
|
||||
the dashboard and every starting screen carry a one-line tip about hands-off
|
||||
@@ -160,10 +164,12 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
favicon follows the line beside him: dashed amber while Plan2Code is
|
||||
working or picking up your answers, solid green when it is your move, solid
|
||||
red when it has gone quiet or the connection is lost (busy is dashed so the
|
||||
states differ by pattern, not only color). A finished session goes back to
|
||||
the plain icon, so a console left in a background tab can be checked at a
|
||||
glance.
|
||||
- **Help.** The **?** at the top right opens a Help dialog with 18 topics,
|
||||
states differ by pattern, not only color). A finished session stays green
|
||||
while it still offers a button to press (back to the dashboard, a review),
|
||||
turns red if that press was never collected, and goes back to the plain
|
||||
icon once nothing is left, so a console left in a background tab can be
|
||||
checked at a glance.
|
||||
- **Help.** The **?** at the top right opens a Help dialog with 19 topics,
|
||||
one per tab down the left (across the top on a narrow window), opening on
|
||||
the one for where you are. It is part of the page itself, so it still reads
|
||||
fully when the page has lost its program.
|
||||
@@ -210,7 +216,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
|
||||
@@ -218,7 +224,9 @@ and hides it while *Hide unavailable workflows* is on. Its chip has a visible
|
||||
removes the folder (any other spec also asks you to type its name). Click a card and Planny
|
||||
flies while it gets ready;
|
||||
a few seconds later the same page is that skill's console, already running. No
|
||||
command names to remember.
|
||||
command names to remember. Pathfinder, Plan, Quick Task and Revise plan can also
|
||||
start from one of your [Notebook](#your-notebook) tabs: see *Sent from the
|
||||
dashboard* there.
|
||||
|
||||
Handoffs this checkout has not picked up yet follow the specs in the picker as
|
||||
dashed **Handoff** chips, each with its title and age. Select one and the skill
|
||||
@@ -385,8 +393,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
|
||||
@@ -396,7 +404,11 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
- **The dialog.** A click opens it; the button never switches anything by
|
||||
itself. **Use helpers** or **Work alone**, the instruction the agent follows
|
||||
(**Reset to default** puts the shipped one back), and how many helpers may
|
||||
run at once (1 to 20; your agent's own limit still applies). **Save** sends
|
||||
run at once (1 to 20; your agent's own limit still applies). Under Helpers,
|
||||
**Helper strength** sets how strong a model and how much effort helpers get:
|
||||
**Balanced** (the default), **Thrifty** (one step lighter; reviews never
|
||||
below standard), **Best** (strongest and high effort, except lookups) or
|
||||
**Match my session** (nothing set on helpers). **Save** sends
|
||||
it; the agent hears of it at its next check-in, as a setting, not as
|
||||
something you typed.
|
||||
- **Saved per project and per skill**, on until switched off, in
|
||||
@@ -406,38 +418,180 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
appears before Ask: one row per helper with what it was asked and whether it
|
||||
is running, done or failed, plus a one-line result at the end. Rows change at
|
||||
the agent's check-ins, not live. *Working alone* means your agent has no way
|
||||
to start helpers here. The tab clears when you go back to the dashboard.
|
||||
to start helpers here. Each row may carry one quiet line such as "Standard,
|
||||
medium effort" ("Session model" when the helper runs on yours). The rules
|
||||
live in `helper-strength.md` and apply in terminal sessions too. The tab
|
||||
clears when you go back to the dashboard.
|
||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||
they show in the tab too.
|
||||
|
||||
### Your notepad
|
||||
### Your notebook
|
||||
|
||||
The **Notepad** icon in the top bar, on the dashboard, every skill and the
|
||||
The **Notebook** icon in the top bar, on the dashboard, every skill and the
|
||||
finished screen, opens a large dialog with a scratch pad for the folder you are
|
||||
working in.
|
||||
|
||||
- **Markdown, styled as you type.** Headings, lists, bold and code take their
|
||||
look in place while the text itself stays plain Markdown (saved as
|
||||
`note.md`, up to 1 MB).
|
||||
- **Tabs.** A row of named tabs sits across the top, each with its own text and
|
||||
its own pictures. **+ New tab** asks for a name first (1 to 40 characters, no
|
||||
two the same in any case, up to 20 tabs), in a small dialog. There is no
|
||||
toolbar under the row: a double-click (or **F2**) on a tab renames it, the **x**
|
||||
beside its name deletes it (the **Delete** key does too), and tabs are moved
|
||||
only by dragging them. The tab you left open is the one you come back to.
|
||||
Delete opens a dialog that asks twice and takes the tab's text and pictures
|
||||
with it; with no tab left, the dialog asks you to make one. A notebook from before tabs opens
|
||||
as one tab called **Notes**.
|
||||
- **Markdown, styled as you type.** The editor shows Markdown in place:
|
||||
headings grow, bullets draw, bold, code, quotes and links take their look, and
|
||||
the marks come back on the line you are on. The text itself stays plain
|
||||
Markdown (saved as the tab's `note.md`, up to 1 MB).
|
||||
- **Pictures beside it.** Paste a screenshot, drop files on the dialog or press
|
||||
**Add image**: each becomes a thumbnail in a strip under the text (up to 200).
|
||||
Click one for a full-screen preview (arrow keys step through, Esc closes);
|
||||
its **X** asks before it deletes.
|
||||
- **It saves itself**, about a second after you stop typing and when you close
|
||||
the dialog. If the connection drops, your text stays in the page and is
|
||||
retried, and the tab warns before you close it with something unsaved.
|
||||
**Add image**: each becomes a thumbnail in a strip under the text (up to 200
|
||||
per tab). Click one for a full-screen preview (arrow keys step through, Esc
|
||||
closes); its **X** asks before it deletes.
|
||||
- **It saves itself**, about a second after you stop typing, when you close the
|
||||
dialog and before you switch tabs. If a tab's text cannot be saved, switching
|
||||
is refused ("Not saved yet, so staying on this tab") rather than losing it.
|
||||
If the connection drops, your text stays in the page and is retried, and the
|
||||
browser tab warns before you close it with something unsaved.
|
||||
- **One per folder, kept between sessions.** Every session started in the same
|
||||
folder (each git worktree counts as its own) opens the same notepad, in
|
||||
folder (each git worktree counts as its own) opens the same notebook, in
|
||||
`~/.plan2code/notepads/<folder-name>-<12 hex>/`: `meta.json` (which folder it
|
||||
belongs to), `note.md` and `images/`. Two pages open on one folder share it,
|
||||
and the last save wins.
|
||||
belongs to), `tabs.json` (the tabs, their order and the last one open) and one
|
||||
folder per tab, `tabs/<id>/`, holding its `note.md` and `images/`. Two pages
|
||||
open on one folder share it, and the last save wins.
|
||||
- **Private.** It never goes into your project, your session or anything the
|
||||
agent reads, so the agent never sees it. It stays on this machine.
|
||||
agent reads, so the agent never sees it, unless you send a tab (next
|
||||
bullet). It stays on this machine. A box filled from a tab is an ordinary
|
||||
draft from then on: like anything you type, its text is kept with the
|
||||
session's draft and its pictures with its uploads, unread until you send it.
|
||||
- **Sent from the dashboard.** On a lit Pathfinder, Plan or Quick Task card
|
||||
with *Start fresh*, and on a lit Revise plan card with a spec picked that has
|
||||
no plan change waiting, the confirm pane offers **Start with a note from your
|
||||
Notebook**. Turn it on and pick a tab: empty tabs are grayed, a tab you have
|
||||
sent shows a small **sent** badge, and a preview shows the whole tab, its text
|
||||
and its pictures. The first five pictures are ticked; at most five can be, so
|
||||
untick one to tick another. A tab over 50 KB gets a *Long tab* note so you can
|
||||
trim it first, and the pane's command line reads `+ note: <tab>`. Pressing
|
||||
**Start** is the consent, and nothing is put on the launch itself. The skill's
|
||||
first open text box marked `"fill": "note"` (the idea box, or Revise plan's
|
||||
*What should change* box) then arrives filled, once, with the tab's text and
|
||||
the ticked pictures attached, and you can edit it before you press **Send**. A
|
||||
tab or picture deleted in between leaves the box empty (with a note) or skips
|
||||
the picture. Only sending that box hands the agent the text: **Send**, or
|
||||
**Stop** or **Back to the dashboard**, which take the answers you have ready
|
||||
with them (their dialog says so). Start alone, then going back before the box
|
||||
is sent, sends nothing and marks nothing. After it, the tab shows the **sent**
|
||||
badge and a muted *Sent to <Skill> · <Date>* line under its text.
|
||||
- **Removed only when you say.** No automatic cleanup touches it. Once the
|
||||
newest file in a notepad is 30 days old or more, *User Preferences →
|
||||
newest file in a notebook is 30 days old or more, *User Preferences →
|
||||
Cleanup* offers it as one item named after its folder's full path
|
||||
(*Notepad for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notepad, text and pictures.
|
||||
(*Notebook for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notebook, every tab's text and pictures.
|
||||
|
||||
### Activities
|
||||
|
||||
The **die** in the top bar, right of the megaphone, opens **Activities**: small
|
||||
games to play while you wait, say through a long build. Two ship today,
|
||||
**Snake** and **Mini golf**. With two games the window shows a picker, one
|
||||
button per game, and remembers your last pick. The header shows the current
|
||||
game's best, such as **Activities · Snake best: 12**, or **Snake: no best yet**.
|
||||
|
||||
- **Snake** speeds up as it grows: 120 ms a step at its starting three cells,
|
||||
4 ms quicker for each cell beyond, never under 60 ms, and 3% quicker again
|
||||
for each level. Every 5 foods is a new level, and the first few each bring
|
||||
something new: **Rocks** at level 2 (a cell flashes before it turns to
|
||||
stone, and never right ahead of the head), **Mystery boxes** at 3,
|
||||
**Portals** at 4, **Comets** at 5 (into the head is a crash, through the
|
||||
body cuts the tail there), **Chaos** at 6, where surprises also happen on
|
||||
their own, and **Ice** at 7, where a turn slides on for two steps before it
|
||||
takes (a frosty arrow off the head shows the turn coming; the ice melts at
|
||||
level 8). Each level serves its own fruit (an apple, then cherries, an
|
||||
orange, grapes, a banana, a strawberry, watermelon, a peach and, at level 9,
|
||||
a glinting golden apple) on its own scenery: a plain garden, then a meadow,
|
||||
a desert, a lagoon, a starry night, a carnival, ice, a volcano and gold,
|
||||
each a faint tint and a scatter of small marks over the usual board. The
|
||||
last food of every odd level from 3 on is a **boss fruit**: four cells big
|
||||
and crowned, it takes three bites (a point a level each, and the head must
|
||||
leave it between bites), and the last bite scores the food plus 5 points a
|
||||
level. From level 2 a **runaway fruit** on two little feet sometimes turns
|
||||
up in place of a power-up: once you are within three cells it hops up to two
|
||||
cells away, rests two steps between hops and tires after seven, so corner it
|
||||
or wear it out for 6 points a level before it runs off after 12 seconds. Food eaten within 2.6 seconds of the last builds a
|
||||
combo (x2 up to x5). Power-ups turn up every few seconds and fade if left: **Shield**
|
||||
(takes one crash: wraps through a wall, smashes a rock), **Turbo** (faster,
|
||||
double points), **Slow-mo**, **Magnet** (food slides toward you),
|
||||
**Ghost** (walls wrap) and **Scissors** (half the tail, a point per cell
|
||||
cut). A mystery box holds one of ten surprises: Jackpot, Gold rush, Earthquake,
|
||||
Meteor shower, Mirror world (flipped keys), Lights out, Disco fever (triple
|
||||
points), Big snack, Incoming! (a comet) and Treasure. Passing your best
|
||||
mid-round plays a fanfare. A power-up, surprise or level banner opens on
|
||||
the half of the board away from the snake's head, and fades almost clear
|
||||
while the head is under it or heading into it, so it never hides what you
|
||||
are about to hit. The start and end screens show how many of the 24
|
||||
power-ups, surprises, levels and specials you have ever found, and what to look for
|
||||
next.
|
||||
- **Mini golf** is eighteen hand-made, thoroughly silly holes seen from above.
|
||||
The front nine, **Pirate Cove**, floats in a shark sea: Walk the Plank,
|
||||
Shipwreck Cove, Cannon Alley, Treasure Beach, Kraken's Lagoon, Ghost Ship,
|
||||
The Ship's Wheel, Skull Island and Captain's Plunder, with barrels,
|
||||
cannonballs, a rolling powder keg, a scuttling crab, a kraken's tentacle and a
|
||||
skull you putt through. The back nine, the **Caves of Doom**, is dark but for
|
||||
the ball's own light and whatever glows: Into the Dark, Stalagmite Forest,
|
||||
Lava Lake, Mine Cart Madness, Crystal Pinball, The Bottomless Pit, Glowworm
|
||||
Grotto, Crusher Corridor and The Dragon's Hoard, with glowing pools, lava, a
|
||||
bottomless pit, a bobbing fireball, runaway mine carts, stone crushers that
|
||||
slam shut in turn, portals and a sleeping dragon. Each hole opens with a quip,
|
||||
and splashes, bonks and tunnels pop up a word or two. Play is quick and
|
||||
arcade style: the aim follows the mouse (or hold left or right to turn it,
|
||||
slowly at first, then faster), and it points back at the cup each time the
|
||||
ball stops. A click or space starts the power meter beside the ball; a second
|
||||
sets the power. The needle crawls near the bottom, so soft putts are easy,
|
||||
and races near the top: the gold **MAX** band just under full putts 1.15
|
||||
times as hard, and the red band past it is an overswing that shanks the ball
|
||||
off line at reduced power. A ring round the waiting ball is the shot clock:
|
||||
after 6 seconds the meter starts by itself, and a meter left for three trips
|
||||
dribbles the ball a few inches. Hold space or the mouse button while the ball
|
||||
rolls to play it three times as fast. Par is set per hole (59 for the
|
||||
round), the ball is picked up after 8 strokes, and the round shows its +/-
|
||||
par. A scorecard (front nine and back nine) shows between holes; space, a
|
||||
click or 1.5 seconds moves on.
|
||||
- **Power-ups.** A glowing pad the ball rolls over is held for your next putt
|
||||
only (the pill at the bottom right says which): a **Lucky Doubloon** makes the
|
||||
putt free (a hole still scores at least 1), a **Cannonball** fires it 1.6
|
||||
times as hard, a **Ghost Ball** floats over water, sand, bumpers and movers
|
||||
(but sinks if it stops on water), a **Parrot Magnet** bends it toward the cup,
|
||||
a **Rubber Duck** keeps its full speed off walls, a **Treasure Map** makes the
|
||||
cup huge, and a **Spyglass** draws where the putt will roll while the meter
|
||||
runs, following the needle. One
|
||||
is held at a time, a new pad replaces it, and a held one carries over to the
|
||||
next hole.
|
||||
- **It never hides your turn.** A new question, a sign-off or a finish pauses
|
||||
the game at once and shows a banner with **Go to it**, which closes the window
|
||||
on that question. Hiding the page or clicking away from it pauses it too, and
|
||||
nothing resumes by itself. Any game key (arrows, W/A/S/D, space, P) or, in
|
||||
Mini golf, a click on the board plays on, and the banner stays down until the
|
||||
next new question or finish.
|
||||
- **A countdown first.** Every game counts down 3, 2, 1 before a round starts
|
||||
and before it plays on after a pause, so nothing moves before you are ready.
|
||||
P or Esc during the count pauses again.
|
||||
- **Keys.** Arrows or W/A/S/D steer, space starts and plays, P pauses, Esc
|
||||
closes the window with the game paused. A page with no mouse or trackpad
|
||||
(touch only) shows "Activities need a keyboard." in place of the board.
|
||||
- **Best scores** show beside the score while you play and after each round.
|
||||
Snake keeps its highest score. Mini golf keeps its lowest full round, and a
|
||||
half-played round never counts. **Reset best scores** clears them after a
|
||||
second click to confirm.
|
||||
The line under the board is a pair of colored chips, Score and Best, with a
|
||||
meter between them filling toward the best (for a game where the highest
|
||||
wins). Reaching the best makes its chip glow; passing it turns the line into
|
||||
a rainbow with a NEW BEST tag and a burst of sparks, once a round. A round
|
||||
that beats a saved best ends with **New best!** on the end screen, and Mini
|
||||
golf, which only knows at the end, fires its sparks then. Reduced motion keeps
|
||||
the colors and drops the movement.
|
||||
- **Private.** Best scores, Snake's surprises found, the last pick and the **Show Activities** switch
|
||||
(User Preferences, which hides the die everywhere) are saved in
|
||||
`~/.plan2code/console/looks.json`. Nothing about Activities reaches the agent
|
||||
or the session.
|
||||
|
||||
### Session meter
|
||||
|
||||
@@ -680,6 +834,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
|
||||
@@ -748,10 +915,11 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notepad for one folder: `meta.json`, `note.md` and `images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them, except a tab you send) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width, the Show Activities switch, the last activity picked (`lastActivity`), best scores (flat `activityBest<Id>` keys: `activityBestSnake`, `activityBestGolf`) and each game's memo (`activityMemo<Id>`: Snake's surprises found) | always |
|
||||
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
||||
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
||||
| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents), read by the `plan2code` command and the desktop app | always |
|
||||
| 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
|
||||
@@ -781,8 +949,8 @@ the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||
`console/`, `bin/`, `launcher.json`, `install.json` (what you installed, which
|
||||
`plan2code update` reads), `models.json`, `handoffs/` (old handoffs go by
|
||||
age, above) and `notepads/`. Each notepad whose newest file is 30 days old or
|
||||
more is listed as one item, *Notepad for* its folder, and goes whole; no
|
||||
age, above) and `notepads/`. Each notebook whose newest file is 30 days old or
|
||||
more is listed as one item, *Notebook for* its folder, and goes whole; no
|
||||
automatic sweep ever removes one. It also lists each
|
||||
folder in the project's `specs--completed/` whose newest file is more than 30
|
||||
days old: archived specs Finalize moved there. Deleting one is permanent:
|
||||
@@ -822,7 +990,7 @@ this:
|
||||
|
||||
### Routes
|
||||
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the notepad. Like every page route, they are on `127.0.0.1`
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the notebook. Like every page route, they are on `127.0.0.1`
|
||||
behind the session cookie, and the ones that write also check the request's
|
||||
origin.
|
||||
|
||||
@@ -834,19 +1002,25 @@ origin.
|
||||
| `POST /submit` | The Send. A note may carry `images` and `files`, each `[{ path, name }]`: at most 5 together, images in `images` and documents in `files`, every path inside this session's `uploads/`, otherwise 400. |
|
||||
| `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. |
|
||||
| `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. |
|
||||
| `GET /overview?spec=specs/<name>` | The Overview tab's read of `<spec>/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. |
|
||||
| `GET /overview?spec=specs/<name>[&file=map\|draft]` | The Overview tab's read of `<spec>/overview.md` (or, with `file=`, the Map tab's `pathfinder/map.md` or the Plan draft tab's live `PLAN-DRAFT-*.md`), as `text/markdown` with `cache-control: no-store` and the file's spec-relative name, URL-encoded, in `x-spec-file`. A missing file is a 204. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get the same 204 as a missing file, as does an unscanned `spec` or an unknown `file`. |
|
||||
| `GET /handoff?id=<id>` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. |
|
||||
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
|
||||
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
|
||||
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||
| `GET /notepad` | The notepad for the folder this session runs in: `{ text, savedAt, images: [{ id, url, thumb }] }`. Reading never creates a file. |
|
||||
| `POST /notepad/text` | `{ text }`. Saves `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 413 `too-long` (over 1 MB). |
|
||||
| `POST /notepad/image` | Raw `image/jpeg` (the page re-encodes every picture first). Writes `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures). |
|
||||
| `POST /notepad/thumb?id=<uuid>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found`, 415 `not-jpeg`, 413 `too-large`. |
|
||||
| `POST /notepad/image/delete` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found`. |
|
||||
| `GET /notepad/images/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||
| `GET /notepad[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name, sent? }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
|
||||
| `POST /notepad/text?tab=<id>` | `{ text }`. Saves that tab's `note.md` and answers `{ ok, savedAt }`; 400 `bad`, 404 `no-such-tab`, 413 `too-long` (over 1 MB). |
|
||||
| `POST /notepad/image?tab=<id>` | Raw `image/jpeg` (the page re-encodes every picture first). Writes the tab's `images/<uuid>.jpg` and answers `{ ok, id, url }`; 415 `not-jpeg`, 413 `too-large` (over 4 MB), 409 `too-many` (200 pictures in the tab). |
|
||||
| `POST /notepad/thumb?id=<uuid>&tab=<id>` | Raw `image/jpeg`: that picture's thumbnail. 404 `not-found` or `no-such-tab`, 415 `not-jpeg`, 413 `too-large`. |
|
||||
| `POST /notepad/image/delete?tab=<id>` | `{ id }`. Deletes a picture and its thumbnail; 404 `not-found` or `no-such-tab`. |
|
||||
| `POST /notepad/tab` | `{ name }`. Makes a tab, which becomes the last one used, and answers `{ ok, id, name }`; 400 `bad-name`, 409 `duplicate-name` (any case) or `too-many-tabs` (20). |
|
||||
| `POST /notepad/tab/rename` | `{ id, name }`. Answers `{ ok, id, name }`; 400 `bad-name`, 404 `no-such-tab`, 409 `duplicate-name`. |
|
||||
| `POST /notepad/tab/delete` | `{ id }`. Removes the tab from the index, then its folder (text and pictures); 404 `no-such-tab`. |
|
||||
| `POST /notepad/tab/order` | `{ order: [id] }`, every current id exactly once; 400 `bad` otherwise. |
|
||||
| `POST /notepad/tab/last` | `{ id }`. Remembers the open tab; 404 `no-such-tab`. |
|
||||
| `POST /notepad/tab/sent` | `{ id, workflow, spec? }`. Records that the tab was sent (`workflow` one of `pathfinder`, `plan`, `quick-task`, `revise-plan`; `spec` like `specs/<name>`) as `sent: { workflow, spec?, at }` on its `tabs.json` entry, shown back in `GET /notepad`'s `tabs`. The page posts it only after the Send that carried the filled box; 400 `bad-sent`, 404 `no-such-tab`. |
|
||||
| `GET /notepad/images/<tab>/<uuid>.jpg`, `<uuid>.thumb.jpg` | Serves a picture or its thumbnail as `image/jpeg`, only by a tab id and a UUID name, a regular file (never a link) whose real path stays inside `~/.plan2code/notepads/`; anything else is 404. |
|
||||
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
||||
|
||||
## For maintainers
|
||||
@@ -860,7 +1034,7 @@ origin.
|
||||
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and OverType 2.6.1 (MIT) for the notepad's editor; the page's policy blocks the `<style>` OverType injects, so its CSS ships in `public/styles/notepad.css`, regenerated by `node scripts/vendor-overtype.mjs` after an upgrade (steps in the architecture doc's Notepad point) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, and CodeMirror 6 (MIT) for the notebook's editor as one bundled file, `public/vendor/codemirror.esm.js`, made by the dev-only `node scripts/vendor-codemirror.mjs` from a pinned lock (about 500 KB, loaded only when the Notebook is first opened); the page's policy blocks the `<style>` element CodeMirror writes, so the editor lives in a shadow root where it adopts its rules as a constructed stylesheet (steps in the architecture doc's Notebook point) |
|
||||
|
||||
Edit `src/` only. `skills/` is a committed build artifact: regenerate it with
|
||||
`npm run build:skills` and commit it with the source change, since `npm test`
|
||||
@@ -922,14 +1096,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 **Notepad** in the top bar (Markdown and pictures, one per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, private: the agent reads a tab only when you start Pathfinder, Plan, Quick Task or Revise plan from the dashboard with it and send the box it fills (an idea box marked `fill: "note"`, up to five ticked pictures attached), which then marks the tab sent via `POST /notepad/tab/sent`; the agent CLI never imports the store; removed only through Cleanup once a month untouched), **Activities** behind the top bar's die (two small games, Snake and Mini golf, listed in `public/activities.js` with one module per game under `public/activities/`, a picker once two are listed, driven by `screens/activities.js` (keys, key releases for a game with `release()`, canvas pointer events for a game with `pointer()`, one frame timer), paused whenever the person's turn comes and resumed only by the person, best scores in flat `activityBest<Id>` keys in `looks.json` (lowest wins for a game that sets `lowerIsBetter`), and one number a game may keep between sessions in `activityMemo<Id>` (Snake's tally of surprises found), never shown to the agent), a built-in 19-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder, Plan, Revise plan) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the seven helper skills); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -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.
|
||||
@@ -103,6 +103,9 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
|
||||
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
|
||||
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
|
||||
- When `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone).
|
||||
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
|
||||
- When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load.
|
||||
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests").
|
||||
- Never fix CRLF by hand, one file at a time: run `npm run fix:eol` (`scripts/fix-line-endings.mjs`). Windows Python in text mode, among other tools, writes CRLF into files git keeps as LF; a whole session's edits once came out CRLF and 14 other files were found the same way. It now also runs as `pretest`, in the pre-commit hook and after every agent Write or Edit (see the LF gotcha in Code Style).
|
||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
||||
- When a test checks how `cmd.exe` finds a `.cmd`/`.bat` (current folder before PATH), clear `NoDefaultCurrentDirectoryInExePath` for the run under test (`env_remove` in Rust, `undefined` in a `test-launcher.mjs` `box.run` env): some shells (Claude Code's among them) already set it, and the decoy `.cmd` test for custom agents passed without its fix until it did.
|
||||
@@ -2,6 +2,85 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v3.0.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **New Session** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
|
||||
- **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.
|
||||
- **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review.
|
||||
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort".
|
||||
- **web console**: picking a spec on the dashboard that is not documented yet now shows its main files as read-only tabs in the top bar, like the **Overview** tab of a documented spec: **Map** for a Pathfinder map (`pathfinder/map.md`) and **Plan draft** for Plan's live `PLAN-DRAFT-*.md`, each when it exists. Once the spec has an `overview.md`, Overview replaces them.
|
||||
- **web console**: start Pathfinder, Plan or Quick Task (on **Start fresh**) or Revise plan (on a picked spec with no plan change waiting) from a Notebook tab. A lit card's confirm pane offers **Start with a note from your Notebook**, with the tab list, a preview of the whole tab and up to five ticked pictures (the first five start ticked; a tab over 50 KB says so). The skill's first box arrives filled with the tab's text and pictures, editable, and the agent reads it only once you send it; nothing about the tab rides the launch itself. The tab then shows a **sent** badge and a "Sent to <Skill> · <Date>" line in the Notebook, and the Notebook's privacy line now reads: the agent never reads your Notebook, and a tab reaches it only when you start a workflow with it.
|
||||
- **web console**: **Activities**, a die in the top bar right of the megaphone, opens a window of small games to play while you wait, say through a long build. The first is **Snake**, built in-house from local files (arrows or WASD, space, P to pause, Esc to close). It speeds up as it grows and gets wilder each level: every 5 foods brings something new (rocks that flash before they land, mystery boxes, portals, tail-cutting comets, chaos, then ice, where a turn slides two steps before it takes), six power-ups turn up on their own (Shield, Turbo, Slow-mo, Magnet, Ghost, Scissors), a mystery box holds one of ten surprises (Jackpot, Gold rush, Mirror world, Lights out, Disco fever and more), each level serves its own fruit (an apple, then cherries, an orange, grapes, a banana, a strawberry, watermelon, a peach and a golden apple) on its own scenery (meadow, desert, lagoon, starry night, carnival, ice, volcano, gold), the last food of every odd level from 3 on is a crowned four-cell boss fruit that takes three bites, a runaway fruit on little feet hops away until you corner it or tire it out, quick eating builds a combo up to x5, and passing your best plays a fanfare. A level, power-up or surprise banner opens on the half of the board away from the snake and fades almost clear while the snake is under it or heading into it, so it never hides a crash. The start and end screens count the surprises you have found so far and hint at what waits next. The second is **Mini golf**: eighteen goofy holes seen from above, a pirate front nine (Pirate Cove: a shark sea, cannonballs, a kraken, a ghost ship, a skull to putt through) and a cave back nine (the Caves of Doom: dark but for the ball's light, with lava, a bottomless pit, mine carts, stone crushers and a sleeping dragon), played arcade style: the aim follows the mouse (or held arrows, turning faster the longer they are held) and points back at the cup after every stop, one click or space starts a power meter beside the ball and a second sets the power (slow near the bottom for soft putts, fast near the top, with a gold MAX band for a 1.15x putt and a red overswing band past it that shanks the ball), a 6 second shot clock starts the meter for you, a meter left running dribbles the ball, and holding space or the mouse fast-forwards the roll, with par per hole, at most 8 strokes a hole, and its best kept as the lowest full round. Glowing power-up pads help the next putt: a free putt, a cannon shot, a ghost ball that floats over water, a cup magnet, a rubber duck that keeps its speed off walls, a huge cup, and a spyglass that shows where the putt will roll. With two games, a picker chooses between them. A new question, a sign-off or a finish pauses the game at once and shows a banner with **Go to it**, so a game never hides your turn; hiding the page or clicking away pauses it too. Nothing resumes until you press a game key or click the board, and resuming puts the your-turn banner away until the next question. Every round start and every play-on after a pause counts down 3, 2, 1 first, so a game never moves before you are ready. The window's header shows the current game's best. Best scores (shown beside the score and after each round, cleared by **Reset best scores**; the score line is a pair of colored chips with a meter filling toward the best, which glows when you reach it, turns into a rainbow with a burst of sparks when you pass it, and ends the round with **New best!**) and the last pick are saved privately in `~/.plan2code/console/looks.json` and never reach the agent. **User Preferences → Activities → Show Activities** hides the die everywhere, and Help has a new Activities topic.
|
||||
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
|
||||
- **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli <id>` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed.
|
||||
- **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app.
|
||||
- **desktop app**: the taskbar entry now shows when Plan2Code needs you, mirroring the console's tab icon. Windows: a green dot on your move (a finished screen too, while it still offers a button to press, such as back to the dashboard or a review), a red dot on needs attention (or a finished screen whose press was never collected), none while busy or once nothing is left to press, and one short burst of flashes when the window is not focused (the button stays lit until focused). macOS: a red `!` dock badge on needs attention and one bounce (the system badge cannot be green). Linux: a count badge where the desktop supports it, plus the urgency hint. The dot clears when the agent ends, the page reloads or the page stops answering. **User Preferences → Desktop app** (inside the app only) has the switch **Show on the taskbar when Plan2Code needs me**, on by default and saved in the app's own `app.json`.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **docs**: all prose, help text, skill prompts and comments now use US English spelling (color, gray, behavior, canceled, -ize), and `npm test` checks it (`scripts/test-us-english.mjs`).
|
||||
- **web console**: **User Preferences → Highlight color** now offers 38 colors in two rows of nineteen, covering the range of a Paint-style picker: new **Maroon**, **Peach**, **Brown**, **Cream**, **Lemon**, **Forest**, **Mint**, **Aqua**, **Lavender**, **Pink** and **Mono** (near-black in light mode, near-white in dark). Five near twins were merged (Copper into Rust, Marigold into Gold, Mustard into Lemon, Jade into Emerald, Lilac into Violet); a saved choice of one of those keeps its twin instead of falling back to Ocean.
|
||||
- **web console**: the **Subagents** dialog is wider and shorter, like the Notebook: Helpers and At most share a row, and the four Helper strength choices sit side by side, each wearing the Subagents tab's colored level badge (Thrifty light, Balanced standard, Best strongest, Match my session plain), now ordered from lightest to strongest.
|
||||
- **launcher**: after you pick the agent, `plan2code` now asks whether to turn its permission prompts off (Yes by default, so pressing Enter starts it as before), and only for an agent that has a flag for it: every built-in does, a custom agent only when it has bypass arguments. `plan2code --keep-permissions` keeps the prompts without asking; with no terminal to ask on, prompts are off as before. The installer no longer prints its warning about the command starting agents with prompts off.
|
||||
- **launcher**: when no agent CLI is installed, `plan2code` now prints each supported agent's install command and official page, and points at User Preferences → Agents for another CLI, before it exits.
|
||||
- **desktop app**: a clean start is now one press. Pathfinder's **Start fresh** menu option reads **Start New Session** under the app, and sending it asks the app for its New Session (the resume command is copied first; declining the app's confirm leaves the usual finish). A finished step that names a skill to run next shows a **Start a New Session** button beside its command, also copying the command first. The plain web console keeps its wording and does neither. The app's console frame also now allows clipboard writes, so the copied command and every **Copy** button can reach the clipboard there.
|
||||
- **desktop app**: the launch card's agent choice is built from the agents that are installed, so a machine with only Devin or Codex starts on it with Start enabled, instead of assuming Claude Code.
|
||||
- **desktop app**: the window now opens maximized, filling the screen with the title bar and taskbar still showing; restoring it from maximized gives the old 1280x800 size.
|
||||
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
|
||||
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
|
||||
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
|
||||
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching the terminal's own default; untick it for an agent that keeps its normal approval prompts.
|
||||
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
|
||||
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight color. Its confirmation no longer claims "What it was doing is not saved" (not always true).
|
||||
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
|
||||
- **desktop app**: the collapsed terminal panel's **Expand** button now reads **View Agent Terminal**, and docked right it 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.
|
||||
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter (and, under Claude Code, its send-now chord) into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
|
||||
- **desktop app**: **New Session** now starts the fresh agent on a new console session, so the session meter starts over at green. Before, the fresh agent joined the window's old session, and the meter stayed red after the very press it asks for. The brief of where you were is still written from the old session first, and the old console shuts itself down once the window moves on.
|
||||
- **web console**: the **Wrapping up** dialog after **Stop session** no longer closes itself when the stop lands: it turns into **Done**, with every step ticked, and stays up until you close it, so someone who stepped away comes back to an answer. Its "you can close the window/tab if you need to" line is gone.
|
||||
- **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 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
|
||||
|
||||
- **web console**: on the dashboard, canceling one spec's Delete and quickly opening another's no longer leaves **Delete it** doing nothing; the first dialog's late close cleared the second dialog's spec.
|
||||
- **web console**: a handoff's **Copy** button keeps showing **Copied** (or **Copy was refused**) when the dashboard redraws while the clipboard answers, instead of the word landing on a button that was already replaced.
|
||||
- **web console**: a finished screen's press (**Commit it now**, **Update CHANGELOG first**, **Back to the dashboard**, **Continue here**, a review) that nothing picks up, because the agent's turn ended while the screen waited, no longer says "Opening Changelog…" forever. After a minute of silence the line beside Planny says Plan2Code is not running and the choice is saved, with **continue** to type in the terminal (a button that types it there, under the app).
|
||||
- **desktop app**: under Claude Code, the console's **continue** button also sends Claude Code's send-now chord (ctrl+x ctrl+s), so a `continue` it held as a queued message behind a stuck turn is delivered in one press instead of waiting in the terminal.
|
||||
- **desktop app**: links that leave the console (**Open pull request**, links in documents, the feedback button) open in the default browser instead of doing nothing; when no browser can be started, the page shows the link with a **Copy** button to paste into one.
|
||||
- **web console**: answers sent and not picked up bring up the "not running, type **continue**" help after a minute of the agent's silence (three when it said it was working), instead of after its quiet allowance, which a build can set to half an hour.
|
||||
- **web console**: a failed Send says why: the lost-contact state and its reconnect help at once when the console is gone, the console's reason when it refuses the send, or that the console is still up and Send can be pressed again.
|
||||
- **desktop app**: a test console started inside the app (for example by `cargo test` during a build) can no longer take over the window. Before, the window followed it, then fell back to an empty dashboard once the test shut it down, and the build's question sat on a page no one could see. The app now ignores any page whose session is not in its own console store.
|
||||
- **desktop app**: a console too busy to answer a health check in time (a machine running a test suite) is given a second, longer look and then resumed on the same session. It is no longer swapped for a fresh, empty dashboard mid-build.
|
||||
|
||||
## v2.11.1
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: a card whose thread ends with the person's own words now blocks the patch that settles or reopens it, until the agent replies in the same thread. Exempt once the item is deleted, or the whole session is ending.
|
||||
|
||||
## v2.11.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web console**: the Notebook has named **tabs**. Each tab is its own Markdown note with its own pictures, kept in its own folder under the notebook's (`tabs/<id>/note.md` and `images/`, with a `tabs.json` index). **+ New tab** asks for a name (1 to 40 characters, no two alike in any case, up to 20 tabs). A tab can be renamed (button, double-click or F2), reordered (drag, Move left and Move right, or Alt with the arrow keys) and deleted, which asks twice and removes its text and pictures. The tab left open is the one that opens next, and with no tab left the dialog offers to make one. Saves and pictures are bound to the tab they were made in, so switching never moves either; a switch that cannot save first stays put and says why.
|
||||
- **web console**: five routes (`POST /notepad/tab`, `/tab/rename`, `/tab/delete`, `/tab/order`, `/tab/last`), `?tab=` on the text and picture routes, and picture addresses that carry the tab (`/notepad/images/<tab>/<uuid>.jpg`).
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the Notepad is now called the **Notebook** (the icon is unchanged), in the top bar, the dialog, the Help, the docs and the screenshots. Code names, routes and the `~/.plan2code/notepads/` folder keep their names, so nothing already saved moves. The dialog's line about it being never shared to the AI Agent is bold, in the highlight color.
|
||||
- **web console**: every document tab and the Overview has a **Back to Questions** button (Dashboard or Git on those screens) left of Print and Download, with a highlight border, and that header row stays at the top of the pane while the document scrolls.
|
||||
- **web console**: the Notebook editor is now CodeMirror 6 with live in-place Markdown: headings grow, bullets draw and the marks come back on the line the cursor is on. It replaces OverType after a spike showed typing in a 200 KB note about four times faster. The editor ships as one vendored file loaded only when the Notebook first opens, and runs in a shadow root so the page's content-security policy stays as strict as before.
|
||||
- **web console**: an existing notebook opens as one tab called **Notes**. Reading it writes nothing; the first edit moves the note and pictures into the tab, and a crash part way is finished by the next write.
|
||||
- **contributors**: `scripts/vendor-codemirror.mjs` and its lock file build the editor bundle reproducibly; the OverType vendor script, its CSS and its page helpers are gone.
|
||||
|
||||
## v2.10.0
|
||||
|
||||
### ✨ Added
|
||||
@@ -31,12 +110,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.
|
||||
@@ -57,9 +136,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).
|
||||
@@ -70,7 +149,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
|
||||
|
||||
@@ -95,9 +174,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.
|
||||
@@ -106,7 +185,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
|
||||
|
||||
@@ -151,7 +230,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
|
||||
@@ -161,7 +240,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.
|
||||
@@ -183,7 +262,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
|
||||
|
||||
@@ -275,7 +354,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.
|
||||
|
||||
@@ -285,7 +364,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.
|
||||
|
||||
@@ -311,7 +390,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.
|
||||
@@ -401,7 +480,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
|
||||
|
||||
@@ -411,7 +490,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.
|
||||
|
||||
@@ -441,7 +520,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.
|
||||
|
||||
@@ -23,7 +23,7 @@ The install command always opens a menu. Back at your prompt with no output at a
|
||||
|
||||
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
|
||||
|
||||
The **Notepad** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent).
|
||||
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`). Private: the agent never reads your Notebook. A tab reaches it only when you start a workflow with it.
|
||||
|
||||
## Commands
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
||||
|
||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||
|
||||
Version 2.10.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 3.0.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -82,12 +82,52 @@ Install (`I`) adds `plan2code` as a global command (Advanced `A` → `D` adds ju
|
||||
dashboard opens right there, in **Claude Code**, **Devin** or **Codex**. With more than one installed it asks which and
|
||||
remembers your pick; `plan2code --cli claude`, `--cli devin` or `--cli codex` skips the question, and `--model <name>`
|
||||
chooses the model. It works in cmd, PowerShell, Git Bash, macOS and Linux shells, and needs the
|
||||
Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permission prompts off
|
||||
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex); run
|
||||
`claude /plan2code` yourself if you want prompts. The installer then offers a desktop shortcut (answer `y`),
|
||||
Claude Code, Devin or Codex CLI on your `PATH`. After you pick the agent it asks whether to turn its
|
||||
permission prompts off (Yes by default; `--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass`
|
||||
in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex, a custom agent's bypass arguments, and no question for a
|
||||
custom agent that has none). `plan2code --keep-permissions` keeps the prompts without asking. The installer then offers a desktop shortcut (answer `y`),
|
||||
which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||
</details>
|
||||
|
||||
<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>
|
||||
|
||||
The installer also offers the **Plan2Code desktop app**: one window with the dashboard and your agent's
|
||||
terminal side by side, docked right (or bottom) and collapsible. Every console page, not only the
|
||||
dashboard, opens inside it. A launch card asks which agent, model and effort to start on, with
|
||||
permission checks off as its own tick (on by default, matching the terminal flow; untick it to keep
|
||||
the agent's approval prompts). A **New Session** button in the top bar replaces the agent with a fresh
|
||||
one on a brief built from the session, and the console's own Session meter points at it when a
|
||||
session is getting long. Once it is installed, `plan2code` opens the app instead of running the agent
|
||||
in your terminal. `plan2code --classic` keeps the terminal flow, and so does a Linux machine with no
|
||||
display (over SSH, say) or any machine over an SSH session. `plan2code update` updates the skills, the
|
||||
command and the app together, and the bar offers the same **Update skills** when the app and the
|
||||
installed skills disagree.
|
||||
|
||||
The first release is unsigned, so macOS (**Open Anyway** in System Settings, Privacy & Security) or
|
||||
Windows (**More info**, then **Run anyway**) may ask you to allow it once. The app starts the agent
|
||||
with its normal approval prompts unless you tick the launch card's permission-checks-off option (the
|
||||
plain `plan2code` command above, without the app, asks instead, with prompts off by default too). Details:
|
||||
[docs/desktop-app.md](docs/desktop-app.md).
|
||||
</details>
|
||||
|
||||
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
|
||||
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
|
||||
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
|
||||
@@ -150,8 +190,10 @@ next check-in, and it never holds up your answers.
|
||||
|
||||
There is more on the page when you need it. Notes on any question can carry screenshots and
|
||||
documents. The folder label in the bottom bar opens your workspace, where you add other folders
|
||||
as read-only context and point at them by `@name`. The **Notepad** in the top bar is a private pad of your own for the
|
||||
folder, in Markdown with pictures, that the agent never sees. The session meter in the top bar turns from green
|
||||
as read-only context and point at them by `@name`. The **Notebook** in the top bar is a private pad of your own for the
|
||||
folder, in Markdown with pictures, that the agent reads only when you start a workflow from one of its tabs on
|
||||
the dashboard and send the box it fills. The **die** beside it opens **Activities**,
|
||||
two small games (Snake and Mini golf) to play through a long wait, which pause the moment it is your turn. The session meter in the top bar turns from green
|
||||
to red as a session grows long and suggests a fresh one. **Stop session** saves your place and gives
|
||||
you the command to carry on later, and **Back to the dashboard** takes you home to pick the next
|
||||
step in the same session.
|
||||
@@ -186,7 +228,7 @@ The dashboard's cards, and when each one lights up for the spec you pick:
|
||||
| Refresh AGENTS.md | Brings AGENTS.md and its notes up to date with what the project has learned lately. | The project has an AGENTS.md |
|
||||
| Pathfinder | A foggy idea becomes a clear list of decisions, settled one question at a time. | You start fresh, or the spec is still being explored |
|
||||
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map, a drafted plan or a bug diagnosis |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases, built or not |
|
||||
| Document | The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. | The spec has a drafted plan |
|
||||
| Implement | Builds the next phase, task by task, with a report and your sign-off at the end. | The spec has phases with tasks still to build |
|
||||
| Implement + review | One phase built, then a careful review of the changes, then your sign-off. All in one run. | The spec has phases with tasks still to build |
|
||||
@@ -373,7 +415,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.
|
||||
|
||||
@@ -418,7 +460,7 @@ edits out through the skills CLI.
|
||||
|
||||
Core reference:
|
||||
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notepad in the top bar
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook and Activities in the top bar
|
||||
- **[QUICK-REFERENCE.md](QUICK-REFERENCE.md)** — the one-page card: commands, inputs, outputs, decision tree
|
||||
- **[.readme/walkthrough.md](.readme/walkthrough.md)** — one feature from a sentence to archived specs, session by session
|
||||
- **[AGENTS.md](AGENTS.md)** — architecture and contributor guide for this repo
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
# The Plan2Code desktop app
|
||||
|
||||
One window for working with an AI agent. The app opens the Plan2Code dashboard as its main surface,
|
||||
runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **New Session**
|
||||
button that replaces the agent with a fresh one on a brief the app builds from its own record of the
|
||||
session. The fresh agent gets a console session of its own, so the Session meter starts over with it.
|
||||
It is an addition: `/plan2code` typed inside an agent works exactly as before, with or
|
||||
without the app.
|
||||
|
||||
## Get it
|
||||
|
||||
The installer offers the app after the skills and the `plan2code` command:
|
||||
|
||||
```
|
||||
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
|
||||
```
|
||||
|
||||
Answer **Y** to "Also install the Plan2Code desktop app?" (it is the default). It downloads the file
|
||||
for your system from the GitHub release, checks it against the release's checksum list and puts it in
|
||||
`~/.plan2code/app/`. If a checksum does not match, the file is thrown away and nothing is installed.
|
||||
If the download fails, the skills and the `plan2code` command are still installed; the installer says
|
||||
so, and you can run the installer again later.
|
||||
|
||||
Releases carry one file per system:
|
||||
|
||||
| System | File |
|
||||
| --- | --- |
|
||||
| Windows (64-bit Intel or AMD) | `plan2code-app-<version>-windows-x64.exe` |
|
||||
| macOS (Apple silicon) | `plan2code-app-<version>-macos-arm64` |
|
||||
| macOS (Intel) | `plan2code-app-<version>-macos-x64` |
|
||||
| Linux (64-bit Intel or AMD) | `plan2code-app-<version>-linux-x64` |
|
||||
|
||||
On any other system the installer says there is no build for it and carries on without the app.
|
||||
|
||||
Each of those is a plain executable, not an OS-level installer package (no `.msi`, no NSIS `.exe`
|
||||
setup, no `.dmg` with a drag-to-Applications step): the installer above places it directly, already
|
||||
verified. `plan2code-app`'s own `npm run build` can produce `.msi`/NSIS/`.dmg`/`.deb` bundles locally
|
||||
(Tauri's bundler is on), but the release workflow does not build or publish them; nothing today
|
||||
downloads or runs one.
|
||||
|
||||
You also need Node.js 18 or newer (the app checks at start and says what to install) and:
|
||||
|
||||
- **Windows:** the WebView2 runtime, which comes with Windows 11 and current Windows 10.
|
||||
- **Linux:** WebKitGTK 4.1 (`libwebkit2gtk-4.1`) and a desktop session.
|
||||
|
||||
## Start it
|
||||
|
||||
Run `plan2code` in your project, as always. When the app is installed and a window can open,
|
||||
`plan2code` asks which agent and model (as before) and then opens the app on that folder instead of
|
||||
running the agent in your terminal. The desktop shortcut the installer can create runs the same
|
||||
command, so it opens the app too.
|
||||
|
||||
Three things keep today's terminal flow:
|
||||
|
||||
- **`plan2code --classic`** runs the agent in your terminal even when the app is installed.
|
||||
- **No display.** On Linux without a display (over SSH, in a container) `plan2code` falls back to the
|
||||
terminal flow by itself.
|
||||
- **An SSH or service session on macOS or Windows.** The same fallback applies there, since neither
|
||||
has a desktop to open a window on either.
|
||||
- **Not a project folder.** If the folder is not a git repository and has no `AGENTS.md` or `specs/`,
|
||||
`plan2code` asks you to confirm before opening the app on it.
|
||||
|
||||
## What's in the window
|
||||
|
||||
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, 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 once a finished step has nothing left to press (a finished screen
|
||||
that still offers a button, such as back to the dashboard, keeps the green dot), and it clears when
|
||||
the agent ends or the page reloads. Turn it off with **Show on the taskbar when Plan2Code needs
|
||||
me** under **User Preferences → Desktop app** (shown only inside the app). The per-system details are in
|
||||
[plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar).
|
||||
|
||||
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
|
||||
**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
|
||||
ended; a short line (why the agent ended, a New Session's brief, or what went wrong); and, at the right
|
||||
end, the one next step for the console or the skills when there is one (**Reconnect the console**,
|
||||
**Update skills**), with "+N more" if anything else is waiting behind it. The console itself, opening inside the
|
||||
window (not only the dashboard — every console page, including Ask, Workspace, Notebook, Help,
|
||||
Preferences and Git), already shows which page is open and its own **Session** meter (how much plan2code
|
||||
work this session has done) in its own bar, so the app's bar does not repeat either. That Session meter
|
||||
is the one place for "is this session getting long" under the app, too: the app does not keep a second,
|
||||
separate context-window meter of its own, so there is only ever one gauge to read and only one place its
|
||||
threshold is tuned. The terminal panel has its own toolbar: dock it to the bottom or the right, collapse
|
||||
it to a thin strip, or maximize it; its size is remembered. An "agent may need you" badge appears on a
|
||||
collapsed or small panel once the agent has sat quiet for a while. **Change project** (in the project
|
||||
menu) asks first if an agent is running, then stops it and the console before opening the new folder.
|
||||
|
||||
If the console itself ever needs reconnecting (it stopped, or the skills were just updated), every path
|
||||
to that offers the same **Reconnect the console** button — never "Restart the console" in one place and
|
||||
"Start it again" in another for the same action — and only one shows at a time.
|
||||
|
||||
The console also knows when it is running inside the app (the agent it talks to carries that signal):
|
||||
its session meter, the "Before you close this" guide on a finished step, and the dashboard's red-session
|
||||
banner all point at the app's own **New Session** button instead of a command to paste into a new
|
||||
conversation, since New Session already does that in one click; and the console's own "update available"
|
||||
banner never shows, since the app's **Update skills** button (below) already covers it with no shell
|
||||
involved. A slash command still offered to continue a step (such as `/plan2code-4-finalize`) stays
|
||||
exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real
|
||||
agent CLI.
|
||||
|
||||
## Keep it up to date
|
||||
|
||||
`plan2code update` brings the skills, the `plan2code` command and the app up together. If the app
|
||||
and the installed skills ever differ in version, the app's top bar says so and offers **Update
|
||||
skills**, which runs that same update when you press it. It never updates on its own.
|
||||
|
||||
## The first release is unsigned
|
||||
|
||||
The app is not code-signed yet, so your system may stop it the first time it starts. It is the same
|
||||
file the installer verified against the release's checksum list.
|
||||
|
||||
**macOS.** If macOS says the app "cannot be opened because Apple cannot check it for malicious
|
||||
software": open **System Settings**, then **Privacy & Security**, scroll to the message about
|
||||
`plan2code-app`, and press **Open Anyway**. Start `plan2code` again and confirm.
|
||||
|
||||
**Windows.** If SmartScreen shows "Windows protected your PC": press **More info**, then **Run
|
||||
anyway**.
|
||||
|
||||
**Linux.** Nothing to allow. If the file is not executable, run
|
||||
`chmod +x ~/.plan2code/app/plan2code-app`.
|
||||
|
||||
## Permission checks are off by default, same as the terminal
|
||||
|
||||
The launch card's permission-mode tick is **on by default** (checks off), matching `plan2code` run the
|
||||
plain way, where the same question defaults to prompts off: the agent starts with checks off (`--permission-mode bypassPermissions` in Claude Code,
|
||||
`--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex), reading,
|
||||
writing and running commands in your project folder without asking; the agent's amber **checks off** badge in
|
||||
the top bar says so while that agent runs. Untick it before pressing Start agent to keep the agent's normal approval prompts instead.
|
||||
New Session keeps the same choice. Work in a folder you are happy for the agent to change, and keep it under
|
||||
version control.
|
||||
|
||||
## Remove it
|
||||
|
||||
Choose **Uninstall** in the installer menu: it removes the app with everything else Plan2Code
|
||||
installed. To remove only the app, delete the `~/.plan2code/app/` folder.
|
||||
@@ -335,7 +335,7 @@ footer a { color: inherit; }
|
||||
<div><h3>Review before you approve</h3><p>Review the code first, on the sign-off card, reviews exactly the files the phase changed. You tick which findings get fixed, then approve.</p></div>
|
||||
<div><h3>The Ask tab</h3><p>A chat beside the cards for anything you want to know. It is answered at the agent's next check-in and never holds up your answers.</p></div>
|
||||
<div><h3>Attachments on notes</h3><p>Paste a screenshot or attach a document to a note on any question, and show instead of describe.</p></div>
|
||||
<div><h3>A notepad of your own</h3><p>A private pad for each project folder, in Markdown with pictures. It never goes into your project, and the agent never sees it.</p></div>
|
||||
<div><h3>A notebook of your own</h3><p>A private pad for each project folder, in Markdown with pictures. It never goes into your project, and the agent never sees it.</p></div>
|
||||
<div><h3>Workspace folders</h3><p>Add a shared library or a design folder as read-only context, and point at it by its <code>@name</code>.</p></div>
|
||||
<div><h3>Session meter</h3><p>A ring in the top bar turns from green to red as a session grows long, and suggests when a fresh one would serve you better.</p></div>
|
||||
<div><h3>Runs on your machine</h3><p>A small program Plan2Code starts for you serves the page on <code>127.0.0.1</code>. No account, no dependencies, and nothing leaves your computer.</p></div>
|
||||
@@ -358,9 +358,9 @@ footer a { color: inherit; }
|
||||
<figure style="grid-column:1/-1;max-width:calc(50% - 12px);justify-self:center">
|
||||
<picture class="shot">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="screenshots/notepad-dark.webp">
|
||||
<img src="screenshots/notepad-light.webp" width="2560" height="1600" loading="lazy" alt="The Notepad open over a question: a few lines of Markdown styled as they are typed.">
|
||||
<img src="screenshots/notepad-light.webp" width="2560" height="1600" loading="lazy" alt="The Notebook open over a question: two named tabs, and a heading, bullets and bold styled in place as they are typed.">
|
||||
</picture>
|
||||
<figcaption>Your own notepad, private to the folder.</figcaption>
|
||||
<figcaption>Your own notebook, private to the folder.</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
Before Width: | Height: | Size: 98 KiB After Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 107 KiB After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 108 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 111 KiB After Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 89 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 112 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 119 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 97 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 103 KiB |
|
Before Width: | Height: | Size: 73 KiB After Width: | Height: | Size: 73 KiB |
|
Before Width: | Height: | Size: 78 KiB After Width: | Height: | Size: 78 KiB |
|
Before Width: | Height: | Size: 55 KiB After Width: | Height: | Size: 62 KiB |
|
Before Width: | Height: | Size: 59 KiB After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 116 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 96 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 104 KiB |
@@ -20,6 +20,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const readline = require('readline');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// Load project version metadata
|
||||
let projectVersion = { name: 'Plan2Code', version: 'unknown' };
|
||||
@@ -160,7 +161,10 @@ const SOURCE_PROMPTS = [
|
||||
name: 'pathfinder',
|
||||
displayName: 'Pathfinder Mode',
|
||||
description: 'charting of a foggy idea as a map of decision questions, cleared one at a time',
|
||||
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-quick-task.md',
|
||||
@@ -175,6 +179,7 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -186,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',
|
||||
@@ -195,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',
|
||||
@@ -218,6 +229,7 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -233,6 +245,7 @@ const SOURCE_PROMPTS = [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -245,7 +258,10 @@ const SOURCE_PROMPTS = [
|
||||
description: 'Comprehensive post-implementation review with spec compliance checking',
|
||||
isUtility: true,
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.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-4-finalize.md',
|
||||
@@ -983,6 +999,9 @@ async function install({ unattended = false, outcome = {} } = {}) {
|
||||
const launcherFailed = failed ? false : (await installLauncher({ quiet: true, unattended })) !== 0;
|
||||
outcome.launcher = !failed && !launcherFailed;
|
||||
|
||||
// The desktop app comes last and is an extra: its failure leaves the install a success.
|
||||
if (!failed && !launcherFailed) await offerDesktopApp({ unattended, outcome });
|
||||
|
||||
// Summary
|
||||
console.log(`${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
|
||||
console.log(`${COLORS.CYAN}║${COLORS.RESET}${' '.repeat(75)}${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
@@ -1212,10 +1231,11 @@ function runInteractive() {
|
||||
const botResult = uninstallPlan2CodeBot();
|
||||
const statusLineResult = uninstallStatusLine();
|
||||
const launcherResult = uninstallLauncher();
|
||||
uninstallDesktopApp();
|
||||
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);
|
||||
}
|
||||
@@ -1302,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);
|
||||
}
|
||||
@@ -2297,8 +2317,8 @@ function uninstallPlan2CodeBot() {
|
||||
|
||||
/**
|
||||
* `plan2code` typed in any directory opens the dashboard skill there in Claude Code
|
||||
* (`claude /plan2code --permission-mode bypassPermissions`) or Devin
|
||||
* (`devin --permission-mode bypass -- /plan2code`), asking which when both are installed.
|
||||
* (`claude /plan2code`), Devin (`devin -- /plan2code`) or Codex (`codex $plan2code`), asking
|
||||
* which when more than one is installed, then whether to turn permission prompts off.
|
||||
* The launcher is copied out of the package into ~/.plan2code/bin/ because the installer
|
||||
* normally runs from an npx cache directory that npm is free to delete; the shims in the bin
|
||||
* directory point at that stable copy.
|
||||
@@ -2317,10 +2337,14 @@ const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.m
|
||||
const LAUNCHER_VERSION_DEST = path.join(path.dirname(LAUNCHER_DEST), 'version.json');
|
||||
// What a global install put on this machine, so `plan2code update` reinstalls exactly that.
|
||||
const INSTALL_RECORD = path.join(os.homedir(), '.plan2code', 'install.json');
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'statusline', 'loop', 'metrics', 'bot'];
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'app', 'statusline', 'loop', 'metrics', 'bot'];
|
||||
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
|
||||
|
||||
/** `~/.plan2code/install.json` as `{ version, scope, pieces }`, or null when missing or unparsable. */
|
||||
/**
|
||||
* `~/.plan2code/install.json` as `{ version, scope, pieces }`, or null when missing or unparsable.
|
||||
* `skipped` lists optional pieces (the desktop app) the person said no to, so an unattended
|
||||
* `plan2code update` does not install them; it is left out of the file while empty.
|
||||
*/
|
||||
function readInstallRecord() {
|
||||
try {
|
||||
const record = JSON.parse(fs.readFileSync(INSTALL_RECORD, 'utf8'));
|
||||
@@ -2330,12 +2354,14 @@ function readInstallRecord() {
|
||||
}
|
||||
|
||||
/** Temp file, then rename, so a crash never leaves a half-written record. A failure only skips the record. */
|
||||
function writeInstallRecord(pieces) {
|
||||
function writeInstallRecord(pieces, skipped = (readInstallRecord() || {}).skipped || []) {
|
||||
const record = {
|
||||
version: projectVersion.version,
|
||||
scope: 'global',
|
||||
pieces: [...new Set(pieces)].filter((piece) => INSTALL_PIECES.includes(piece)).sort(),
|
||||
};
|
||||
const declined = [...new Set(skipped)].filter((piece) => INSTALL_PIECES.includes(piece) && !record.pieces.includes(piece)).sort();
|
||||
if (declined.length > 0) record.skipped = declined;
|
||||
const tmp = `${INSTALL_RECORD}.${process.pid}.tmp`;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(INSTALL_RECORD), { recursive: true });
|
||||
@@ -2354,6 +2380,12 @@ function recordInstalled(piece) {
|
||||
writeInstallRecord([...(record ? record.pieces : []), piece]);
|
||||
}
|
||||
|
||||
/** Remember that an optional piece was declined. Needs a record: one holding no pieces would make update do nothing. */
|
||||
function recordSkipped(piece) {
|
||||
const record = readInstallRecord();
|
||||
if (record) writeInstallRecord(record.pieces, [...(record.skipped || []), piece]);
|
||||
}
|
||||
|
||||
/** Drop a piece after its uninstall; no record means nothing to forget. */
|
||||
function forgetInstalled(piece) {
|
||||
const record = readInstallRecord();
|
||||
@@ -2539,6 +2571,8 @@ function isOurShortcut(file) {
|
||||
/**
|
||||
* Put a shortcut on the desktop that runs `plan2code --pick-folder` through the shim in
|
||||
* `binDir`, so the person picks the project folder in a native dialog before the CLI opens.
|
||||
* It is the same `plan2code` command as a typed one, so it opens the desktop app instead
|
||||
* when the app is installed (the launcher decides; the shortcut never names the app).
|
||||
* On Windows it opens in PowerShell — PowerShell 7 (`pwsh`) when installed, Windows
|
||||
* PowerShell otherwise — running the `.ps1` shim, rather than cmd.exe running the `.cmd` one.
|
||||
*/
|
||||
@@ -2575,7 +2609,7 @@ function installDesktopShortcut(binDir, file) {
|
||||
P2C_FILE: file,
|
||||
P2C_SCRIPT: `${shim}.ps1`,
|
||||
P2C_ARGS: LAUNCHER_PICK_FOLDER_FLAG,
|
||||
P2C_DESCRIPTION: 'Open the Plan2Code dashboard in Claude Code, Devin or Codex',
|
||||
P2C_DESCRIPTION: 'Open Plan2Code: the desktop app when it is installed, otherwise your agent in a terminal',
|
||||
P2C_ICON: icon,
|
||||
}
|
||||
);
|
||||
@@ -2595,7 +2629,7 @@ function installDesktopShortcut(binDir, file) {
|
||||
`# ${LAUNCHER_MARKER}`,
|
||||
'Type=Application',
|
||||
`Name=${SHORTCUT_NAME}`,
|
||||
'Comment=Open the Plan2Code dashboard in Claude Code, Devin or Codex',
|
||||
'Comment=Open Plan2Code: the desktop app when it is installed, otherwise your agent in a terminal',
|
||||
`Exec="${shim}" ${LAUNCHER_PICK_FOLDER_FLAG}`,
|
||||
...(icon ? [`Icon=${icon}`] : []),
|
||||
'Terminal=true',
|
||||
@@ -2696,7 +2730,6 @@ async function installLauncher({ quiet = false, unattended = false } = {}) {
|
||||
recordInstalled('launcher');
|
||||
// The shortcut is a convenience on top of the command, so a failure here only warns.
|
||||
if (!unattended) await offerDesktopShortcut(binDir);
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The ${LAUNCHER_COMMAND} command starts the agent with permission prompts off (${COLORS.CYAN}--permission-mode bypassPermissions${COLORS.RESET} in Claude Code, ${COLORS.CYAN}bypass${COLORS.RESET} in Devin, ${COLORS.CYAN}--dangerously-bypass-approvals-and-sandbox${COLORS.RESET} in Codex). Run ${COLORS.CYAN}claude /plan2code${COLORS.RESET} yourself if you want prompts.`);
|
||||
console.log('');
|
||||
// Inside install() the final summary prints the steps once, after everything else.
|
||||
if (!quiet) printGettingStarted({ commandInstalled: true });
|
||||
@@ -2745,6 +2778,210 @@ function uninstallLauncher() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DESKTOP APP
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* The desktop app is one plain executable per system, attached to each GitHub release by
|
||||
* .github/workflows/release-app.yml as `plan2code-app-<version>-<os>-<arch>[.exe]` beside
|
||||
* `plan2code-app-<version>-SHA256SUMS.txt`. Installing it downloads the file for this machine,
|
||||
* checks it against that list and puts it in ~/.plan2code/app/, where the launcher looks.
|
||||
* PLAN2CODE_RELEASE_BASE replaces the release download URL (the tests serve a stand-in).
|
||||
* The app is an extra on top of the skills and the command: when it cannot be installed they
|
||||
* stay installed, and `plan2code --classic` is today's flow.
|
||||
*/
|
||||
const APP_DIR = path.join(os.homedir(), '.plan2code', 'app');
|
||||
const APP_DEST = path.join(APP_DIR, process.platform === 'win32' ? 'plan2code-app.exe' : 'plan2code-app');
|
||||
const APP_DOWNLOAD_TIMEOUT_MS = 120000;
|
||||
|
||||
function releaseBase(version) {
|
||||
const base = process.env.PLAN2CODE_RELEASE_BASE || `https://github.com/jparkerweb/plan2code/releases/download/v${version}`;
|
||||
return base.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/** The release file for a system, or null when the app is not built for it. */
|
||||
function appAssetName(version, platform = process.platform, arch = process.arch) {
|
||||
const system = { win32: 'windows', darwin: 'macos', linux: 'linux' }[platform];
|
||||
const cpu = { x64: 'x64', arm64: 'arm64' }[arch];
|
||||
if (!system || !cpu) return null;
|
||||
return `plan2code-app-${version}-${system}-${cpu}${platform === 'win32' ? '.exe' : ''}`;
|
||||
}
|
||||
|
||||
/** The SHA-256 a checksum list (`<hex> <name>` or `<hex> *<name>` lines) gives for `name`, or null. */
|
||||
function checksumFor(list, name) {
|
||||
for (const line of list.split(/\r?\n/)) {
|
||||
const match = line.trim().match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
|
||||
if (match && match[2] === name) return match[1].toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The bytes at `url`; an HTTP error is thrown with its `status`. */
|
||||
async function download(url) {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(APP_DOWNLOAD_TIMEOUT_MS) });
|
||||
if (!response.ok) {
|
||||
const error = new Error(`HTTP ${response.status} from ${url}`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the app at `dest`, replacing an older one. The new file is written beside it first, and
|
||||
* the old one is renamed aside rather than overwritten: Windows will not overwrite a running
|
||||
* program but will rename it, and the old file goes when the app next ends.
|
||||
*/
|
||||
function placeApp(bytes, dest) {
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||||
const tmp = `${dest}.${process.pid}.tmp`;
|
||||
const aside = `${dest}.old`;
|
||||
fs.writeFileSync(tmp, bytes, { mode: 0o755 });
|
||||
try {
|
||||
fs.rmSync(aside, { force: true });
|
||||
} catch {}
|
||||
let movedAside = false;
|
||||
try {
|
||||
fs.renameSync(dest, aside);
|
||||
movedAside = true;
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.renameSync(tmp, dest);
|
||||
} catch (error) {
|
||||
if (movedAside) {
|
||||
try {
|
||||
fs.renameSync(aside, dest);
|
||||
} catch {}
|
||||
}
|
||||
fs.rmSync(tmp, { force: true });
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
fs.rmSync(aside, { force: true });
|
||||
} catch {}
|
||||
if (process.platform !== 'win32') fs.chmodSync(dest, 0o755);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download, verify and place the desktop app for this release. Returns 0, or 1 after saying
|
||||
* plainly why not (and that the skills and the command are fine); `outcome.app` is true or false.
|
||||
*/
|
||||
async function installDesktopApp({ quiet = false, unattended = false, outcome = {} } = {}) {
|
||||
if (quiet) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING THE DESKTOP APP${COLORS.RESET}`);
|
||||
} else {
|
||||
displaySectionHeader('DESKTOP APP', '[ INSTALL ]');
|
||||
}
|
||||
const version = projectVersion.version;
|
||||
const name = appAssetName(version);
|
||||
const base = releaseBase(version);
|
||||
const fail = (reason) => {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} The desktop app was not installed: ${reason}`);
|
||||
console.log(` ${COLORS.DIM}The skills and the plan2code command are installed and work as before; run ${COLORS.CYAN}plan2code --classic${COLORS.DIM} to stay in your terminal, or install again later.${COLORS.RESET}`);
|
||||
console.log('');
|
||||
outcome.app = false;
|
||||
return 1;
|
||||
};
|
||||
// No build for this system or this release yet (the version is bumped on main before the
|
||||
// release's files are attached): not a failure when unattended, since an update must not fail
|
||||
// for it and an app that is installed stays as it is.
|
||||
const noBuild = (reason) => {
|
||||
if (!unattended) return fail(reason);
|
||||
outcome.app = false;
|
||||
outcome.appMissing = reason;
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No desktop app update: ${reason}${COLORS.RESET}`);
|
||||
console.log('');
|
||||
return 0;
|
||||
};
|
||||
|
||||
if (!name) return noBuild(`there is no desktop app build for ${process.platform}-${process.arch}.`);
|
||||
let bytes;
|
||||
try {
|
||||
const list = (await download(`${base}/plan2code-app-${version}-SHA256SUMS.txt`)).toString('utf8');
|
||||
const expected = checksumFor(list, name);
|
||||
if (!expected) return fail(`the release's checksum list has no entry for ${name}.`);
|
||||
bytes = await download(`${base}/${name}`);
|
||||
const actual = crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
if (actual !== expected) {
|
||||
return fail(`${name} does not match its checksum (expected ${expected.slice(0, 12)}..., got ${actual.slice(0, 12)}...), so it was thrown away.`);
|
||||
}
|
||||
} catch (error) {
|
||||
return error.status === 404
|
||||
? noBuild(`release v${version} has no desktop app file for ${process.platform}-${process.arch} yet.`)
|
||||
: fail(`could not download it (${error.message}).`);
|
||||
}
|
||||
try {
|
||||
placeApp(bytes, APP_DEST);
|
||||
} catch (error) {
|
||||
return fail(`the file was verified but could not be put in ${APP_DIR} (${error.message}); close the app and try again.`);
|
||||
}
|
||||
recordInstalled('app');
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${APP_DEST}`);
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The app is unsigned, and it starts the agent with permission checks off. See docs/desktop-app.md for how to allow it on macOS and Windows.`);
|
||||
console.log('');
|
||||
outcome.app = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The app step of a skills install. Interactive: ask (default yes), and remember a no.
|
||||
* Unattended (`plan2code update`): yes, without asking, unless the app is already recorded (the
|
||||
* update loop updates it as its own piece) or was declined before.
|
||||
*/
|
||||
async function offerDesktopApp({ unattended = false, outcome = {} } = {}) {
|
||||
const record = readInstallRecord();
|
||||
// A system the app is not built for is never asked about, or retried on every update.
|
||||
if (!appAssetName(projectVersion.version)) {
|
||||
if (!unattended) console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No desktop app is built for ${process.platform}-${process.arch}; skipping it.${COLORS.RESET}`);
|
||||
return;
|
||||
}
|
||||
if (unattended) {
|
||||
if (record && (record.pieces.includes('app') || (record.skipped || []).includes('app'))) return;
|
||||
await installDesktopApp({ quiet: true, unattended, outcome });
|
||||
return;
|
||||
}
|
||||
if (!process.stdin.isTTY) return;
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
const answer = await new Promise((resolve) => {
|
||||
rl.question(` ${COLORS.CYAN}Also install the Plan2Code desktop app?${COLORS.RESET} (Y/n): `, resolve);
|
||||
});
|
||||
rl.close();
|
||||
if (answer.trim().toLowerCase().startsWith('n')) {
|
||||
recordSkipped('app');
|
||||
return;
|
||||
}
|
||||
await installDesktopApp({ quiet: true, outcome });
|
||||
}
|
||||
|
||||
/** Remove the desktop app and what the installer left beside it. */
|
||||
function uninstallDesktopApp() {
|
||||
displaySectionHeader('DESKTOP APP', '[ UNINSTALL ]');
|
||||
let removed = false;
|
||||
for (const file of [APP_DEST, `${APP_DEST}.old`]) {
|
||||
if (!fs.existsSync(file)) continue;
|
||||
try {
|
||||
fs.rmSync(file, { force: true });
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file}`);
|
||||
removed = true;
|
||||
} catch (error) {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to remove ${file}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
forgetInstalled('app');
|
||||
try {
|
||||
fs.rmdirSync(APP_DIR);
|
||||
} catch {}
|
||||
if (!removed) console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No desktop app found${COLORS.RESET}`);
|
||||
console.log('');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// UPDATE (`plan2code update` runs the npx install with --update)
|
||||
// ============================================================================
|
||||
@@ -2757,6 +2994,7 @@ function uninstallLauncher() {
|
||||
const UPDATE_STEPS = {
|
||||
skills: install,
|
||||
launcher: installLauncher,
|
||||
app: installDesktopApp,
|
||||
statusline: installStatusLine,
|
||||
loop: installPlan2CodeLoop,
|
||||
metrics: installPlan2CodeMetrics,
|
||||
@@ -2786,6 +3024,8 @@ async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
try {
|
||||
const code = await steps[piece]({ quiet: true, unattended: true, outcome });
|
||||
results[piece] = code === 0 ? 'updated' : 'failed: see the messages above';
|
||||
// The release has no app file yet: the installed one stays, and the update does not fail.
|
||||
if (piece === 'app' && code === 0 && outcome.appMissing) results[piece] = 'kept (no new desktop app file yet)';
|
||||
} catch (error) {
|
||||
results[piece] = `failed: ${error.message}`;
|
||||
}
|
||||
@@ -2796,13 +3036,15 @@ async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
results.skills = outcome.skills ? 'updated' : 'failed: see the messages above';
|
||||
}
|
||||
if (piece === 'skills' && outcome.launcher === true) results.launcher = 'updated';
|
||||
// The same for the app, when install() brought it in for the first time.
|
||||
if (piece === 'skills' && outcome.app === true) results.app = 'updated';
|
||||
console.log('');
|
||||
}
|
||||
|
||||
console.log(`${COLORS.BRIGHT}UPDATE SUMMARY${COLORS.RESET}`);
|
||||
const failed = [];
|
||||
for (const piece of INSTALL_PIECES.filter((p) => p in results)) {
|
||||
const ok = results[piece] === 'updated';
|
||||
const ok = results[piece] === 'updated' || results[piece].startsWith('kept');
|
||||
if (!ok) failed.push(piece);
|
||||
console.log(` ${ok ? COLORS.GREEN + SYMBOLS.SUCCESS : COLORS.RED + SYMBOLS.ERROR}${COLORS.RESET} ${piece}: ${results[piece]}`);
|
||||
}
|
||||
@@ -2840,4 +3082,4 @@ if (require.main === module) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { update, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
|
||||
module.exports = { update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.10.0",
|
||||
"version": "3.0.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -8,7 +8,9 @@
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"build:skills": "node install.js --build-skills",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs"
|
||||
"fix:eol": "node scripts/fix-line-endings.mjs",
|
||||
"pretest": "node scripts/fix-line-endings.mjs",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-activities.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0",
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src-tauri", "fake-agent"]
|
||||
@@ -0,0 +1,55 @@
|
||||
# plan2code-app
|
||||
|
||||
The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a **New Session** button. Built with Tauri 2 (Rust and a web view).
|
||||
|
||||
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 once a finished step has nothing left to press; a finished screen that still offers a button (back to the dashboard, a review) keeps the green dot. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
|
||||
|
||||
## Layout
|
||||
|
||||
| Path | What it is |
|
||||
|---|---|
|
||||
| `src-tauri/` | The Rust app |
|
||||
| `ui/` | The app page (plain HTML, CSS and JavaScript, no framework) |
|
||||
| `fake-agent/` | A stand-in agent program the tests run in a real pseudo-terminal |
|
||||
| `package.json` | The app's own npm packages (xterm, the Tauri CLI). Separate from the repo root so the root and the console stay dependency-free |
|
||||
|
||||
## Build and run
|
||||
|
||||
Needs the Rust toolchain pinned in `rust-toolchain.toml`, Node 18+, and the Tauri 2 system packages for your system (WebView2 on Windows, WebKitGTK on Linux).
|
||||
|
||||
```
|
||||
cd plan2code-app
|
||||
npm install
|
||||
npm run dev # run the app
|
||||
npm run build # build the installable bundle
|
||||
```
|
||||
|
||||
## Tests
|
||||
|
||||
```
|
||||
cd plan2code-app
|
||||
node scripts/vendor.mjs # once: the xterm files cargo builds against
|
||||
cargo fmt --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
```
|
||||
|
||||
The `app` workflow runs all three on Windows, macOS and Linux, and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
|
||||
|
||||
Real Claude, Devin and Codex are never started by a test. The real window and terminal panel are checked by hand before each release.
|
||||
@@ -0,0 +1,130 @@
|
||||
# Release checklist
|
||||
|
||||
Run this before every release of the desktop app, on each system the release builds for: Windows
|
||||
x64, macOS Apple silicon and Linux x64. Automated tests cover the logic and never start a real
|
||||
window, a real terminal panel, or a real Claude, Devin or Codex, so everything here is by hand.
|
||||
|
||||
Work from the pre-release build: publish a GitHub pre-release so `release-app.yml` attaches the files,
|
||||
then install from it. Tick each box per system and note anything that is a rough edge rather than a
|
||||
failure.
|
||||
|
||||
`npm run build` here runs `tauri build` with bundling on, so a local build also produces `.msi`/NSIS
|
||||
`.exe`/`.dmg`/`.deb` installer packages under `src-tauri/target/release/bundle/`. Ignore those: the
|
||||
release workflow builds with `--no-bundle` and attaches only the plain executable per system (see
|
||||
`.github/workflows/release-app.yml`); `install.js` is the only installer, and it places that plain
|
||||
file directly after checking it against the release's checksum list.
|
||||
|
||||
## Before you start
|
||||
|
||||
- [ ] `node scripts/check-versions.mjs --tag v<version>` passes (version.json, package.json,
|
||||
CHANGELOG.md and the app's tauri.conf.json, package.json and Cargo.toml all agree)
|
||||
- [ ] `npm test` passes at the repo root, with the app absent
|
||||
- [ ] `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings` and
|
||||
`cargo test --workspace` pass in `plan2code-app/`, and the `app` workflow is green on all
|
||||
three systems
|
||||
- [ ] The pre-release has one `plan2code-app-<version>-<os>-<arch>` file per system and a
|
||||
`plan2code-app-<version>-SHA256SUMS.txt`
|
||||
|
||||
## Install and launch (each system)
|
||||
|
||||
- [ ] Run the installer from the pre-release: it offers the app, downloads it, verifies the checksum
|
||||
and places it in `~/.plan2code/app/`
|
||||
- [ ] A deliberately corrupted download is rejected with the checksum message, and the skills and
|
||||
the `plan2code` command are still installed
|
||||
- [ ] `plan2code` in a project asks for the agent and model, then opens the app on that folder
|
||||
- [ ] The agent and model picked in the launcher are the ones the app starts at once, with no
|
||||
launch card or checklist shown first, and New Session keeps them
|
||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||
- [ ] The desktop shortcut opens the folder picker and then the app
|
||||
- [ ] macOS: the first start is stopped by Gatekeeper, **Open Anyway** in System Settings (Privacy &
|
||||
Security) lets it through, and `docs/desktop-app.md` describes what you saw
|
||||
- [ ] macOS and Linux: start the app from the Dock, Finder or a `.desktop` file (not a terminal) on
|
||||
a machine where Node is only on PATH through nvm, Homebrew or Volta: the first-run checklist
|
||||
still finds Node and the installed CLIs, and the console and an agent still start
|
||||
- [ ] Windows: SmartScreen's **More info**, then **Run anyway**, lets it through, and
|
||||
`docs/desktop-app.md` describes what you saw
|
||||
- [ ] `plan2code update` updates the skills, the command and the app, including while the app is
|
||||
running (Windows replaces the file by renaming the old one aside)
|
||||
|
||||
## The window (each system)
|
||||
|
||||
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
|
||||
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
|
||||
- [ ] The bar shows the project folder; the permission note appears only while an agent started
|
||||
with checks off is running, never otherwise
|
||||
- [ ] The OS window title (and so the taskbar entry) reads **Plan2Code - <folder name>**,
|
||||
not just **Plan2Code**; open a second window on a different folder and confirm they read
|
||||
apart in the taskbar without needing to restore either one
|
||||
- [ ] The first run (no `firstRunDone` saved yet) shows the checklist (Node, an agent CLI, the
|
||||
project folder, the skills version) before the launch card; a later launch goes straight to
|
||||
the launch card
|
||||
- [ ] The launch card offers agent, model, effort (Claude and Codex only) and permission mode
|
||||
(checks off is ticked by default, matching the plain `plan2code` launcher; untick it for
|
||||
an agent that keeps its normal approval prompts); a CLI it could not find is named, not
|
||||
just disabled
|
||||
- [ ] **Dock the terminal to the right**: the splitter becomes vertical, the toolbar stacks, and the
|
||||
dashboard keeps the rest of the width; dock it back to the bottom
|
||||
- [ ] **Collapse** the terminal to a thin strip (either dock) and **View Agent Terminal** brings it
|
||||
back; its size from before collapsing is remembered
|
||||
- [ ] Docked right, collapsed: the **View Agent Terminal** label reads top-to-bottom and fits inside the strip,
|
||||
not sideways text running off the edge
|
||||
- [ ] Collapse the terminal (or shrink it small), let the agent go quiet for a while mid-answer: the
|
||||
"agent may need you" badge appears on the strip; expanding it clears the badge
|
||||
- [ ] 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; 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
|
||||
from where it was, not blank, and the dashboard reconnects to the same session
|
||||
- [ ] When the app and the installed skills differ in version, the bar's right end offers **Update
|
||||
skills**, and nothing updates until it is pressed; with the console stopped as well, Reconnect
|
||||
the console shows first and "+1 more" names the update
|
||||
|
||||
## The terminal panel, with each real agent (each system)
|
||||
|
||||
Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
|
||||
- [ ] Startup screen draws correctly
|
||||
- [ ] Typing a prompt and getting an answer
|
||||
- [ ] A long streamed answer scrolls and stays readable
|
||||
- [ ] Resizing the window reflows the agent's screen
|
||||
- [ ] Pasting several lines
|
||||
- [ ] A line with Unicode and emoji
|
||||
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
|
||||
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
|
||||
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
|
||||
just left of it
|
||||
|
||||
## Agent lifecycle
|
||||
|
||||
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
|
||||
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
|
||||
dashboard shows the pick-up chip with a brief that matches the session
|
||||
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
|
||||
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
|
||||
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
||||
- [ ] Cmd+Q on macOS asks the same
|
||||
- [ ] 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, a green dot on a finished screen that still offers a button (back to the dashboard, a review), and no dot while the agent is busy, once a finished step has nothing left to press, or after the agent ends
|
||||
- [ ] Windows: with the window unfocused, the button gives one short burst of flashes when it becomes your move or needs attention (not again on a repeat) and stays lit until the window gets focus
|
||||
- [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background
|
||||
- [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused
|
||||
- [ ] 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
|
||||
- [ ] `npm test` still passes with the app installed on this machine
|
||||
@@ -0,0 +1,9 @@
|
||||
[package]
|
||||
name = "fake-agent"
|
||||
version = "3.0.0"
|
||||
description = "A stand-in agent program for the Plan2Code app's tests"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
terminal_size = "0.4"
|
||||
@@ -0,0 +1,136 @@
|
||||
//! A stand-in for Claude, Devin and Codex in the app's tests.
|
||||
//!
|
||||
//! It behaves the same on Windows, macOS and Linux. Commands, one per line on
|
||||
//! stdin (these words are the contract the app's integration tests rely on):
|
||||
//!
|
||||
//! STEP <n> print one progress line a second for n seconds, then `STEP DONE`
|
||||
//! EXIT <c> exit with code c
|
||||
//! SIZE print the terminal size once
|
||||
//! PID print the agent's process id as `PID <n>`
|
||||
//! <other> echoed back as `echo: <line>`
|
||||
//!
|
||||
//! A change in terminal size is reported on its own as `SIZE <cols>x<rows>`.
|
||||
|
||||
use std::io::{self, BufRead, Write};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use terminal_size::{terminal_size, Height, Width};
|
||||
|
||||
fn size_text() -> Option<String> {
|
||||
terminal_size().map(|(Width(w), Height(h))| format!("SIZE {w}x{h}"))
|
||||
}
|
||||
|
||||
fn say(line: &str) {
|
||||
let mut out = io::stdout().lock();
|
||||
let _ = writeln!(out, "{line}\r");
|
||||
let _ = out.flush();
|
||||
}
|
||||
|
||||
/// What a command line asks the agent to do.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Command {
|
||||
Step(u64),
|
||||
Exit(i32),
|
||||
Size,
|
||||
Pid,
|
||||
/// `ENV NAME`: print the variable's value, for tests of what an agent is given.
|
||||
Env(String),
|
||||
Echo(String),
|
||||
}
|
||||
|
||||
pub fn parse(line: &str) -> Command {
|
||||
let line = line.trim();
|
||||
if let Some(rest) = line.strip_prefix("STEP ") {
|
||||
if let Ok(n) = rest.trim().parse() {
|
||||
return Command::Step(n);
|
||||
}
|
||||
}
|
||||
if let Some(rest) = line.strip_prefix("EXIT ") {
|
||||
if let Ok(code) = rest.trim().parse() {
|
||||
return Command::Exit(code);
|
||||
}
|
||||
}
|
||||
if line == "SIZE" {
|
||||
return Command::Size;
|
||||
}
|
||||
if line == "PID" {
|
||||
return Command::Pid;
|
||||
}
|
||||
if let Some(name) = line.strip_prefix("ENV ") {
|
||||
return Command::Env(name.trim().to_string());
|
||||
}
|
||||
Command::Echo(line.to_string())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
say("FAKE-AGENT ready");
|
||||
if let Some(size) = size_text() {
|
||||
say(&size);
|
||||
}
|
||||
|
||||
// Report a resize on its own, by watching the size, so the same code works
|
||||
// where there is no resize signal (Windows).
|
||||
thread::spawn(|| {
|
||||
let mut last = size_text();
|
||||
loop {
|
||||
thread::sleep(Duration::from_millis(100));
|
||||
let now = size_text();
|
||||
if now != last {
|
||||
if let Some(text) = &now {
|
||||
say(text);
|
||||
}
|
||||
last = now;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let stdin = io::stdin();
|
||||
for line in stdin.lock().lines() {
|
||||
let Ok(line) = line else { break };
|
||||
match parse(&line) {
|
||||
Command::Step(n) => {
|
||||
for i in 1..=n {
|
||||
say(&format!("working {i}/{n}"));
|
||||
thread::sleep(Duration::from_secs(1));
|
||||
}
|
||||
say("STEP DONE");
|
||||
}
|
||||
Command::Exit(code) => {
|
||||
say(&format!("exiting {code}"));
|
||||
std::process::exit(code);
|
||||
}
|
||||
Command::Size => say(&size_text().unwrap_or_else(|| "SIZE unknown".into())),
|
||||
Command::Pid => say(&format!("PID {}", std::process::id())),
|
||||
Command::Env(name) => say(&format!(
|
||||
"ENV {name}={}",
|
||||
std::env::var(&name).unwrap_or_default()
|
||||
)),
|
||||
Command::Echo(text) => say(&format!("echo: {text}")),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_the_command_words() {
|
||||
assert_eq!(parse("STEP 3"), Command::Step(3));
|
||||
assert_eq!(parse("EXIT 7\r\n"), Command::Exit(7));
|
||||
assert_eq!(parse("SIZE"), Command::Size);
|
||||
assert_eq!(parse("PID"), Command::Pid);
|
||||
assert_eq!(
|
||||
parse("ENV PLAN2CODE_IN_APP"),
|
||||
Command::Env("PLAN2CODE_IN_APP".into())
|
||||
);
|
||||
assert_eq!(parse("hello there"), Command::Echo("hello there".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_number_is_just_an_echo() {
|
||||
assert_eq!(parse("STEP x"), Command::Echo("STEP x".into()));
|
||||
assert_eq!(parse("EXIT"), Command::Echo("EXIT".into()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,262 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
"@xterm/xterm": "6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "2.12.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/api": {
|
||||
"version": "2.12.4",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.4.tgz",
|
||||
"integrity": "sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==",
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/tauri"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli/-/cli-2.12.3.tgz",
|
||||
"integrity": "sha512-f7/LsY74SVb1ChmOPw1ajOpxii0GSzDAgmWHRci8JUYuuai04rXsSbFobpmB0sP2DdlvMD/B5ZotEn8GOGMRUg==",
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"bin": {
|
||||
"tauri": "tauri.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
},
|
||||
"funding": {
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/tauri"
|
||||
},
|
||||
"optionalDependencies": {
|
||||
"@tauri-apps/cli-darwin-arm64": "2.12.3",
|
||||
"@tauri-apps/cli-darwin-x64": "2.12.3",
|
||||
"@tauri-apps/cli-linux-arm-gnueabihf": "2.12.3",
|
||||
"@tauri-apps/cli-linux-arm64-gnu": "2.12.3",
|
||||
"@tauri-apps/cli-linux-arm64-musl": "2.12.3",
|
||||
"@tauri-apps/cli-linux-riscv64-gnu": "2.12.3",
|
||||
"@tauri-apps/cli-linux-x64-gnu": "2.12.3",
|
||||
"@tauri-apps/cli-linux-x64-musl": "2.12.3",
|
||||
"@tauri-apps/cli-win32-arm64-msvc": "2.12.3",
|
||||
"@tauri-apps/cli-win32-ia32-msvc": "2.12.3",
|
||||
"@tauri-apps/cli-win32-x64-msvc": "2.12.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-darwin-arm64": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-arm64/-/cli-darwin-arm64-2.12.3.tgz",
|
||||
"integrity": "sha512-xmVNoJOOKzKLj7GLHXmXLimRby9M42aBIJa0sB80N7o24eKV5JiVmToKTRLVH9yhL05GZ/B6rSSOmbzNFJwBAA==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-darwin-x64": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-darwin-x64/-/cli-darwin-x64-2.12.3.tgz",
|
||||
"integrity": "sha512-URd+0usfmUQQyb5kNPiKt2OT8gp7oGU7QR+qOppB6e35mpVBFFVNhWc9oWb3p0u71fDJ09DpF4T6m9xYxoIB8g==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"darwin"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-arm-gnueabihf": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm-gnueabihf/-/cli-linux-arm-gnueabihf-2.12.3.tgz",
|
||||
"integrity": "sha512-0kwUVx2LbmOoTRlwF1oDww7th4/NSluv4ZBQ6KRZsFKg4g0TlTcIiJ0VehqkQYUeC9xIT1Mk6XtF52mI155VSQ==",
|
||||
"cpu": [
|
||||
"arm"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-arm64-gnu": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-gnu/-/cli-linux-arm64-gnu-2.12.3.tgz",
|
||||
"integrity": "sha512-gKSGDx6fx+HBLQmG6guChFdisbrCSdx9Yli+j5teOa64gm1CeM+C6NLru5Pj3ZkkEep05BmCFjxvX+cjqAycZQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-arm64-musl": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-arm64-musl/-/cli-linux-arm64-musl-2.12.3.tgz",
|
||||
"integrity": "sha512-Yr59qMy/gcvAfBuFdCGlAmGiLsYWMFDbsP4bAI6iNBzcJTGrYWZGeiQhGDo29MQwfF/NUBqyM2qljXu5tZ6wjQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-riscv64-gnu": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-riscv64-gnu/-/cli-linux-riscv64-gnu-2.12.3.tgz",
|
||||
"integrity": "sha512-jKr0/REBMnLKC0OwPQZkyge0mKDaNZ0b/AbfGwVyCgFfwS730EVLfVDo3nt7MUu6jJaytRq08+xSj5qfy+U1+Q==",
|
||||
"cpu": [
|
||||
"riscv64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-x64-gnu": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-gnu/-/cli-linux-x64-gnu-2.12.3.tgz",
|
||||
"integrity": "sha512-gTkEqJAGCMROGanxHnzaJzQ+/rXl39HWVg0/hDODS1wDWBGqoceqGC6Qm1+mQbyT11xnsB8mKu/gyVID/YpFIw==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-linux-x64-musl": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-linux-x64-musl/-/cli-linux-x64-musl-2.12.3.tgz",
|
||||
"integrity": "sha512-T2dTxL1svRym71fZtaW4pZYXbthbfFsEJr1NeOUg/p7laWXZbUt/8DMSZf8recu9f7+1F/Lv00HtzsEu6vDO9w==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"linux"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-win32-arm64-msvc": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-arm64-msvc/-/cli-win32-arm64-msvc-2.12.3.tgz",
|
||||
"integrity": "sha512-eoiQwpEZWbpsVHcM9BAzqqe4TCHszvr3rsM7pUQ4ofLK0lF1i1d/jX0Qo5DYMqcrUtwQuDdDuOCbcT0Izf1VwQ==",
|
||||
"cpu": [
|
||||
"arm64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-win32-ia32-msvc": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-ia32-msvc/-/cli-win32-ia32-msvc-2.12.3.tgz",
|
||||
"integrity": "sha512-kE+KUg6Dbbkgvcw0m99wJVIToFQzJqpMBAXah74WqxaLzssNwSTUccrHp6+QVzMhjQP330tvekFmnQF+0NbE6Q==",
|
||||
"cpu": [
|
||||
"ia32"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@tauri-apps/cli-win32-x64-msvc": {
|
||||
"version": "2.12.3",
|
||||
"resolved": "https://registry.npmjs.org/@tauri-apps/cli-win32-x64-msvc/-/cli-win32-x64-msvc-2.12.3.tgz",
|
||||
"integrity": "sha512-L7wndWAgX2mLW7alswpL3d1R0P9FN2WYBgHaQkAYEBxHHGkY4vFX9CjcRQ1LAxDAMIJxrY7/aDziFJeChS84NQ==",
|
||||
"cpu": [
|
||||
"x64"
|
||||
],
|
||||
"dev": true,
|
||||
"license": "Apache-2.0 OR MIT",
|
||||
"optional": true,
|
||||
"os": [
|
||||
"win32"
|
||||
],
|
||||
"engines": {
|
||||
"node": ">= 10"
|
||||
}
|
||||
},
|
||||
"node_modules/@xterm/addon-fit": {
|
||||
"version": "0.11.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/addon-fit/-/addon-fit-0.11.0.tgz",
|
||||
"integrity": "sha512-jYcgT6xtVYhnhgxh3QgYDnnNMYTcf8ElbxxFzX0IZo+vabQqSPAjC3c1wJrKB5E19VwQei89QCiZZP86DCPF7g==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@xterm/xterm": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/@xterm/xterm/-/xterm-6.0.0.tgz",
|
||||
"integrity": "sha512-TQwDdQGtwwDt+2cgKDLn0IRaSxYu1tSUjgKarSDkUM0ZNiSRXFpjxEsvc/Zgc5kq5omJ+V0a8/kIM2WD3sMOYg==",
|
||||
"license": "MIT",
|
||||
"workspaces": [
|
||||
"addons/*"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
{
|
||||
"name": "plan2code-app",
|
||||
"version": "3.0.0",
|
||||
"private": true,
|
||||
"description": "Plan2Code desktop app (Tauri). Separate from the repo root so the root and the web console stay dependency-free.",
|
||||
"scripts": {
|
||||
"tauri": "tauri",
|
||||
"dev": "tauri dev",
|
||||
"build": "tauri build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tauri-apps/api": "2.12.4",
|
||||
"@xterm/addon-fit": "0.11.0",
|
||||
"@xterm/xterm": "6.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tauri-apps/cli": "2.12.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
[toolchain]
|
||||
channel = "1.98.1"
|
||||
profile = "minimal"
|
||||
@@ -0,0 +1,17 @@
|
||||
// Copies the xterm files the page loads from node_modules into ui/vendor/, so the
|
||||
// page is plain files with no bundler. Run before `tauri dev` and `tauri build`.
|
||||
import { copyFileSync, mkdirSync } from 'node:fs';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const root = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||
const out = join(root, 'ui', 'vendor');
|
||||
mkdirSync(out, { recursive: true });
|
||||
|
||||
const files = [
|
||||
['node_modules/@xterm/xterm/lib/xterm.js', 'xterm.js'],
|
||||
['node_modules/@xterm/xterm/css/xterm.css', 'xterm.css'],
|
||||
['node_modules/@xterm/addon-fit/lib/addon-fit.js', 'addon-fit.js'],
|
||||
];
|
||||
for (const [from, to] of files) copyFileSync(join(root, from), join(out, to));
|
||||
console.log(`vendored ${files.length} xterm files into ui/vendor/`);
|
||||
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "plan2code-app"
|
||||
version = "3.0.0"
|
||||
description = "Plan2Code desktop app"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
[lib]
|
||||
name = "plan2code_app_lib"
|
||||
path = "src/lib.rs"
|
||||
|
||||
[build-dependencies]
|
||||
tauri-build = { version = "2.5", features = [] }
|
||||
|
||||
[dependencies]
|
||||
tauri = { version = "2.12", features = [] }
|
||||
tauri-plugin-dialog = "2"
|
||||
portable-pty = "0.9.0"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "1"
|
||||
chrono = "0.4"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[target.'cfg(windows)'.dependencies]
|
||||
# Already pulled in by portable-pty itself; named directly here only for the
|
||||
# Job Object APIs it does not expose (ending a `cmd /c` npm shim's whole
|
||||
# process tree, not just the shim).
|
||||
winapi = { version = "0.3.9", features = ["handleapi", "jobapi2", "minwindef", "ntdef", "winnt"] }
|
||||
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
tauri_build::build()
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title"]
|
||||
}
|
||||
|
After Width: | Height: | Size: 6.0 KiB |
|
After Width: | Height: | Size: 15 KiB |
|
After Width: | Height: | Size: 1.3 KiB |
|
After Width: | Height: | Size: 23 KiB |
|
After Width: | Height: | Size: 43 KiB |
@@ -0,0 +1,440 @@
|
||||
//! At most one agent per project folder: start it, end it, restart it (always
|
||||
//! at once: the app confirms with the person first, so nothing here waits for
|
||||
//! a quiet moment), and notice when it ends by itself.
|
||||
//! Knows nothing about Tauri: state changes and output go to one callback.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::{Arc, Mutex, MutexGuard};
|
||||
use std::thread;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::{agent_launch_spec, Agent, PermissionMode};
|
||||
use crate::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "state", rename_all = "lowercase")]
|
||||
pub enum AgentState {
|
||||
Idle,
|
||||
Running,
|
||||
/// The agent ended without a Restart press, or could not be started.
|
||||
Ended {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Runs just before a Restart starts the fresh agent, and returns the line the
|
||||
/// bar shows about it (`None` for no line). It must not call back into the
|
||||
/// manager: it runs with the manager's state locked.
|
||||
pub type BeforeFresh = Arc<dyn Fn() -> Option<String> + Send + Sync>;
|
||||
|
||||
/// What the page needs to draw the bar. `generation` counts the agents started
|
||||
/// so far: a new number means a fresh agent, so the terminal clears.
|
||||
#[derive(Clone, Debug, Serialize)]
|
||||
pub struct AgentSnapshot {
|
||||
#[serde(flatten)]
|
||||
pub state: AgentState,
|
||||
pub kind: Option<String>,
|
||||
pub generation: u64,
|
||||
/// The running (or last started) agent's permission mode, so the bar's
|
||||
/// note can name it instead of assuming bypass.
|
||||
pub mode: Option<PermissionMode>,
|
||||
/// What the last Restart left for the dashboard, for the bar.
|
||||
#[serde(rename = "briefNote", skip_serializing_if = "Option::is_none")]
|
||||
pub brief_note: Option<String>,
|
||||
}
|
||||
|
||||
pub enum AgentEvent {
|
||||
Output(Vec<u8>),
|
||||
State(AgentSnapshot),
|
||||
}
|
||||
|
||||
/// Receives events from several threads. State events are sent while the
|
||||
/// manager holds its lock, so a sink must not call back into the manager.
|
||||
pub type Sink = Arc<dyn Fn(AgentEvent) + Send + Sync>;
|
||||
|
||||
struct Running {
|
||||
host: Arc<PtyHost>,
|
||||
}
|
||||
|
||||
/// What a Restart starts again, besides the brief: the agent, its model and
|
||||
/// effort (when it has one), and its permission mode. Restart reuses this
|
||||
/// whole, unchanged choice (Task 9.6).
|
||||
#[derive(Clone)]
|
||||
struct StartChoice {
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
}
|
||||
|
||||
/// Recent output from the current generation is kept bounded, so a page
|
||||
/// reload or a fresh output channel can redraw the screen instead of staying
|
||||
/// blank. About enough for a full screen redraw with some headroom, never
|
||||
/// the whole scrollback.
|
||||
const REPLAY_LIMIT: usize = 256 * 1024;
|
||||
|
||||
/// Appends `bytes` to `replay`, dropping from the front (the oldest) when
|
||||
/// that would put it over `limit`: the tail, what a redraw actually needs,
|
||||
/// is always what is kept.
|
||||
fn append_replay(replay: &mut Vec<u8>, bytes: &[u8], limit: usize) {
|
||||
replay.extend_from_slice(bytes);
|
||||
if replay.len() > limit {
|
||||
let excess = replay.len() - limit;
|
||||
replay.drain(..excess);
|
||||
}
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
state: AgentState,
|
||||
running: Option<Running>,
|
||||
/// What a Restart starts again: the choice and the brief.
|
||||
last_start: Option<(StartChoice, Option<String>)>,
|
||||
size: (u16, u16),
|
||||
brief_note: Option<String>,
|
||||
/// Cleared when a fresh agent starts; see `REPLAY_LIMIT`.
|
||||
replay: Vec<u8>,
|
||||
}
|
||||
|
||||
struct Shared {
|
||||
folder: PathBuf,
|
||||
sink: Sink,
|
||||
before_fresh: Mutex<Option<BeforeFresh>>,
|
||||
/// Environment every agent this manager starts gets, on top of its own:
|
||||
/// the in-app signal that sends the agent's console pages to this window.
|
||||
extra_env: Mutex<Vec<(String, String)>>,
|
||||
/// Bumped for every agent started. Output and exits from an older agent
|
||||
/// compare against it and are dropped.
|
||||
generation: AtomicU64,
|
||||
inner: Mutex<Inner>,
|
||||
}
|
||||
|
||||
pub struct AgentManager {
|
||||
shared: Arc<Shared>,
|
||||
}
|
||||
|
||||
fn lock(inner: &Mutex<Inner>) -> MutexGuard<'_, Inner> {
|
||||
// A panic in another thread must not take the whole app's agent control down.
|
||||
inner
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
pub fn new(folder: PathBuf, sink: Sink) -> AgentManager {
|
||||
AgentManager {
|
||||
shared: Arc::new(Shared {
|
||||
folder,
|
||||
sink,
|
||||
before_fresh: Mutex::new(None),
|
||||
extra_env: Mutex::new(Vec::new()),
|
||||
generation: AtomicU64::new(0),
|
||||
inner: Mutex::new(Inner {
|
||||
state: AgentState::Idle,
|
||||
running: None,
|
||||
last_start: None,
|
||||
size: (80, 24),
|
||||
brief_note: None,
|
||||
replay: Vec::new(),
|
||||
}),
|
||||
}),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn folder(&self) -> &PathBuf {
|
||||
&self.shared.folder
|
||||
}
|
||||
|
||||
/// Run `hook` before every Restart starts its fresh agent.
|
||||
pub fn set_before_fresh(&self, hook: BeforeFresh) {
|
||||
if let Ok(mut slot) = self.shared.before_fresh.lock() {
|
||||
*slot = Some(hook);
|
||||
}
|
||||
}
|
||||
|
||||
/// Give every agent started from now on these variables (replacing any set before).
|
||||
pub fn set_env(&self, env: Vec<(String, String)>) {
|
||||
if let Ok(mut slot) = self.shared.extra_env.lock() {
|
||||
*slot = env;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start `kind` (built-in or custom) on `model`, `effort` and `mode`, with `brief` (`None` is
|
||||
/// the placeholder brief: the plain `/plan2code` prompt, which opens the
|
||||
/// dashboard). A second start while an agent runs is refused. Restart
|
||||
/// reuses this exact choice, so a later call replaces it for good.
|
||||
pub fn start(
|
||||
&self,
|
||||
kind: Agent,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: PermissionMode,
|
||||
brief: Option<String>,
|
||||
) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.state == AgentState::Running {
|
||||
return Err("an agent is already running for this project".to_string());
|
||||
}
|
||||
inner.brief_note = None;
|
||||
let previous = inner.last_start.replace((
|
||||
StartChoice {
|
||||
kind,
|
||||
model,
|
||||
effort,
|
||||
mode,
|
||||
},
|
||||
brief,
|
||||
));
|
||||
match self.shared.spawn(&mut inner) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
// A start that never ran must not take away what Restart would
|
||||
// have started again.
|
||||
inner.last_start = previous;
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> AgentSnapshot {
|
||||
self.shared.snapshot(&lock(&self.shared.inner))
|
||||
}
|
||||
|
||||
/// The current generation's recent output, for a page that just mounted
|
||||
/// (a reload or a fresh window) to redraw instead of staying blank.
|
||||
pub fn replay(&self) -> Vec<u8> {
|
||||
lock(&self.shared.inner).replay.clone()
|
||||
}
|
||||
|
||||
/// The model and effort the current (or last) start chose. The bar only
|
||||
/// ever needs `snapshot`'s `kind` and `mode`; this exists so a test can
|
||||
/// confirm Restart keeps the other two of the four just as unchanged.
|
||||
pub fn model_and_effort(&self) -> (Option<String>, Option<String>) {
|
||||
match &lock(&self.shared.inner).last_start {
|
||||
Some((choice, _)) => (choice.model.clone(), choice.effort.clone()),
|
||||
None => (None, None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_active(&self) -> bool {
|
||||
lock(&self.shared.inner).state == AgentState::Running
|
||||
}
|
||||
|
||||
pub fn input(&self, bytes: &[u8]) -> Result<(), String> {
|
||||
let host = lock(&self.shared.inner)
|
||||
.running
|
||||
.as_ref()
|
||||
.map(|r| Arc::clone(&r.host));
|
||||
match host {
|
||||
Some(host) => host.write(bytes),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The terminal changed size. Remembered, so a fresh agent starts at it.
|
||||
pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
inner.size = (cols, rows);
|
||||
match &inner.running {
|
||||
Some(running) => running.host.resize(cols, rows),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Kill the agent (if any) and start a fresh one on the same brief, at
|
||||
/// once, whatever it is doing. The app asks the person to confirm before
|
||||
/// calling this: there is no in-between "waiting" state here, because the
|
||||
/// agent's own output (status lines, a spinner) never truly goes quiet, so
|
||||
/// a "wait for it to finish" rule would wait forever in practice. Restart
|
||||
/// also answers an ended agent, where nothing is lost by it.
|
||||
pub fn restart(&self) -> Result<(), String> {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
if inner.state == AgentState::Idle {
|
||||
return Err("no agent has been started".to_string());
|
||||
}
|
||||
self.shared.replace(&mut inner)
|
||||
}
|
||||
|
||||
/// End the agent for good (quitting). Nothing starts afterwards, and the
|
||||
/// agent's process is gone when this returns.
|
||||
pub fn stop(&self) {
|
||||
let host = {
|
||||
let mut inner = lock(&self.shared.inner);
|
||||
// Older agents' output and exits stop counting from here.
|
||||
self.shared.generation.fetch_add(1, Ordering::SeqCst);
|
||||
let host = inner.running.take().map(|r| r.host);
|
||||
inner.state = AgentState::Idle;
|
||||
inner.last_start = None;
|
||||
self.shared.emit(&inner);
|
||||
host
|
||||
};
|
||||
if let Some(host) = host {
|
||||
let _ = host.kill();
|
||||
let _ = host.wait();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AgentManager {
|
||||
fn drop(&mut self) {
|
||||
self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
impl Shared {
|
||||
fn snapshot(&self, inner: &Inner) -> AgentSnapshot {
|
||||
AgentSnapshot {
|
||||
state: inner.state.clone(),
|
||||
kind: inner
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| choice.kind.id().to_string()),
|
||||
mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode),
|
||||
generation: self.generation.load(Ordering::SeqCst),
|
||||
brief_note: inner.brief_note.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
fn emit(&self, inner: &Inner) {
|
||||
(self.sink)(AgentEvent::State(self.snapshot(inner)));
|
||||
}
|
||||
|
||||
/// Start the agent in `inner.last_start` and watch for it to end.
|
||||
fn spawn(self: &Arc<Self>, inner: &mut Inner) -> Result<(), String> {
|
||||
let (choice, brief) = inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?;
|
||||
let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string());
|
||||
let mut spec = agent_launch_spec(
|
||||
&choice.kind,
|
||||
&self.folder,
|
||||
choice.model.as_deref(),
|
||||
choice.effort.as_deref(),
|
||||
choice.mode,
|
||||
&prompt,
|
||||
);
|
||||
if let Ok(extra) = self.extra_env.lock() {
|
||||
spec.env.extend(extra.iter().cloned());
|
||||
}
|
||||
let generation = self.generation.fetch_add(1, Ordering::SeqCst) + 1;
|
||||
|
||||
let on_output = {
|
||||
let shared = Arc::clone(self);
|
||||
move |bytes: Vec<u8>| {
|
||||
// Taking the lock here, briefly, keeps this behind the state
|
||||
// change that announces its agent (`spawn`'s caller holds the
|
||||
// lock until it has emitted), so the page clears its screen
|
||||
// before the banner. It is released before the send below,
|
||||
// which can be slow, so typing (`input`) is never stuck
|
||||
// behind a flood of output.
|
||||
let stale = {
|
||||
let mut in_order = lock(&shared.inner);
|
||||
if shared.generation.load(Ordering::SeqCst) != generation {
|
||||
true
|
||||
} else {
|
||||
append_replay(&mut in_order.replay, &bytes, REPLAY_LIMIT);
|
||||
false
|
||||
}
|
||||
};
|
||||
if stale {
|
||||
return;
|
||||
}
|
||||
(shared.sink)(AgentEvent::Output(bytes));
|
||||
}
|
||||
};
|
||||
let host = Arc::new(PtyHost::start(
|
||||
StartOptions {
|
||||
program: spec.program,
|
||||
args: spec.args,
|
||||
env: spec.env,
|
||||
cwd: Some(spec.cwd),
|
||||
cols: inner.size.0,
|
||||
rows: inner.size.1,
|
||||
},
|
||||
on_output,
|
||||
)?);
|
||||
|
||||
inner.running = Some(Running {
|
||||
host: Arc::clone(&host),
|
||||
});
|
||||
inner.state = AgentState::Running;
|
||||
// A fresh agent starts on a clean screen; its replay must too.
|
||||
inner.replay.clear();
|
||||
self.emit(inner);
|
||||
|
||||
let shared = Arc::clone(self);
|
||||
thread::spawn(move || {
|
||||
let reason = match host.wait_described() {
|
||||
Ok((_, Some(signal))) => format!("was ended by a signal ({signal})"),
|
||||
Ok((code, None)) => format!("exited with code {code}"),
|
||||
Err(e) => format!("stopped: {e}"),
|
||||
};
|
||||
shared.on_exit(generation, reason);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Kill the running agent (if any) and start a fresh one on the same
|
||||
/// brief. A fresh agent that cannot start leaves the state `Ended`.
|
||||
fn replace(self: &Arc<Self>, inner: &mut Inner) -> Result<(), String> {
|
||||
// Bumping the generation first drops whatever the old agent still says.
|
||||
self.generation.fetch_add(1, Ordering::SeqCst);
|
||||
if let Some(old) = inner.running.take() {
|
||||
let _ = old.host.kill();
|
||||
}
|
||||
let hook = self.before_fresh.lock().ok().and_then(|slot| slot.clone());
|
||||
inner.brief_note = hook.and_then(|run| run());
|
||||
match self.spawn(inner) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended {
|
||||
reason: format!("could not start the agent: {e}"),
|
||||
};
|
||||
self.emit(inner);
|
||||
Err(e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The agent's process ended. Stale if a newer agent has replaced it.
|
||||
fn on_exit(self: &Arc<Self>, generation: u64, reason: String) {
|
||||
let mut inner = lock(&self.inner);
|
||||
if self.generation.load(Ordering::SeqCst) != generation {
|
||||
return;
|
||||
}
|
||||
inner.running = None;
|
||||
// Ended on its own: say why and start nothing.
|
||||
inner.state = AgentState::Ended { reason };
|
||||
self.emit(&inner);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod replay_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn under_the_limit_keeps_everything() {
|
||||
let mut replay = b"hello ".to_vec();
|
||||
append_replay(&mut replay, b"world", 20);
|
||||
assert_eq!(replay, b"hello world");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_the_limit_drops_the_oldest_bytes_and_keeps_the_tail() {
|
||||
let mut replay = b"0123456789".to_vec();
|
||||
append_replay(&mut replay, b"ABCDE", 10);
|
||||
// 15 bytes written, a 10-byte limit: the oldest 5 ("01234") are gone.
|
||||
assert_eq!(replay, b"56789ABCDE");
|
||||
assert_eq!(replay.len(), 10);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_write_longer_than_the_limit_keeps_only_its_own_tail() {
|
||||
let mut replay = Vec::new();
|
||||
append_replay(&mut replay, b"0123456789", 4);
|
||||
assert_eq!(replay, b"6789");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
//! This window's announce endpoint: `console.mjs open`, run by the agent inside
|
||||
//! the app, POSTs the page it wants shown here instead of opening a browser.
|
||||
//! Loopback only, one random token per window, so two windows never hear each
|
||||
//! other's agents. Knows nothing about Tauri: the caller gets each accepted
|
||||
//! notice through a callback.
|
||||
|
||||
use std::collections::hash_map::RandomState;
|
||||
use std::hash::{BuildHasher, Hasher};
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{Ipv4Addr, SocketAddr, TcpListener, TcpStream};
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// The most an announce request may weigh: a URL and two short names.
|
||||
const MAX_REQUEST: usize = 8 * 1024;
|
||||
const READ_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// A page the console wants shown: where it is, the session it belongs to and
|
||||
/// the skill it runs.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct PageNotice {
|
||||
pub url: String,
|
||||
pub sid: String,
|
||||
pub workflow: String,
|
||||
}
|
||||
|
||||
/// Says whether the window took the page. Only a page it took becomes the
|
||||
/// window's current session, so a refused one never steers the next `open`.
|
||||
pub type OnPage = Arc<dyn Fn(PageNotice) -> bool + Send + Sync>;
|
||||
|
||||
pub struct AnnounceServer {
|
||||
port: u16,
|
||||
token: String,
|
||||
/// The page most recently announced: what `GET /session` answers, so an
|
||||
/// agent's `open` joins the window's current session whatever its own
|
||||
/// environment (fixed when it started) says.
|
||||
current: Arc<Mutex<Option<PageNotice>>>,
|
||||
}
|
||||
|
||||
/// What a checked request asks for.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Request {
|
||||
/// `POST /page`: show this page.
|
||||
Page(PageNotice),
|
||||
/// `GET /session`: name the session the window shows now.
|
||||
Session,
|
||||
}
|
||||
|
||||
/// Why a request was refused, as the status the caller answers with.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Refused(pub u16, pub &'static str);
|
||||
|
||||
/// A random token from the OS-seeded hasher: 128 bits as hex. The standard
|
||||
/// library's `RandomState` keys come from the operating system's random source.
|
||||
fn random_token() -> String {
|
||||
let mut out = String::new();
|
||||
for round in 0..2u8 {
|
||||
let mut hasher = RandomState::new().build_hasher();
|
||||
hasher.write_u8(round);
|
||||
hasher.write_u128(
|
||||
std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.map(|d| d.as_nanos())
|
||||
.unwrap_or(0),
|
||||
);
|
||||
out.push_str(&format!("{:016x}", hasher.finish()));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn same_token(a: &str, b: &str) -> bool {
|
||||
// Compared in full whatever the first difference, so timing says nothing.
|
||||
let (a, b) = (a.as_bytes(), b.as_bytes());
|
||||
let mut diff = (a.len() != b.len()) as u8;
|
||||
for i in 0..a.len().min(b.len()) {
|
||||
diff |= a[i] ^ b[i];
|
||||
}
|
||||
diff == 0
|
||||
}
|
||||
|
||||
/// A console page URL the app may show: plain http on loopback with a port and
|
||||
/// a `/s/<token>/` path, which is all the console ever hands out.
|
||||
pub fn acceptable_url(url: &str) -> bool {
|
||||
let Some(rest) = url.strip_prefix("http://127.0.0.1:") else {
|
||||
return false;
|
||||
};
|
||||
let Some((port, path)) = rest.split_once('/') else {
|
||||
return false;
|
||||
};
|
||||
port.parse::<u16>().is_ok_and(|p| p > 0)
|
||||
&& path.starts_with("s/")
|
||||
&& !url.contains(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Check one request (its head as text, its body as bytes) against `token`.
|
||||
pub fn check_request(head: &str, body: &[u8], token: &str) -> Result<Request, Refused> {
|
||||
let mut lines = head.split("\r\n");
|
||||
let request_line = lines.next().unwrap_or("");
|
||||
let route = request_line.split(' ').take(2).collect::<Vec<_>>();
|
||||
if route != ["POST", "/page"] && route != ["GET", "/session"] {
|
||||
return Err(Refused(404, "not found"));
|
||||
}
|
||||
let mut given = None;
|
||||
for line in lines {
|
||||
let Some((name, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
match name.trim().to_ascii_lowercase().as_str() {
|
||||
"x-plan2code-token" => given = Some(value.trim().to_string()),
|
||||
// A browser page sending this would be some site guessing at the port.
|
||||
"origin" => return Err(Refused(403, "not from a page")),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if !given.is_some_and(|given| same_token(&given, token)) {
|
||||
return Err(Refused(403, "bad token"));
|
||||
}
|
||||
if route[0] == "GET" {
|
||||
return Ok(Request::Session);
|
||||
}
|
||||
let notice: PageNotice = serde_json::from_slice(body).map_err(|_| Refused(400, "bad body"))?;
|
||||
if !acceptable_url(¬ice.url) || notice.sid.len() > 128 || notice.workflow.len() > 64 {
|
||||
return Err(Refused(400, "bad page"));
|
||||
}
|
||||
Ok(Request::Page(notice))
|
||||
}
|
||||
|
||||
fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
204 => "No Content",
|
||||
400 => "Bad Request",
|
||||
403 => "Forbidden",
|
||||
_ => "Not Found",
|
||||
}
|
||||
}
|
||||
|
||||
fn respond(stream: &mut TcpStream, status: u16, body: &str) {
|
||||
let _ = write!(
|
||||
stream,
|
||||
"HTTP/1.1 {status} {}\r\nContent-Type: application/json\r\nContent-Length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
reason(status),
|
||||
body.len()
|
||||
);
|
||||
}
|
||||
|
||||
/// Read one request: the head up to the blank line, then the body the
|
||||
/// `Content-Length` header names. Anything over `MAX_REQUEST` is refused.
|
||||
fn read_request(stream: &mut TcpStream) -> Result<(String, Vec<u8>), Refused> {
|
||||
let _ = stream.set_read_timeout(Some(READ_TIMEOUT));
|
||||
let mut buf = Vec::new();
|
||||
let mut chunk = [0u8; 1024];
|
||||
let split = loop {
|
||||
if let Some(at) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
|
||||
break at;
|
||||
}
|
||||
if buf.len() > MAX_REQUEST {
|
||||
return Err(Refused(400, "too big"));
|
||||
}
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => return Err(Refused(400, "incomplete")),
|
||||
Ok(n) => buf.extend_from_slice(&chunk[..n]),
|
||||
}
|
||||
};
|
||||
let head = String::from_utf8_lossy(&buf[..split]).into_owned();
|
||||
let length = head
|
||||
.split("\r\n")
|
||||
.filter_map(|line| line.split_once(':'))
|
||||
.find(|(name, _)| name.trim().eq_ignore_ascii_case("content-length"))
|
||||
.and_then(|(_, value)| value.trim().parse::<usize>().ok())
|
||||
.unwrap_or(0);
|
||||
if length > MAX_REQUEST {
|
||||
return Err(Refused(400, "too big"));
|
||||
}
|
||||
let mut body = buf[split + 4..].to_vec();
|
||||
while body.len() < length {
|
||||
match stream.read(&mut chunk) {
|
||||
Ok(0) | Err(_) => return Err(Refused(400, "incomplete")),
|
||||
Ok(n) => body.extend_from_slice(&chunk[..n]),
|
||||
}
|
||||
}
|
||||
body.truncate(length);
|
||||
Ok((head, body))
|
||||
}
|
||||
|
||||
impl AnnounceServer {
|
||||
/// Listen on a random loopback port. `on_page` runs on the server's own
|
||||
/// thread for every accepted notice.
|
||||
pub fn start(on_page: OnPage) -> Result<AnnounceServer, String> {
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
|
||||
let token = random_token();
|
||||
let expected = token.clone();
|
||||
let current: Arc<Mutex<Option<PageNotice>>> = Arc::new(Mutex::new(None));
|
||||
let shared = Arc::clone(¤t);
|
||||
thread::spawn(move || {
|
||||
for stream in listener.incoming() {
|
||||
let Ok(mut stream) = stream else { continue };
|
||||
let (status, body) = match read_request(&mut stream)
|
||||
.and_then(|(head, body)| check_request(&head, &body, &expected))
|
||||
{
|
||||
Ok(Request::Page(notice)) => {
|
||||
if on_page(notice.clone()) {
|
||||
if let Ok(mut slot) = shared.lock() {
|
||||
*slot = Some(notice);
|
||||
}
|
||||
(204, String::new())
|
||||
} else {
|
||||
// `open` reads anything but 2xx as "the app did not take the page".
|
||||
(409, String::new())
|
||||
}
|
||||
}
|
||||
Ok(Request::Session) => {
|
||||
let now = shared.lock().ok().and_then(|slot| slot.clone());
|
||||
(
|
||||
200,
|
||||
serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string()),
|
||||
)
|
||||
}
|
||||
Err(Refused(status, _)) => (status, String::new()),
|
||||
};
|
||||
respond(&mut stream, status, &body);
|
||||
}
|
||||
});
|
||||
Ok(AnnounceServer {
|
||||
port,
|
||||
token,
|
||||
current,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn url(&self) -> String {
|
||||
format!("http://127.0.0.1:{}/page", self.port)
|
||||
}
|
||||
|
||||
pub fn token(&self) -> &str {
|
||||
&self.token
|
||||
}
|
||||
|
||||
/// The page most recently announced, if any.
|
||||
pub fn current(&self) -> Option<PageNotice> {
|
||||
self.current.lock().ok().and_then(|slot| slot.clone())
|
||||
}
|
||||
|
||||
/// Forget the page most recently announced, so the next agent's `open`
|
||||
/// starts a session of its own instead of joining that one. New Session
|
||||
/// does this: a fresh agent's session meter starts over with it.
|
||||
pub fn forget_current(&self) {
|
||||
if let Ok(mut slot) = self.current.lock() {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// What goes on the agent's process so its `console.mjs open` shows pages
|
||||
/// here. Every value belongs to this window. `embed_origin` is the origin of
|
||||
/// the app page, so a console the agent starts allows being framed by it.
|
||||
pub fn agent_env(&self, embed_origin: &str, app_version: &str) -> Vec<(String, String)> {
|
||||
vec![
|
||||
("PLAN2CODE_IN_APP".to_string(), "1".to_string()),
|
||||
("PLAN2CODE_APP_VERSION".to_string(), app_version.to_string()),
|
||||
(
|
||||
"PLAN2CODE_EMBED_ORIGIN".to_string(),
|
||||
embed_origin.to_string(),
|
||||
),
|
||||
("PLAN2CODE_APP_ANNOUNCE".to_string(), self.url()),
|
||||
("PLAN2CODE_APP_TOKEN".to_string(), self.token.clone()),
|
||||
]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::mpsc::channel;
|
||||
use std::sync::Mutex;
|
||||
|
||||
fn request(token: &str, body: &str) -> (String, Vec<u8>) {
|
||||
(
|
||||
format!("POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}", body.len()),
|
||||
body.as_bytes().to_vec(),
|
||||
)
|
||||
}
|
||||
|
||||
const GOOD: &str = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
|
||||
|
||||
#[test]
|
||||
fn accepts_a_good_notice() {
|
||||
let (head, body) = request("t", GOOD);
|
||||
let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else {
|
||||
panic!("not accepted")
|
||||
};
|
||||
assert_eq!(
|
||||
(notice.sid.as_str(), notice.workflow.as_str()),
|
||||
("s1", "plan")
|
||||
);
|
||||
let get = "GET /session HTTP/1.1\r\nx-plan2code-token: t";
|
||||
assert_eq!(check_request(get, b"", "t"), Ok(Request::Session));
|
||||
assert_eq!(
|
||||
check_request(get, b"", "other"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_wrong_or_missing_token() {
|
||||
let (head, body) = request("nope", GOOD);
|
||||
assert_eq!(
|
||||
check_request(&head, &body, "t"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
let head = "POST /page HTTP/1.1\r\nHost: x";
|
||||
assert_eq!(
|
||||
check_request(head, GOOD.as_bytes(), "t"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_browser_origin_and_other_routes() {
|
||||
let (head, body) = request("t", GOOD);
|
||||
let with_origin = format!("{head}\r\nOrigin: http://evil.example");
|
||||
assert_eq!(
|
||||
check_request(&with_origin, &body, "t"),
|
||||
Err(Refused(403, "not from a page"))
|
||||
);
|
||||
let other = head.replace("/page", "/other");
|
||||
assert_eq!(
|
||||
check_request(&other, &body, "t"),
|
||||
Err(Refused(404, "not found"))
|
||||
);
|
||||
let get = head.replace("POST", "GET");
|
||||
assert_eq!(
|
||||
check_request(&get, &body, "t"),
|
||||
Err(Refused(404, "not found")),
|
||||
"GET is for /session only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bad_body_and_a_url_that_is_not_the_console() {
|
||||
let (head, _) = request("t", "x");
|
||||
assert_eq!(
|
||||
check_request(&head, b"not json", "t"),
|
||||
Err(Refused(400, "bad body"))
|
||||
);
|
||||
for url in [
|
||||
"http://example.com/s/abc/",
|
||||
"https://127.0.0.1:5/s/a/",
|
||||
"http://127.0.0.1:5/other",
|
||||
"javascript:alert(1)",
|
||||
"http://127.0.0.1:0/s/a/",
|
||||
] {
|
||||
let body = format!(r#"{{"url":"{url}","sid":"s","workflow":"w"}}"#);
|
||||
assert_eq!(
|
||||
check_request(&head, body.as_bytes(), "t"),
|
||||
Err(Refused(400, "bad page")),
|
||||
"{url}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn tokens_differ_between_windows() {
|
||||
assert_ne!(random_token(), random_token());
|
||||
assert_eq!(random_token().len(), 32);
|
||||
assert!(same_token("abc", "abc") && !same_token("abc", "abd") && !same_token("abc", "ab"));
|
||||
}
|
||||
|
||||
fn post(port: u16, token: &str, body: &str) -> u16 {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(
|
||||
stream,
|
||||
"POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
let mut answer = String::new();
|
||||
stream.read_to_string(&mut answer).unwrap();
|
||||
answer.split(' ').nth(1).unwrap().parse().unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_windows_hear_only_their_own_agent() {
|
||||
let (tx_a, rx_a) = channel();
|
||||
let (tx_b, rx_b) = channel();
|
||||
let (tx_a, tx_b) = (Mutex::new(tx_a), Mutex::new(tx_b));
|
||||
let a =
|
||||
AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
let b =
|
||||
AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
assert_ne!(a.url(), b.url());
|
||||
let port = |s: &AnnounceServer| {
|
||||
s.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse::<u16>()
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
assert_eq!(post(port(&a), a.token(), GOOD), 204);
|
||||
assert_eq!(
|
||||
post(port(&b), a.token(), GOOD),
|
||||
403,
|
||||
"window A's token does nothing in window B"
|
||||
);
|
||||
assert_eq!(rx_a.recv_timeout(Duration::from_secs(3)).unwrap().sid, "s1");
|
||||
assert!(rx_b.recv_timeout(Duration::from_millis(300)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn agent_env_names_this_windows_values() {
|
||||
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
|
||||
let env = server.agent_env("http://127.0.0.1:1430", "3.0.0");
|
||||
let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
|
||||
assert_eq!(get("PLAN2CODE_IN_APP").as_deref(), Some("1"));
|
||||
assert_eq!(
|
||||
get("PLAN2CODE_EMBED_ORIGIN").as_deref(),
|
||||
Some("http://127.0.0.1:1430")
|
||||
);
|
||||
assert_eq!(get("PLAN2CODE_APP_VERSION").as_deref(), Some("3.0.0"));
|
||||
assert_eq!(get("PLAN2CODE_APP_ANNOUNCE"), Some(server.url()));
|
||||
assert_eq!(get("PLAN2CODE_APP_TOKEN").as_deref(), Some(server.token()));
|
||||
assert_eq!(
|
||||
get("PLAN2CODE_CONSOLE_SID"),
|
||||
None,
|
||||
"the window's session is asked for, not fixed at start"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_session_is_what_was_announced_last() {
|
||||
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
|
||||
let port: u16 = server
|
||||
.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse()
|
||||
.unwrap();
|
||||
let ask = |token: &str| {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(stream, "GET /session HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\nConnection: close\r\n\r\n").unwrap();
|
||||
let mut answer = String::new();
|
||||
stream.read_to_string(&mut answer).unwrap();
|
||||
answer
|
||||
};
|
||||
assert!(
|
||||
ask(server.token()).ends_with("null"),
|
||||
"nothing announced yet"
|
||||
);
|
||||
assert_eq!(post(port, server.token(), GOOD), 204);
|
||||
assert!(ask(server.token()).contains(r#""sid":"s1""#));
|
||||
assert!(ask("wrong").starts_with("HTTP/1.1 403"));
|
||||
assert_eq!(server.current().unwrap().workflow, "plan");
|
||||
server.forget_current();
|
||||
assert!(
|
||||
ask(server.token()).ends_with("null"),
|
||||
"forgotten: the next open starts its own session"
|
||||
);
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_page_the_window_refuses_is_not_its_session() {
|
||||
// A test's throwaway console: remembered, it would steer the next
|
||||
// agent `open` away from the window's real session.
|
||||
let server = AnnounceServer::start(Arc::new(|_| false)).unwrap();
|
||||
let port: u16 = server
|
||||
.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
post(port, server.token(), GOOD),
|
||||
409,
|
||||
"open hears that the app did not take it"
|
||||
);
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,283 @@
|
||||
//! 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"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,544 @@
|
||||
//! The restart brief: what a fresh agent needs to pick a session up where it
|
||||
//! stopped, written from the console's session files and the spec on disk. It
|
||||
//! is derived on demand and never cached. The Ask chat is left out (FR-7).
|
||||
|
||||
use std::fs;
|
||||
use std::io::Read;
|
||||
use std::path::Path;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// How many of the person's most recent answers the brief carries.
|
||||
const RECENT_ANSWERS: usize = 10;
|
||||
|
||||
/// How many of the session's most recent `events.ndjson` lines the brief carries.
|
||||
const RECENT_EVENTS: usize = 5;
|
||||
|
||||
/// The git argument for the last five commits, one line each.
|
||||
const RECENT_COMMITS: &str = "-5";
|
||||
|
||||
/// How long the one-line next step may run before it is cut.
|
||||
const NEXT_STEP_MAX: usize = 200;
|
||||
|
||||
/// The skill a console workflow runs, as the dashboard launches it.
|
||||
pub fn skill_for_workflow(workflow: &str) -> Option<&'static str> {
|
||||
Some(match workflow {
|
||||
"init" => "plan2code-init",
|
||||
"init-update" => "plan2code-init-update",
|
||||
"pathfinder" => "plan2code-0-pathfinder",
|
||||
"plan" => "plan2code-1-plan",
|
||||
"revise-plan" => "plan2code-1b-revise-plan",
|
||||
"quick-task" => "plan2code-quick-task",
|
||||
"document" => "plan2code-2-document",
|
||||
"implement" => "plan2code-3-implement",
|
||||
"implement-review" => "plan2code-3-implement-review",
|
||||
"review" => "plan2code-review",
|
||||
"finalize" => "plan2code-4-finalize",
|
||||
"handoff" => "plan2code-handoff",
|
||||
"git" => "plan2code-git",
|
||||
"changelog" => "plan2code-changelog",
|
||||
"xray" => "plan2code-xray",
|
||||
"diagnose" => "plan2code-diagnose",
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
/// What the repository looks like now: `git status --short`, and the last
|
||||
/// commits. `None` when the folder is not a git repository.
|
||||
pub struct GitSummary {
|
||||
pub status: String,
|
||||
pub log: String,
|
||||
}
|
||||
|
||||
pub fn git_summary(folder: &Path) -> Option<GitSummary> {
|
||||
let status = git(folder, &["status", "--short"])?;
|
||||
// A repository with no commits yet has no log: the status alone is the record.
|
||||
let log = git(folder, &["log", RECENT_COMMITS, "--oneline"]).unwrap_or_default();
|
||||
Some(GitSummary { status, log })
|
||||
}
|
||||
|
||||
/// Longest a git call may hold up the caller. The brief is built while the
|
||||
/// agent's state is locked, so a slow repository must not stall the window.
|
||||
const GIT_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
fn git(folder: &Path, args: &[&str]) -> Option<String> {
|
||||
let mut command = Command::new("git");
|
||||
command
|
||||
.arg("-C")
|
||||
.arg(folder)
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
|
||||
}
|
||||
let mut child = command.spawn().ok()?;
|
||||
let mut out = child.stdout.take()?;
|
||||
let reader = thread::spawn(move || {
|
||||
let mut bytes = Vec::new();
|
||||
let _ = out.read_to_end(&mut bytes);
|
||||
bytes
|
||||
});
|
||||
let deadline = Instant::now() + GIT_TIMEOUT;
|
||||
let status = loop {
|
||||
if let Some(status) = child.try_wait().ok()? {
|
||||
break status;
|
||||
}
|
||||
if Instant::now() >= deadline {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return None;
|
||||
}
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
let bytes = reader.join().ok()?;
|
||||
status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&bytes).trim_end().to_string())
|
||||
}
|
||||
|
||||
/// The brief as Markdown. `state` is a session's `state.json`; `spec_dir` is
|
||||
/// the spec folder on disk, when the session has one; `git` is the repository
|
||||
/// summary, when the folder is one; `events` is the session's `events.ndjson`,
|
||||
/// oldest first.
|
||||
pub fn build_brief(
|
||||
state: &Value,
|
||||
spec_dir: Option<&Path>,
|
||||
git: Option<&GitSummary>,
|
||||
events: &[Value],
|
||||
) -> String {
|
||||
let workflow = str_field(state, "workflow").unwrap_or("");
|
||||
let skill = skill_for_workflow(workflow);
|
||||
let spec = str_field(state, "specDir");
|
||||
let mut out = String::new();
|
||||
|
||||
out.push_str("## Where you were\n\n");
|
||||
match skill {
|
||||
Some(skill) => out.push_str(&format!("- Skill: {skill} (workflow `{workflow}`)\n")),
|
||||
None => out.push_str(&format!("- Workflow: `{workflow}`\n")),
|
||||
}
|
||||
match spec {
|
||||
Some(spec) => out.push_str(&format!("- Spec: {spec}\n")),
|
||||
None => out.push_str("- Spec: none yet\n"),
|
||||
}
|
||||
out.push('\n');
|
||||
|
||||
out.push_str("## Progress\n\n");
|
||||
let headline = state.get("headline");
|
||||
let stage = headline.and_then(|h| str_field(h, "stage")).unwrap_or("");
|
||||
let cleared = headline
|
||||
.and_then(|h| h.get("cleared"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let total = headline
|
||||
.and_then(|h| h.get("total"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let activity = state
|
||||
.get("agent")
|
||||
.and_then(|a| str_field(a, "activity"))
|
||||
.map(str::trim)
|
||||
.filter(|a| !a.is_empty());
|
||||
if !stage.is_empty() {
|
||||
out.push_str(&format!("{stage}: {cleared} of {total} done.\n"));
|
||||
if let Some(activity) = activity {
|
||||
out.push_str(&format!("Doing: {activity}\n"));
|
||||
}
|
||||
out.push('\n');
|
||||
} else if let Some(activity) = activity {
|
||||
out.push_str(&format!("Doing: {activity}\n\n"));
|
||||
} else {
|
||||
out.push_str("No progress posted yet.\n\n");
|
||||
}
|
||||
|
||||
let items = state
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]);
|
||||
|
||||
out.push_str("### Open questions\n\n");
|
||||
let open: Vec<&Value> = items
|
||||
.iter()
|
||||
.filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened")))
|
||||
.collect();
|
||||
if open.is_empty() {
|
||||
out.push_str("None.\n\n");
|
||||
} else {
|
||||
for item in open {
|
||||
out.push_str(&format!("- {}\n", title_of(item)));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
out.push_str("## Recent answers and decisions\n\n");
|
||||
let answered: Vec<&Value> = items
|
||||
.iter()
|
||||
.filter(|i| str_field(i, "status") == Some("answered"))
|
||||
.collect();
|
||||
let recent = &answered[answered.len().saturating_sub(RECENT_ANSWERS)..];
|
||||
if recent.is_empty() {
|
||||
out.push_str("None yet.\n\n");
|
||||
} else {
|
||||
for item in recent {
|
||||
let answer = answer_text(item);
|
||||
let answer = if answer.is_empty() {
|
||||
"answered".to_string()
|
||||
} else {
|
||||
answer
|
||||
};
|
||||
out.push_str(&format!("- {}: {answer}\n", title_of(item)));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
if let Some(git) = git {
|
||||
out.push_str("## Git\n\n");
|
||||
out.push_str("Changes:\n\n```\n");
|
||||
out.push_str(if git.status.is_empty() {
|
||||
"clean"
|
||||
} else {
|
||||
&git.status
|
||||
});
|
||||
out.push_str("\n```\n\n");
|
||||
if !git.log.is_empty() {
|
||||
out.push_str("Last commits:\n\n```\n");
|
||||
out.push_str(&git.log);
|
||||
out.push_str("\n```\n\n");
|
||||
}
|
||||
}
|
||||
|
||||
if !events.is_empty() {
|
||||
out.push_str("## Recent activity\n\n");
|
||||
let recent = &events[events.len().saturating_sub(RECENT_EVENTS)..];
|
||||
for event in recent {
|
||||
out.push_str(&format!("- {}\n", render_event(event)));
|
||||
}
|
||||
out.push('\n');
|
||||
}
|
||||
|
||||
out.push_str("## Next task\n\n");
|
||||
out.push_str(&next_step(spec_dir, skill));
|
||||
out.push('\n');
|
||||
out
|
||||
}
|
||||
|
||||
/// One `events.ndjson` line, as a terse line for a fresh agent. A shape this
|
||||
/// does not special-case falls back to its raw `type`.
|
||||
fn render_event(event: &Value) -> String {
|
||||
let kind = str_field(event, "type").unwrap_or("event");
|
||||
match kind {
|
||||
"post" => {
|
||||
let items = event.get("items").and_then(Value::as_u64).unwrap_or(0);
|
||||
format!("post ({items} items)")
|
||||
}
|
||||
"consume" => match str_field(event, "kind") {
|
||||
Some(kind) => format!("consume: {kind}"),
|
||||
None => "consume".to_string(),
|
||||
},
|
||||
"open" => {
|
||||
if event
|
||||
.get("resumed")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
"open (resumed)".to_string()
|
||||
} else {
|
||||
"open".to_string()
|
||||
}
|
||||
}
|
||||
other => other.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The one-line next step: the first open task of the spec's in-progress phase
|
||||
/// (or, failing that, the first phase not started); otherwise the skill's name;
|
||||
/// otherwise "Open the dashboard".
|
||||
pub fn next_step(spec_dir: Option<&Path>, skill: Option<&str>) -> String {
|
||||
if let Some(task) = spec_dir.and_then(open_task) {
|
||||
return cut(&task);
|
||||
}
|
||||
match skill {
|
||||
Some(skill) => format!("Continue with {skill}"),
|
||||
None => "Open the dashboard".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The first `- [ ]` task line of the active phase file, as one line of text.
|
||||
fn open_task(spec_dir: &Path) -> Option<String> {
|
||||
let overview = fs::read_to_string(spec_dir.join("overview.md")).ok()?;
|
||||
let phase = active_phase(&overview)?;
|
||||
let text = fs::read_to_string(spec_dir.join(format!("phase-{phase}.md"))).ok()?;
|
||||
let line = text
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.find(|l| l.starts_with("- [ ]"))?;
|
||||
Some(line.trim_start_matches("- [ ]").trim().replace("**", ""))
|
||||
}
|
||||
|
||||
/// The phase number the overview marks in progress (`[/]`), else the first
|
||||
/// one not started (`[ ]`).
|
||||
fn active_phase(overview: &str) -> Option<u32> {
|
||||
let phase_of = |line: &str| {
|
||||
let rest = &line[line.find("phase-")? + "phase-".len()..];
|
||||
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
|
||||
digits.parse::<u32>().ok()
|
||||
};
|
||||
let rows = || {
|
||||
overview
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.filter(|l| l.starts_with("- ["))
|
||||
};
|
||||
rows()
|
||||
.find(|l| l.starts_with("- [/]"))
|
||||
.and_then(phase_of)
|
||||
.or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of))
|
||||
}
|
||||
|
||||
fn cut(text: &str) -> String {
|
||||
let mut out: String = text.chars().take(NEXT_STEP_MAX).collect();
|
||||
if text.chars().count() > NEXT_STEP_MAX {
|
||||
out.push('…');
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn str_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
|
||||
value.get(key).and_then(Value::as_str)
|
||||
}
|
||||
|
||||
fn title_of(item: &Value) -> String {
|
||||
let title = str_field(item, "title")
|
||||
.or_else(|| str_field(item, "id"))
|
||||
.unwrap_or("(untitled)");
|
||||
title.trim().to_string()
|
||||
}
|
||||
|
||||
/// An answer as the person gave it: the option's label for a pick, plus any
|
||||
/// words they typed. Empty when the answer carries nothing to show.
|
||||
fn answer_text(item: &Value) -> String {
|
||||
let Some(answer) = item.get("answer") else {
|
||||
return String::new();
|
||||
};
|
||||
let options = item.get("options").and_then(Value::as_array);
|
||||
let label = |k: &str| {
|
||||
options
|
||||
.and_then(|list| list.iter().find(|o| str_field(o, "k") == Some(k)))
|
||||
.and_then(|o| str_field(o, "text"))
|
||||
.unwrap_or(k)
|
||||
.to_string()
|
||||
};
|
||||
let mut parts: Vec<String> = Vec::new();
|
||||
if let Some(k) = str_field(answer, "k") {
|
||||
parts.push(label(k));
|
||||
}
|
||||
if let Some(list) = answer.get("ks").and_then(Value::as_array) {
|
||||
let picks: Vec<String> = list.iter().filter_map(Value::as_str).map(label).collect();
|
||||
if !picks.is_empty() {
|
||||
parts.push(picks.join(", "));
|
||||
}
|
||||
}
|
||||
if let Some(yes) = answer.get("yes").and_then(Value::as_bool) {
|
||||
parts.push(if yes { "yes" } else { "no" }.to_string());
|
||||
}
|
||||
if let Some(verdict) = str_field(answer, "verdict") {
|
||||
parts.push(verdict.to_string());
|
||||
}
|
||||
if let Some(text) = str_field(answer, "text")
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
{
|
||||
parts.push(text.to_string());
|
||||
}
|
||||
parts.join("; ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use serde_json::json;
|
||||
|
||||
fn fixture(name: &str) -> std::path::PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn mid_implement_spec() -> std::path::PathBuf {
|
||||
let spec = fixture("spec").join("specs").join("feature");
|
||||
fs::create_dir_all(&spec).unwrap();
|
||||
fs::write(
|
||||
spec.join("overview.md"),
|
||||
"- [x] [Phase 1: Foundations](./phase-1.md)\n- [/] [Phase 2: Restart](./phase-2.md)\n- [ ] [Phase 3: Later](./phase-3.md)\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(spec.join("phase-2.md"), "## Tasks\n\n- [x] **Task 2.1:** Done already\n- [ ] **Task 2.2:** Write the **reader**\n- [ ] **Task 2.3:** Later\n").unwrap();
|
||||
spec
|
||||
}
|
||||
|
||||
fn mid_implement_state() -> Value {
|
||||
json!({
|
||||
"schema": 1,
|
||||
"workflow": "implement",
|
||||
"specDir": "specs/feature",
|
||||
"headline": { "stage": "Phase 2: Restart", "cleared": 1, "total": 3 },
|
||||
"items": [
|
||||
{ "id": "q1", "title": "Which format", "status": "answered", "kind": "choice",
|
||||
"options": [{ "k": "A", "text": "Markdown" }, { "k": "B", "text": "Plain text" }],
|
||||
"answer": { "k": "A" } },
|
||||
{ "id": "q2", "title": "Keep the header", "status": "answered", "kind": "confirm", "answer": { "yes": true } },
|
||||
{ "id": "q3", "title": "Anything else?", "status": "open", "kind": "text" }
|
||||
]
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mid_implement_session_carries_every_section() {
|
||||
let spec = mid_implement_spec();
|
||||
let git = GitSummary {
|
||||
status: " M src/lib.rs".to_string(),
|
||||
log: "abc1234 Add the reader".to_string(),
|
||||
};
|
||||
let brief = build_brief(&mid_implement_state(), Some(&spec), Some(&git), &[]);
|
||||
assert!(brief.contains("Skill: plan2code-3-implement (workflow `implement`)"));
|
||||
assert!(brief.contains("Spec: specs/feature"));
|
||||
assert!(brief.contains("Phase 2: Restart: 1 of 3 done."));
|
||||
assert!(brief.contains("### Open questions\n\n- Anything else?"));
|
||||
assert!(brief.contains("- Which format: Markdown"));
|
||||
assert!(brief.contains("- Keep the header: yes"));
|
||||
assert!(brief.contains(" M src/lib.rs"));
|
||||
assert!(brief.contains("abc1234 Add the reader"));
|
||||
assert!(brief.contains("## Next task\n\nTask 2.2: Write the reader"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_names_only_the_last_ten_answers() {
|
||||
let items: Vec<Value> = (0..12)
|
||||
.map(|n| json!({ "id": format!("q{n}"), "title": format!("Question {n}"), "status": "answered", "answer": { "text": format!("Answer {n}") } }))
|
||||
.collect();
|
||||
let state = json!({ "schema": 1, "workflow": "pathfinder", "items": items });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(!brief.contains("Question 0:"));
|
||||
assert!(!brief.contains("Question 1:"));
|
||||
assert!(brief.contains("- Question 2: Answer 2"));
|
||||
assert!(brief.contains("- Question 11: Answer 11"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_pathfinder_session_without_a_spec_says_so() {
|
||||
let state = json!({ "schema": 1, "workflow": "pathfinder", "headline": { "stage": "Charting", "cleared": 2, "total": 5 } });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("Skill: plan2code-0-pathfinder"));
|
||||
assert!(brief.contains("- Spec: none yet"));
|
||||
assert!(!brief.contains("## Git"));
|
||||
assert!(brief.contains("## Next task\n\nContinue with plan2code-0-pathfinder"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_with_no_spec_and_no_skill_opens_the_dashboard() {
|
||||
let state = json!({ "schema": 1, "workflow": "dashboard" });
|
||||
assert!(
|
||||
build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn chat_entries_never_reach_the_brief() {
|
||||
let home = fixture("chat");
|
||||
let dir = home.join("sessions").join("s1");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(
|
||||
dir.join("state.json"),
|
||||
r#"{"schema": 1, "workflow": "implement"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
dir.join("chat.ndjson"),
|
||||
"{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let session = crate::session_reader::load(&home, "s1").unwrap();
|
||||
let brief = build_brief(&session.state, None, None, &[]);
|
||||
assert!(!brief.contains("CHAT-ONLY-WORDS"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_folder_that_is_not_a_repository_has_no_git_summary() {
|
||||
assert!(git_summary(&fixture("not-a-repo")).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_names_what_the_agent_was_doing() {
|
||||
let state = json!({
|
||||
"schema": 1,
|
||||
"workflow": "implement",
|
||||
"headline": { "stage": "Phase 2: Restart", "cleared": 1, "total": 3 },
|
||||
"agent": { "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" },
|
||||
});
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains(
|
||||
"Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_activity_without_a_headline_still_shows() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement", "agent": { "status": "working", "activity": "Reading the spec" } });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("Doing: Reading the spec\n"));
|
||||
assert!(!brief.contains("No progress posted yet."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_empty_activity_falls_back_to_no_progress_posted() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement", "agent": { "status": "idle", "activity": "" } });
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("No progress posted yet."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_names_a_few_recent_events() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
let events = vec![
|
||||
json!({ "at": "2026-10-23T01:00:00.000Z", "type": "listening", "port": 4100 }),
|
||||
json!({ "at": "2026-10-23T01:08:00.000Z", "type": "open", "resumed": true }),
|
||||
json!({ "at": "2026-10-23T01:08:47.152Z", "type": "post", "items": 3 }),
|
||||
json!({ "at": "2026-10-23T01:09:00.000Z", "type": "consume", "kind": "submit" }),
|
||||
];
|
||||
let brief = build_brief(&state, None, None, &events);
|
||||
assert!(brief.contains("## Recent activity\n\n- listening\n- open (resumed)\n- post (3 items)\n- consume: submit\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_the_last_five_events_are_named() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
let events: Vec<Value> = (0..8)
|
||||
.map(|n| json!({ "type": "upload", "id": format!("f{n}") }))
|
||||
.collect();
|
||||
let brief = build_brief(&state, None, None, &events);
|
||||
assert_eq!(brief.matches("- upload\n").count(), RECENT_EVENTS);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_events_means_no_recent_activity_section() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
assert!(!build_brief(&state, None, None, &[]).contains("## Recent activity"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skill_name_maps_to_its_workflow() {
|
||||
assert_eq!(
|
||||
skill_for_workflow("quick-task"),
|
||||
Some("plan2code-quick-task")
|
||||
);
|
||||
assert_eq!(skill_for_workflow("unknown"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,536 @@
|
||||
//! The Node web console as a supervised child: `console.mjs open` starts a
|
||||
//! detached server and prints the session's JSON, `stop` ends it, and a plain
|
||||
//! GET on the session URL is the health check. Knows nothing about Tauri.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::net::{TcpStream, ToSocketAddrs};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::session_reader;
|
||||
|
||||
/// How long a health check waits for the console before calling it dead. The
|
||||
/// server is on loopback, so anything longer is a hang, not a slow network.
|
||||
const HEALTH_TIMEOUT: Duration = Duration::from_secs(3);
|
||||
|
||||
/// The second, longer look a server gets before it is restarted, as the
|
||||
/// console's own `open` gives one: a machine busy with a test run can keep a
|
||||
/// healthy server from answering inside the first.
|
||||
const BUSY_HEALTH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||
|
||||
/// A running console session, as `console.mjs open` reports it.
|
||||
#[derive(Clone, Serialize)]
|
||||
pub struct ConsoleSession {
|
||||
pub sid: String,
|
||||
pub url: String,
|
||||
pub pid: u32,
|
||||
pub port: u16,
|
||||
/// The console says it can be framed by the app. An older one does not
|
||||
/// print this, and its page would be refused in the frame.
|
||||
pub embed: bool,
|
||||
}
|
||||
|
||||
/// What the person is told when the installed console is too old for the app.
|
||||
pub const OLD_CONSOLE: &str =
|
||||
"The installed Plan2Code console is too old to show inside the app. Press Update skills, then try again.";
|
||||
|
||||
/// One supervised console for one project folder.
|
||||
pub struct ConsoleSupervisor {
|
||||
console_dir: PathBuf,
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
session: ConsoleSession,
|
||||
stopped: bool,
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
/// A `node console.mjs ...` call with no console window on Windows: the app is
|
||||
/// a GUI program, so a bare Command would flash one open per call.
|
||||
fn node_command(console_dir: &Path) -> Command {
|
||||
let mut command = Command::new("node");
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
// directories (Task 9.9): run `node` with the PATH that finds it anyway.
|
||||
command.env("PATH", crate::node_check::resolved_path());
|
||||
command.arg(console_dir.join("console.mjs"));
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command
|
||||
}
|
||||
|
||||
/// The origin the app's own page has, which is what the console's embed mode
|
||||
/// must be told to allow as the frame parent. Tauri serves the page on
|
||||
/// `http://tauri.localhost` on Windows (and Android) and `tauri://localhost`
|
||||
/// on macOS and Linux.
|
||||
pub fn app_origin() -> &'static str {
|
||||
if cfg!(windows) {
|
||||
"http://tauri.localhost"
|
||||
} else {
|
||||
"tauri://localhost"
|
||||
}
|
||||
}
|
||||
|
||||
/// The origin (`scheme://host[:port]`) of the app page's own URL, which is what
|
||||
/// the console's embed mode must allow as the frame parent. In a release build
|
||||
/// that is `app_origin()`, but `tauri dev` serves the page from its own dev
|
||||
/// server on a loopback port, so the real URL is asked rather than assumed.
|
||||
pub fn origin_of(url: &str) -> Option<String> {
|
||||
let (scheme, rest) = url.split_once("://")?;
|
||||
let authority = rest.split(['/', '?', '#']).next()?;
|
||||
if authority.is_empty() || !matches!(scheme, "http" | "https" | "tauri") {
|
||||
return None;
|
||||
}
|
||||
Some(format!("{scheme}://{authority}"))
|
||||
}
|
||||
|
||||
/// Where the installed console lives: an explicit override first (tests and
|
||||
/// dev), then the file the console keeps for the app, then the skill install.
|
||||
pub fn find_console_dir() -> Result<PathBuf, String> {
|
||||
let has_console = |dir: &Path| dir.join("console.mjs").is_file();
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_CONSOLE_DIR") {
|
||||
let dir = PathBuf::from(dir);
|
||||
if has_console(&dir) {
|
||||
return Ok(dir);
|
||||
}
|
||||
}
|
||||
// The console writes its pointer under PLAN2CODE_CONSOLE_HOME when that
|
||||
// relocates it, else under ~/.plan2code/console.
|
||||
let pointer = match std::env::var("PLAN2CODE_CONSOLE_HOME") {
|
||||
Ok(home) => PathBuf::from(home).join("console-dir"),
|
||||
Err(_) => {
|
||||
let home = std::env::home_dir().ok_or("no home folder found")?;
|
||||
home.join(".plan2code").join("console").join("console-dir")
|
||||
}
|
||||
};
|
||||
if let Ok(text) = std::fs::read_to_string(&pointer) {
|
||||
let dir = PathBuf::from(text.trim());
|
||||
if has_console(&dir) {
|
||||
return Ok(dir);
|
||||
}
|
||||
}
|
||||
let dir = std::env::home_dir()
|
||||
.ok_or("no home folder found")?
|
||||
.join(".agents")
|
||||
.join("skills")
|
||||
.join("plan2code")
|
||||
.join("references")
|
||||
.join("web-console");
|
||||
if has_console(&dir) {
|
||||
return Ok(dir);
|
||||
}
|
||||
Err(format!(
|
||||
"the web console is not installed (looked in $PLAN2CODE_CONSOLE_DIR, {} and {})",
|
||||
pointer.display(),
|
||||
dir.display()
|
||||
))
|
||||
}
|
||||
|
||||
/// Parse the one JSON object `console.mjs open` prints on stdout.
|
||||
fn parse_open_output(stdout: &[u8]) -> Result<ConsoleSession, String> {
|
||||
let text = String::from_utf8_lossy(stdout);
|
||||
let line = text
|
||||
.lines()
|
||||
.rev()
|
||||
.find(|l| l.trim_start().starts_with('{'))
|
||||
.ok_or_else(|| format!("console open printed no JSON: {}", text.trim()))?;
|
||||
let value: serde_json::Value = serde_json::from_str(line.trim()).map_err(err)?;
|
||||
let get = |key: &str| value.get(key).and_then(|v| v.as_str().map(String::from));
|
||||
let num = |key: &str| value.get(key).and_then(|v| v.as_u64());
|
||||
Ok(ConsoleSession {
|
||||
sid: get("sid").ok_or("console open: no sid in output")?,
|
||||
url: get("url").ok_or("console open: no url in output")?,
|
||||
pid: num("pid").ok_or("console open: no pid in output")? as u32,
|
||||
port: num("port").ok_or("console open: no port in output")? as u16,
|
||||
embed: num("embed").is_some_and(|n| n >= 1),
|
||||
})
|
||||
}
|
||||
|
||||
/// Split `http://<host>:<port><path>` into its parts; the console only ever
|
||||
/// listens on loopback http.
|
||||
fn split_url(url: &str) -> Result<(String, u16, String), String> {
|
||||
let rest = url
|
||||
.strip_prefix("http://")
|
||||
.ok_or_else(|| format!("not an http url: {url}"))?;
|
||||
let (authority, path) = match rest.split_once('/') {
|
||||
Some((a, p)) => (a, format!("/{p}")),
|
||||
None => (rest, "/".to_string()),
|
||||
};
|
||||
let (host, port) = authority
|
||||
.rsplit_once(':')
|
||||
.ok_or_else(|| format!("no port in url: {url}"))?;
|
||||
let port: u16 = port
|
||||
.parse()
|
||||
.map_err(|_| format!("bad port in url: {url}"))?;
|
||||
Ok((host.to_string(), port, path))
|
||||
}
|
||||
|
||||
impl ConsoleSupervisor {
|
||||
/// Find the installed console, run `open --workflow dashboard --no-open` in
|
||||
/// the project folder with `PLAN2CODE_EMBED_ORIGIN` set, and keep the
|
||||
/// session it prints.
|
||||
pub fn start(project_dir: PathBuf, embed_origin: String) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?;
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// `open` for the dashboard, or, with `resume`, the same session again on
|
||||
/// a new server (so the page and its place in a skill survive a dead server).
|
||||
/// A console the agent's `open` started and announced: this supervisor
|
||||
/// now owns its health and its stop, though it did not start it.
|
||||
pub fn adopt(
|
||||
project_dir: PathBuf,
|
||||
embed_origin: String,
|
||||
url: &str,
|
||||
sid: &str,
|
||||
) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let (_, port, _) = split_url(url)?;
|
||||
let session = ConsoleSession {
|
||||
sid: sid.to_string(),
|
||||
url: url.to_string(),
|
||||
pid: 0,
|
||||
port,
|
||||
embed: true,
|
||||
};
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn open_session(
|
||||
console_dir: &Path,
|
||||
project_dir: &Path,
|
||||
embed_origin: &str,
|
||||
resume: Option<&str>,
|
||||
) -> Result<ConsoleSession, String> {
|
||||
let mut command = node_command(console_dir);
|
||||
command.arg("open");
|
||||
match resume {
|
||||
Some(sid) => command.args(["--resume", sid, "--no-open"]),
|
||||
None => command.args(["--workflow", "dashboard", "--no-open"]),
|
||||
};
|
||||
let output = command
|
||||
.current_dir(project_dir)
|
||||
.env("PLAN2CODE_EMBED_ORIGIN", embed_origin)
|
||||
.output()
|
||||
.map_err(err)?;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"console open failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
let session = parse_open_output(&output.stdout)?;
|
||||
if !session.embed {
|
||||
// Do not leave an old console running that the frame cannot show.
|
||||
let _ = node_command(console_dir)
|
||||
.args(["stop", "--session", &session.sid])
|
||||
.current_dir(project_dir)
|
||||
.output();
|
||||
return Err(OLD_CONSOLE.to_string());
|
||||
}
|
||||
Ok(session)
|
||||
}
|
||||
|
||||
pub fn session(&self) -> &ConsoleSession {
|
||||
&self.session
|
||||
}
|
||||
|
||||
/// The console moved to another address or session (an announced page that
|
||||
/// is not the one this supervisor opened): health, stop and the restart
|
||||
/// brief follow it from now on.
|
||||
pub fn follow(&mut self, url: &str, sid: &str) {
|
||||
if self.session.url == url && self.session.sid == sid {
|
||||
return;
|
||||
}
|
||||
if let Ok((_, port, _)) = split_url(url) {
|
||||
self.session.port = port;
|
||||
}
|
||||
self.session.url = url.to_string();
|
||||
self.session.sid = sid.to_string();
|
||||
}
|
||||
|
||||
/// Was `stop()` called on this supervisor.
|
||||
pub fn stopped(&self) -> bool {
|
||||
self.stopped
|
||||
}
|
||||
|
||||
/// A GET on the session URL: any HTTP answer means the server is alive.
|
||||
pub fn health(&self) -> bool {
|
||||
self.health_within(HEALTH_TIMEOUT)
|
||||
}
|
||||
|
||||
fn health_within(&self, timeout: Duration) -> bool {
|
||||
if self.stopped {
|
||||
return false;
|
||||
}
|
||||
let Ok((host, port, path)) = split_url(&self.session.url) else {
|
||||
return false;
|
||||
};
|
||||
let Some(addr) = (host.as_str(), port)
|
||||
.to_socket_addrs()
|
||||
.ok()
|
||||
.and_then(|mut a| a.next())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
let Ok(mut stream) = TcpStream::connect_timeout(&addr, timeout) else {
|
||||
return false;
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(timeout));
|
||||
let _ = stream.set_write_timeout(Some(timeout));
|
||||
let request = format!("GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n");
|
||||
if stream.write_all(request.as_bytes()).is_err() {
|
||||
return false;
|
||||
}
|
||||
let mut status = [0u8; 64];
|
||||
match stream.read(&mut status) {
|
||||
Ok(n) => String::from_utf8_lossy(&status[..n]).starts_with("HTTP/"),
|
||||
Err(_) => false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Health check plus a fresh `open` when the server is gone. Returns true
|
||||
/// when a new session was started. Never loops: the caller (the bar) asks
|
||||
/// and shows the outcome.
|
||||
pub fn restart_if_dead(&mut self) -> Result<bool, String> {
|
||||
if self.stopped || self.health() || self.health_within(BUSY_HEALTH_TIMEOUT) {
|
||||
return Ok(false);
|
||||
}
|
||||
let sid = self.session.sid.clone();
|
||||
let on_disk = session_on_disk(&sid);
|
||||
let (console_dir, project_dir, embed_origin) =
|
||||
(&self.console_dir, &self.project_dir, &self.embed_origin);
|
||||
self.session = resume_or_fresh(&sid, on_disk, |resume| {
|
||||
Self::open_session(console_dir, project_dir, embed_origin, resume)
|
||||
})?;
|
||||
self.stopped = false;
|
||||
Ok(true)
|
||||
}
|
||||
|
||||
/// `console.mjs stop --session <sid>`: the console's own orderly shutdown.
|
||||
pub fn stop(&mut self) -> Result<(), String> {
|
||||
if self.stopped {
|
||||
return Ok(());
|
||||
}
|
||||
let output = node_command(&self.console_dir)
|
||||
.args(["stop", "--session", &self.session.sid])
|
||||
.current_dir(&self.project_dir)
|
||||
.output()
|
||||
.map_err(err)?;
|
||||
self.stopped = true;
|
||||
if !output.status.success() {
|
||||
return Err(format!(
|
||||
"console stop failed: {}",
|
||||
String::from_utf8_lossy(&output.stderr).trim()
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Is the session's folder still in the console's home. Unknown (no home
|
||||
/// directory) counts as there, so the answer never throws a session away. A
|
||||
/// sid that is not a plain folder name (empty, `..`, a path) is never there.
|
||||
pub fn session_on_disk(sid: &str) -> bool {
|
||||
if Path::new(sid).file_name() != Some(std::ffi::OsStr::new(sid)) {
|
||||
return false;
|
||||
}
|
||||
session_reader::console_home()
|
||||
.is_none_or(|home| session_reader::session_dir(&home, sid).is_dir())
|
||||
}
|
||||
|
||||
/// The same session, so the page and a skill's place in it survive, tried
|
||||
/// twice. Only a session gone from disk starts a new one: falling back to a
|
||||
/// fresh dashboard while the folder is still there once swapped a build's page
|
||||
/// for an empty dashboard mid-run, and the agent went on posting to a session
|
||||
/// the window no longer showed. A failure is the bar's to report, with Retry.
|
||||
fn resume_or_fresh<F>(sid: &str, on_disk: bool, mut open: F) -> Result<ConsoleSession, String>
|
||||
where
|
||||
F: FnMut(Option<&str>) -> Result<ConsoleSession, String>,
|
||||
{
|
||||
if !on_disk {
|
||||
return open(None);
|
||||
}
|
||||
open(Some(sid)).or_else(|_| open(Some(sid)))
|
||||
}
|
||||
|
||||
impl Drop for ConsoleSupervisor {
|
||||
/// The app going away takes the console it started with it. `stop` is
|
||||
/// idempotent, so a session ended by hand just returns early here.
|
||||
fn drop(&mut self) {
|
||||
let _ = self.stop();
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn splits_the_session_url() {
|
||||
let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap();
|
||||
assert_eq!(
|
||||
(host.as_str(), port, path.as_str()),
|
||||
("127.0.0.1", 51617, "/s/abc/")
|
||||
);
|
||||
let (_, _, path) = split_url("http://localhost:9").unwrap();
|
||||
assert_eq!(path, "/");
|
||||
assert!(split_url("https://127.0.0.1:1/x").is_err());
|
||||
assert!(split_url("http://127.0.0.1/x").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn origin_comes_from_the_pages_own_url() {
|
||||
assert_eq!(
|
||||
origin_of("http://127.0.0.1:1430/index.html").as_deref(),
|
||||
Some("http://127.0.0.1:1430")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("http://tauri.localhost/").as_deref(),
|
||||
Some("http://tauri.localhost")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("https://tauri.localhost").as_deref(),
|
||||
Some("https://tauri.localhost")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("tauri://localhost/index.html?x=1").as_deref(),
|
||||
Some("tauri://localhost")
|
||||
);
|
||||
assert_eq!(origin_of("file:///x"), None);
|
||||
assert_eq!(origin_of("not a url"), None);
|
||||
assert_eq!(origin_of("http:///x"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_announced_console_is_adopted_with_its_port() {
|
||||
// Only needs a console to be installed; skipped where there is none.
|
||||
let Ok(dir) = find_console_dir() else { return };
|
||||
let _ = dir;
|
||||
let mut sup = ConsoleSupervisor::adopt(
|
||||
PathBuf::from("."),
|
||||
"http://tauri.localhost".into(),
|
||||
"http://127.0.0.1:5555/s/t/",
|
||||
"sid-9",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(sup.session().port, sup.session().sid.as_str()),
|
||||
(5555, "sid-9")
|
||||
);
|
||||
assert!(sup.session().embed);
|
||||
assert!(
|
||||
ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err()
|
||||
);
|
||||
sup.follow("http://127.0.0.1:6000/s/u/", "sid-10");
|
||||
assert_eq!(
|
||||
(sup.session().port, sup.session().sid.as_str()),
|
||||
(6000, "sid-10")
|
||||
);
|
||||
// Never started a server here: nothing for Drop to stop.
|
||||
sup.stopped = true;
|
||||
}
|
||||
|
||||
fn opened(sid: &str) -> ConsoleSession {
|
||||
ConsoleSession {
|
||||
sid: sid.to_string(),
|
||||
url: "http://127.0.0.1:5/s/t/".into(),
|
||||
pid: 1,
|
||||
port: 5,
|
||||
embed: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_plain_folder_name_can_be_a_session_on_disk() {
|
||||
// `<home>/sessions/` and `<home>` are folders too: these must not pass.
|
||||
for sid in ["", ".", "..", "../x", "a/b", "a\\b"] {
|
||||
assert!(!session_on_disk(sid), "{sid:?} counted as a session");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_resume_of_a_session_still_on_disk_never_opens_a_fresh_dashboard() {
|
||||
// A build's console that was slow to answer: swapping its page for a
|
||||
// new dashboard left the agent posting to a session nobody could see.
|
||||
let mut calls = Vec::new();
|
||||
let result = resume_or_fresh("s1", true, |resume| {
|
||||
calls.push(resume.map(str::to_string));
|
||||
Err("busy".to_string())
|
||||
});
|
||||
assert!(result.is_err(), "the failure is reported, not papered over");
|
||||
assert!(
|
||||
calls.iter().all(|c| c.as_deref() == Some("s1")),
|
||||
"only ever resumed: {calls:?}"
|
||||
);
|
||||
assert_eq!(calls.len(), 2, "the resume is tried twice");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_resume_that_works_the_second_time_keeps_the_session() {
|
||||
let mut tries = 0;
|
||||
let session = resume_or_fresh("s1", true, |resume| {
|
||||
tries += 1;
|
||||
assert_eq!(resume, Some("s1"));
|
||||
if tries == 1 {
|
||||
Err("busy".to_string())
|
||||
} else {
|
||||
Ok(opened("s1"))
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.sid, "s1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_gone_from_disk_starts_a_fresh_dashboard() {
|
||||
let mut calls = Vec::new();
|
||||
let session = resume_or_fresh("s1", false, |resume| {
|
||||
calls.push(resume.map(str::to_string));
|
||||
Ok(opened(if resume.is_some() { "s1" } else { "s2" }))
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.sid, "s2");
|
||||
assert_eq!(calls, vec![None], "nothing on disk to resume");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_open_output() {
|
||||
let json =
|
||||
br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1}
|
||||
"#;
|
||||
let session = parse_open_output(json).unwrap();
|
||||
assert_eq!(
|
||||
(session.sid.as_str(), session.port, session.pid),
|
||||
("s1", 5, 42)
|
||||
);
|
||||
assert!(session.embed);
|
||||
let old = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42}"#;
|
||||
assert!(
|
||||
!parse_open_output(old).unwrap().embed,
|
||||
"a console that does not say it embeds is too old"
|
||||
);
|
||||
assert!(parse_open_output(b"not json\n").is_err());
|
||||
assert!(parse_open_output(br#"{"ok":true,"sid":"s1"}"#).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,270 @@
|
||||
//! Writes a handoff the dashboard already knows how to list: a `.md` document
|
||||
//! and its `.json` record in `~/.plan2code/handoffs/`, in the shape
|
||||
//! `src/web-console/handoffs.mjs` reads (`v: 1`, the local-minute id, `usedAt`
|
||||
//! null). The console is not changed for this, so the dashboard's **Pick it up
|
||||
//! here** chip appears as it does for a handoff the Handoff skill wrote.
|
||||
|
||||
use std::fs::{self, OpenOptions};
|
||||
use std::io::Write;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use chrono::{DateTime, Datelike, Local, SecondsFormat, Timelike, Utc};
|
||||
use serde_json::json;
|
||||
|
||||
/// `~/.plan2code/handoffs`, or `PLAN2CODE_HANDOFFS_DIR` when it is moved.
|
||||
pub fn handoffs_dir() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_HANDOFFS_DIR") {
|
||||
return Some(PathBuf::from(dir));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("handoffs"))
|
||||
}
|
||||
|
||||
/// What the dashboard needs to resume the session the handoff came from.
|
||||
pub struct Record<'a> {
|
||||
pub title: &'a str,
|
||||
pub worktree: &'a str,
|
||||
pub project: &'a str,
|
||||
/// `specs/<name>`, or none.
|
||||
pub spec: Option<&'a str>,
|
||||
pub workflow: &'a str,
|
||||
pub skill: &'a str,
|
||||
}
|
||||
|
||||
/// Write `body` as the handoff's document and the record beside it, under an
|
||||
/// id made from `when`'s local minute. Returns the id. The record is claimed
|
||||
/// exclusively, so two writes in the same minute never share an id; a failed
|
||||
/// write leaves nothing behind.
|
||||
pub fn write(
|
||||
dir: &Path,
|
||||
when: DateTime<Local>,
|
||||
record: &Record,
|
||||
body: &str,
|
||||
) -> Result<String, String> {
|
||||
validate(record)?;
|
||||
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
let base = format!(
|
||||
"{:04}-{:02}-{:02}-{:02}{:02}-handoff",
|
||||
when.year(),
|
||||
when.month(),
|
||||
when.day(),
|
||||
when.hour(),
|
||||
when.minute()
|
||||
);
|
||||
let written = when
|
||||
.with_timezone(&Utc)
|
||||
.to_rfc3339_opts(SecondsFormat::Millis, true);
|
||||
for n in 1.. {
|
||||
let id = if n == 1 {
|
||||
base.clone()
|
||||
} else {
|
||||
format!("{base}-{n}")
|
||||
};
|
||||
let md = dir.join(format!("{id}.md"));
|
||||
let json_file = dir.join(format!("{id}.json"));
|
||||
if md.exists() {
|
||||
continue;
|
||||
}
|
||||
let mut claim = match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&json_file)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e.to_string()),
|
||||
};
|
||||
let meta = json!({
|
||||
"v": 1,
|
||||
"id": id,
|
||||
"title": record.title,
|
||||
"worktree": record.worktree,
|
||||
"project": record.project,
|
||||
"spec": record.spec,
|
||||
"workflow": record.workflow,
|
||||
"skill": record.skill,
|
||||
"written": written,
|
||||
"fromStop": false,
|
||||
"usedAt": null,
|
||||
});
|
||||
let text = serde_json::to_string_pretty(&meta).map_err(|e| e.to_string())? + "\n";
|
||||
if let Err(e) = claim.write_all(text.as_bytes()) {
|
||||
let _ = fs::remove_file(&json_file);
|
||||
return Err(e.to_string());
|
||||
}
|
||||
if let Err(e) = write_document(&md, &title_line(record.title), body) {
|
||||
let _ = fs::remove_file(&json_file);
|
||||
return Err(e);
|
||||
}
|
||||
return Ok(id);
|
||||
}
|
||||
unreachable!("the id loop only ends by returning")
|
||||
}
|
||||
|
||||
fn write_document(md: &Path, heading: &str, body: &str) -> Result<(), String> {
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(md)
|
||||
.map_err(|e| e.to_string())?;
|
||||
file.write_all(format!("{heading}\n\n{body}").as_bytes())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn title_line(title: &str) -> String {
|
||||
format!("# Handoff: {title}")
|
||||
}
|
||||
|
||||
/// Delete a handoff the person has not picked up (its record has no `usedAt`),
|
||||
/// both files. A picked-up one, or one already gone, is left alone.
|
||||
pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> {
|
||||
let json_file = dir.join(format!("{id}.json"));
|
||||
let Ok(text) = fs::read_to_string(&json_file) else {
|
||||
return Ok(());
|
||||
};
|
||||
let used = serde_json::from_str::<serde_json::Value>(&text)
|
||||
.ok()
|
||||
.is_some_and(|meta| !meta["usedAt"].is_null());
|
||||
if used {
|
||||
return Ok(());
|
||||
}
|
||||
for file in [json_file, dir.join(format!("{id}.md"))] {
|
||||
match fs::remove_file(&file) {
|
||||
Ok(()) => {}
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e.to_string()),
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The same rules the console applies to the record, so a bad field is refused
|
||||
/// here rather than written and then ignored.
|
||||
fn validate(record: &Record) -> Result<(), String> {
|
||||
let lower_dashes =
|
||||
|s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-');
|
||||
if !lower_dashes(record.workflow) {
|
||||
return Err(format!(
|
||||
"workflow must be lowercase letters and dashes, got {:?}",
|
||||
record.workflow
|
||||
));
|
||||
}
|
||||
let skill_ok = !record.skill.is_empty()
|
||||
&& record
|
||||
.skill
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
|
||||
if !skill_ok {
|
||||
return Err(format!(
|
||||
"skill must be a skill name, got {:?}",
|
||||
record.skill
|
||||
));
|
||||
}
|
||||
if let Some(spec) = record.spec {
|
||||
let name = spec.strip_prefix("specs/");
|
||||
if name.is_none_or(|n| {
|
||||
n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\')
|
||||
}) {
|
||||
return Err(format!("spec must be specs/<name>, got {spec:?}"));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The clock's local time, for the id. Tests pass their own.
|
||||
pub fn now() -> DateTime<Local> {
|
||||
Local::now()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
|
||||
fn record() -> Record<'static> {
|
||||
Record {
|
||||
title: "Restart of plan2code-3-implement",
|
||||
worktree: "C:\\git\\plan2code",
|
||||
project: "C:\\git\\plan2code",
|
||||
spec: Some("specs/feature"),
|
||||
workflow: "implement",
|
||||
skill: "plan2code-3-implement",
|
||||
}
|
||||
}
|
||||
|
||||
fn at(hour: u32, minute: u32) -> DateTime<Local> {
|
||||
Local
|
||||
.with_ymd_and_hms(2026, 10, 21, hour, minute, 0)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_record_has_the_shape_the_dashboard_reads() {
|
||||
let dir = fixture("shape");
|
||||
let id = write(&dir, at(13, 52), &record(), "## Next task\n\nTask 5.2").unwrap();
|
||||
assert_eq!(id, "2026-10-21-1352-handoff");
|
||||
let meta: serde_json::Value =
|
||||
serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(meta["v"], 1);
|
||||
assert_eq!(meta["id"], id.as_str());
|
||||
assert_eq!(meta["workflow"], "implement");
|
||||
assert_eq!(meta["skill"], "plan2code-3-implement");
|
||||
assert_eq!(meta["spec"], "specs/feature");
|
||||
assert_eq!(meta["fromStop"], false);
|
||||
assert!(meta["usedAt"].is_null());
|
||||
assert!(meta["written"].as_str().unwrap().ends_with('Z'));
|
||||
let doc = fs::read_to_string(dir.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.starts_with("# Handoff: Restart of plan2code-3-implement\n\n"));
|
||||
assert!(doc.contains("## Next task"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_write_in_the_same_minute_takes_the_next_id() {
|
||||
let dir = fixture("clash");
|
||||
let first = write(&dir, at(9, 0), &record(), "one").unwrap();
|
||||
let second = write(&dir, at(9, 0), &record(), "two").unwrap();
|
||||
assert_eq!(first, "2026-10-21-0900-handoff");
|
||||
assert_eq!(second, "2026-10-21-0900-handoff-2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_bad_workflow_is_refused_before_anything_is_written() {
|
||||
let dir = fixture("bad");
|
||||
let mut bad = record();
|
||||
bad.workflow = "Implement";
|
||||
assert!(write(&dir, at(9, 0), &bad, "x").is_err());
|
||||
assert!(!dir.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unused_handoff_is_retired_and_a_picked_up_one_is_kept() {
|
||||
let dir = fixture("retire");
|
||||
let unused = write(&dir, at(10, 0), &record(), "one").unwrap();
|
||||
let used = write(&dir, at(10, 1), &record(), "two").unwrap();
|
||||
fs::write(
|
||||
dir.join(format!("{used}.json")),
|
||||
r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
retire_if_unused(&dir, &unused).unwrap();
|
||||
retire_if_unused(&dir, &used).unwrap();
|
||||
assert!(!dir.join(format!("{unused}.json")).exists());
|
||||
assert!(!dir.join(format!("{unused}.md")).exists());
|
||||
assert!(dir.join(format!("{used}.json")).exists());
|
||||
assert!(dir.join(format!("{used}.md")).exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spec_must_be_one_folder_under_specs() {
|
||||
let mut bad = record();
|
||||
bad.spec = Some("specs/a/b");
|
||||
assert!(validate(&bad).is_err());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
//! The parts of the app that tests reach directly.
|
||||
|
||||
pub mod agent_manager;
|
||||
pub mod agents;
|
||||
pub mod announce;
|
||||
pub mod attention;
|
||||
pub mod brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod handoff;
|
||||
pub mod node_check;
|
||||
pub mod project;
|
||||
pub mod pty_host;
|
||||
pub mod restart_brief;
|
||||
pub mod session_reader;
|
||||
pub mod settings;
|
||||
pub mod versions;
|
||||
@@ -0,0 +1,342 @@
|
||||
//! The Node 18+ check (FR-13). The console and the skills run on Node, so the
|
||||
//! app refuses to start without it and says what to install.
|
||||
//!
|
||||
//! An app started from the Dock, Finder or a `.desktop` file, rather than a
|
||||
//! terminal, inherits a minimal PATH: none of nvm, Homebrew or Volta's
|
||||
//! directories, which a login shell's own profile adds. `resolved_path`
|
||||
//! (Task 9.9) is what every process this app spawns (the console, an update,
|
||||
//! an agent CLI) should run with, not the bare inherited one; `node_check`,
|
||||
//! `console_supervisor`, `versions` and `agents` all use it.
|
||||
|
||||
use std::process::Command;
|
||||
use std::sync::Mutex;
|
||||
|
||||
pub const MIN_NODE_MAJOR: u32 = 18;
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum NodeStatus {
|
||||
Ok(String),
|
||||
TooOld(String),
|
||||
Missing,
|
||||
}
|
||||
|
||||
/// Major version from `node --version` output such as `v20.11.1`.
|
||||
pub fn parse_node_major(output: &str) -> Option<u32> {
|
||||
let text = output.trim().strip_prefix('v')?;
|
||||
text.split('.').next()?.parse().ok()
|
||||
}
|
||||
|
||||
/// Classify the output of `node --version`.
|
||||
pub fn classify(output: &str) -> NodeStatus {
|
||||
let version = output.trim().to_string();
|
||||
match parse_node_major(output) {
|
||||
Some(major) if major >= MIN_NODE_MAJOR => NodeStatus::Ok(version),
|
||||
Some(_) => NodeStatus::TooOld(version),
|
||||
None => NodeStatus::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn check_node() -> NodeStatus {
|
||||
match Command::new("node")
|
||||
.env("PATH", resolved_path())
|
||||
.arg("--version")
|
||||
.output()
|
||||
{
|
||||
Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)),
|
||||
_ => NodeStatus::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
/// `--node <path>` or `--node=<path>`: the launcher's own `node`, already
|
||||
/// resolved under the person's real shell. Only its directory is used here,
|
||||
/// so it joins the PATH the normal way rather than replacing every lookup.
|
||||
fn node_override_dir(args: &[String]) -> Option<String> {
|
||||
let mut i = 1; // args[0] is the program name
|
||||
while i < args.len() {
|
||||
let value = if args[i] == "--node" {
|
||||
args.get(i + 1).cloned()
|
||||
} else {
|
||||
args[i].strip_prefix("--node=").map(str::to_string)
|
||||
};
|
||||
if let Some(path) = value.filter(|v| !v.is_empty()) {
|
||||
return std::path::Path::new(&path)
|
||||
.parent()
|
||||
.map(|dir| dir.to_string_lossy().into_owned());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// The login shell's own PATH: running it as a login shell sources
|
||||
/// `.zprofile`, `.bash_profile` or `.profile`, which a GUI launch never does.
|
||||
/// Windows sets PATH outside any shell's startup files, so this is unix only.
|
||||
#[cfg(unix)]
|
||||
fn login_shell_path() -> Option<String> {
|
||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
|
||||
let out = Command::new(&shell)
|
||||
.args(["-lc", "echo $PATH"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let path = String::from_utf8_lossy(&out.stdout).trim().to_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. 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> {
|
||||
let (program, arg) = if cfg!(windows) {
|
||||
("where", "node")
|
||||
} else {
|
||||
("which", "node")
|
||||
};
|
||||
let out = Command::new(program)
|
||||
.env("PATH", resolved_path())
|
||||
.arg(arg)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.next()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// The plain message shown when the check fails; `None` when Node is fine.
|
||||
pub fn problem_message(status: &NodeStatus) -> Option<String> {
|
||||
match status {
|
||||
NodeStatus::Ok(_) => None,
|
||||
NodeStatus::TooOld(v) => Some(format!(
|
||||
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and this computer has {v}.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
|
||||
)),
|
||||
NodeStatus::Missing => Some(format!(
|
||||
"Plan2Code needs Node.js {MIN_NODE_MAJOR} or newer, and it was not found.\n\nInstall the current LTS release from https://nodejs.org and start Plan2Code again."
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn accepts_node_18_and_newer() {
|
||||
assert_eq!(classify("v18.0.0\n"), NodeStatus::Ok("v18.0.0".into()));
|
||||
assert_eq!(classify("v20.11.1"), NodeStatus::Ok("v20.11.1".into()));
|
||||
assert_eq!(classify("v24.12.0\r\n"), NodeStatus::Ok("v24.12.0".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_node_older_than_18() {
|
||||
assert_eq!(classify("v16.20.2"), NodeStatus::TooOld("v16.20.2".into()));
|
||||
assert_eq!(classify("v17.9.1"), NodeStatus::TooOld("v17.9.1".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn treats_garbage_as_missing() {
|
||||
assert_eq!(classify("not a version"), NodeStatus::Missing);
|
||||
assert_eq!(classify(""), NodeStatus::Missing);
|
||||
assert_eq!(classify("v"), NodeStatus::Missing);
|
||||
assert_eq!(classify("vx.1.2"), NodeStatus::Missing);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn message_only_for_a_problem() {
|
||||
assert!(problem_message(&NodeStatus::Ok("v20.0.0".into())).is_none());
|
||||
assert!(problem_message(&NodeStatus::Missing)
|
||||
.unwrap()
|
||||
.contains("nodejs.org"));
|
||||
assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into()))
|
||||
.unwrap()
|
||||
.contains("v16.0.0"));
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app")
|
||||
.chain(list.iter().copied())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_node_override_names_its_directory_in_both_forms() {
|
||||
let want = if cfg!(windows) {
|
||||
"C:\\nvm\\v20"
|
||||
} else {
|
||||
"/home/x/.nvm/v20"
|
||||
};
|
||||
let bin = if cfg!(windows) {
|
||||
"C:\\nvm\\v20\\node.exe"
|
||||
} else {
|
||||
"/home/x/.nvm/v20/node"
|
||||
};
|
||||
assert_eq!(
|
||||
node_override_dir(&args(&["--node", bin])).as_deref(),
|
||||
Some(want)
|
||||
);
|
||||
assert_eq!(
|
||||
node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(),
|
||||
Some(want)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_override_or_a_missing_value_is_none() {
|
||||
assert_eq!(node_override_dir(&args(&[])), None);
|
||||
assert_eq!(node_override_dir(&args(&["--node"])), None);
|
||||
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));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,290 @@
|
||||
//! Which project folder the app works on: the folder the launcher passes in,
|
||||
//! else the one the launcher remembers, else the person picks. The launcher's
|
||||
//! memory is `~/.plan2code/launcher.json` (`lastFolder`, `lastCli`), shared so
|
||||
//! the app and `plan2code` agree on both.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents;
|
||||
|
||||
/// Where the project folder came from, in the order it is tried.
|
||||
#[derive(Clone, Copy, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum ProjectSource {
|
||||
Argument,
|
||||
Remembered,
|
||||
Picked,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ProjectDir {
|
||||
pub dir: PathBuf,
|
||||
pub source: ProjectSource,
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
fn launcher_file() -> Option<PathBuf> {
|
||||
Some(
|
||||
std::env::home_dir()?
|
||||
.join(".plan2code")
|
||||
.join("launcher.json"),
|
||||
)
|
||||
}
|
||||
|
||||
fn read_launcher() -> serde_json::Map<String, serde_json::Value> {
|
||||
launcher_file()
|
||||
.and_then(|file| std::fs::read_to_string(file).ok())
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The folder the launcher remembers, when it is still a directory.
|
||||
fn remembered_folder() -> Option<PathBuf> {
|
||||
let dir = PathBuf::from(read_launcher().get("lastFolder")?.as_str()?);
|
||||
dir.is_dir().then_some(dir)
|
||||
}
|
||||
|
||||
/// The id of the agent the launcher last ran (it may be a custom one). The
|
||||
/// bar's picker starts on it until the app has a choice of its own
|
||||
/// (`settings.rs`); a caller ignores an id that no longer resolves.
|
||||
pub fn remembered_agent() -> Option<String> {
|
||||
Some(read_launcher().get("lastCli")?.as_str()?.to_string()).filter(|id| !id.is_empty())
|
||||
}
|
||||
|
||||
/// `--project <dir>`, `--project=<dir>` or the first bare argument: the folder
|
||||
/// the launcher passed in when it started the app.
|
||||
fn argument_folder(args: &[String]) -> Option<PathBuf> {
|
||||
let mut i = 1; // args[0] is the program name
|
||||
while i < args.len() {
|
||||
let arg = &args[i];
|
||||
if arg == "--agent" || arg == "--model" {
|
||||
// Their values are not folders, even when a folder of that name exists.
|
||||
i += 2;
|
||||
continue;
|
||||
}
|
||||
if arg == "--project" {
|
||||
i += 1;
|
||||
if i < args.len() {
|
||||
let dir = PathBuf::from(&args[i]);
|
||||
return dir.is_dir().then_some(dir);
|
||||
}
|
||||
} else if let Some(dir) = arg.strip_prefix("--project=") {
|
||||
let dir = PathBuf::from(dir);
|
||||
return dir.is_dir().then_some(dir);
|
||||
} else if !arg.starts_with('-') {
|
||||
let dir = PathBuf::from(arg);
|
||||
return dir.is_dir().then_some(dir);
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// What the launcher chose before it opened the app: `--agent <id>` and `--model <id>` (or the
|
||||
/// `=` forms). An unknown agent or a missing value is ignored, and a model only counts beside
|
||||
/// an agent, since a model name belongs to one agent.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq)]
|
||||
pub struct LaunchChoice {
|
||||
/// An agent id, built-in or custom; resolved at use through `agents::find_agent`.
|
||||
pub agent: Option<String>,
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
fn flag_value(args: &[String], flag: &str) -> Option<String> {
|
||||
let prefix = format!("{flag}=");
|
||||
let mut i = 1;
|
||||
while i < args.len() {
|
||||
let arg = &args[i];
|
||||
if arg == flag {
|
||||
return args
|
||||
.get(i + 1)
|
||||
.filter(|v| !v.is_empty() && !v.starts_with('-'))
|
||||
.cloned();
|
||||
}
|
||||
if let Some(value) = arg.strip_prefix(&prefix) {
|
||||
return (!value.is_empty()).then(|| value.to_string());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn launch_choice(args: &[String]) -> LaunchChoice {
|
||||
launch_choice_in(args, agents::agents_file().as_deref())
|
||||
}
|
||||
|
||||
/// `launch_choice` with the custom agents read from `agents_file` (`None`: built-ins only).
|
||||
pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchChoice {
|
||||
let agent = flag_value(args, "--agent")
|
||||
.map(|id| id.to_lowercase())
|
||||
.filter(|id| agents::find_agent_in(id, agents_file).is_some());
|
||||
let model = agent.as_ref().and_then(|_| flag_value(args, "--model"));
|
||||
LaunchChoice { agent, model }
|
||||
}
|
||||
|
||||
/// The folder to open on: the launcher's argument wins, then its memory, then
|
||||
/// nothing (the page asks with the folder picker).
|
||||
pub fn resolve(args: &[String]) -> Option<ProjectDir> {
|
||||
if let Some(dir) = argument_folder(args) {
|
||||
return Some(ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Argument,
|
||||
});
|
||||
}
|
||||
remembered_folder().map(|dir| ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Remembered,
|
||||
})
|
||||
}
|
||||
|
||||
/// A folder the person picked becomes the remembered one, so the next start
|
||||
/// (app or launcher) opens on it. The launcher's other keys are kept.
|
||||
pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
|
||||
let file = launcher_file().ok_or("no home folder found")?;
|
||||
let mut state = read_launcher();
|
||||
state.insert(
|
||||
"lastFolder".to_string(),
|
||||
serde_json::Value::String(dir.to_string_lossy().into_owned()),
|
||||
);
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(err)?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
|
||||
std::fs::write(file, json).map_err(err)?;
|
||||
Ok(ProjectDir {
|
||||
dir: dir.to_path_buf(),
|
||||
source: ProjectSource::Picked,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
fn launch_choice(args: &[String]) -> LaunchChoice {
|
||||
launch_choice_in(args, None)
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app")
|
||||
.chain(list.iter().copied())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
|
||||
let want = LaunchChoice {
|
||||
agent: Some(AgentKind::Codex.id().to_string()),
|
||||
model: Some("gpt-5".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
launch_choice(&args(&[
|
||||
"--project",
|
||||
".",
|
||||
"--agent",
|
||||
"codex",
|
||||
"--model",
|
||||
"gpt-5"
|
||||
])),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent=codex", "--model=gpt-5"])),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])),
|
||||
want
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "claude"])),
|
||||
LaunchChoice {
|
||||
agent: Some(AgentKind::Claude.id().to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--model", "opus"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_agent_or_a_missing_value_is_ignored() {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "emacs", "--model", "x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&["--agent"])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "--model", "x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent=", "--model=x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&[])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "devin", "--model"])),
|
||||
LaunchChoice {
|
||||
agent: Some(AgentKind::Devin.id().to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_agent_id_is_accepted_when_the_file_names_it() {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-project-custom-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let want = LaunchChoice {
|
||||
agent: Some("goose".into()),
|
||||
model: Some("m1".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "goose"]), None),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_and_model_values_are_never_taken_for_a_folder() {
|
||||
// A folder named like the agent exists right here, so a bare-argument reading would pick it.
|
||||
let cwd = std::env::temp_dir().join(format!("p2c-project-args-{}", std::process::id()));
|
||||
std::fs::create_dir_all(cwd.join("codex")).unwrap();
|
||||
let named = cwd.join("codex").to_string_lossy().into_owned();
|
||||
let found = argument_folder(&args(&["--agent", &named, "--model", &named]));
|
||||
assert_eq!(found, None);
|
||||
// Beside --project, the folder wins as before.
|
||||
let found = argument_folder(&args(&["--project", &named, "--agent", "codex"]));
|
||||
assert_eq!(found, Some(cwd.join("codex")));
|
||||
let _ = std::fs::remove_dir_all(&cwd);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,294 @@
|
||||
//! A command running in a pseudo-terminal, so full-screen agent programs see a
|
||||
//! real terminal. Knows nothing about Tauri: output goes to a callback.
|
||||
|
||||
use std::io::{Read, Write};
|
||||
use std::path::PathBuf;
|
||||
#[cfg(unix)]
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::thread;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use portable_pty::{native_pty_system, Child, ChildKiller, CommandBuilder, MasterPty, PtySize};
|
||||
|
||||
/// Output is sent to the page at most once per this long, so a flood of text
|
||||
/// does not stall the web view.
|
||||
pub const BATCH_INTERVAL: Duration = Duration::from_millis(16);
|
||||
|
||||
/// On macOS and Linux the kill is a hang-up signal, which a program can ignore.
|
||||
/// This long after it, a command that is still running is killed outright.
|
||||
#[cfg(unix)]
|
||||
const HANGUP_GRACE: Duration = Duration::from_secs(2);
|
||||
|
||||
/// What to run, where, and how big the terminal starts.
|
||||
pub struct StartOptions {
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub cwd: Option<PathBuf>,
|
||||
pub cols: u16,
|
||||
pub rows: u16,
|
||||
}
|
||||
|
||||
/// A running command in a pseudo-terminal.
|
||||
pub struct PtyHost {
|
||||
master: Mutex<Box<dyn MasterPty + Send>>,
|
||||
writer: Mutex<Box<dyn Write + Send>>,
|
||||
child: Arc<Mutex<Box<dyn Child + Send + Sync>>>,
|
||||
killer: Mutex<Box<dyn ChildKiller + Send + Sync>>,
|
||||
#[cfg(unix)]
|
||||
pid: Option<u32>,
|
||||
/// Set once the command has been waited for, so a late kill never signals
|
||||
/// a process id that may have been given to something else.
|
||||
#[cfg(unix)]
|
||||
exited: Arc<AtomicBool>,
|
||||
/// A Windows Job Object the spawned process was assigned to, so ending
|
||||
/// it (`kill`, or this host simply being dropped) ends every process
|
||||
/// still in it, not just the one directly spawned: a `cmd /c` npm shim's
|
||||
/// real agent process is a child of that child, invisible to a plain
|
||||
/// `TerminateProcess`. A raw handle value, not `HANDLE`, so the struct
|
||||
/// stays `Send`. `None` when the job could not be made; `kill` then
|
||||
/// falls back to ending just the one process, as before.
|
||||
#[cfg(windows)]
|
||||
job: Option<usize>,
|
||||
}
|
||||
|
||||
fn size(cols: u16, rows: u16) -> PtySize {
|
||||
PtySize {
|
||||
rows,
|
||||
cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
e.to_string()
|
||||
}
|
||||
|
||||
impl PtyHost {
|
||||
/// Start the command. `on_output` gets the output in chunks, at most one per
|
||||
/// `BATCH_INTERVAL`, until the command's output ends.
|
||||
pub fn start<F>(options: StartOptions, mut on_output: F) -> Result<PtyHost, String>
|
||||
where
|
||||
F: FnMut(Vec<u8>) + Send + 'static,
|
||||
{
|
||||
let pair = native_pty_system()
|
||||
.openpty(size(options.cols, options.rows))
|
||||
.map_err(err)?;
|
||||
|
||||
let mut command = CommandBuilder::new(&options.program);
|
||||
command.args(&options.args);
|
||||
// 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 {
|
||||
command.env(key, value);
|
||||
}
|
||||
if let Some(cwd) = &options.cwd {
|
||||
command.cwd(cwd);
|
||||
}
|
||||
let child = pair.slave.spawn_command(command).map_err(err)?;
|
||||
// The child holds its own end; keeping ours open would stop the reader
|
||||
// from ever seeing the end of the output.
|
||||
drop(pair.slave);
|
||||
|
||||
let mut reader = pair.master.try_clone_reader().map_err(err)?;
|
||||
let writer = pair.master.take_writer().map_err(err)?;
|
||||
let killer = child.clone_killer();
|
||||
#[cfg(unix)]
|
||||
let pid = child.process_id();
|
||||
#[cfg(windows)]
|
||||
let job = windows_job::assign(child.as_ref());
|
||||
|
||||
// One thread reads as fast as the terminal produces; another gathers
|
||||
// what arrived into one send per interval.
|
||||
let (tx, rx) = mpsc::channel::<Vec<u8>>();
|
||||
thread::spawn(move || {
|
||||
let mut buf = [0u8; 8192];
|
||||
loop {
|
||||
match reader.read(&mut buf) {
|
||||
Ok(0) | Err(_) => break,
|
||||
Ok(n) => {
|
||||
if tx.send(buf[..n].to_vec()).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
thread::spawn(move || {
|
||||
// Blocks for the first chunk, then collects until the interval is up.
|
||||
while let Ok(first) = rx.recv() {
|
||||
let mut batch = first;
|
||||
let deadline = Instant::now() + BATCH_INTERVAL;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
if left.is_zero() {
|
||||
break;
|
||||
}
|
||||
match rx.recv_timeout(left) {
|
||||
Ok(more) => batch.extend_from_slice(&more),
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => break,
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => {
|
||||
on_output(batch);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
on_output(batch);
|
||||
}
|
||||
});
|
||||
|
||||
Ok(PtyHost {
|
||||
master: Mutex::new(pair.master),
|
||||
writer: Mutex::new(writer),
|
||||
child: Arc::new(Mutex::new(child)),
|
||||
killer: Mutex::new(killer),
|
||||
#[cfg(unix)]
|
||||
pid,
|
||||
#[cfg(unix)]
|
||||
exited: Arc::new(AtomicBool::new(false)),
|
||||
#[cfg(windows)]
|
||||
job,
|
||||
})
|
||||
}
|
||||
|
||||
/// Send keystrokes (or pasted text) to the command.
|
||||
pub fn write(&self, bytes: &[u8]) -> Result<(), String> {
|
||||
let mut writer = self.writer.lock().map_err(err)?;
|
||||
writer.write_all(bytes).map_err(err)?;
|
||||
writer.flush().map_err(err)
|
||||
}
|
||||
|
||||
/// Tell the command the terminal changed size.
|
||||
pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> {
|
||||
self.master
|
||||
.lock()
|
||||
.map_err(err)?
|
||||
.resize(size(cols, rows))
|
||||
.map_err(err)
|
||||
}
|
||||
|
||||
/// End the command. Safe to call while `wait` is blocked in another thread.
|
||||
pub fn kill(&self) -> Result<(), String> {
|
||||
let result = self.killer.lock().map_err(err)?.kill().map_err(err);
|
||||
// The job object, when there is one, ends the whole process tree:
|
||||
// killing just the directly spawned process (above) leaves a
|
||||
// `cmd /c` npm shim's real agent process running.
|
||||
#[cfg(windows)]
|
||||
if let Some(job) = self.job {
|
||||
windows_job::terminate(job);
|
||||
}
|
||||
// portable-pty 0.9 on Windows has the TerminateProcess result inverted: it
|
||||
// returns Err (a stale error) when the kill worked and Ok when it failed, so
|
||||
// its answer says nothing there.
|
||||
if cfg!(windows) {
|
||||
return Ok(());
|
||||
}
|
||||
// portable-pty only sends SIGHUP on macOS and Linux; follow it with
|
||||
// SIGKILL if the command is still there after the grace period.
|
||||
#[cfg(unix)]
|
||||
if let Some(pid) = self.pid {
|
||||
let exited = Arc::clone(&self.exited);
|
||||
thread::spawn(move || {
|
||||
thread::sleep(HANGUP_GRACE);
|
||||
if !exited.load(Ordering::SeqCst) {
|
||||
// SAFETY: plain signal to a process id the command still holds.
|
||||
unsafe { libc::kill(pid as i32, libc::SIGKILL) };
|
||||
}
|
||||
});
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// Block until the command ends and return its exit code. A command ended by
|
||||
/// a signal reports 1.
|
||||
pub fn wait(&self) -> Result<u32, String> {
|
||||
self.wait_described().map(|(code, _)| code)
|
||||
}
|
||||
|
||||
/// Like `wait`, with the name of the signal that ended the command, when
|
||||
/// there was one (macOS and Linux).
|
||||
pub fn wait_described(&self) -> Result<(u32, Option<String>), String> {
|
||||
let child = Arc::clone(&self.child);
|
||||
let mut child = child.lock().map_err(err)?;
|
||||
let status = child.wait().map_err(err)?;
|
||||
#[cfg(unix)]
|
||||
self.exited.store(true, Ordering::SeqCst);
|
||||
Ok((status.exit_code(), status.signal().map(str::to_string)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Closing the job's last handle ends every process still in it (`job` was
|
||||
/// made with `JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE`): a safety net for a host
|
||||
/// dropped without `kill` ever being called, on top of `kill`'s own explicit
|
||||
/// `TerminateJobObject`.
|
||||
#[cfg(windows)]
|
||||
impl Drop for PtyHost {
|
||||
fn drop(&mut self) {
|
||||
if let Some(job) = self.job {
|
||||
windows_job::close(job);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A Windows Job Object groups a spawned process with every process it goes
|
||||
/// on to spawn itself (a child joins its parent's job automatically, unless
|
||||
/// it asks to break away, which `cmd /c` does not), so ending the job ends
|
||||
/// the whole tree. Nothing here calls back into `PtyHost`.
|
||||
#[cfg(windows)]
|
||||
mod windows_job {
|
||||
use portable_pty::Child;
|
||||
use std::os::windows::io::RawHandle;
|
||||
use winapi::shared::minwindef::DWORD;
|
||||
use winapi::shared::ntdef::HANDLE;
|
||||
use winapi::um::handleapi::CloseHandle;
|
||||
use winapi::um::jobapi2::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject,
|
||||
};
|
||||
use winapi::um::winnt::{
|
||||
JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
};
|
||||
|
||||
/// Create a job, set it to kill everything in it when its last handle
|
||||
/// closes, and assign `child` to it. `None` on any failure (an older
|
||||
/// Windows without nested-job support, say): `kill` then falls back to
|
||||
/// ending just the one process, as it always did.
|
||||
pub fn assign(child: &(dyn Child + Send + Sync)) -> Option<usize> {
|
||||
let process: RawHandle = child.as_raw_handle()?;
|
||||
unsafe {
|
||||
let job = CreateJobObjectW(std::ptr::null_mut(), std::ptr::null());
|
||||
if job.is_null() {
|
||||
return None;
|
||||
}
|
||||
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = std::mem::zeroed();
|
||||
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
|
||||
let set = SetInformationJobObject(
|
||||
job,
|
||||
JobObjectExtendedLimitInformation,
|
||||
&mut info as *mut _ as *mut _,
|
||||
std::mem::size_of::<JOBOBJECT_EXTENDED_LIMIT_INFORMATION>() as DWORD,
|
||||
);
|
||||
if set == 0 || AssignProcessToJobObject(job, process as HANDLE) == 0 {
|
||||
CloseHandle(job);
|
||||
return None;
|
||||
}
|
||||
Some(job as usize)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn terminate(job: usize) {
|
||||
unsafe {
|
||||
TerminateJobObject(job as HANDLE, 1);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn close(job: usize) {
|
||||
unsafe {
|
||||
CloseHandle(job as HANDLE);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
//! What a Restart leaves for the dashboard: the restart brief, written as a
|
||||
//! pick-up handoff, so the fresh agent (which starts on the plain `/plan2code`
|
||||
//! prompt and lands on the dashboard) finds the chip waiting. Nothing new is
|
||||
//! stored anywhere: the brief is built from the session's files each time.
|
||||
|
||||
use std::path::Path;
|
||||
use std::sync::Mutex;
|
||||
|
||||
use chrono::{DateTime, Local};
|
||||
use serde_json::Value;
|
||||
|
||||
use crate::brief;
|
||||
use crate::handoff;
|
||||
use crate::session_reader;
|
||||
|
||||
pub const READY_NOTE: &str = "Brief ready on the dashboard";
|
||||
|
||||
/// The handoff the last Restart wrote. The next Restart retires it if the person
|
||||
/// has not picked it up, so unused briefs do not pile up as chips.
|
||||
static LAST_BRIEF: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// Write the brief for session `sid` as a handoff. Returns the handoff's id,
|
||||
/// or `None` when there is nothing worth picking up: a workflow with no mapped
|
||||
/// skill (the dashboard, or one not yet known), whose only next step would be
|
||||
/// "Open the dashboard" where the fresh agent lands anyway, and a session that
|
||||
/// finished, whose finished screen already named what comes next, and one
|
||||
/// that has posted nothing yet (no spec, progress, activity or questions),
|
||||
/// whose brief would only repeat the skill's name. A session
|
||||
/// that names no worktree is an error, not a `None`, since that is a broken
|
||||
/// session rather than an empty one.
|
||||
pub fn leave_brief(
|
||||
console_home: &Path,
|
||||
handoffs: &Path,
|
||||
sid: &str,
|
||||
when: DateTime<Local>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let session = session_reader::load(console_home, sid).map_err(|e| e.to_string())?;
|
||||
let state = &session.state;
|
||||
let workflow = text(state, "workflow").unwrap_or("");
|
||||
let Some(skill) = brief::skill_for_workflow(workflow) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if finished(state) || empty(state) {
|
||||
return Ok(None);
|
||||
}
|
||||
let worktree = text(state, "worktree").ok_or("the session names no worktree")?;
|
||||
let project = text(state, "project").unwrap_or(worktree);
|
||||
let spec = text(state, "specDir").filter(|s| valid_spec(s));
|
||||
let spec_dir = spec.map(|s| Path::new(worktree).join(s));
|
||||
let git = brief::git_summary(Path::new(worktree));
|
||||
let events = session_reader::read_ndjson(&session.dir.join("events.ndjson"));
|
||||
let body = brief::build_brief(state, spec_dir.as_deref(), git.as_ref(), &events);
|
||||
let title = match spec {
|
||||
Some(spec) => format!("Restart of {skill} on {spec}"),
|
||||
None => format!("Restart of {skill}"),
|
||||
};
|
||||
let record = handoff::Record {
|
||||
title: &title,
|
||||
worktree,
|
||||
project,
|
||||
spec,
|
||||
workflow,
|
||||
skill,
|
||||
};
|
||||
handoff::write(handoffs, when, &record, &body).map(Some)
|
||||
}
|
||||
|
||||
/// The bar's line for a Restart on session `sid`, written to the real console
|
||||
/// and handoff folders. `None` when there was nothing to leave.
|
||||
pub fn note_for_restart(sid: &str) -> Option<String> {
|
||||
let console_home = session_reader::console_home()?;
|
||||
let handoffs = handoff::handoffs_dir()?;
|
||||
match leave_brief(&console_home, &handoffs, sid, handoff::now()) {
|
||||
Ok(Some(id)) => {
|
||||
let previous = LAST_BRIEF
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut last| last.replace(id.clone()));
|
||||
if let Some(previous) = previous.filter(|p| *p != id) {
|
||||
let _ = handoff::retire_if_unused(&handoffs, &previous);
|
||||
}
|
||||
Some(READY_NOTE.to_string())
|
||||
}
|
||||
Ok(None) => None,
|
||||
Err(why) => Some(format!("The brief could not be written: {why}")),
|
||||
}
|
||||
}
|
||||
|
||||
fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> {
|
||||
state
|
||||
.get(key)
|
||||
.and_then(Value::as_str)
|
||||
.filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The session posted a `finish` that is not a pause. A pause's headline starts
|
||||
/// with "Paused" (the page's `finishPaused`) and keeps a place worth picking up.
|
||||
fn finished(state: &Value) -> bool {
|
||||
let Some(finish) = state.get("finish").filter(|f| f.is_object()) else {
|
||||
return false;
|
||||
};
|
||||
let headline = finish
|
||||
.get("headline")
|
||||
.and_then(Value::as_str)
|
||||
.unwrap_or("")
|
||||
.trim_start();
|
||||
!headline
|
||||
.get(..6)
|
||||
.is_some_and(|word| word.eq_ignore_ascii_case("paused"))
|
||||
}
|
||||
|
||||
/// Nothing a fresh agent could pick up beyond the skill's name.
|
||||
fn empty(state: &Value) -> bool {
|
||||
let stage = state.get("headline").and_then(|h| text(h, "stage"));
|
||||
let activity = state
|
||||
.get("agent")
|
||||
.and_then(|a| text(a, "activity"))
|
||||
.filter(|a| !a.trim().is_empty());
|
||||
let items = state
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.is_some_and(|items| !items.is_empty());
|
||||
text(state, "specDir").is_none() && stage.is_none() && activity.is_none() && !items
|
||||
}
|
||||
|
||||
fn valid_spec(spec: &str) -> bool {
|
||||
spec.strip_prefix("specs/").is_some_and(|name| {
|
||||
!name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\'])
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use chrono::TimeZone;
|
||||
use std::fs;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
/// A console home with one session on `workflow`, and a project with a spec.
|
||||
fn session(name: &str, workflow: &str, spec: Option<&str>) -> (PathBuf, PathBuf, PathBuf) {
|
||||
let root = fixture(name);
|
||||
let home = root.join("console");
|
||||
let project = root.join("project");
|
||||
let dir = home.join("sessions").join("s1");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::create_dir_all(&project).unwrap();
|
||||
let state = serde_json::json!({
|
||||
"schema": 1,
|
||||
"workflow": workflow,
|
||||
"specDir": spec,
|
||||
"worktree": project.to_string_lossy(),
|
||||
"project": project.to_string_lossy(),
|
||||
"headline": { "stage": "Phase 5: Restart brief", "cleared": 4, "total": 11 },
|
||||
"items": [],
|
||||
});
|
||||
fs::write(dir.join("state.json"), state.to_string()).unwrap();
|
||||
(home, project, root.join("handoffs"))
|
||||
}
|
||||
|
||||
fn when() -> DateTime<Local> {
|
||||
Local.with_ymd_and_hms(2026, 10, 21, 14, 5, 0).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_mid_implement_session_leaves_a_pick_up_the_dashboard_lists() {
|
||||
let (home, project, handoffs) = session("pickup", "implement", Some("specs/feature"));
|
||||
let spec = project.join("specs").join("feature");
|
||||
fs::create_dir_all(&spec).unwrap();
|
||||
fs::write(
|
||||
spec.join("overview.md"),
|
||||
"- [/] [Phase 5: Restart](./phase-5.md)\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
spec.join("phase-5.md"),
|
||||
"- [ ] **Task 5.1:** Create the reader\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.expect("a handoff");
|
||||
assert_eq!(id, "2026-10-21-1405-handoff");
|
||||
let record: Value =
|
||||
serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(record["workflow"], "implement");
|
||||
assert_eq!(record["spec"], "specs/feature");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("## Next task\n\nTask 5.1: Create the reader"));
|
||||
assert!(doc.contains("Phase 5: Restart brief: 4 of 11 done."));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dashboard_session_leaves_nothing() {
|
||||
let (home, _, handoffs) = session("dashboard", "dashboard", None);
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
assert!(!handoffs.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skill_that_has_posted_nothing_leaves_nothing() {
|
||||
let (home, _, handoffs) = session("blank", "quick-task", None);
|
||||
let file = home.join("sessions").join("s1").join("state.json");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||||
state["headline"] = Value::Null;
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_session_leaves_nothing_but_a_paused_one_does() {
|
||||
let (home, _, handoffs) = session("finished", "implement", Some("specs/feature"));
|
||||
let file = home.join("sessions").join("s1").join("state.json");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||||
state["finish"] = serde_json::json!({ "headline": "Phase 5 is built", "dashboard": true });
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
|
||||
state["finish"] = serde_json::json!({ "headline": "Paused at Phase 5" });
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert!(leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_carries_the_agent_activity_and_recent_events() {
|
||||
let (home, _project, handoffs) = session("activity", "implement", None);
|
||||
let dir = home.join("sessions").join("s1");
|
||||
let mut state: Value =
|
||||
serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap();
|
||||
state["agent"] = serde_json::json!({ "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" });
|
||||
fs::write(dir.join("state.json"), state.to_string()).unwrap();
|
||||
fs::write(
|
||||
dir.join("events.ndjson"),
|
||||
"{\"at\":\"2026-10-23T01:08:47.152Z\",\"type\":\"post\",\"items\":0}\n{\"at\":\"2026-10-23T01:09:00.000Z\",\"type\":\"consume\",\"kind\":\"submit\"}\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.expect("a handoff");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("Doing: Spiking Claude's context signal (Task 10.1)"));
|
||||
assert!(doc.contains("## Recent activity\n\n- post (0 items)\n- consume: submit\n"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_session_that_does_not_exist_is_an_error_not_a_brief() {
|
||||
let (home, _, handoffs) = session("missing", "implement", None);
|
||||
assert!(leave_brief(&home, &handoffs, "nope", when()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_spec_that_is_not_one_folder_is_left_out_of_the_record() {
|
||||
let (home, _, handoffs) = session("badspec", "pathfinder", Some("specs/a/b"));
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let record: Value =
|
||||
serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert!(record["spec"].is_null());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
//! Reads a console session's files without disturbing them. The console owns
|
||||
//! `~/.plan2code/console/sessions/<sid>/`: this module only opens files for
|
||||
//! reading. It never creates, locks, renames or removes anything there, so the
|
||||
//! console's own writes are never blocked by the app (NFR-3).
|
||||
|
||||
use std::io;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::thread::sleep;
|
||||
use std::time::Duration;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
/// The one session schema this reader understands (`state.json`'s `schema`).
|
||||
pub const SCHEMA: u64 = 1;
|
||||
|
||||
/// How many times a locked `state.json` is tried again. The console renames
|
||||
/// the file while it writes, so Windows can refuse a read for a moment.
|
||||
const LOCKED_RETRIES: u32 = 5;
|
||||
const RETRY_EVERY: Duration = Duration::from_millis(50);
|
||||
|
||||
/// Windows: ERROR_SHARING_VIOLATION and ERROR_LOCK_VIOLATION.
|
||||
const WINDOWS_SHARING: [i32; 2] = [32, 33];
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ReadError {
|
||||
/// The file is not there.
|
||||
Missing(PathBuf),
|
||||
/// Still locked after every retry.
|
||||
Busy,
|
||||
/// Some other read failure.
|
||||
Unreadable(String),
|
||||
/// Not a JSON object.
|
||||
Malformed(String),
|
||||
/// A schema this app does not read.
|
||||
Schema(u64),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ReadError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ReadError::Missing(file) => write!(f, "{} is missing", file.display()),
|
||||
ReadError::Busy => write!(f, "session busy: the console is still writing its state"),
|
||||
ReadError::Unreadable(why) => write!(f, "could not read the session: {why}"),
|
||||
ReadError::Malformed(why) => write!(f, "the session file is not valid: {why}"),
|
||||
ReadError::Schema(found) => {
|
||||
write!(
|
||||
f,
|
||||
"session schema {found} is not supported (this app reads schema {SCHEMA})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A session's `state.json`, read once. Nothing else in the session folder is
|
||||
/// read here: the Ask chat lives in `chat.ndjson` and stays out of the brief.
|
||||
pub struct Session {
|
||||
pub dir: PathBuf,
|
||||
pub state: Value,
|
||||
}
|
||||
|
||||
/// `~/.plan2code/console`, or `PLAN2CODE_CONSOLE_HOME` when the console is
|
||||
/// relocated (the same rule the console and the supervisor follow).
|
||||
pub fn console_home() -> Option<PathBuf> {
|
||||
if let Ok(home) = std::env::var("PLAN2CODE_CONSOLE_HOME") {
|
||||
return Some(PathBuf::from(home));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("console"))
|
||||
}
|
||||
|
||||
/// `<console home>/sessions/<sid>`.
|
||||
pub fn session_dir(console_home: &Path, sid: &str) -> PathBuf {
|
||||
console_home.join("sessions").join(sid)
|
||||
}
|
||||
|
||||
/// Open and parse the session `sid` under `console_home`.
|
||||
pub fn load(console_home: &Path, sid: &str) -> Result<Session, ReadError> {
|
||||
let dir = session_dir(console_home, sid);
|
||||
let text = read_with_retry(&dir.join("state.json"), |file| {
|
||||
std::fs::read_to_string(file)
|
||||
})?;
|
||||
let state = parse_state(&text)?;
|
||||
Ok(Session { dir, state })
|
||||
}
|
||||
|
||||
/// Read `file` through `read`. A locked file (a sharing or permission error) is
|
||||
/// tried again up to `LOCKED_RETRIES` times, `RETRY_EVERY` apart; then the
|
||||
/// session is reported busy. `read` is a parameter so a test can stand in a
|
||||
/// reader that fails a few times.
|
||||
pub fn read_with_retry<F>(file: &Path, mut read: F) -> Result<String, ReadError>
|
||||
where
|
||||
F: FnMut(&Path) -> io::Result<String>,
|
||||
{
|
||||
let mut retries = 0;
|
||||
loop {
|
||||
match read(file) {
|
||||
Ok(text) => return Ok(text),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
return Err(ReadError::Missing(file.to_path_buf()))
|
||||
}
|
||||
Err(e) if is_locked(&e) => {
|
||||
if retries == LOCKED_RETRIES {
|
||||
return Err(ReadError::Busy);
|
||||
}
|
||||
retries += 1;
|
||||
sleep(RETRY_EVERY);
|
||||
}
|
||||
Err(e) => return Err(ReadError::Unreadable(e.to_string())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_locked(e: &io::Error) -> bool {
|
||||
e.kind() == io::ErrorKind::PermissionDenied
|
||||
|| e.raw_os_error()
|
||||
.is_some_and(|code| WINDOWS_SHARING.contains(&code))
|
||||
}
|
||||
|
||||
/// Parse `state.json` text: a JSON object whose `schema` is `SCHEMA`.
|
||||
pub fn parse_state(text: &str) -> Result<Value, ReadError> {
|
||||
let state: Value =
|
||||
serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?;
|
||||
if !state.is_object() {
|
||||
return Err(ReadError::Malformed("not a JSON object".to_string()));
|
||||
}
|
||||
let schema = state
|
||||
.get("schema")
|
||||
.and_then(Value::as_u64)
|
||||
.ok_or_else(|| ReadError::Malformed("no schema number".to_string()))?;
|
||||
if schema != SCHEMA {
|
||||
return Err(ReadError::Schema(schema));
|
||||
}
|
||||
Ok(state)
|
||||
}
|
||||
|
||||
/// Each line of a `.ndjson` file that parses as JSON, in order. A partial last
|
||||
/// line (the console was mid-write) does not parse and is dropped; so is any
|
||||
/// other line that does not parse. A missing file has no lines.
|
||||
pub fn read_ndjson(file: &Path) -> Vec<Value> {
|
||||
match std::fs::read_to_string(file) {
|
||||
Ok(text) => parse_ndjson(&text),
|
||||
Err(_) => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn parse_ndjson(text: &str) -> Vec<Value> {
|
||||
text.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.filter_map(|line| serde_json::from_str(line).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::cell::Cell;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
const STATE: &str =
|
||||
r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#;
|
||||
|
||||
#[test]
|
||||
fn a_complete_session_loads() {
|
||||
let home = fixture("complete");
|
||||
let dir = session_dir(&home, "s1");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("state.json"), STATE).unwrap();
|
||||
let session = load(&home, "s1").unwrap();
|
||||
assert_eq!(session.state["workflow"], "implement");
|
||||
assert_eq!(session.dir, dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_last_line_is_dropped() {
|
||||
let lines = parse_ndjson("{\"a\":1}\n{\"b\":2}\n{\"c\":");
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_ndjson_file_has_no_lines() {
|
||||
assert!(read_ndjson(&fixture("no-ndjson").join("events.ndjson")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_state_file_is_reported() {
|
||||
let home = fixture("missing");
|
||||
match load(&home, "nope") {
|
||||
Err(ReadError::Missing(file)) => assert!(file.ends_with("state.json")),
|
||||
other => panic!("expected Missing, got {:?}", other.map(|s| s.dir)),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn another_schema_is_rejected_with_a_clear_message() {
|
||||
let err = parse_state(r#"{"schema": 2}"#).unwrap_err();
|
||||
assert_eq!(err, ReadError::Schema(2));
|
||||
assert!(err.to_string().contains("schema 2 is not supported"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_locked_file_that_frees_up_on_the_third_retry_is_read() {
|
||||
let tries = Cell::new(0);
|
||||
let text = read_with_retry(Path::new("state.json"), |_| {
|
||||
tries.set(tries.get() + 1);
|
||||
if tries.get() < 4 {
|
||||
Err(io::Error::from(io::ErrorKind::PermissionDenied))
|
||||
} else {
|
||||
Ok(STATE.to_string())
|
||||
}
|
||||
});
|
||||
assert_eq!(text.unwrap(), STATE);
|
||||
assert_eq!(tries.get(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_file_that_stays_locked_is_busy_not_a_failure() {
|
||||
let tries = Cell::new(0);
|
||||
let result = read_with_retry(Path::new("state.json"), |_| {
|
||||
tries.set(tries.get() + 1);
|
||||
Err(io::Error::from_raw_os_error(32))
|
||||
});
|
||||
assert_eq!(result, Err(ReadError::Busy));
|
||||
assert_eq!(tries.get(), LOCKED_RETRIES + 1);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,284 @@
|
||||
//! The app's own settings file, `~/.plan2code/app.json`. It holds what only the
|
||||
//! app remembers (today: the agent last picked in the bar). The console's
|
||||
//! folders under `~/.plan2code/console/` are never written to from here.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
const LAST_AGENT_KEY: &str = "lastAgent";
|
||||
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
|
||||
/// it was left collapsed.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
|
||||
pub struct TermPanelSettings {
|
||||
pub dock: String,
|
||||
pub fraction: f64,
|
||||
pub collapsed: bool,
|
||||
}
|
||||
|
||||
pub const DEFAULT_TERM_DOCK: &str = "bottom";
|
||||
pub const DEFAULT_TERM_FRACTION: f64 = 0.25;
|
||||
const TERM_FRACTION_MIN: f64 = 0.05;
|
||||
const TERM_FRACTION_MAX: f64 = 0.9;
|
||||
|
||||
pub fn settings_file() -> Option<PathBuf> {
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("app.json"))
|
||||
}
|
||||
|
||||
fn read(file: &Path) -> serde_json::Map<String, serde_json::Value> {
|
||||
std::fs::read_to_string(file)
|
||||
.ok()
|
||||
.and_then(|text| serde_json::from_str(&text).ok())
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The agent id saved in `file` (built-in or custom). Whether it still
|
||||
/// resolves is the caller's check (`agents::find_agent`).
|
||||
pub fn load_last_agent(file: &Path) -> Option<String> {
|
||||
Some(read(file).get(LAST_AGENT_KEY)?.as_str()?.to_string()).filter(|id| !id.is_empty())
|
||||
}
|
||||
|
||||
/// Save the pick, keeping any other key the file holds.
|
||||
pub fn save_last_agent(file: &Path, id: &str) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(
|
||||
LAST_AGENT_KEY.to_string(),
|
||||
serde_json::Value::String(id.to_string()),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// The terminal pane's shape, from the file or the defaults. A dock other
|
||||
/// than `bottom` or `right`, or a fraction outside its range, is the default.
|
||||
pub fn load_term_panel(file: &Path) -> TermPanelSettings {
|
||||
let settings = read(file);
|
||||
let dock = settings
|
||||
.get(TERM_DOCK_KEY)
|
||||
.and_then(|v| v.as_str())
|
||||
.filter(|d| *d == "bottom" || *d == "right")
|
||||
.unwrap_or(DEFAULT_TERM_DOCK)
|
||||
.to_string();
|
||||
let fraction = settings
|
||||
.get(TERM_FRACTION_KEY)
|
||||
.and_then(|v| v.as_f64())
|
||||
.filter(|f| (TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(f))
|
||||
.unwrap_or(DEFAULT_TERM_FRACTION);
|
||||
let collapsed = settings
|
||||
.get(TERM_COLLAPSED_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
TermPanelSettings {
|
||||
dock,
|
||||
fraction,
|
||||
collapsed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the terminal pane's shape, keeping any other key the file holds. An
|
||||
/// invalid dock or an out-of-range fraction is rejected rather than saved.
|
||||
pub fn save_term_panel(
|
||||
file: &Path,
|
||||
dock: &str,
|
||||
fraction: f64,
|
||||
collapsed: bool,
|
||||
) -> Result<(), String> {
|
||||
if dock != "bottom" && dock != "right" {
|
||||
return Err(format!("unknown dock: {dock}"));
|
||||
}
|
||||
if !(TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(&fraction) {
|
||||
return Err(format!("fraction out of range: {fraction}"));
|
||||
}
|
||||
let mut settings = read(file);
|
||||
settings.insert(
|
||||
TERM_DOCK_KEY.to_string(),
|
||||
serde_json::Value::String(dock.to_string()),
|
||||
);
|
||||
settings.insert(
|
||||
TERM_FRACTION_KEY.to_string(),
|
||||
serde_json::Number::from_f64(fraction)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
settings.insert(
|
||||
TERM_COLLAPSED_KEY.to_string(),
|
||||
serde_json::Value::Bool(collapsed),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// Whether the first-run checklist has already passed once. Once it has,
|
||||
/// later launches go straight to the launch card (Task 9.4).
|
||||
pub fn load_first_run_done(file: &Path) -> bool {
|
||||
read(file)
|
||||
.get(FIRST_RUN_DONE_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Remember that the checklist passed, keeping any other key the file holds.
|
||||
pub fn save_first_run_done(file: &Path) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(
|
||||
FIRST_RUN_DONE_KEY.to_string(),
|
||||
serde_json::Value::Bool(true),
|
||||
);
|
||||
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())?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings))
|
||||
.map_err(|e| e.to_string())?;
|
||||
std::fs::write(file, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_file(name: &str) -> PathBuf {
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir.join("app.json")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_has_no_choice() {
|
||||
assert_eq!(load_last_agent(&temp_file("missing")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_choice_round_trips_and_other_keys_survive() {
|
||||
let file = temp_file("round-trip");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_last_agent(&file, "devin").unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("devin".to_string()));
|
||||
save_last_agent(&file, "goose").unwrap();
|
||||
assert_eq!(
|
||||
load_last_agent(&file),
|
||||
Some("goose".to_string()),
|
||||
"a custom id round-trips"
|
||||
);
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_id_is_returned_as_stored_and_the_caller_checks_it() {
|
||||
let file = temp_file("unknown");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"lastAgent": "nope"}"#).unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("nope".to_string()));
|
||||
assert!(crate::agents::find_agent_in("nope", None).is_none());
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_term_panel_defaults_to_bottom_at_a_quarter() {
|
||||
let want = TermPanelSettings {
|
||||
dock: "bottom".into(),
|
||||
fraction: 0.25,
|
||||
collapsed: false,
|
||||
};
|
||||
assert_eq!(load_term_panel(&temp_file("term-missing")), want);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_term_panel_round_trips_and_other_keys_survive() {
|
||||
let file = temp_file("term-round-trip");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_term_panel(&file, "right", 0.4, true).unwrap();
|
||||
assert_eq!(
|
||||
load_term_panel(&file),
|
||||
TermPanelSettings {
|
||||
dock: "right".into(),
|
||||
fraction: 0.4,
|
||||
collapsed: true
|
||||
}
|
||||
);
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_dock_or_an_out_of_range_fraction_is_refused() {
|
||||
let file = temp_file("term-bad-save");
|
||||
assert!(save_term_panel(&file, "top", 0.3, false).is_err());
|
||||
assert!(save_term_panel(&file, "bottom", 0.0, false).is_err());
|
||||
assert!(save_term_panel(&file, "bottom", 1.0, false).is_err());
|
||||
assert!(!file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn first_run_is_not_done_until_it_is_saved() {
|
||||
let file = temp_file("first-run");
|
||||
assert!(!load_first_run_done(&file));
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_first_run_done(&file).unwrap();
|
||||
assert!(load_first_run_done(&file));
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
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");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"termDock": "top", "termFraction": 5}"#).unwrap();
|
||||
let loaded = load_term_panel(&file);
|
||||
assert_eq!(loaded.dock, "bottom");
|
||||
assert_eq!(loaded.fraction, 0.25);
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,305 @@
|
||||
//! Whether the app and the installed skills are on the same Plan2Code version, and the
|
||||
//! one-click way to bring them level. The app's own version is the one in `tauri.conf.json`
|
||||
//! (Tauri reads it into the package info); the skills' version is the `version.json` the
|
||||
//! installer writes beside the launcher in `~/.plan2code/bin/` on every install and update.
|
||||
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Command, Stdio};
|
||||
use std::sync::mpsc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
/// How long `run_update` lets the installer run before giving up on it.
|
||||
pub const UPDATE_TIMEOUT: Duration = Duration::from_secs(300);
|
||||
|
||||
#[derive(Debug, PartialEq, Eq, Serialize)]
|
||||
pub struct VersionStatus {
|
||||
pub app: String,
|
||||
/// The installed skills' version, or none when it cannot be read.
|
||||
pub skills: Option<String>,
|
||||
/// True only when both are readable `X.Y.Z` versions and they differ: an unknown version is
|
||||
/// never a reason to nag.
|
||||
pub mismatch: bool,
|
||||
/// Only meaningful when `mismatch` is true: the skills are ahead of this app, so another
|
||||
/// Update skills run cannot fix it (a newer app is what is missing), as against the usual
|
||||
/// case of the skills sitting behind the app.
|
||||
pub skills_ahead: bool,
|
||||
}
|
||||
|
||||
/// `~/.plan2code/bin`, or `PLAN2CODE_LAUNCHER_DIR` when it is set (tests only, the same
|
||||
/// convention `PLAN2CODE_CONSOLE_HOME` and `PLAN2CODE_APP_AGENT_BIN` already use).
|
||||
fn launcher_dir() -> Option<PathBuf> {
|
||||
if let Ok(dir) = std::env::var("PLAN2CODE_LAUNCHER_DIR") {
|
||||
return Some(PathBuf::from(dir));
|
||||
}
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("bin"))
|
||||
}
|
||||
|
||||
/// `X.Y.Z` as three numbers; anything else (a pre-release tag, a missing part) is none.
|
||||
fn parse(version: &str) -> Option<(u64, u64, u64)> {
|
||||
let mut parts = version.trim().split('.');
|
||||
let triple = (
|
||||
parts.next()?.parse().ok()?,
|
||||
parts.next()?.parse().ok()?,
|
||||
parts.next()?.parse().ok()?,
|
||||
);
|
||||
parts.next().is_none().then_some(triple)
|
||||
}
|
||||
|
||||
/// The `version` field of a `version.json` file.
|
||||
pub fn version_in(file: &Path) -> Option<String> {
|
||||
let text = std::fs::read_to_string(file).ok()?;
|
||||
let json: serde_json::Value = serde_json::from_str(&text).ok()?;
|
||||
json.get("version")?.as_str().map(str::to_string)
|
||||
}
|
||||
|
||||
/// The skills' version as the installer last wrote it.
|
||||
pub fn installed_skills_version() -> Option<String> {
|
||||
version_in(&launcher_dir()?.join("version.json"))
|
||||
}
|
||||
|
||||
pub fn status(app: &str, skills: Option<String>) -> VersionStatus {
|
||||
let (mismatch, skills_ahead) = match (parse(app), skills.as_deref().and_then(parse)) {
|
||||
(Some(a), Some(s)) => (a != s, s > a),
|
||||
_ => (false, false),
|
||||
};
|
||||
VersionStatus {
|
||||
app: app.to_string(),
|
||||
skills,
|
||||
mismatch,
|
||||
skills_ahead,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the existing installer's update (`plan2code update`, through the launcher's own copy),
|
||||
/// which brings the skills, the launcher and the app level. Pinned to the release tag `app_version`
|
||||
/// names, not `main`, so Update skills never pulls in work the app does not know about yet. Blocks
|
||||
/// until it ends or `UPDATE_TIMEOUT` passes, whichever comes first; the page asks for it with a
|
||||
/// click, never on its own. `on_line` is called with each line of output as it is produced, for a
|
||||
/// live progress readout. Returns the installer's last non-empty line on success.
|
||||
pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result<String, String> {
|
||||
run_update_within(app_version, UPDATE_TIMEOUT, on_line)
|
||||
}
|
||||
|
||||
/// `run_update`, with the timeout as a parameter so a test can use a short one instead of
|
||||
/// `UPDATE_TIMEOUT`'s real five minutes.
|
||||
fn run_update_within(
|
||||
app_version: &str,
|
||||
timeout: Duration,
|
||||
mut on_line: impl FnMut(&str),
|
||||
) -> Result<String, String> {
|
||||
let launcher = launcher_dir()
|
||||
.ok_or("no home folder found")?
|
||||
.join("plan2code.js");
|
||||
if !launcher.is_file() {
|
||||
return Err(format!(
|
||||
"the plan2code command is not installed ({} is missing)",
|
||||
launcher.display()
|
||||
));
|
||||
}
|
||||
let mut command = Command::new("node");
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
// directories (Task 9.9): the update script itself shells out to `npx`
|
||||
// and `git`, which need a PATH that finds them too.
|
||||
command.env("PATH", crate::node_check::resolved_path());
|
||||
command
|
||||
.arg(&launcher)
|
||||
.arg("update")
|
||||
.arg("--tag")
|
||||
.arg(format!("v{app_version}"))
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
|
||||
}
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| format!("could not run node: {e}"))?;
|
||||
let stdout = child.stdout.take().ok_or("no stdout from the update")?;
|
||||
let stderr = child.stderr.take().ok_or("no stderr from the update")?;
|
||||
let (tx, rx) = mpsc::channel::<String>();
|
||||
let err_tx = tx.clone();
|
||||
let out_thread = std::thread::spawn(move || {
|
||||
for line in BufReader::new(stdout).lines().map_while(Result::ok) {
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let err_thread = std::thread::spawn(move || {
|
||||
for line in BufReader::new(stderr).lines().map_while(Result::ok) {
|
||||
if err_tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
let deadline = Instant::now() + timeout;
|
||||
let poll = Duration::from_millis(200).min(timeout);
|
||||
let mut last_line = String::new();
|
||||
loop {
|
||||
match rx.recv_timeout(poll) {
|
||||
Ok(line) => {
|
||||
if !line.trim().is_empty() {
|
||||
last_line = line.clone();
|
||||
}
|
||||
on_line(&line);
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Timeout) if Instant::now() < deadline => continue,
|
||||
Err(mpsc::RecvTimeoutError::Timeout) => {
|
||||
let _ = child.kill();
|
||||
let _ = child.wait();
|
||||
return Err(format!("the update timed out after {}s", timeout.as_secs()));
|
||||
}
|
||||
Err(mpsc::RecvTimeoutError::Disconnected) => break,
|
||||
}
|
||||
}
|
||||
let _ = out_thread.join();
|
||||
let _ = err_thread.join();
|
||||
let status = child.wait().map_err(|e| e.to_string())?;
|
||||
if status.success() {
|
||||
Ok(last_line)
|
||||
} else {
|
||||
Err(format!("the update did not finish: {last_line}"))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_file(name: &str, content: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-versions-{}-{name}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("version.json");
|
||||
std::fs::write(&file, content).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_versions_do_not_mismatch() {
|
||||
let s = status("3.0.0", Some("3.0.0".into()));
|
||||
assert_eq!(
|
||||
s,
|
||||
VersionStatus {
|
||||
app: "3.0.0".into(),
|
||||
skills: Some("3.0.0".into()),
|
||||
mismatch: false,
|
||||
skills_ahead: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn different_versions_mismatch_in_either_direction() {
|
||||
assert!(status("3.0.0", Some("2.11.0".into())).mismatch);
|
||||
assert!(status("3.0.0", Some("3.1.0".into())).mismatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn skills_ahead_names_which_direction_the_mismatch_runs() {
|
||||
assert!(!status("3.0.0", Some("2.11.0".into())).skills_ahead);
|
||||
assert!(status("3.0.0", Some("3.1.0".into())).skills_ahead);
|
||||
assert!(!status("3.0.0", Some("3.0.0".into())).skills_ahead);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_or_odd_version_never_mismatches() {
|
||||
assert!(!status("3.0.0", None).mismatch);
|
||||
assert!(!status("3.0.0", Some("3.0.0-beta".into())).mismatch);
|
||||
assert!(!status("3.0", Some("3.0.0".into())).mismatch);
|
||||
assert!(!status("3.0.0", Some("".into())).mismatch);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reads_the_version_field_of_a_version_file() {
|
||||
let file = temp_file("ok", r#"{ "name": "Plan2Code", "version": "2.11.0" }"#);
|
||||
assert_eq!(version_in(&file).as_deref(), Some("2.11.0"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_broken_version_file_reads_as_none() {
|
||||
let missing = std::env::temp_dir()
|
||||
.join("p2c-versions-does-not-exist")
|
||||
.join("version.json");
|
||||
assert_eq!(version_in(&missing), None);
|
||||
assert_eq!(version_in(&temp_file("broken", "{ not json")), None);
|
||||
assert_eq!(version_in(&temp_file("nover", r#"{ "name": "x" }"#)), None);
|
||||
}
|
||||
|
||||
// `PLAN2CODE_LAUNCHER_DIR` is process-global, so these tests serialize on it.
|
||||
static ENV_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Points `launcher_dir()` at a fresh folder holding a fake `plan2code.js` (plain Node
|
||||
/// source, no quoting needed), runs `body`, then restores the environment.
|
||||
fn with_fake_launcher<T>(name: &str, script: &str, body: impl FnOnce() -> T) -> T {
|
||||
let _guard = ENV_LOCK.lock().unwrap();
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"p2c-versions-launcher-{}-{name}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("plan2code.js"), script).unwrap();
|
||||
std::env::set_var("PLAN2CODE_LAUNCHER_DIR", &dir);
|
||||
let result = body();
|
||||
std::env::remove_var("PLAN2CODE_LAUNCHER_DIR");
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
result
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_streams_lines_live_and_returns_the_last_one_on_success() {
|
||||
let lines = std::sync::Mutex::new(Vec::<String>::new());
|
||||
let result =
|
||||
with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || {
|
||||
run_update_within("9.9.9", Duration::from_secs(10), |line| {
|
||||
lines.lock().unwrap().push(line.to_string())
|
||||
})
|
||||
});
|
||||
assert_eq!(result, Ok("line2".to_string()));
|
||||
assert_eq!(
|
||||
*lines.lock().unwrap(),
|
||||
vec!["line1".to_string(), "line2".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_pins_the_install_to_the_app_s_own_release_tag() {
|
||||
let result = with_fake_launcher(
|
||||
"tag",
|
||||
"console.log(process.argv.slice(2).join(' '));",
|
||||
|| run_update_within("9.9.9", Duration::from_secs(10), |_| {}),
|
||||
);
|
||||
assert_eq!(result, Ok("update --tag v9.9.9".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_fails_with_the_installer_s_own_last_line() {
|
||||
let result = with_fake_launcher("fail", "console.log('oops'); process.exit(1);", || {
|
||||
run_update_within("9.9.9", Duration::from_secs(10), |_| {})
|
||||
});
|
||||
assert_eq!(result, Err("the update did not finish: oops".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn run_update_gives_up_after_its_timeout_and_kills_the_child() {
|
||||
let result = with_fake_launcher("hang", "setInterval(() => {}, 1000);", || {
|
||||
run_update_within("9.9.9", Duration::from_millis(300), |_| {})
|
||||
});
|
||||
assert_eq!(result, Err("the update timed out after 0s".to_string()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_launcher_is_an_error_not_a_panic() {
|
||||
let result = with_fake_launcher("missing", "", || {
|
||||
std::fs::remove_file(launcher_dir().unwrap().join("plan2code.js")).unwrap();
|
||||
run_update_within("9.9.9", Duration::from_secs(10), |_| {})
|
||||
});
|
||||
assert!(result.unwrap_err().contains("is missing"));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
{
|
||||
"$schema": "https://schema.tauri.app/config/2",
|
||||
"productName": "Plan2Code",
|
||||
"version": "3.0.0",
|
||||
"identifier": "com.plan2code.app",
|
||||
"build": {
|
||||
"frontendDist": "../ui",
|
||||
"beforeDevCommand": "node scripts/vendor.mjs",
|
||||
"beforeBuildCommand": "node scripts/vendor.mjs"
|
||||
},
|
||||
"app": {
|
||||
"windows": [
|
||||
{
|
||||
"title": "Plan2Code",
|
||||
"width": 1280,
|
||||
"height": 800,
|
||||
"maximized": true,
|
||||
"url": "index.html"
|
||||
}
|
||||
],
|
||||
"security": {
|
||||
"csp": "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src ipc: http://ipc.localhost; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'",
|
||||
"dangerousDisableAssetCspModification": ["style-src"]
|
||||
},
|
||||
"withGlobalTauri": true
|
||||
},
|
||||
"bundle": {
|
||||
"active": true,
|
||||
"targets": "all",
|
||||
"icon": [
|
||||
"icons/32x32.png",
|
||||
"icons/128x128.png",
|
||||
"icons/icon.icns",
|
||||
"icons/icon.ico"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,434 @@
|
||||
//! The agent lifecycle against the fake agent in a real pseudo-terminal. Real
|
||||
//! agents are never started here: `PLAN2CODE_APP_AGENT_BIN` points every agent
|
||||
//! kind at the fake one.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::sync::mpsc::{channel, Receiver, RecvTimeoutError};
|
||||
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_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV,
|
||||
};
|
||||
|
||||
mod common;
|
||||
use common::process_alive;
|
||||
|
||||
const TIMEOUT: Duration = Duration::from_secs(20);
|
||||
const READY: &str = "FAKE-AGENT ready";
|
||||
|
||||
struct Harness {
|
||||
manager: AgentManager,
|
||||
rx: Receiver<AgentEvent>,
|
||||
/// Everything the agents printed, in order.
|
||||
seen: String,
|
||||
/// Every state change, in order.
|
||||
states: Vec<AgentSnapshot>,
|
||||
/// How many of `states` `wait_state` has already looked at.
|
||||
cursor: usize,
|
||||
}
|
||||
|
||||
impl Harness {
|
||||
fn new() -> Harness {
|
||||
static BIN: Once = Once::new();
|
||||
BIN.call_once(|| std::env::set_var(AGENT_BIN_ENV, common::fake_agent()));
|
||||
let (tx, rx) = channel();
|
||||
let tx = Mutex::new(tx);
|
||||
let sink = Arc::new(move |event| {
|
||||
let _ = tx.lock().unwrap().send(event);
|
||||
});
|
||||
Harness {
|
||||
manager: AgentManager::new(PathBuf::from("."), sink),
|
||||
rx,
|
||||
seen: String::new(),
|
||||
states: Vec::new(),
|
||||
cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, event: AgentEvent) {
|
||||
match event {
|
||||
AgentEvent::Output(bytes) => {
|
||||
let text = String::from_utf8_lossy(&bytes).into_owned();
|
||||
// Windows' pseudo-terminal asks where the cursor is (ESC [ 6 n)
|
||||
// and holds the output until told, as xterm does on its own.
|
||||
for _ in text.matches("[6n") {
|
||||
self.manager.input(b"\x1b[1;1R").unwrap();
|
||||
}
|
||||
self.seen.push_str(&text);
|
||||
}
|
||||
AgentEvent::State(snapshot) => self.states.push(snapshot),
|
||||
}
|
||||
}
|
||||
|
||||
/// Handle events for `how_long`, answering the terminal's questions.
|
||||
fn pump_for(&mut self, how_long: Duration) {
|
||||
let deadline = Instant::now() + how_long;
|
||||
loop {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match self.rx.recv_timeout(left) {
|
||||
Ok(event) => self.take(event),
|
||||
Err(_) => return,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn wait_for_output(&mut self, needle: &str, times: usize) {
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
while self.seen.matches(needle).count() < times {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match self.rx.recv_timeout(left) {
|
||||
Ok(event) => self.take(event),
|
||||
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => {
|
||||
panic!("never saw {needle:?} {times} time(s); got {:?}", self.seen)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The next state change (after the last one this returned) that matches.
|
||||
fn wait_state(
|
||||
&mut self,
|
||||
what: &str,
|
||||
matches: impl Fn(&AgentSnapshot) -> bool,
|
||||
) -> AgentSnapshot {
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
loop {
|
||||
while self.cursor < self.states.len() {
|
||||
let snapshot = self.states[self.cursor].clone();
|
||||
self.cursor += 1;
|
||||
if matches(&snapshot) {
|
||||
return snapshot;
|
||||
}
|
||||
}
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match self.rx.recv_timeout(left) {
|
||||
Ok(event) => self.take(event),
|
||||
Err(_) => panic!("never saw the state {what}; got {:?}", self.states),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn start_and_wait_ready(&mut self) {
|
||||
self.manager
|
||||
.start(
|
||||
Agent::Builtin(AgentKind::Claude),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
self.wait_for_output(READY, 1);
|
||||
}
|
||||
|
||||
fn type_line(&self, line: &str) {
|
||||
self.manager.input(format!("{line}\r").as_bytes()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
fn is_running(snapshot: &AgentSnapshot) -> bool {
|
||||
snapshot.state == AgentState::Running
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_second_start_while_running_is_refused() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let generation = h.manager.snapshot().generation;
|
||||
|
||||
let refused = h.manager.start(
|
||||
Agent::Builtin(AgentKind::Devin),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
None,
|
||||
);
|
||||
assert!(refused.is_err(), "a second start must be refused");
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(after.state, AgentState::Running);
|
||||
assert_eq!(
|
||||
after.generation, generation,
|
||||
"the running agent was replaced"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
|
||||
let mut h = Harness::new();
|
||||
h.manager
|
||||
.start(
|
||||
Agent::Builtin(AgentKind::Codex),
|
||||
Some("gpt-5".to_string()),
|
||||
Some("high".to_string()),
|
||||
PermissionMode::Checked,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
let before = h.manager.snapshot();
|
||||
assert_eq!(before.kind, Some("codex".to_string()));
|
||||
assert_eq!(before.mode, Some(PermissionMode::Checked));
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
(Some("gpt-5".to_string()), Some("high".to_string()))
|
||||
);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(
|
||||
after.kind,
|
||||
Some("codex".to_string()),
|
||||
"restart must keep the same agent"
|
||||
);
|
||||
assert_eq!(
|
||||
after.mode,
|
||||
Some(PermissionMode::Checked),
|
||||
"restart must keep the same permission mode"
|
||||
);
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
(Some("gpt-5".to_string()), Some("high".to_string())),
|
||||
"restart must keep the same model and effort"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_between_steps_replaces_the_agent_at_once() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let generation = h.manager.snapshot().generation;
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
let now = h.manager.snapshot();
|
||||
assert_eq!(now.state, AgentState::Running);
|
||||
assert!(now.generation > generation, "a fresh agent was not started");
|
||||
h.wait_for_output(READY, 2);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn restart_mid_step_kills_the_step_at_once_instead_of_waiting_for_it() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("STEP 30");
|
||||
h.wait_for_output("working 1/30", 1);
|
||||
|
||||
let started = Instant::now();
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
// Running again straight away: no wait for the step to finish.
|
||||
h.wait_state("Running again", is_running);
|
||||
h.wait_for_output(READY, 2);
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"restart must not wait on the step; took {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
assert!(
|
||||
!h.seen.contains("STEP DONE"),
|
||||
"the step should have been cut short, not finished"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_that_exits_by_itself_ends_with_its_code_and_nothing_restarts() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("EXIT 7");
|
||||
|
||||
let ended = h.wait_state("Ended", |s| matches!(s.state, AgentState::Ended { .. }));
|
||||
match &ended.state {
|
||||
AgentState::Ended { reason } => assert!(reason.contains('7'), "reason was {reason:?}"),
|
||||
other => panic!("expected Ended, got {other:?}"),
|
||||
}
|
||||
|
||||
// Nothing starts without a press.
|
||||
h.pump_for(Duration::from_millis(1500));
|
||||
assert!(matches!(
|
||||
h.manager.snapshot().state,
|
||||
AgentState::Ended { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
h.seen.matches(READY).count(),
|
||||
1,
|
||||
"an agent started by itself"
|
||||
);
|
||||
assert!(!h.manager.is_active());
|
||||
|
||||
// A press of Restart starts a fresh one on the same brief.
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
assert_eq!(h.manager.snapshot().state, AgentState::Running);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn quitting_with_a_running_agent_stops_it() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
assert!(h.manager.is_active());
|
||||
h.type_line("PID");
|
||||
h.wait_for_output("PID ", 1);
|
||||
let pid = h
|
||||
.seen
|
||||
.rsplit("PID ")
|
||||
.next()
|
||||
.unwrap()
|
||||
.trim_start()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse::<u32>()
|
||||
.expect("the agent's pid");
|
||||
assert!(
|
||||
process_alive(pid),
|
||||
"the agent should be running before the stop"
|
||||
);
|
||||
|
||||
h.manager.stop();
|
||||
|
||||
assert!(!process_alive(pid), "the agent's process outlived stop()");
|
||||
|
||||
assert_eq!(h.manager.snapshot().state, AgentState::Idle);
|
||||
assert!(!h.manager.is_active());
|
||||
// The stopped agent does not come back or print again.
|
||||
let before = h.seen.len();
|
||||
h.pump_for(Duration::from_millis(1000));
|
||||
assert!(
|
||||
!h.seen[before..].contains(READY),
|
||||
"an agent started after the stop"
|
||||
);
|
||||
assert!(
|
||||
h.manager.restart().is_err(),
|
||||
"there is nothing left to restart"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_replay_buffer_holds_recent_output_and_clears_on_a_fresh_agent() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned();
|
||||
assert!(
|
||||
replay.contains(READY),
|
||||
"replay should hold what was just printed; got {replay:?}"
|
||||
);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned();
|
||||
assert_eq!(
|
||||
replay.matches(READY).count(),
|
||||
1,
|
||||
"a fresh agent's replay must not carry the old one's output"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_restart_runs_the_brief_hook_and_the_bar_gets_its_note() {
|
||||
let mut h = Harness::new();
|
||||
let runs = Arc::new(Mutex::new(0));
|
||||
let counter = Arc::clone(&runs);
|
||||
h.manager.set_before_fresh(Arc::new(move || {
|
||||
*counter.lock().unwrap() += 1;
|
||||
Some("Brief ready on the dashboard".to_string())
|
||||
}));
|
||||
h.start_and_wait_ready();
|
||||
assert_eq!(*runs.lock().unwrap(), 0, "a first start leaves no brief");
|
||||
assert_eq!(h.manager.snapshot().brief_note, None);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
*runs.lock().unwrap(),
|
||||
1,
|
||||
"the restart did not run the brief once"
|
||||
);
|
||||
assert_eq!(
|
||||
h.manager.snapshot().brief_note.as_deref(),
|
||||
Some("Brief ready on the dashboard")
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() {
|
||||
let mut h = Harness::new();
|
||||
h.manager.set_env(vec![
|
||||
("PLAN2CODE_IN_APP".to_string(), "1".to_string()),
|
||||
(
|
||||
"PLAN2CODE_CONSOLE_SID".to_string(),
|
||||
"sid-window-a".to_string(),
|
||||
),
|
||||
]);
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
h.wait_for_output("ENV PLAN2CODE_IN_APP=1", 1);
|
||||
h.type_line("ENV PLAN2CODE_CONSOLE_SID");
|
||||
h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-a", 1);
|
||||
|
||||
// The signal changes with the console; a Restart starts on the newest.
|
||||
h.manager.set_env(vec![(
|
||||
"PLAN2CODE_CONSOLE_SID".to_string(),
|
||||
"sid-window-b".to_string(),
|
||||
)]);
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
h.type_line("ENV PLAN2CODE_CONSOLE_SID");
|
||||
h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-b", 1);
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
h.wait_for_output("ENV PLAN2CODE_IN_APP=\r", 1);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_with_no_signal_set_gets_none() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
h.wait_for_output("ENV PLAN2CODE_IN_APP=", 1);
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
//! Shared by the integration tests: where the fake agent program is, and
|
||||
//! whether a process id is still alive.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::sync::Once;
|
||||
|
||||
/// Is a process with this id still there? Asks the operating system.
|
||||
#[allow(dead_code)]
|
||||
pub fn process_alive(pid: u32) -> bool {
|
||||
if cfg!(windows) {
|
||||
let out = Command::new("tasklist")
|
||||
.args(["/FI", &format!("PID eq {pid}"), "/NH"])
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.split_whitespace()
|
||||
.any(|word| word == pid.to_string())
|
||||
} else {
|
||||
Command::new("kill")
|
||||
.args(["-0", &pid.to_string()])
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn fake_agent() -> PathBuf {
|
||||
// `cargo test` does not build another package's program, so build it once.
|
||||
static BUILD: Once = Once::new();
|
||||
BUILD.call_once(|| {
|
||||
let status = Command::new(env!("CARGO"))
|
||||
.args(["build", "-p", "fake-agent"])
|
||||
.status()
|
||||
.expect("run cargo");
|
||||
assert!(status.success(), "could not build the fake agent");
|
||||
});
|
||||
// The test binary is in target/<profile>/deps; the fake agent is one up.
|
||||
let exe = std::env::current_exe().unwrap();
|
||||
let path = exe
|
||||
.parent()
|
||||
.and_then(|deps| deps.parent())
|
||||
.unwrap()
|
||||
.join(format!("fake-agent{}", std::env::consts::EXE_SUFFIX));
|
||||
assert!(
|
||||
path.exists(),
|
||||
"{} is missing after building the fake agent",
|
||||
path.display()
|
||||
);
|
||||
path
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
//! The supervisor against the real console: a temp project, no agent, no
|
||||
//! Tauri. `PLAN2CODE_CONSOLE_DIR` points the lookup at the repo's own console
|
||||
//! source and `PLAN2CODE_CONSOLE_HOME` keeps the sessions out of the user's
|
||||
//! real console folder. Skipped entirely when node is not on PATH.
|
||||
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, ConsoleSupervisor};
|
||||
|
||||
fn have_node() -> bool {
|
||||
Command::new("node")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn repo_console_dir() -> PathBuf {
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console")
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-sup-{name}-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn setup() -> Option<PathBuf> {
|
||||
if !have_node() {
|
||||
eprintln!("skipping: node is not on PATH");
|
||||
return None;
|
||||
}
|
||||
let console = repo_console_dir();
|
||||
assert!(
|
||||
console.join("console.mjs").is_file(),
|
||||
"console source missing at {}",
|
||||
console.display()
|
||||
);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_HOME", temp_dir("home"));
|
||||
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
|
||||
// Run inside the desktop app, the agent's in-app variables would have this
|
||||
// console announce itself to the live window and take it over.
|
||||
for name in [
|
||||
"PLAN2CODE_IN_APP",
|
||||
"PLAN2CODE_APP_ANNOUNCE",
|
||||
"PLAN2CODE_APP_TOKEN",
|
||||
"PLAN2CODE_CONSOLE_SID",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
}
|
||||
Some(temp_dir("project"))
|
||||
}
|
||||
|
||||
fn kill_pid(pid: u32) {
|
||||
#[cfg(windows)]
|
||||
let _ = Command::new("taskkill")
|
||||
.args(["/PID", &pid.to_string(), "/F"])
|
||||
.output();
|
||||
#[cfg(not(windows))]
|
||||
let _ = Command::new("kill").args(["-9", &pid.to_string()]).output();
|
||||
}
|
||||
|
||||
/// The detached server can take a beat to bind or die; ask until `want` holds.
|
||||
fn until_health(sup: &ConsoleSupervisor, want: bool) -> bool {
|
||||
let deadline = Instant::now() + Duration::from_secs(15);
|
||||
while Instant::now() < deadline {
|
||||
if sup.health() == want {
|
||||
return true;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn starts_answers_and_stops() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start");
|
||||
assert!(!sup.session().sid.is_empty());
|
||||
assert!(sup.session().url.starts_with("http://127.0.0.1:"));
|
||||
assert!(sup.session().pid > 0);
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
|
||||
sup.stop().expect("stop");
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"the console still answered after stop()"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_killed_console_is_dead_and_restarts() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start");
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
let first_sid = sup.session().sid.clone();
|
||||
|
||||
kill_pid(sup.session().pid);
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"a killed console still looked alive"
|
||||
);
|
||||
|
||||
assert!(
|
||||
sup.restart_if_dead().expect("restart"),
|
||||
"restart_if_dead did nothing"
|
||||
);
|
||||
assert_eq!(
|
||||
sup.session().sid,
|
||||
first_sid,
|
||||
"a dead console comes back on the same session, so its page and place survive"
|
||||
);
|
||||
assert!(
|
||||
until_health(&sup, true),
|
||||
"the restarted console never answered"
|
||||
);
|
||||
sup.stop().expect("stop");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_live_console_is_not_restarted() {
|
||||
let Some(project) = setup() else { return };
|
||||
let mut sup = ConsoleSupervisor::start(project, app_origin().to_string()).expect("start");
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
assert!(!sup.restart_if_dead().expect("restart check"));
|
||||
sup.stop().expect("stop");
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
//! The PTY host against the fake agent in a real pseudo-terminal. Real agents
|
||||
//! are never started here.
|
||||
|
||||
use std::sync::mpsc::{channel, Receiver, RecvTimeoutError};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
mod common;
|
||||
use common::fake_agent;
|
||||
|
||||
fn start_fake() -> (PtyHost, Receiver<Vec<u8>>) {
|
||||
let (tx, rx) = channel();
|
||||
let host = PtyHost::start(
|
||||
StartOptions {
|
||||
program: fake_agent().to_string_lossy().into_owned(),
|
||||
args: vec![],
|
||||
env: vec![],
|
||||
cwd: None,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
},
|
||||
move |bytes| {
|
||||
let _ = tx.send(bytes);
|
||||
},
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
(host, rx)
|
||||
}
|
||||
|
||||
/// Collect output until `needle` appears; panic with what arrived if it does not.
|
||||
/// Windows' pseudo-terminal asks where the cursor is (ESC [ 6 n) and holds the
|
||||
/// output until it is told, as a real terminal such as xterm does on its own.
|
||||
fn wait_for(host: &PtyHost, rx: &Receiver<Vec<u8>>, seen: &mut String, needle: &str) {
|
||||
let deadline = Instant::now() + Duration::from_secs(20);
|
||||
while !seen.contains(needle) {
|
||||
let left = deadline.saturating_duration_since(Instant::now());
|
||||
match rx.recv_timeout(left) {
|
||||
Ok(bytes) => {
|
||||
let text = String::from_utf8_lossy(&bytes);
|
||||
for _ in text.matches("[6n") {
|
||||
host.write(b"[1;1R").unwrap();
|
||||
}
|
||||
seen.push_str(&text);
|
||||
}
|
||||
Err(RecvTimeoutError::Timeout) | Err(RecvTimeoutError::Disconnected) => {
|
||||
panic!("never saw {needle:?}; got {seen:?}")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn banner_arrives() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.kill().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_line_is_echoed() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"hello there\r").unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "echo: hello there");
|
||||
host.kill().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resize_reaches_the_child() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "SIZE 80x24");
|
||||
host.resize(100, 30).unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "SIZE 100x30");
|
||||
host.kill().unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exit_code_is_returned() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"EXIT 3\r").unwrap();
|
||||
assert_eq!(host.wait().unwrap(), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn kill_ends_a_running_step() {
|
||||
let (host, rx) = start_fake();
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"STEP 30\r").unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "working 1/30");
|
||||
let started = Instant::now();
|
||||
host.kill().unwrap();
|
||||
host.wait().unwrap();
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"kill took too long"
|
||||
);
|
||||
}
|
||||
|
||||
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
|
||||
/// program (here, the fake agent) its grandchild. `kill` must end both, not
|
||||
/// just `cmd.exe` (Task 9.8).
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn kill_ends_a_cmd_wrapped_grandchild_too() {
|
||||
use common::process_alive;
|
||||
use plan2code_app_lib::agents::windows_command;
|
||||
use std::fs;
|
||||
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-pty-cmdshim-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let shim = dir.join("shim.cmd");
|
||||
fs::write(
|
||||
&shim,
|
||||
format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (program, args) = windows_command("shim", vec![], &dir.to_string_lossy());
|
||||
let path = format!(
|
||||
"{};{}",
|
||||
dir.to_string_lossy(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
let (tx, rx) = channel();
|
||||
let host = PtyHost::start(
|
||||
// `cmd /c shim.cmd` is a bare name: like a real npm shim, cmd.exe
|
||||
// only finds it on PATH, never by the current directory alone.
|
||||
StartOptions {
|
||||
program,
|
||||
args,
|
||||
env: vec![("PATH".to_string(), path)],
|
||||
cwd: None,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
},
|
||||
move |bytes| {
|
||||
let _ = tx.send(bytes);
|
||||
},
|
||||
)
|
||||
.expect("start the cmd-wrapped fake agent");
|
||||
|
||||
let mut seen = String::new();
|
||||
wait_for(&host, &rx, &mut seen, "FAKE-AGENT ready");
|
||||
host.write(b"PID\r").unwrap();
|
||||
wait_for(&host, &rx, &mut seen, "PID ");
|
||||
let pid: u32 = seen
|
||||
.rsplit("PID ")
|
||||
.next()
|
||||
.unwrap()
|
||||
.trim_start()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("the grandchild's pid");
|
||||
assert!(
|
||||
process_alive(pid),
|
||||
"the grandchild should be running before kill"
|
||||
);
|
||||
|
||||
host.kill().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
while process_alive(pid) && Instant::now() < deadline {
|
||||
std::thread::sleep(Duration::from_millis(50));
|
||||
}
|
||||
assert!(!process_alive(pid), "the grandchild outlived kill()");
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
}
|
||||
@@ -0,0 +1,333 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta http-equiv="Content-Security-Policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' ipc: http://ipc.localhost; frame-src http://127.0.0.1:*; object-src 'none'; base-uri 'none'">
|
||||
<title>Plan2Code</title>
|
||||
<link rel="stylesheet" href="vendor/xterm.css">
|
||||
<style>
|
||||
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; background: #1e1e1e; color: #ddd; }
|
||||
body { display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* The console's dark tokens and its default highlight (Ocean). app.js sets
|
||||
the four accent ones to the person's own highlight once the console page
|
||||
says which it is, and keeps them for the next launch. */
|
||||
:root {
|
||||
--panel: #201d1a; --panel-2: #262220; --ink: #f0ece5; --ink-2: #b6afa3; --ink-3: #8b8376; --rule-2: #46403a;
|
||||
--accent: #619fe5; --accent-soft: #1a2533; --accent-ink: #0c1117; --accent-line: #3d5978;
|
||||
}
|
||||
|
||||
#bar { flex: none; border-bottom: 1px solid #444; }
|
||||
/* The console's top bar buttons (.btn small ghost), sized to this bar:
|
||||
quiet until hovered, then in the highlight color. New Session is the
|
||||
one that is often the next step, so it wears the highlight outline at
|
||||
rest, like the console's standby buttons. */
|
||||
#bar button {
|
||||
appearance: none; font: inherit; font-size: 12px; font-weight: 600; line-height: 1.2;
|
||||
padding: 4px 10px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink-2);
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
#bar button:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); background: var(--panel-2); }
|
||||
#bar button:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
#bar button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
#bar #agent-restart { background: transparent; border-color: var(--accent-line); color: var(--accent); }
|
||||
#bar #agent-restart:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent); }
|
||||
#bar-row { height: 34px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px; font-size: 12px; white-space: nowrap; overflow-x: auto; overflow-y: hidden; }
|
||||
#bar [hidden] { display: none !important; }
|
||||
/* The project and agent menus' triggers: plain text until hovered, a
|
||||
caret saying there is more behind them. */
|
||||
#bar .bar-menu { display: inline-flex; align-items: center; gap: 6px; flex: none; border-color: transparent; background: transparent; color: var(--ink); padding: 4px 8px; }
|
||||
#bar .bar-menu:hover:not(:disabled), #bar .bar-menu[aria-expanded="true"] { background: var(--panel-2); border-color: transparent; color: var(--ink); }
|
||||
.bar-caret { color: var(--ink-3); font-size: 10px; }
|
||||
#project-name { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.agent-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: #666; }
|
||||
.agent-dot.is-ok { background: #6a9955; }
|
||||
.agent-dot.is-warn { background: #d7ba7d; }
|
||||
#agent-ended { color: var(--ink-3); font-weight: 400; }
|
||||
#agent-bypass { flex: none; font-size: 11px; font-weight: 600; line-height: 1.3; padding: 0 7px; border-radius: 999px; border: 1px solid #d7ba7d; color: #d7ba7d; }
|
||||
#agent-none { color: var(--ink-3); }
|
||||
#agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; }
|
||||
#agent-status.is-error { color: #f48771; }
|
||||
#bar-grow { flex: 1; min-width: 0; }
|
||||
/* The one next step for the console or the skills, at the right end. */
|
||||
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||
#next-step-text { overflow: hidden; text-overflow: ellipsis; max-width: 320px; }
|
||||
#next-step-text.is-ok { color: #6a9955; }
|
||||
#next-step-text.is-warn { color: #d7ba7d; }
|
||||
#next-step-text.is-err { color: #f48771; }
|
||||
#next-step-text.is-busy::before {
|
||||
content: ""; display: inline-block; width: 8px; height: 8px; margin-right: 6px; vertical-align: -1px;
|
||||
border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: bar-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes bar-spin { to { transform: rotate(360deg); } }
|
||||
#bar #next-step-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
#bar #next-step-button:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); filter: brightness(1.12); }
|
||||
#next-step-more { color: var(--ink-3); font-size: 11px; border-bottom: 1px dotted var(--ink-3); cursor: help; }
|
||||
/* The menus sit outside the scrolling row (fixed, placed under their
|
||||
trigger by app.js), so the row's overflow never clips them. */
|
||||
.bar-dropdown {
|
||||
position: fixed; z-index: 20; min-width: 240px; max-width: 380px; padding: 6px; box-sizing: border-box;
|
||||
font-size: 12px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: 8px; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.bar-dropdown-head { margin: 0; padding: 4px 8px 8px; color: var(--ink-3); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.bar-dropdown-head b { color: var(--ink); font-weight: 600; }
|
||||
.bar-dropdown-head .is-warn { color: #d7ba7d; }
|
||||
#bar .bar-dropdown button {
|
||||
display: block; width: 100%; text-align: left; font-weight: 400; padding: 6px 8px; border: 0; border-radius: 6px;
|
||||
background: transparent; color: var(--ink);
|
||||
}
|
||||
#bar .bar-dropdown button:hover:not(:disabled), #bar .bar-dropdown button:focus-visible { background: var(--panel-2); color: var(--accent); }
|
||||
|
||||
#workspace { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
#workspace.dock-right { flex-direction: row; }
|
||||
|
||||
#dashboard { flex: 1; min-height: 0; min-width: 0; position: relative; }
|
||||
#console-frame { position: absolute; inset: 0; width: 100%; height: 100%; border: 0; background: #1e1e1e; }
|
||||
#dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: #1e1e1e; text-align: center; padding: 16px; box-sizing: border-box; }
|
||||
#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 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) {
|
||||
fill: none; stroke: var(--ink-2); stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
#dashboard-state-planny .ps-shell { fill: var(--panel-2); }
|
||||
#dashboard-state-planny .ps-smile { stroke-width: 0.9; }
|
||||
#dashboard-state-planny .ps-arm path { stroke-width: 1.2; }
|
||||
#dashboard-state-planny :is(.ps-arm circle, .ps-foot) { fill: var(--ink-2); stroke: none; }
|
||||
#dashboard-state-planny .ps-eye { fill: var(--ink); }
|
||||
#dashboard-state-planny .ps-mug { fill: var(--panel-2); stroke-width: 1; }
|
||||
#dashboard-state-planny .ps-handle { stroke-width: 0.9; }
|
||||
#dashboard-state-planny .ps-coffee { fill: #9a6b47; }
|
||||
#dashboard-state-planny .ps-steam path {
|
||||
fill: none; stroke: var(--ink-3); stroke-width: 0.7; stroke-linecap: round;
|
||||
animation: ps-steam 2.4s ease-in-out infinite; opacity: 0;
|
||||
}
|
||||
#dashboard-state-planny .ps-steam path:nth-child(2) { animation-delay: 0.8s; }
|
||||
#dashboard-state-planny .ps-steam path:nth-child(3) { animation-delay: 1.6s; }
|
||||
@keyframes ps-steam {
|
||||
0% { opacity: 0; transform: translateY(1px); }
|
||||
35% { opacity: 0.9; }
|
||||
100% { opacity: 0; transform: translateY(-2.4px); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#dashboard-state-planny .ps-steam path { animation: none; opacity: 0.8; }
|
||||
}
|
||||
/* The console's buttons (.btn, with .primary for the way forward): the
|
||||
one action wears the highlight, Cancel is a plain button. */
|
||||
#dashboard-state-actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
|
||||
#dashboard-state-actions button {
|
||||
appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; line-height: 1.2;
|
||||
padding: 7px 13px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
transition: filter 0.12s, background 0.12s;
|
||||
}
|
||||
#dashboard-state-actions button:hover { background: var(--panel-2); }
|
||||
#dashboard-state-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
#dashboard-state-actions #dashboard-state-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
#dashboard-state-actions #dashboard-state-button:hover { background: var(--accent); filter: brightness(1.08); }
|
||||
#dashboard-state-actions button[hidden] { display: none; }
|
||||
|
||||
#launch-card {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
align-items: stretch; justify-content: center; gap: 10px; background: #1e1e1e;
|
||||
padding: 24px; box-sizing: border-box; width: min(360px, 100%); margin: 0 auto;
|
||||
}
|
||||
#launch-card[hidden] { display: none; }
|
||||
#launch-card h2 { margin: 0 0 6px; font-size: 17px; text-align: center; }
|
||||
#launch-card label { font-size: 12px; color: #9ab; }
|
||||
#launch-card select, #launch-card input[type="text"] {
|
||||
width: 100%; box-sizing: border-box; margin: 4px 0 2px; padding: 6px 8px;
|
||||
background: #2a2a2a; color: #ddd; border: 1px solid #555; border-radius: 4px; font: inherit;
|
||||
}
|
||||
#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; }
|
||||
.agent-explainer button, #launch-missing button { font: inherit; font-size: 12px; margin-left: 6px; padding: 1px 8px; cursor: pointer; }
|
||||
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: #75beff; text-decoration: underline; }
|
||||
#launch-effort-row[hidden] { display: none; }
|
||||
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: #ccc; font-size: 13px; cursor: pointer; }
|
||||
#launch-bypass-row input { margin: 0; }
|
||||
#launch-bypass-warning { margin: 0; font-size: 12px; color: #d7ba7d; }
|
||||
#launch-bypass-warning[hidden] { display: none; }
|
||||
#launch-start {
|
||||
margin-top: 6px; padding: 8px; background: #2d6a4f; color: #fff; border: 0; border-radius: 4px;
|
||||
font: inherit; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
#launch-start:hover { background: #357a5c; }
|
||||
#launch-start:disabled { background: #444; color: #888; cursor: not-allowed; }
|
||||
|
||||
#first-run {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
align-items: stretch; justify-content: center; gap: 14px; background: #1e1e1e;
|
||||
padding: 24px; box-sizing: border-box; width: min(420px, 100%); margin: 0 auto;
|
||||
}
|
||||
#first-run[hidden] { display: none; }
|
||||
#first-run h2 { margin: 0; font-size: 17px; text-align: center; }
|
||||
#first-run-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 10px; }
|
||||
.first-run-row { display: flex; align-items: flex-start; gap: 8px; font-size: 13px; }
|
||||
.first-run-mark { flex: none; width: 16px; text-align: center; font-weight: 700; }
|
||||
.first-run-row.is-pass .first-run-mark { color: #6a9955; }
|
||||
.first-run-row.is-fail .first-run-mark { color: #d7ba7d; }
|
||||
.first-run-body { flex: 1; min-width: 0; }
|
||||
.first-run-title { color: #ddd; }
|
||||
.first-run-detail { color: #9ab; font-size: 12px; margin-top: 2px; }
|
||||
.first-run-detail code { color: #ddd; }
|
||||
.first-run-row button {
|
||||
margin-top: 4px; background: none; border: 1px solid #555; color: #ccc; border-radius: 3px;
|
||||
font: inherit; font-size: 12px; padding: 3px 8px; cursor: pointer;
|
||||
}
|
||||
.first-run-row button:hover { background: #333; }
|
||||
#first-run-start {
|
||||
margin-top: 6px; padding: 8px; background: #2d6a4f; color: #fff; border: 0; border-radius: 4px;
|
||||
font: inherit; font-weight: 600; cursor: pointer;
|
||||
}
|
||||
#first-run-start:hover { background: #357a5c; }
|
||||
#first-run-start:disabled { background: #444; color: #888; cursor: not-allowed; }
|
||||
|
||||
#term-handle { flex: none; background: #2a2a2a; }
|
||||
#term-handle:hover { background: #3d3d3d; }
|
||||
#term-handle[hidden] { display: none; }
|
||||
#workspace:not(.dock-right) #term-handle { height: 6px; cursor: row-resize; }
|
||||
#workspace.dock-right #term-handle { width: 6px; cursor: col-resize; }
|
||||
|
||||
#term-panel { flex: none; display: flex; flex-direction: column; min-height: 0; min-width: 0; }
|
||||
#workspace:not(.dock-right) #term-panel { border-top: 1px solid #444; }
|
||||
#workspace.dock-right #term-panel { border-left: 1px solid #444; }
|
||||
#term-panel.collapsed { height: 28px !important; }
|
||||
#workspace.dock-right #term-panel.collapsed { width: 28px !important; height: auto !important; }
|
||||
#term-panel.collapsed #term { display: none; }
|
||||
#term-toolbar { flex: none; display: flex; align-items: center; gap: 6px; padding: 3px 6px; background: #252525; font-size: 11px; }
|
||||
#workspace.dock-right #term-toolbar { flex-direction: column; align-items: stretch; }
|
||||
#term-toolbar-spacer { flex: 1; min-height: 0; }
|
||||
#term-toolbar button {
|
||||
background: none; border: 1px solid #555; color: #ccc; border-radius: 3px;
|
||||
font-size: 11px; padding: 2px 6px; cursor: pointer; font-family: inherit;
|
||||
}
|
||||
#term-toolbar button:hover { background: #333; }
|
||||
#term-toolbar button[aria-pressed="true"] { color: #fff; border-color: #888; }
|
||||
#term-panel.collapsed #term-dock, #term-panel.collapsed #term-maximize { display: none; }
|
||||
/* Docked right and collapsed, the panel is a 28px-wide strip: "View Agent
|
||||
Terminal" does not fit sideways, so it reads top-to-bottom instead, rotated the
|
||||
same way a reader would turn the panel to read it. */
|
||||
#workspace.dock-right #term-panel.collapsed #term-toolbar { padding: 6px 2px; align-items: center; }
|
||||
#workspace.dock-right #term-panel.collapsed #term-collapse {
|
||||
writing-mode: vertical-rl; text-orientation: mixed; padding: 6px 2px;
|
||||
}
|
||||
#term-badge { color: #d7ba7d; font-size: 14px; line-height: 1; }
|
||||
#term-badge[hidden] { display: none; }
|
||||
#term { flex: 1; min-height: 0; min-width: 0; padding: 4px; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<header id="bar">
|
||||
<div id="bar-row">
|
||||
<button id="project-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="project-menu" hidden><span id="project-name"></span><span class="bar-caret" aria-hidden="true">▾</span></button>
|
||||
<!-- Whenever an agent exists, running or ended, just left of its menu. -->
|
||||
<button id="agent-restart" hidden>New Session</button>
|
||||
<button id="agent-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="agent-menu" hidden><span id="agent-dot" class="agent-dot" aria-hidden="true"></span><span id="agent-name"></span><span id="agent-ended" hidden>ended</span><span id="agent-bypass" title="Permission checks are off: the agent runs commands and changes files without asking" hidden>checks off</span><span class="bar-caret" aria-hidden="true">▾</span></button>
|
||||
<span id="agent-none">No agent</span>
|
||||
<span id="agent-status" role="status"></span>
|
||||
<span id="bar-grow"></span>
|
||||
<!-- The console's or the skills' one next step (meter.js barNextSteps), when there is one. -->
|
||||
<span id="next-step" role="status" hidden>
|
||||
<span id="next-step-text"></span>
|
||||
<button id="next-step-button" hidden></button>
|
||||
<span id="next-step-more" hidden></span>
|
||||
</span>
|
||||
</div>
|
||||
<div id="project-menu" class="bar-dropdown" role="menu" aria-label="Project" hidden>
|
||||
<p class="bar-dropdown-head">Project<br><b id="project-path"></b></p>
|
||||
<button id="change-project" role="menuitem">Change project...</button>
|
||||
</div>
|
||||
<div id="agent-menu" class="bar-dropdown" role="menu" aria-label="Agent" hidden>
|
||||
<p id="agent-menu-head" class="bar-dropdown-head"></p>
|
||||
<button id="change-agent" role="menuitem" hidden>Change agent...</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="workspace">
|
||||
<main id="dashboard">
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></iframe>
|
||||
<div id="dashboard-state" hidden>
|
||||
<!-- Planny on a coffee break: shown only before a New Session press,
|
||||
the one state here that is a question rather than a status. The
|
||||
console's own Planny (shell, star eye, smile, feet, resting left
|
||||
arm) with the right arm reaching out to a steaming mug. -->
|
||||
<svg id="dashboard-state-planny" viewBox="0 7 29 23" aria-hidden="true" focusable="false" hidden>
|
||||
<rect class="ps-foot" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="ps-foot" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="ps-shell" x="3" y="7" width="16" height="20" rx="3.2" />
|
||||
<path class="ps-eye" d="M11 10.95 L11.79 12.91 L13.9 13.06 L12.28 14.42 L12.79 16.47 L11 15.35 L9.21 16.47 L9.72 14.42 L8.1 13.06 L10.21 12.91 Z" />
|
||||
<path class="ps-smile" d="M8.3 18.4 Q11 21 13.7 18.4" />
|
||||
<g class="ps-arm"><path d="M3 18 L1.3 21" /><circle cx="1.3" cy="21" r="0.85" /></g>
|
||||
<g class="ps-steam">
|
||||
<path d="M23 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
<path d="M24.4 17.1 q0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
<path d="M25.8 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
</g>
|
||||
<g class="ps-arm"><path d="M19 18 L21.6 20.6" /><circle cx="21.6" cy="20.6" r="0.85" /></g>
|
||||
<path class="ps-handle" d="M26.7 19.6 h0.3 a1.15 1.15 0 0 1 0 2.3 h-0.3" />
|
||||
<rect class="ps-mug" x="22.4" y="18.4" width="4.3" height="4.6" rx="0.8" />
|
||||
<rect class="ps-coffee" x="23" y="19" width="3.1" height="0.8" rx="0.35" />
|
||||
</svg>
|
||||
<p id="dashboard-state-text"></p>
|
||||
<span id="dashboard-state-actions">
|
||||
<button id="dashboard-state-button" hidden></button>
|
||||
<button id="dashboard-state-cancel" hidden>Cancel</button>
|
||||
</span>
|
||||
</div>
|
||||
<div id="first-run" hidden>
|
||||
<h2>Before you start</h2>
|
||||
<ul id="first-run-list"></ul>
|
||||
<button id="first-run-start" type="button" disabled>Start</button>
|
||||
</div>
|
||||
<form id="launch-card" hidden>
|
||||
<h2>Start an agent</h2>
|
||||
<label for="launch-agent">Agent</label>
|
||||
<select id="launch-agent">
|
||||
<option value="claude">Claude Code</option>
|
||||
<option value="devin">Devin</option>
|
||||
<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>
|
||||
<div id="launch-effort-row">
|
||||
<label for="launch-effort">Effort</label>
|
||||
<select id="launch-effort"></select>
|
||||
</div>
|
||||
<label id="launch-bypass-row">
|
||||
<input id="launch-bypass" type="checkbox" checked>
|
||||
Turn permission checks off for this agent
|
||||
</label>
|
||||
<p id="launch-bypass-warning">Permission checks will be off: the agent can run commands and change files without asking first.</p>
|
||||
<button id="launch-start" type="submit">Start agent</button>
|
||||
</form>
|
||||
</main>
|
||||
<div id="term-handle" title="Drag to resize the terminal panel"></div>
|
||||
<section id="term-panel">
|
||||
<div id="term-toolbar">
|
||||
<span id="term-badge" title="The agent has been quiet a while" hidden>●</span>
|
||||
<span id="term-toolbar-spacer"></span>
|
||||
<button id="term-dock" type="button">Dock right</button>
|
||||
<button id="term-maximize" type="button" aria-pressed="false">Maximize</button>
|
||||
<button id="term-collapse" type="button" aria-pressed="false">Collapse</button>
|
||||
</div>
|
||||
<div id="term"></div>
|
||||
</section>
|
||||
</div>
|
||||
<script src="vendor/xterm.js"></script>
|
||||
<script src="vendor/addon-fit.js"></script>
|
||||
<script type="module" src="app.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,165 @@
|
||||
// The bar's pure decisions, kept out of app.js so they can be imported and
|
||||
// tested without a DOM or `window.__TAURI__` (app.js touches both at module
|
||||
// scope, the same reason the web console keeps its own pure logic in
|
||||
// answers.js rather than app.js).
|
||||
|
||||
// The button label for each next-step action. Both ways of reconnecting the
|
||||
// console read the same, wherever they come from.
|
||||
export const NEXT_STEP_LABELS = {
|
||||
reconnect: 'Reconnect the console',
|
||||
'restart-console': 'Reconnect the console',
|
||||
update: 'Update skills',
|
||||
};
|
||||
|
||||
/**
|
||||
* What the console page's **continue** button types into the agent's
|
||||
* terminal, one write each: the word, then Enter. Claude Code holds typed
|
||||
* text as a queued message while its turn is busy, and the button only shows
|
||||
* once the agent stopped checking in with the console, so by then the turn is
|
||||
* stuck and the queued word would never send by itself: for it, the send-now
|
||||
* chord (ctrl+x ctrl+s) follows. Any id it does not know (a custom agent)
|
||||
* gets the plain word and Enter.
|
||||
*/
|
||||
export function continueKeys(kind) {
|
||||
const keys = ['continue', '\r'];
|
||||
if (kind === 'claude') keys.push('\x18\x13');
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* Which agent the launch card starts on, from `agent_availability`'s list
|
||||
* (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. 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 : [];
|
||||
const rememberedEntry = list.find((a) => a.id === remembered);
|
||||
if (rememberedEntry && rememberedEntry.installed) return remembered;
|
||||
const builtIn = list.find((a) => a.installed && !a.custom);
|
||||
if (builtIn) return builtIn.id;
|
||||
const custom = list.find((a) => a.installed && a.custom);
|
||||
if (custom) return custom.id;
|
||||
if (remembered && (rememberedEntry || list.length === 0)) return remembered;
|
||||
return list.length > 0 ? list[0].id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the right end of the bar offers, most pressing first: the bar shows
|
||||
* the first step (short text plus its one button) and counts the rest as
|
||||
* "+N more". `consoleDead` is whether the console stopped answering;
|
||||
* `version` is the skills/app version state, or null when they agree:
|
||||
* `{ kind: 'mismatch' | 'ahead' | 'remains', skills, app }`,
|
||||
* `{ kind: 'updating', line }`, `{ kind: 'updated' }`, `{ kind: 'too-old' }`
|
||||
* or `{ kind: 'failed', error }`.
|
||||
*
|
||||
* Only one control for "reconnect the console" is ever offered: after an
|
||||
* update, its Reconnect (which stops the old console first, so the new skills
|
||||
* are really picked up) covers a console that has also stopped.
|
||||
*/
|
||||
export function barNextSteps({ consoleDead = false, version = null } = {}) {
|
||||
const v = version || {};
|
||||
const steps = [];
|
||||
if (v.kind === 'updated') {
|
||||
steps.push({ id: 'updated', text: 'Skills updated', title: 'Updated. Reconnect the console to use the new version.', tone: 'ok', action: 'restart-console' });
|
||||
} else if (consoleDead) {
|
||||
steps.push({ id: 'console-dead', text: 'Console stopped', title: 'The console stopped, so the dashboard cannot show.', tone: 'err', action: 'reconnect' });
|
||||
}
|
||||
switch (v.kind) {
|
||||
case 'too-old':
|
||||
steps.push({ id: 'too-old', text: 'Console too old for this app', title: 'The installed console is too old for the app. Update skills to fix it.', tone: 'warn', action: 'update' });
|
||||
break;
|
||||
case 'mismatch':
|
||||
steps.push({ id: 'mismatch', text: `Skills v${v.skills}, app v${v.app}`, title: `The installed skills are v${v.skills}, this app is v${v.app}.`, tone: 'warn', action: 'update' });
|
||||
break;
|
||||
case 'updating': {
|
||||
const line = v.line || 'Updating Plan2Code...';
|
||||
steps.push({ id: 'updating', text: line, title: line, tone: 'warn', busy: true, action: null });
|
||||
break;
|
||||
}
|
||||
case 'remains':
|
||||
steps.push({ id: 'remains', text: `Still mismatched: skills v${v.skills}, app v${v.app}`, title: `Updated, but the mismatch remains (skills v${v.skills}, app v${v.app}).`, tone: 'warn', action: null });
|
||||
break;
|
||||
case 'failed':
|
||||
steps.push({ id: 'failed', text: 'Update failed', title: String(v.error || 'The update did not finish.'), tone: 'err', action: 'update' });
|
||||
break;
|
||||
case 'ahead':
|
||||
steps.push({ id: 'ahead', text: `Skills v${v.skills} are newer than this app`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return steps.map((step) => ({ ...step, label: step.action ? NEXT_STEP_LABELS[step.action] : null }));
|
||||
}
|
||||
|
||||
// Below this many px of its own width, the console's "Notes on this" aside
|
||||
// stacks under the main column instead of sitting beside it
|
||||
// (src/web-console/public/styles/responsive.css's 1080px breakpoint).
|
||||
export const CONSOLE_ASIDE_BREAKPOINT_PX = 1080;
|
||||
// A roomy default width for the terminal docked at the side, before the
|
||||
// console's own width is taken into account.
|
||||
const IDEAL_RIGHT_PANE_PX = 440;
|
||||
|
||||
/**
|
||||
* The terminal panel's width, as a share of the window, for a first run with
|
||||
* nothing saved yet: docked right, at whatever width keeps the console's own
|
||||
* aside panel from stacking, down to `minFraction` when the window is too
|
||||
* narrow for both (its own minimum still wins over squeezing the console).
|
||||
*/
|
||||
export function defaultRightFraction(windowWidth, { minFraction, maxFraction, idealPanePx = IDEAL_RIGHT_PANE_PX, consoleMinPx = CONSOLE_ASIDE_BREAKPOINT_PX } = {}) {
|
||||
const roomForConsole = Math.max(0, windowWidth - consoleMinPx);
|
||||
const panePx = Math.min(idealPanePx, roomForConsole);
|
||||
const fraction = windowWidth > 0 ? panePx / windowWidth : minFraction;
|
||||
return Math.min(maxFraction, Math.max(minFraction, fraction));
|
||||
}
|
||||
|
||||
/**
|
||||
* The OS window title for a project folder: its own name (the repo's, most
|
||||
* of the time) after "Plan2Code - ", so two or more windows read apart in a
|
||||
* taskbar without opening each to see which project is which. Trailing
|
||||
* slashes and a drive root (`C:\`, `/`) leave nothing to show, so that falls
|
||||
* back to the plain title rather than a trailing "Plan2Code - ".
|
||||
*/
|
||||
export function windowTitleFor(dir) {
|
||||
const name = lastSegment(dir);
|
||||
return name ? `Plan2Code - ${name}` : "Plan2Code";
|
||||
}
|
||||
|
||||
/**
|
||||
* A project folder's own name, for the bar's project menu: the same last
|
||||
* segment the window title uses, or the whole path when there is none (a
|
||||
* root such as `/`), so the menu never shows an empty name.
|
||||
*/
|
||||
export function folderName(dir) {
|
||||
return lastSegment(dir) || String(dir || "").trim();
|
||||
}
|
||||
|
||||
function lastSegment(dir) {
|
||||
return String(dir || "")
|
||||
.trim()
|
||||
.replace(/[\\/]+$/, "")
|
||||
.split(/[\\/]/)
|
||||
.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;
|
||||
}
|
||||
@@ -0,0 +1,89 @@
|
||||
// The terminal panel: an xterm instance. It knows nothing about agents; the
|
||||
// page decides what goes in and where the keystrokes and size changes go.
|
||||
// Needs xterm.js and addon-fit.js loaded first (they set window.Terminal and
|
||||
// window.FitAddon), and withGlobalTauri for window.__TAURI__.
|
||||
|
||||
const { invoke } = window.__TAURI__.core;
|
||||
|
||||
export async function mountTerminal(container, { onInput, onResize }) {
|
||||
// Windows' pseudo-terminal rewraps lines itself; xterm needs to know the
|
||||
// backend and build to cope with that.
|
||||
const platform = await invoke('platform_info');
|
||||
const windowsPty = platform.os === 'windows'
|
||||
? { backend: 'conpty', buildNumber: platform.windowsBuild }
|
||||
: undefined;
|
||||
|
||||
const term = new window.Terminal({
|
||||
cursorBlink: true,
|
||||
fontFamily: 'Consolas, Menlo, "DejaVu Sans Mono", monospace',
|
||||
fontSize: 13,
|
||||
scrollback: 5000,
|
||||
windowsPty,
|
||||
});
|
||||
const fit = new window.FitAddon.FitAddon();
|
||||
term.loadAddon(fit);
|
||||
term.open(container);
|
||||
fit.fit();
|
||||
|
||||
// Keystrokes and pasted text go on as typed.
|
||||
term.onData((data) => onInput(data));
|
||||
|
||||
// A size change in the page becomes a size change in the pseudo-terminal.
|
||||
// The window's own resize event and the container's ResizeObserver both
|
||||
// fire for the same change, and a drag can fire either one many times a
|
||||
// second: `fit.fit()` stays immediate (cheap, local, keeps the screen
|
||||
// looking right as it happens), but the pty resize call is debounced to
|
||||
// one, on the settled size, so xterm and the pty always end up agreeing.
|
||||
const RESIZE_DEBOUNCE_MS = 100;
|
||||
let resizeTimer = null;
|
||||
const refit = () => {
|
||||
fit.fit();
|
||||
clearTimeout(resizeTimer);
|
||||
resizeTimer = setTimeout(() => {
|
||||
resizeTimer = null;
|
||||
onResize(term.cols, term.rows);
|
||||
}, RESIZE_DEBOUNCE_MS);
|
||||
};
|
||||
window.addEventListener('resize', refit);
|
||||
new ResizeObserver(refit).observe(container);
|
||||
|
||||
// Copy on selection, and an explicit shortcut for it: Ctrl+C is the pty's
|
||||
// own interrupt, so Ctrl+Shift+C (Windows, Linux) or Cmd+C (macOS) copies
|
||||
// instead, without being typed. Ctrl+V / Cmd+V paste from the clipboard
|
||||
// explicitly, rather than depending on the hidden textarea's own native
|
||||
// paste making it through every webview the same way.
|
||||
term.onSelectionChange(() => {
|
||||
const text = term.getSelection();
|
||||
if (text && navigator.clipboard) navigator.clipboard.writeText(text).catch(() => {});
|
||||
});
|
||||
term.attachCustomKeyEventHandler((event) => {
|
||||
if (event.type !== 'keydown' || !navigator.clipboard) return true;
|
||||
const key = event.key.toLowerCase();
|
||||
if (key === 'c' && ((event.ctrlKey && event.shiftKey) || (event.metaKey && !event.ctrlKey))) {
|
||||
const text = term.getSelection();
|
||||
if (text) navigator.clipboard.writeText(text).catch(() => {});
|
||||
return false;
|
||||
}
|
||||
if (key === 'v' && (event.ctrlKey || event.metaKey)) {
|
||||
navigator.clipboard
|
||||
.readText()
|
||||
.then((text) => {
|
||||
if (text) onInput(text);
|
||||
})
|
||||
.catch(() => {});
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
|
||||
return {
|
||||
size: () => ({ cols: term.cols, rows: term.rows }),
|
||||
// A fresh agent starts on a clean screen.
|
||||
reset() {
|
||||
term.reset();
|
||||
fit.fit();
|
||||
},
|
||||
write: (data) => term.write(data),
|
||||
focus: () => term.focus(),
|
||||
};
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -81,18 +81,46 @@ const SHOTS = {
|
||||
// The git board draws itself from a real repository, so this shot runs in
|
||||
// its own git sample project; the post only hands the board back to you.
|
||||
git: { workflow: "git", posts: ["git"], repo: true },
|
||||
// The Notepad dialog over the plan question, with a few lines of Markdown
|
||||
// typed into it. The store is the scratch folder's, never the real one.
|
||||
// The Notebook dialog over the plan question, with two named tabs: Call notes
|
||||
// (a heading, bullets and bold, shown live) and Ideas, with the first one
|
||||
// open. The store is the scratch folder's, never the real one.
|
||||
notepad: {
|
||||
workflow: "plan",
|
||||
posts: ["question"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-notepad");
|
||||
await page.waitForSelector("#notepad-modal[open]", { timeout: 10000 });
|
||||
await page.waitForFunction(() => !document.querySelector("#notepad-modal textarea").readOnly, null, { timeout: 10000 });
|
||||
await page.locator("#notepad-modal textarea").fill(
|
||||
"# Before the call\n\n- Ask about **paging**: cursor or offset?\n- Who signs in to the API?\n- Check the `/tasks` limit with the team\n"
|
||||
const editor = page.locator("#notepad-editor .cm-content");
|
||||
const newTab = async (name) => {
|
||||
await page.click((await page.locator("#notepad-empty").isVisible()) ? "#notepad-empty-new" : "#notepad-tab-new");
|
||||
await page.fill("#notepad-name", name);
|
||||
await page.keyboard.press("Enter");
|
||||
await page.waitForFunction(
|
||||
(n) => [...document.querySelectorAll("#notepad-tabs .notepad-tab")].some((b) => b.textContent === n && b.getAttribute("aria-selected") === "true"),
|
||||
name,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
await editor.click();
|
||||
};
|
||||
// The second theme's run finds the first one's tabs, kept in the same store.
|
||||
await page.waitForFunction(
|
||||
() => document.querySelector("#notepad-tabs .notepad-tab") || !document.getElementById("notepad-empty").hidden,
|
||||
null,
|
||||
{ timeout: 10000 },
|
||||
);
|
||||
if (!(await page.locator("#notepad-tabs .notepad-tab").count())) {
|
||||
// The list marker is typed once: the editor carries a list on at Enter.
|
||||
await newTab("Call notes");
|
||||
await page.keyboard.type(
|
||||
"# Before the call\n\n- Ask about **paging**: cursor or offset?\nWho signs in to the API?\nCheck the `/tasks` limit with the team\n\n"
|
||||
);
|
||||
await newTab("Ideas");
|
||||
await page.keyboard.type("Retry policy for the export job.\nWhat should the page size cap be?");
|
||||
}
|
||||
await sleep(1000);
|
||||
await page.locator("#notepad-tabs .notepad-tab", { hasText: /^Call notes$/ }).click();
|
||||
await page.locator("#notepad-editor .cm-h1").waitFor({ timeout: 10000 });
|
||||
await page.locator("#notepad-editor .cm-line").last().click();
|
||||
await sleep(1800);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -0,0 +1,78 @@
|
||||
// Checks that every file carrying the product's version agrees, the desktop app's included:
|
||||
// version.json, package.json, CHANGELOG.md's top heading, and the app's tauri.conf.json,
|
||||
// package.json and Cargo.toml. The release-app workflow runs it before building, with
|
||||
// --tag <the release tag>, so a release cannot ship an app that names another version.
|
||||
//
|
||||
// node scripts/check-versions.mjs [--tag v3.0.0]
|
||||
//
|
||||
// Exit 0 when they agree, 1 when they do not (each file and its version is printed).
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
|
||||
const readJson = (file) => JSON.parse(fs.readFileSync(file, "utf8")).version;
|
||||
const CARGO_VERSION = /^\s*version\s*=\s*"([^"]+)"/m;
|
||||
const CHANGELOG_HEADING = /^##\s+v?(\d+\.\d+\.\d+)\b/m;
|
||||
|
||||
/** Each file that carries the version, with how to read it. Paths are relative to the repo root. */
|
||||
const SOURCES = [
|
||||
{ file: "version.json", read: readJson },
|
||||
{ file: "package.json", read: readJson },
|
||||
{ file: "CHANGELOG.md", read: (file) => fs.readFileSync(file, "utf8").match(CHANGELOG_HEADING)?.[1] },
|
||||
{ file: "plan2code-app/src-tauri/tauri.conf.json", read: readJson },
|
||||
{ file: "plan2code-app/package.json", read: readJson },
|
||||
{
|
||||
file: "plan2code-app/src-tauri/Cargo.toml",
|
||||
// The first `version =` line is the [package] one; dependencies come after it.
|
||||
read: (file) => fs.readFileSync(file, "utf8").match(CARGO_VERSION)?.[1],
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* `{ ok, versions: [{ file, version }], problems: [string] }` for the tree at `root`. A file that
|
||||
* is missing or has no readable version is a problem, as is any disagreement, and a `tag`
|
||||
* (`v3.0.0` or `3.0.0`) that names another version.
|
||||
*/
|
||||
export function checkVersions(root = ROOT, { tag } = {}) {
|
||||
const versions = [];
|
||||
const problems = [];
|
||||
for (const { file, read } of SOURCES) {
|
||||
let version;
|
||||
try {
|
||||
version = read(path.join(root, file));
|
||||
} catch (error) {
|
||||
problems.push(`${file}: cannot be read (${error.code || error.message})`);
|
||||
continue;
|
||||
}
|
||||
if (!version) {
|
||||
problems.push(`${file}: no version found`);
|
||||
continue;
|
||||
}
|
||||
versions.push({ file, version });
|
||||
}
|
||||
const expected = versions.find((v) => v.file === "version.json")?.version;
|
||||
for (const { file, version } of versions) {
|
||||
if (expected && version !== expected) problems.push(`${file} says ${version}, version.json says ${expected}`);
|
||||
}
|
||||
if (tag && expected && tag.replace(/^v/, "") !== expected) {
|
||||
problems.push(`the release tag ${tag} names ${tag.replace(/^v/, "")}, version.json says ${expected}`);
|
||||
}
|
||||
return { ok: problems.length === 0, versions, problems };
|
||||
}
|
||||
|
||||
if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {
|
||||
const args = process.argv.slice(2);
|
||||
const tagAt = args.indexOf("--tag");
|
||||
const tag = tagAt >= 0 ? args[tagAt + 1] : undefined;
|
||||
if (tagAt >= 0 && !tag) {
|
||||
console.error("Usage: node scripts/check-versions.mjs [--tag v3.0.0]");
|
||||
process.exit(2);
|
||||
}
|
||||
const { ok, versions, problems } = checkVersions(ROOT, { tag });
|
||||
for (const { file, version } of versions) console.log(`${version.padEnd(10)} ${file}`);
|
||||
for (const problem of problems) console.error(`MISMATCH: ${problem}`);
|
||||
process.exit(ok ? 0 : 1);
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Turn CRLF line endings back into LF in the working tree.
|
||||
//
|
||||
// .gitattributes stores every text file as LF and checks it out as LF, so git
|
||||
// itself never puts a CRLF on disk. Tools do: a Python script writing in text
|
||||
// mode on Windows, an editor, a generator. A CRLF file still commits clean
|
||||
// (git normalizes it), but until then it inflates scripts/validate-char-count.js,
|
||||
// fills `git diff` and `git status` with warnings, and trips tests that read the
|
||||
// raw bytes. This puts the working tree back the way git would check it out.
|
||||
//
|
||||
// node scripts/fix-line-endings.mjs fix every text file git sees
|
||||
// node scripts/fix-line-endings.mjs --check list them, exit 1 if any
|
||||
// node scripts/fix-line-endings.mjs --hook fix the one file a Claude Code
|
||||
// PostToolUse hook names on stdin
|
||||
// --root <dir> work on another repo (tests)
|
||||
//
|
||||
// "Every text file git sees" is what is tracked plus what is untracked but not
|
||||
// ignored, less anything .gitattributes marks binary or that holds a NUL byte.
|
||||
// npm test runs the fix first (pretest), so every suite reads LF.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const args = process.argv.slice(2);
|
||||
const rootAt = args.indexOf("--root");
|
||||
const ROOT = path.resolve(rootAt >= 0 ? args[rootAt + 1] : path.dirname(path.dirname(fileURLToPath(import.meta.url))));
|
||||
const mode = args.includes("--hook") ? "hook" : args.includes("--check") ? "check" : "fix";
|
||||
|
||||
const git = (gitArgs, input) => execFileSync("git", ["-C", ROOT, ...gitArgs], { input, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
||||
|
||||
// The repo's files that are tracked, or untracked and not ignored, relative to
|
||||
// ROOT with forward slashes.
|
||||
function repoFiles() {
|
||||
return git(["ls-files", "-z", "--cached", "--others", "--exclude-standard"]).split("\0").filter(Boolean);
|
||||
}
|
||||
|
||||
// The files .gitattributes marks binary (or -text), never to be touched.
|
||||
function binaries(files) {
|
||||
if (!files.length) return new Set();
|
||||
const out = git(["check-attr", "-z", "--stdin", "binary", "text"], files.join("\0") + "\0").split("\0");
|
||||
const skip = new Set();
|
||||
for (let i = 0; i + 2 < out.length; i += 3) {
|
||||
const [file, attr, value] = [out[i], out[i + 1], out[i + 2]];
|
||||
if ((attr === "binary" && value === "set") || (attr === "text" && value === "unset")) skip.add(file);
|
||||
}
|
||||
return skip;
|
||||
}
|
||||
|
||||
// Rewrites one file with LF endings if it has any CRLF. Returns whether it did.
|
||||
function fixFile(abs, write) {
|
||||
let bytes;
|
||||
try {
|
||||
if (!fs.statSync(abs).isFile()) return false;
|
||||
bytes = fs.readFileSync(abs);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
if (bytes.includes(0) || !bytes.includes("\r\n")) return false;
|
||||
if (write) fs.writeFileSync(abs, bytes.toString("latin1").replace(/\r\n/g, "\n"), "latin1");
|
||||
return true;
|
||||
}
|
||||
|
||||
// The file a PostToolUse hook for Write or Edit names, fixed if it is a text
|
||||
// file inside the repo that git would check out. Never fails the tool call.
|
||||
function hook() {
|
||||
let file = "";
|
||||
try {
|
||||
const event = JSON.parse(fs.readFileSync(0, "utf8") || "{}");
|
||||
file = (event.tool_input && (event.tool_input.file_path || event.tool_input.notebook_path)) || (event.tool_response && event.tool_response.filePath) || "";
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
if (!file) return;
|
||||
const abs = path.resolve(file);
|
||||
const rel = path.relative(ROOT, abs);
|
||||
if (!rel || rel.startsWith("..") || path.isAbsolute(rel)) return;
|
||||
const relGit = rel.split(path.sep).join("/");
|
||||
try {
|
||||
if (git(["check-ignore", "-q", "--no-index", relGit]) !== null) return;
|
||||
} catch {
|
||||
// check-ignore exits 1 when the path is not ignored: carry on.
|
||||
}
|
||||
if (binaries([relGit]).size) return;
|
||||
if (fixFile(abs, true)) process.stdout.write(`fix-line-endings: ${relGit} had CRLF line endings, now LF\n`);
|
||||
}
|
||||
|
||||
if (mode === "hook") {
|
||||
try {
|
||||
hook();
|
||||
} catch {}
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const files = repoFiles();
|
||||
const skip = binaries(files);
|
||||
const found = files.filter((f) => !skip.has(f) && fixFile(path.join(ROOT, f), mode === "fix"));
|
||||
if (mode === "check") {
|
||||
if (found.length) {
|
||||
console.error(`${found.length} file(s) have CRLF line endings (run: npm run fix:eol):`);
|
||||
for (const f of found) console.error(` ${f}`);
|
||||
process.exit(1);
|
||||
}
|
||||
process.exit(0);
|
||||
}
|
||||
if (found.length) {
|
||||
console.log(`fix-line-endings: ${found.length} file(s) turned from CRLF to LF:`);
|
||||
for (const f of found) console.log(` ${f}`);
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
// `node --test` with the files run side by side capped at 8 and at one per
|
||||
// spare core. A flat 8 kept a big machine from swamping the page tests, but on
|
||||
// a 3 or 4 core CI runner it ran 8 browsers at once, nearly triple Node's own
|
||||
// default, and page tests timed out at random. Arguments pass straight through.
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import os from "node:os";
|
||||
|
||||
const concurrency = Math.max(1, Math.min(8, os.availableParallelism() - 1));
|
||||
const r = spawnSync(process.execPath, ["--test", `--test-concurrency=${concurrency}`, ...process.argv.slice(2)], { stdio: "inherit" });
|
||||
process.exit(r.status ?? 1);
|
||||
@@ -46,10 +46,10 @@ export function tempProject(files = {}) {
|
||||
// test still cleans up, and a page error fails the test. `clock: true` gives
|
||||
// the page Playwright's fake clock before it loads (s.page.clock), so a test
|
||||
// can jump past the page's silence limits instead of sitting through them.
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false, env, init } = {}) {
|
||||
fs.rmSync(REMEMBERED, { force: true });
|
||||
const cwd = project || tempProject();
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd, env }).json;
|
||||
const s = {
|
||||
sid: opened.sid,
|
||||
session: opened.session,
|
||||
@@ -95,7 +95,16 @@ export async function openSession(browser, { t, workflow, payload: first, projec
|
||||
if (first) s.post(first);
|
||||
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
if (clock) await s.context.clock.install();
|
||||
// A script run before the page's own, such as a stand-in for the app's frame.
|
||||
if (init) await s.context.addInitScript(init);
|
||||
s.page = await s.context.newPage();
|
||||
// Playwright's own default (30s) assumes a dedicated machine: the whole
|
||||
// suite runs dozens of these pages at once, and a host under that load can
|
||||
// leave one of them waiting past 30s for its turn at the CPU to paint a
|
||||
// dropdown or settle a click, with nothing wrong in the page itself. Twice
|
||||
// the default still catches a genuinely broken page, just gives a busy host
|
||||
// room to breathe.
|
||||
s.page.setDefaultTimeout(60000);
|
||||
s.page.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
@@ -105,7 +114,7 @@ export async function openSession(browser, { t, workflow, payload: first, projec
|
||||
// The page has adopted a state frame: app.js has replaced the boot pane the
|
||||
// markup ships with.
|
||||
export async function drawn(page) {
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 30000 });
|
||||
}
|
||||
|
||||
// Presses Send on the page and collects the send the way an agent's `wait`
|
||||
@@ -125,3 +134,38 @@ export const textOf = async (locator) => (await locator.innerText()).trim();
|
||||
|
||||
// The scroll offset of the first element matching `selector`.
|
||||
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
|
||||
|
||||
// Scrolls what `locator` names to `top` ("end" for its bottom), or as far as
|
||||
// it goes when that is less, and returns where it landed. A redraw can replace
|
||||
// the element between Playwright finding it and the scroll, and one not laid
|
||||
// out yet cannot scroll, so it scrolls again until the element on the page
|
||||
// holds a place past its top.
|
||||
export async function scrollCard(locator, top) {
|
||||
const deadline = Date.now() + 5000;
|
||||
for (;;) {
|
||||
const at = await locator.evaluate((el, want) => {
|
||||
if (!el.isConnected) return null;
|
||||
const max = el.scrollHeight - el.clientHeight;
|
||||
const target = want === "end" ? max : Math.min(want, max);
|
||||
el.scrollTop = target;
|
||||
return max > 0 && Math.abs(el.scrollTop - target) < 1 ? el.scrollTop : null;
|
||||
}, top);
|
||||
if (at !== null) return at;
|
||||
if (Date.now() > deadline) throw new Error(`the element never held a scroll to ${top}`);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
|
||||
// The computed `props` of the element `locator` names. A redraw can replace the
|
||||
// element between Playwright finding it and the read, and an element off the
|
||||
// page reads "" for every style, so a read of one is taken again.
|
||||
export async function stylesOf(locator, props) {
|
||||
const deadline = Date.now() + 5000;
|
||||
for (;;) {
|
||||
const got = await locator.evaluate((x, ps) => (x.isConnected ? Object.fromEntries(ps.map((p) => [p, getComputedStyle(x)[p]])) : null), props);
|
||||
if (got) return got;
|
||||
if (Date.now() > deadline) throw new Error(`${props.join(", ")}: the element never stayed on the page long enough to read`);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
export const styleOf = async (locator, prop) => (await stylesOf(locator, [prop]))[prop];
|
||||
@@ -99,6 +99,11 @@ export function gitInit(dir, branch = "main") {
|
||||
g("config", "user.email", "t@example.com");
|
||||
g("config", "user.name", "Test");
|
||||
g("config", "commit.gpgsign", "false");
|
||||
// No background maintenance after a commit: on macOS it held
|
||||
// .git/objects/maintenance.lock while copyFixture copied the template, and
|
||||
// the copy failed with ENOENT once the lock was gone.
|
||||
g("config", "maintenance.auto", "false");
|
||||
g("config", "gc.auto", "0");
|
||||
return g;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,132 @@
|
||||
// The rules of ~/.plan2code/agents.json, console side (src/web-console/agents.mjs),
|
||||
// against the shared cases every reader's tests load (scripts/fixtures/agents-cases.json),
|
||||
// plus what only the console does: finding a command and checking a save.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
import { MAX_AGENTS, buildArgs, makeId, normalizeAgents, resolveCommand, validateForSave } from "../src/web-console/agents.mjs";
|
||||
|
||||
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "agents-cases.json"), "utf8"));
|
||||
const WINDOWS = process.platform === "win32";
|
||||
|
||||
for (const c of CASES.files) {
|
||||
test(`agents file: ${c.name}`, () => {
|
||||
const { agents, warnings } = normalizeAgents(c.raw);
|
||||
assert.deepEqual(agents, c.agents);
|
||||
if (!c.warnings.length) assert.deepEqual(warnings, []);
|
||||
for (const part of c.warnings) {
|
||||
assert.ok(warnings.some((w) => w.includes(part)), `a warning names "${part}": ${JSON.stringify(warnings)}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
for (const c of CASES.buildArgs) {
|
||||
test(`buildArgs: ${c.name}`, () => {
|
||||
assert.deepEqual(buildArgs(c.entry, c.options), c.args);
|
||||
});
|
||||
}
|
||||
|
||||
for (const c of CASES.ids) {
|
||||
test(`makeId: ${c.name}`, () => {
|
||||
assert.equal(makeId(c.input, c.taken), c.id);
|
||||
});
|
||||
}
|
||||
|
||||
test("normalizeAgents takes the parsed file too, and never throws on odd input", () => {
|
||||
assert.deepEqual(normalizeAgents({ schema: 1, agents: [{ id: "goose", name: "Goose", command: "goose" }] }).agents.map((a) => a.id), ["goose"]);
|
||||
for (const odd of [0, true, "null", "42", "\"text\"", [], () => {}]) {
|
||||
assert.deepEqual(normalizeAgents(odd).agents, [], String(odd));
|
||||
}
|
||||
});
|
||||
|
||||
test("the fixture covers every rule it promises", () => {
|
||||
assert.ok(CASES.files.length >= 20 && CASES.buildArgs.length >= 10 && CASES.ids.length >= 8);
|
||||
const many = CASES.files.find((c) => c.name.startsWith("51 entries"));
|
||||
assert.equal(many.agents.length, MAX_AGENTS);
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------- resolveCommand */
|
||||
|
||||
function fakePath(t) {
|
||||
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
|
||||
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
|
||||
const bin = path.join(base, "bin");
|
||||
const spaced = path.join(base, "with space");
|
||||
fs.mkdirSync(bin);
|
||||
fs.mkdirSync(spaced);
|
||||
return { base, bin, spaced };
|
||||
}
|
||||
|
||||
test("resolveCommand finds a bare name on PATH, a full path, and misses what is not there", (t) => {
|
||||
const { bin, spaced } = fakePath(t);
|
||||
const name = WINDOWS ? "goose.exe" : "goose";
|
||||
fs.writeFileSync(path.join(bin, name), "");
|
||||
const opts = { path: [spaced, `"${bin}"`].join(path.delimiter), pathext: ".EXE;.CMD" };
|
||||
assert.equal(resolveCommand("goose", opts)?.toLowerCase(), path.join(bin, name).toLowerCase(), "a bare name, PATH entry quoted");
|
||||
assert.equal(resolveCommand(path.join(bin, name), opts), path.join(bin, name), "a full path");
|
||||
assert.equal(resolveCommand(` "${path.join(bin, name)}" `, opts), path.join(bin, name), "a quoted, padded full path");
|
||||
assert.equal(resolveCommand("nowhere", opts), null);
|
||||
assert.equal(resolveCommand(path.join(bin, "nowhere"), opts), null);
|
||||
assert.equal(resolveCommand(bin, opts), null, "a folder is not a command");
|
||||
assert.equal(resolveCommand("", opts), null);
|
||||
assert.equal(resolveCommand("goose", { path: "", pathext: ".EXE" }), null, "an empty PATH finds nothing");
|
||||
});
|
||||
|
||||
test("resolveCommand on Windows tries PATHEXT, also in a folder with a space and for a full path", { skip: !WINDOWS && "Windows only" }, (t) => {
|
||||
const { spaced } = fakePath(t);
|
||||
const cmd = path.join(spaced, "aider.cmd");
|
||||
fs.writeFileSync(cmd, "@echo off");
|
||||
const opts = { path: spaced, pathext: ".EXE;.CMD;.BAT" };
|
||||
assert.equal(resolveCommand("aider", opts)?.toLowerCase(), cmd.toLowerCase(), "found through PATHEXT");
|
||||
assert.equal(resolveCommand("aider.cmd", opts), cmd, "a name that already has its extension");
|
||||
assert.equal(resolveCommand(path.join(spaced, "aider"), opts)?.toLowerCase(), cmd.toLowerCase(), "a full path without its extension");
|
||||
assert.equal(resolveCommand("aider", { path: spaced, pathext: ".EXE" }), null, "only the listed extensions");
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------- validateForSave */
|
||||
|
||||
test("validateForSave fills ids from names and every default", () => {
|
||||
const { agents, error } = validateForSave([
|
||||
{ id: "goose", name: "Goose", command: "goose" },
|
||||
{ name: "My Agent", command: " my-agent " },
|
||||
{ name: "goose!", command: "goose2" },
|
||||
]);
|
||||
assert.equal(error, undefined);
|
||||
assert.deepEqual(agents.map((a) => a.id), ["goose", "my-agent", "goose-2"]);
|
||||
assert.equal(agents[1].command, "my-agent");
|
||||
assert.deepEqual(agents[1].modelArgs, ["--model", "{model}"]);
|
||||
assert.equal(agents[1].prompt, "/plan2code");
|
||||
});
|
||||
|
||||
test("validateForSave names the entry and field of the first failure", () => {
|
||||
const cases = [
|
||||
[[{ name: "Goose", command: "goose" }, { name: "GOOSE", command: "x" }], 1, "name"],
|
||||
[[{ name: "Goose", command: " " }], 0, "command"],
|
||||
[[{ name: "", command: "x" }], 0, "name"],
|
||||
[[{ id: "claude", name: "Mine", command: "claude" }], 0, "id"],
|
||||
[[{ id: "Bad Id", name: "Mine", command: "x" }], 0, "id"],
|
||||
[[{ id: "a", name: "A", command: "a" }, { id: "a", name: "B", command: "b" }], 1, "id"],
|
||||
[[{ name: "A", command: "a", args: ["--x", 1] }], 0, "args"],
|
||||
[[{ name: "A", command: "a", models: [{ label: "no id" }] }], 0, "models"],
|
||||
[[{ name: "A", command: "a" }, "text"], 1, ""],
|
||||
];
|
||||
for (const [list, index, field] of cases) {
|
||||
const out = validateForSave(list);
|
||||
assert.ok(out.error, JSON.stringify(list));
|
||||
assert.equal(out.index, index, JSON.stringify(list));
|
||||
assert.equal(out.field, field, JSON.stringify(list));
|
||||
}
|
||||
assert.equal(validateForSave({}).field, "agents");
|
||||
assert.equal(validateForSave(Array.from({ length: MAX_AGENTS + 1 }, (_, i) => ({ name: `A${i}`, command: "a" }))).field, "agents");
|
||||
});
|
||||
|
||||
test("an id the form already carries is never handed to a new entry", () => {
|
||||
const { agents } = validateForSave([{ name: "Goose", command: "a" }, { id: "goose", name: "Other", command: "b" }]);
|
||||
assert.deepEqual(agents.map((a) => a.id), ["goose-2", "goose"]);
|
||||
});
|
||||
@@ -0,0 +1,300 @@
|
||||
// Tests for plan2code-app/ui/meter.js and the app bar's own shape. Run with:
|
||||
// node --test scripts/test-app-meter.mjs
|
||||
//
|
||||
// app.js itself cannot be imported here (it touches `document` and
|
||||
// `window.__TAURI__` at module scope), which is why the bar's pure decisions
|
||||
// live in their own module and the rest is checked as plain text, the same
|
||||
// way the web console's own "shape" tests work.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
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));
|
||||
const INDEX_HTML_PATH = path.join(HERE, "../plan2code-app/ui/index.html");
|
||||
const APP_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/app.js"), "utf8");
|
||||
const INDEX_HTML = fs.readFileSync(INDEX_HTML_PATH, "utf8");
|
||||
|
||||
test("barNextSteps offers nothing while the console runs and the versions agree", () => {
|
||||
assert.deepEqual(barNextSteps(), []);
|
||||
assert.deepEqual(barNextSteps({ consoleDead: false, version: null }), []);
|
||||
});
|
||||
|
||||
test("barNextSteps puts the most pressing step first: a done update, then a stopped console, then the skills", () => {
|
||||
const ids = (input) => barNextSteps(input).map((step) => step.id);
|
||||
assert.deepEqual(ids({ consoleDead: true }), ["console-dead"]);
|
||||
assert.deepEqual(ids({ version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } }), ["mismatch"]);
|
||||
assert.deepEqual(ids({ consoleDead: true, version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } }), ["console-dead", "mismatch"]);
|
||||
assert.deepEqual(ids({ consoleDead: true, version: { kind: "too-old" } }), ["console-dead", "too-old"]);
|
||||
assert.deepEqual(ids({ version: { kind: "updated" } }), ["updated"]);
|
||||
});
|
||||
|
||||
test("only one control for reconnecting the console is ever offered: after an update, its Reconnect covers a stopped console too", () => {
|
||||
const steps = barNextSteps({ consoleDead: true, version: { kind: "updated" } });
|
||||
assert.deepEqual(steps.map((step) => step.action), ["restart-console"], "the plain reconnect steps aside for the one that stops the old console first");
|
||||
});
|
||||
|
||||
test("each version state reads and acts as the old version bar did", () => {
|
||||
const [mismatch] = barNextSteps({ version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } });
|
||||
assert.equal(mismatch.text, "Skills v3.0.0, app v3.1.0");
|
||||
assert.equal(mismatch.label, "Update skills");
|
||||
const [ahead] = barNextSteps({ version: { kind: "ahead", skills: "3.2.0", app: "3.1.0" } });
|
||||
assert.equal(ahead.action, null, "another Update skills run cannot help when the skills are ahead");
|
||||
assert.match(ahead.title, /newer than this app \(v3\.1\.0\)\. Get the new app\./);
|
||||
const [updating] = barNextSteps({ version: { kind: "updating", line: "Installing skills (4 of 9)" } });
|
||||
assert.deepEqual([updating.text, updating.busy, updating.action], ["Installing skills (4 of 9)", true, null], "no button while it runs");
|
||||
const [remains] = barNextSteps({ version: { kind: "remains", skills: "3.0.0", app: "3.1.0" } });
|
||||
assert.equal(remains.action, null);
|
||||
assert.equal(remains.title, "Updated, but the mismatch remains (skills v3.0.0, app v3.1.0).");
|
||||
const [failed] = barNextSteps({ version: { kind: "failed", error: "npm exited with code 1" } });
|
||||
assert.deepEqual([failed.tone, failed.title, failed.label], ["err", "npm exited with code 1", "Update skills"], "a failed update can be tried again");
|
||||
const [tooOld] = barNextSteps({ version: { kind: "too-old" } });
|
||||
assert.equal(tooOld.label, "Update skills", "an old console is fixed by the skills update");
|
||||
});
|
||||
|
||||
test("every control that reconnects the console carries the same label, never 'Restart the console' or 'Start it again'", () => {
|
||||
assert.equal(NEXT_STEP_LABELS.reconnect, "Reconnect the console");
|
||||
assert.equal(NEXT_STEP_LABELS["restart-console"], "Reconnect the console");
|
||||
assert.doesNotMatch(APP_JS, /'Restart the console'|"Start it again"/, "no stale label text left in app.js");
|
||||
});
|
||||
|
||||
test("app.js draws the bar's right end through barNextSteps, not a hand-rolled copy of its order", () => {
|
||||
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState \}\);/);
|
||||
for (const gone of ["console-again", "version-update", "permissions-note", "console-status", "project-dir"]) {
|
||||
assert.ok(!INDEX_HTML.includes(`id="${gone}"`), `index.html still has #${gone}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Claude Code holds typed text as a queued message while its turn is busy,
|
||||
// and the continue button only shows once the agent stopped checking in, so
|
||||
// by then the turn is stuck and the queued word would never send by itself.
|
||||
test("continueKeys types continue and Enter, and under Claude Code also its send-now chord (ctrl+x ctrl+s)", () => {
|
||||
assert.deepEqual(continueKeys("claude"), ["continue", "\r", "\x18\x13"]);
|
||||
for (const kind of ["devin", "codex", null, undefined, "something-new"]) {
|
||||
assert.deepEqual(continueKeys(kind), ["continue", "\r"], `${kind} gets the plain word and Enter`);
|
||||
}
|
||||
});
|
||||
|
||||
test("app.js types the continue button's keystrokes through continueKeys, for the running agent's kind", () => {
|
||||
const typeContinue = APP_JS.slice(APP_JS.indexOf("function typeContinue"), APP_JS.indexOf("function typeContinue") + 800);
|
||||
assert.match(typeContinue, /continueKeys\(agent\.kind\)/, "the keystrokes come from continueKeys");
|
||||
assert.doesNotMatch(typeContinue, /data: 'continue'/, "no hand-typed word left beside it");
|
||||
});
|
||||
|
||||
test("the bar reads project menu, New Session, agent menu, with both menus outside the scrolling row", () => {
|
||||
const row = INDEX_HTML.slice(INDEX_HTML.indexOf('<div id="bar-row">'), INDEX_HTML.indexOf('<div id="project-menu"'));
|
||||
const at = (id) => row.indexOf(`id="${id}"`);
|
||||
assert.ok(at("project-menu-button") >= 0 && at("agent-restart") > at("project-menu-button"), "New Session follows the project menu");
|
||||
assert.ok(at("agent-menu-button") > at("agent-restart"), "New Session sits just left of the agent menu");
|
||||
assert.ok(!row.includes('id="project-menu"') && !row.includes('id="agent-menu"'), "the menus are not inside #bar-row, whose overflow would clip them");
|
||||
assert.match(INDEX_HTML, /<div id="agent-menu"[\s\S]*?<button id="change-agent" role="menuitem" hidden>/, "Change agent lives in the agent menu");
|
||||
assert.match(INDEX_HTML, /<div id="project-menu"[\s\S]*?<button id="change-project" role="menuitem">/, "Change project lives in the project menu");
|
||||
});
|
||||
|
||||
test("folderName shows the project folder's own name, or the whole path when it has none", () => {
|
||||
assert.equal(folderName("C:\\git\\azw3-to-pdf"), "azw3-to-pdf");
|
||||
assert.equal(folderName("/home/me/plan2code/"), "plan2code");
|
||||
assert.equal(folderName("/"), "/");
|
||||
assert.equal(folderName(""), "");
|
||||
});
|
||||
|
||||
test("the context-window meter is gone for good: no stray element, poll, or backend call left wired up", () => {
|
||||
for (const needle of ["bar-slot-meter", "context-group", "context-nudge", "context-restart", "Agent context"]) {
|
||||
assert.ok(!INDEX_HTML.includes(needle), `index.html still has ${needle}`);
|
||||
}
|
||||
for (const needle of ["agent_context", "pollMeter", "nudgeDue", "renderMeter", "nudgePercent"]) {
|
||||
assert.ok(!APP_JS.includes(needle), `app.js still has ${needle}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the launch card's permission-mode tick starts checked (off), matching the plain terminal launcher's own always-off default", () => {
|
||||
assert.match(
|
||||
INDEX_HTML,
|
||||
/<input id="launch-bypass" type="checkbox" checked>/,
|
||||
"the checkbox markup itself must carry `checked`, not something app.js sets later"
|
||||
);
|
||||
// The warning sentence starts visible along with it: no `hidden` attribute on this element.
|
||||
assert.match(INDEX_HTML, /<p id="launch-bypass-warning">Permission checks will be off/);
|
||||
// Nothing in app.js resets it back to unchecked on every card show.
|
||||
assert.doesNotMatch(APP_JS, /launchBypassEl\.checked\s*=\s*false/, "no reset back to unchecked anywhere");
|
||||
});
|
||||
|
||||
test("windowTitleFor names the project folder after Plan2Code, so two or more windows read apart in a taskbar", () => {
|
||||
assert.equal(windowTitleFor("C:\\git\\azw3-to-pdf"), "Plan2Code - azw3-to-pdf");
|
||||
assert.equal(windowTitleFor("/home/me/projects/plan2code"), "Plan2Code - plan2code");
|
||||
assert.equal(windowTitleFor("C:\\git\\azw3-to-pdf\\"), "Plan2Code - azw3-to-pdf", "a trailing slash does not leave an empty last segment");
|
||||
assert.equal(windowTitleFor("/"), "Plan2Code", "a root with nothing after it has no folder name to show");
|
||||
assert.equal(windowTitleFor(""), "Plan2Code");
|
||||
assert.equal(windowTitleFor(null), "Plan2Code");
|
||||
assert.equal(windowTitleFor(undefined), "Plan2Code");
|
||||
});
|
||||
|
||||
test("setProjectDir sets the OS window title through windowTitleFor, with a real permission to do so", () => {
|
||||
assert.match(APP_JS, /window\.__TAURI__\.window\.getCurrentWindow\(\)\.setTitle\(windowTitleFor\(dir\)\)/, "setProjectDir is the one place every project-dir change flows through");
|
||||
const caps = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/capabilities/default.json"), "utf8"));
|
||||
assert.ok(caps.permissions.includes("core:window:allow-set-title"), "the capability to call setTitle must be granted, or the call is silently refused at runtime");
|
||||
});
|
||||
|
||||
test("app.js never sets statePlannyEl.hidden directly: SVGElement does not reflect that property to the attribute", () => {
|
||||
assert.doesNotMatch(APP_JS, /statePlannyEl\.hidden\s*=/, "must use toggleAttribute, not the .hidden property, on an <svg>");
|
||||
assert.match(APP_JS, /statePlannyEl\.toggleAttribute\('hidden', !tired\)/);
|
||||
});
|
||||
|
||||
test("the Restart confirmation no longer claims unsaved work, and offers New Session with the tired Planny", () => {
|
||||
const confirmRestart = APP_JS.slice(APP_JS.indexOf("function confirmRestart"), APP_JS.indexOf("function confirmRestart") + 600);
|
||||
assert.doesNotMatch(confirmRestart, /not saved/, "not always true, so it is gone from this dialog specifically");
|
||||
assert.match(confirmRestart, /'Restart the agent on a fresh context window\?',\s*\n\s*'New Session',/);
|
||||
assert.match(confirmRestart, /\{ tired: true \}/, "the confirm dialog asks for the tired Planny");
|
||||
assert.match(INDEX_HTML, /<svg id="dashboard-state-planny"[^>]*hidden>/, "the tired Planny starts hidden in the markup");
|
||||
});
|
||||
|
||||
test("defaultRightFraction gives the terminal a roomy width when the window has space for it, down to the floor when it does not", () => {
|
||||
const opts = { minFraction: 0.1, maxFraction: 0.6 };
|
||||
// Plenty of room: the ideal 440px pane, well inside both the console's own
|
||||
// 1080px minimum and the 0.6 ceiling.
|
||||
assert.equal(defaultRightFraction(1920, opts), 440 / 1920);
|
||||
// Just enough room for the console at 1080px and nothing more for the pane
|
||||
// than that leaves: the pane shrinks to fit, never pushing the console under.
|
||||
assert.equal(defaultRightFraction(1200, opts), 120 / 1200);
|
||||
// No room at all for the console's own 1080px minimum: the pane's floor
|
||||
// wins rather than vanishing to 0 or going negative.
|
||||
assert.equal(defaultRightFraction(1000, opts), 0.1);
|
||||
// The ceiling still applies even with abundant width.
|
||||
assert.equal(defaultRightFraction(3000, { minFraction: 0.1, maxFraction: 0.1 }), 0.1);
|
||||
assert.equal(CONSOLE_ASIDE_BREAKPOINT_PX, 1080, "matches responsive.css's own breakpoint");
|
||||
});
|
||||
|
||||
test("with nothing saved yet, app.js starts the terminal docked right via defaultRightFraction, not the bottom default", () => {
|
||||
assert.match(APP_JS, /paneDock = 'right';\s*\n\s*paneFraction = defaultRightFraction\(/, "the no-saved-state branch sets dock right");
|
||||
assert.match(APP_JS, /\} else \{[\s\S]{0,200}paneDock = 'right'/, "this only runs when state.termPanel is absent, never overriding a saved choice");
|
||||
});
|
||||
|
||||
// Docked right and collapsed, the terminal panel is a 28px-wide strip: the
|
||||
// collapse button's text used to run horizontally off the edge of it
|
||||
// (visible, unreadable). It now reads top-to-bottom instead.
|
||||
test("docked right and collapsed, the terminal panel's View Agent Terminal button fits the strip instead of overflowing it", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1000, height: 600 } });
|
||||
page.on("pageerror", () => {}); // app.js calls into __TAURI__, absent here; the markup and CSS still load fine
|
||||
await page.goto(pathToFileURL(INDEX_HTML_PATH).href);
|
||||
await page.evaluate(() => {
|
||||
document.getElementById("workspace").classList.add("dock-right");
|
||||
document.getElementById("term-panel").classList.add("collapsed");
|
||||
document.getElementById("term-collapse").textContent = "View Agent Terminal";
|
||||
});
|
||||
const fit = await page.evaluate(() => {
|
||||
const el = document.getElementById("term-collapse");
|
||||
return {
|
||||
writingMode: getComputedStyle(el).writingMode,
|
||||
overflowsWidth: el.scrollWidth > el.clientWidth,
|
||||
overflowsPanel: el.getBoundingClientRect().right > document.getElementById("term-panel").getBoundingClientRect().right,
|
||||
};
|
||||
});
|
||||
assert.equal(fit.writingMode, "vertical-rl", "the label is set to run top-to-bottom, not sideways");
|
||||
assert.equal(fit.overflowsWidth, false, "the label text does not overflow its own box");
|
||||
assert.equal(fit.overflowsPanel, false, "the button does not spill past the collapsed panel's edge");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("toggling the tired Planny <svg>'s hidden attribute the way app.js does actually shows and hides it", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 700, height: 500 } });
|
||||
page.on("pageerror", () => {});
|
||||
await page.goto(pathToFileURL(INDEX_HTML_PATH).href);
|
||||
// Setting the .hidden *property* on an <svg> does not reflect to the
|
||||
// attribute the way it does on an HTMLElement; app.js uses
|
||||
// toggleAttribute for exactly this reason. This exercises that real path.
|
||||
const shown = await page.evaluate(() => {
|
||||
document.getElementById("dashboard-state").hidden = false; // a plain div: the .hidden property works fine here
|
||||
const el = document.getElementById("dashboard-state-planny");
|
||||
el.toggleAttribute("hidden", false);
|
||||
return { display: getComputedStyle(el).display, rect: el.getBoundingClientRect() };
|
||||
});
|
||||
assert.notEqual(shown.display, "none", "toggleAttribute(false) makes it visible");
|
||||
assert.ok(shown.rect.width > 0 && shown.rect.height > 0, "it actually takes up space, not just display != none");
|
||||
const hiddenAgain = await page.evaluate(() => {
|
||||
const el = document.getElementById("dashboard-state-planny");
|
||||
el.toggleAttribute("hidden", true);
|
||||
return getComputedStyle(el).display;
|
||||
});
|
||||
assert.equal(hiddenAgain, "none", "toggleAttribute(true) hides it again");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("continueKeys gives a custom agent id the plain word and Enter", () => {
|
||||
assert.deepEqual(continueKeys("my-aider"), ["continue", "\r"]);
|
||||
});
|
||||
|
||||
const AVAIL = (spec) =>
|
||||
spec.map(([id, installed, custom = false]) => ({ id, label: id, installed, custom }));
|
||||
|
||||
test("pickDefaultAgent keeps the remembered agent when it is installed, custom ones included", () => {
|
||||
const list = AVAIL([["claude", true], ["devin", true], ["codex", true], ["mine", true, true]]);
|
||||
assert.equal(pickDefaultAgent(list, "codex"), "codex");
|
||||
assert.equal(pickDefaultAgent(list, "mine"), "mine");
|
||||
});
|
||||
|
||||
test("pickDefaultAgent falls back to the first installed built-in, then the first installed custom agent", () => {
|
||||
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", false], ["codex", true]]), null), "codex");
|
||||
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", true], ["codex", true]]), "claude"), "devin");
|
||||
assert.equal(pickDefaultAgent(AVAIL([["claude", false], ["devin", false], ["codex", false], ["mine", true, true]]), "claude"), "mine");
|
||||
});
|
||||
|
||||
test("pickDefaultAgent with nothing installed returns the remembered id, else the first entry, else null", () => {
|
||||
const none = AVAIL([["claude", false], ["devin", false], ["codex", false]]);
|
||||
assert.equal(pickDefaultAgent(none, "devin"), "devin");
|
||||
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];
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
// Tests for scripts/check-versions.mjs. Run with: node --test scripts/test-check-versions.mjs
|
||||
//
|
||||
// Each test builds a small tree in a temp folder holding the six files that carry the version,
|
||||
// so the check is exercised without depending on what the real repo says today.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { checkVersions } from "./check-versions.mjs";
|
||||
|
||||
const SCRIPT = path.join(path.dirname(fileURLToPath(import.meta.url)), "check-versions.mjs");
|
||||
|
||||
/** A tree with every version file at `version`, each overridable by its path in `over`. */
|
||||
function tree(t, version = "3.0.0", over = {}) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-versions-"));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const files = {
|
||||
"version.json": JSON.stringify({ name: "Plan2Code", version }),
|
||||
"package.json": JSON.stringify({ name: "plan2code", version }),
|
||||
"CHANGELOG.md": `# Changelog\n\n## v${version}\n\n### Added\n\n- something\n\n## v0.0.1\n`,
|
||||
"plan2code-app/src-tauri/tauri.conf.json": JSON.stringify({ productName: "Plan2Code", version }),
|
||||
"plan2code-app/package.json": JSON.stringify({ name: "plan2code-app", version }),
|
||||
"plan2code-app/src-tauri/Cargo.toml": `[package]\nname = "plan2code-app"\nversion = "${version}"\n\n[dependencies]\nserde = { version = "1" }\n`,
|
||||
...over,
|
||||
};
|
||||
for (const [file, content] of Object.entries(files)) {
|
||||
if (content === null) continue;
|
||||
fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, file), content);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
test("versions: six files at one version pass, and each is listed", (t) => {
|
||||
const result = checkVersions(tree(t));
|
||||
assert.equal(result.ok, true, result.problems.join("; "));
|
||||
assert.equal(result.versions.length, 6);
|
||||
assert.ok(result.versions.every((v) => v.version === "3.0.0"));
|
||||
});
|
||||
|
||||
test("versions: the app's tauri.conf.json disagreeing is named", (t) => {
|
||||
const root = tree(t, "3.0.0", {
|
||||
"plan2code-app/src-tauri/tauri.conf.json": JSON.stringify({ version: "2.11.0" }),
|
||||
});
|
||||
const result = checkVersions(root);
|
||||
assert.equal(result.ok, false);
|
||||
assert.deepEqual(result.problems, ["plan2code-app/src-tauri/tauri.conf.json says 2.11.0, version.json says 3.0.0"]);
|
||||
});
|
||||
|
||||
test("versions: Cargo.toml's package version counts, a dependency's does not", (t) => {
|
||||
const root = tree(t, "3.0.0", {
|
||||
"plan2code-app/src-tauri/Cargo.toml": '[package]\nname = "x"\nversion = "3.1.0"\n',
|
||||
});
|
||||
assert.match(checkVersions(root).problems[0], /Cargo\.toml says 3\.1\.0/);
|
||||
});
|
||||
|
||||
test("versions: the changelog's top heading is the one read", (t) => {
|
||||
const root = tree(t, "3.0.0", { "CHANGELOG.md": "# Changelog\n\n## v3.1.0\n\n## v3.0.0\n" });
|
||||
assert.match(checkVersions(root).problems[0], /CHANGELOG\.md says 3\.1\.0/);
|
||||
});
|
||||
|
||||
test("versions: a missing file or an unreadable version is a problem, not a throw", (t) => {
|
||||
const root = tree(t, "3.0.0", { "plan2code-app/package.json": null, "CHANGELOG.md": "# Changelog\n" });
|
||||
const problems = checkVersions(root).problems;
|
||||
assert.ok(problems.some((p) => p.startsWith("plan2code-app/package.json: cannot be read")), problems.join("; "));
|
||||
assert.ok(problems.includes("CHANGELOG.md: no version found"), problems.join("; "));
|
||||
});
|
||||
|
||||
test("versions: a release tag must name the same version, with or without the v", (t) => {
|
||||
const root = tree(t);
|
||||
assert.equal(checkVersions(root, { tag: "v3.0.0" }).ok, true);
|
||||
assert.equal(checkVersions(root, { tag: "3.0.0" }).ok, true);
|
||||
const bad = checkVersions(root, { tag: "v3.0.1" });
|
||||
assert.equal(bad.ok, false);
|
||||
assert.match(bad.problems[0], /release tag v3\.0\.1 names 3\.0\.1/);
|
||||
});
|
||||
|
||||
test("versions: the command exits 0 on agreement and 1 on a mismatch", () => {
|
||||
// The real tree: the exit code and the output agree with each other, whatever it says today.
|
||||
const real = spawnSync(process.execPath, [SCRIPT], { encoding: "utf8" });
|
||||
assert.equal(real.status, real.stderr.includes("MISMATCH") ? 1 : 0);
|
||||
const noTag = spawnSync(process.execPath, [SCRIPT, "--tag"], { encoding: "utf8" });
|
||||
assert.equal(noTag.status, 2);
|
||||
});
|
||||
@@ -7,7 +7,9 @@
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
@@ -186,3 +188,315 @@ test("install.js: --update is in the usage line, and an unknown option still exi
|
||||
assert.equal(result.status, 1);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update]"), result.stderr);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The desktop app: downloaded from a release, checked against its checksum list, placed in
|
||||
// ~/.plan2code/app/. A stand-in release server stands in for GitHub; PLAN2CODE_RELEASE_BASE
|
||||
// points the installer at it, and nothing here reaches the network.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const ASSET = installer.appAssetName(VERSION);
|
||||
const SUMS = `plan2code-app-${VERSION}-SHA256SUMS.txt`;
|
||||
const APP_DIR = path.dirname(installer.APP_DEST);
|
||||
const sha = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
/** A release server for `files` (`{ path: Buffer | string }`); `hits` lists every path asked for. */
|
||||
async function releaseServer(files) {
|
||||
const hits = [];
|
||||
const server = http.createServer((req, res) => {
|
||||
const name = decodeURIComponent(req.url.slice(1));
|
||||
hits.push(name);
|
||||
if (name in files) {
|
||||
res.writeHead(200);
|
||||
res.end(files[name]);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end("not found");
|
||||
}
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
process.env.PLAN2CODE_RELEASE_BASE = `http://127.0.0.1:${server.address().port}/release`;
|
||||
return {
|
||||
hits,
|
||||
close: () => {
|
||||
delete process.env.PLAN2CODE_RELEASE_BASE;
|
||||
server.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A release serving `bytes` as this system's app, listed under `listedHash` (default: its real hash). */
|
||||
function goodRelease(bytes, listedHash = sha(bytes)) {
|
||||
return {
|
||||
[`release/${ASSET}`]: bytes,
|
||||
[`release/${SUMS}`]: `${listedHash} ${ASSET}\n${"0".repeat(64)} plan2code-app-other\n`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Run `fn` with console output captured; resolves `{ result, out }`. */
|
||||
async function captured(fn) {
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
const result = await fn();
|
||||
return { result, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
}
|
||||
|
||||
function freshApp() {
|
||||
fs.rmSync(APP_DIR, { recursive: true, force: true });
|
||||
clearRecord();
|
||||
}
|
||||
|
||||
test("app: the release file is named by system and cpu, and an unbuilt system has none", () => {
|
||||
assert.equal(installer.appAssetName("3.0.0", "win32", "x64"), "plan2code-app-3.0.0-windows-x64.exe");
|
||||
assert.equal(installer.appAssetName("3.0.0", "darwin", "arm64"), "plan2code-app-3.0.0-macos-arm64");
|
||||
assert.equal(installer.appAssetName("3.0.0", "darwin", "x64"), "plan2code-app-3.0.0-macos-x64");
|
||||
assert.equal(installer.appAssetName("3.0.0", "linux", "x64"), "plan2code-app-3.0.0-linux-x64");
|
||||
assert.equal(installer.appAssetName("3.0.0", "freebsd", "x64"), null);
|
||||
assert.equal(installer.appAssetName("3.0.0", "linux", "ia32"), null);
|
||||
});
|
||||
|
||||
test("app: checksumFor reads text and binary mode lines and wants the exact name", () => {
|
||||
const hex = "ab".repeat(32);
|
||||
const list = `${hex} plan2code-app-1-linux-x64\n${"cd".repeat(32)} *plan2code-app-1-macos-arm64\r\nnot a checksum line\n`;
|
||||
assert.equal(installer.checksumFor(list, "plan2code-app-1-linux-x64"), hex);
|
||||
assert.equal(installer.checksumFor(list, "plan2code-app-1-macos-arm64"), "cd".repeat(32));
|
||||
assert.equal(installer.checksumFor(list, "plan2code-app-1-linux"), null);
|
||||
assert.equal(installer.checksumFor("", "x"), null);
|
||||
});
|
||||
|
||||
test("app installed: the file is downloaded, verified, placed and recorded", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const bytes = Buffer.from("pretend this is an executable");
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
const outcome = {};
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.equal(outcome.app, true);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)], "no temp or .old file is left");
|
||||
assert.match(out, /unsigned/);
|
||||
assert.deepEqual(server.hits, [`release/${SUMS}`, `release/${ASSET}`]);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app checksum mismatch: the file is rejected, nothing is placed and the old app stays", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
fs.mkdirSync(APP_DIR, { recursive: true });
|
||||
fs.writeFileSync(installer.APP_DEST, "the app that was already here");
|
||||
writeRecord(["skills", "launcher", "app"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64)));
|
||||
try {
|
||||
const outcome = {};
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome }));
|
||||
assert.equal(result, 1);
|
||||
assert.equal(outcome.app, false);
|
||||
assert.match(out, /does not match its checksum/);
|
||||
// Said plainly: the rest is installed and --classic is today's flow.
|
||||
assert.match(out, /skills and the plan2code command are installed/);
|
||||
assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the app that was already here");
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app: a release without the file, or without a checksum entry, fails plainly and places nothing", { skip: !ASSET }, async () => {
|
||||
for (const files of [{}, { [`release/${SUMS}`]: `${"2".repeat(64)} some-other-file\n` }]) {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const server = await releaseServer(files);
|
||||
try {
|
||||
const outcome = {};
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome }));
|
||||
assert.equal(result, 1, out);
|
||||
assert.equal(outcome.app, false);
|
||||
assert.match(out, /The desktop app was not installed: /);
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false);
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["skills", "launcher"], "a failed install leaves the record as it was");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("app: a server that is not there fails plainly", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
process.env.PLAN2CODE_RELEASE_BASE = "http://127.0.0.1:1/release";
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /could not download it/);
|
||||
} finally {
|
||||
delete process.env.PLAN2CODE_RELEASE_BASE;
|
||||
}
|
||||
});
|
||||
|
||||
test("app update: plan2code update replaces an older app and reports it", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
fs.mkdirSync(APP_DIR, { recursive: true });
|
||||
fs.writeFileSync(installer.APP_DEST, "an older app");
|
||||
writeRecord(["app"]);
|
||||
const bytes = Buffer.from("the newer app");
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
// The real app step, in the real update loop; the record lists only the app.
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: updated/);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app update: a checksum mismatch fails the update naming the app, nothing else", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["app"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64)));
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /Update failed for: app/);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app update: a release with no app file yet keeps the installed app and does not fail the update", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
fs.mkdirSync(APP_DIR, { recursive: true });
|
||||
fs.writeFileSync(installer.APP_DEST, "the installed app");
|
||||
writeRecord(["app"]);
|
||||
// main moves to a new version before the release's files are attached: every file is a 404.
|
||||
const server = await releaseServer({});
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: kept/);
|
||||
assert.doesNotMatch(out, /Update failed/);
|
||||
assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the installed app");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app: interactively, a release with no app file is a plain failure, and a placement error is not called a download error", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
let server = await releaseServer({});
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /has no desktop app file for/);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
|
||||
// The download is fine but the folder cannot be made: a file sits where the app folder goes.
|
||||
fs.mkdirSync(path.dirname(APP_DIR), { recursive: true });
|
||||
fs.writeFileSync(APP_DIR, "in the way");
|
||||
server = await releaseServer(goodRelease(Buffer.from("a good file")));
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /the file was verified but could not be put in/);
|
||||
assert.doesNotMatch(out, /could not download/);
|
||||
} finally {
|
||||
server.close();
|
||||
fs.rmSync(APP_DIR, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("app offered: a system with no build is never asked about, never downloaded for and says nothing red", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("never fetched")));
|
||||
const arch = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
Object.defineProperty(process, "arch", { value: "ia32", configurable: true });
|
||||
try {
|
||||
for (const unattended of [true, false]) {
|
||||
const { out } = await captured(() => installer.offerDesktopApp({ unattended, outcome: {} }));
|
||||
assert.doesNotMatch(out, /was not installed/);
|
||||
}
|
||||
assert.deepEqual(server.hits, []);
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false);
|
||||
} finally {
|
||||
Object.defineProperty(process, "arch", arch);
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app offered: unattended with no app file in the release yet is a dim note, not a failure", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const server = await releaseServer({});
|
||||
try {
|
||||
const outcome = {};
|
||||
const { out } = await captured(() => installer.offerDesktopApp({ unattended: true, outcome }));
|
||||
assert.match(out, /No desktop app update/);
|
||||
assert.doesNotMatch(out, /was not installed/);
|
||||
assert.equal(outcome.app, false);
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app skipped: an unattended offer downloads nothing when the app is recorded or was declined", { skip: !ASSET }, async () => {
|
||||
const server = await releaseServer(goodRelease(Buffer.from("never fetched")));
|
||||
try {
|
||||
// Recorded: the update loop owns it. Declined: the person said no once.
|
||||
for (const record of [{ pieces: ["skills", "app"] }, { pieces: ["skills"], skipped: ["app"] }]) {
|
||||
freshApp();
|
||||
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", ...record }));
|
||||
await captured(() => installer.offerDesktopApp({ unattended: true, outcome: {} }));
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false, JSON.stringify(record));
|
||||
}
|
||||
assert.deepEqual(server.hits, []);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app offered: unattended with nothing recorded about it means yes, and installing clears an old no", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const bytes = Buffer.from("first time app");
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
const outcome = {};
|
||||
await captured(() => installer.offerDesktopApp({ unattended: true, outcome }));
|
||||
assert.equal(outcome.app, true);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
// A recorded decline is dropped once the piece is installed, and the key leaves the file when empty.
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", pieces: ["skills"], skipped: ["app"] }));
|
||||
installer.recordInstalled("app");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["app", "skills"] });
|
||||
});
|
||||
|
||||
test("app declined: the no is remembered next to the pieces, and needs a record to be kept", () => {
|
||||
clearRecord();
|
||||
installer.recordSkipped("app");
|
||||
assert.equal(installer.readInstallRecord(), null, "no record is invented for a decline");
|
||||
writeRecord(["skills"]);
|
||||
installer.recordSkipped("app");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["skills"], skipped: ["app"] });
|
||||
installer.recordInstalled("launcher");
|
||||
assert.deepEqual(installer.readInstallRecord().skipped, ["app"], "other writes keep the decline");
|
||||
});
|
||||