Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0de630603b | ||
|
|
26013db54f | ||
|
|
e00769b56a | ||
|
|
a5a3a81c5f | ||
|
|
681c4a4b85 | ||
|
|
7a4b7c6db8 | ||
|
|
086c735c65 | ||
|
|
d4adb53a3a | ||
|
|
2075d235d8 | ||
|
|
452d8e3895 | ||
|
|
d32925cccf | ||
|
|
f8b54ef708 | ||
|
|
124beb46db | ||
|
|
1121157938 | ||
|
|
e3aba0a637 | ||
|
|
3edb4468a8 | ||
|
|
699a827cae | ||
|
|
765e374584 | ||
|
|
2ab57d9a7e | ||
|
|
17dffac1ea | ||
|
|
36843e4bc9 | ||
|
|
33a0dbd34a | ||
|
|
80ae3decdd | ||
|
|
caef9a0ee3 | ||
|
|
72c827dddf | ||
|
|
498e09bb15 | ||
|
|
68d1f82a2e | ||
|
|
fdf43b197f | ||
|
|
7e2c824d4f | ||
|
|
8890c3ad13 | ||
|
|
f328406bb5 |
No files matched your search
@@ -15,10 +15,13 @@ plan2code/
|
||||
│ │ ├── resolve.md # Per-type resolution + graduating the fog
|
||||
│ │ ├── 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)
|
||||
│ ├── plan2code-review-references/ # Reference files for review skill
|
||||
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
|
||||
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
|
||||
│ │ ├── false-positives.md # Known false-positive patterns
|
||||
│ │ ├── reviewer-brief.md # Fill-in brief for the one fresh helper that runs the analysis
|
||||
│ │ └── session-end.md # Next-step routing at review session end
|
||||
│ ├── plan2code-init-update-references/ # Reference files for init-update skill
|
||||
│ │ └── ai-agent-file-sync.md # Step 7: replace AI configs with AGENTS.md refs
|
||||
@@ -41,17 +44,21 @@ plan2code/
|
||||
│ └── plan2code.ico # Desktop shortcut icon (Windows)
|
||||
├── src/web-console/ # Local browser UI bundled into every skill (Node.js, zero deps, no build)
|
||||
│ ├── console.mjs # CLI the agent drives: open, post, wait, chat, keep, status, stop, help
|
||||
│ ├── server.mjs, lib.mjs, picker.mjs
|
||||
│ ├── console.md, building.md # Agent-facing contract
|
||||
│ ├── server.mjs, routes.mjs, static.mjs, cmd-*.mjs, picker.mjs, and the by-job files (files, sessions, patches, scan, inbox, workspace, settings)
|
||||
│ ├── console.md, console-*.md, notes/, building*.md # Agent-facing contract (console.md read once, the rest on demand)
|
||||
│ └── public/ # Page assets served to the browser
|
||||
├── scripts/ # Development scripts
|
||||
│ ├── bench-web-console.mjs # Start-path timing
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs puppeteer-core)
|
||||
│ ├── capture-screenshots.mjs # Stages web console screens and saves the docs screenshots (needs a local Chrome or Edge, through `playwright-core`)
|
||||
│ ├── browser.mjs # The one place a browser is launched (Chrome, then Edge, through `playwright-core`; `PLAN2CODE_TEST_BROWSER` forces one); page tests, the screenshots and the bench use it
|
||||
│ ├── css-snapshot.mjs # Dev-only: every element's computed style on every screen, both themes; take one before a stylesheet move and `--compare` after
|
||||
│ ├── 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, test-launcher.mjs, test-getting-started.mjs # node --test suites (the last keeps the newcomer docs in step)
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, skill-script-helpers.mjs # Skill script suites and fixtures
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
|
||||
│ └── validate-char-count.js # Pre-commit character count validator
|
||||
├── skills/ # Generated, gitignored build output — one Agent Skill per src/ prompt
|
||||
│ └── plan2code-<name>/ # SKILL.md plus references/ and scripts/ where present
|
||||
@@ -85,7 +92,9 @@ 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 |
|
||||
| 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` |
|
||||
|
||||
## Workflow Prompts (in `src/`)
|
||||
|
||||
@@ -101,11 +110,13 @@ 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 |
|
||||
| `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-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-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer Git commit |
|
||||
| `plan2code-git-commit.md` | git-commit | Commit with a clear message, suggested splits, a branch offer on the default branch, and an optional push |
|
||||
| `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 |
|
||||
| `plan2code-diagnose.md` | diagnose | Find a bug's cause under the find-the-cause-first habit (`references/building-habits.md`) and write it up as `specs/<bug-name>/DIAGNOSIS-<YYYYMMDD>.md` without fixing it, then offer Quick Task to fix it, or Plan when the fix is big. The dashboard scan reports such a folder as spec state `diagnosed` ("Bug diagnosed"), which lights Quick Task (suggested) and Plan. Once Quick Task marks the diagnosis `Fixed` (nothing past it in the folder) the state is `fixed` ("Bug fixed"): no pipeline card lights, the picker never pre-selects it, and Quick Task offers to archive it with `specs.mjs archive` |
|
||||
| `plan2code-changelog.md` | changelog | Check the CHANGELOG version against the default branch, suggest editable entries for new work, keep `package.json` aligned, offer to commit the result through Git |
|
||||
| `plan2code-git.md` | git | Branches, pull (with conflict help), push, publish and commits (clear message, suggested splits) on the web console's git board, or plain instructions in the terminal (`switch to main`, `commit and push`); asks before every push, publish and delete |
|
||||
|
||||
## Naming Convention
|
||||
|
||||
@@ -123,7 +134,7 @@ Examples:
|
||||
|
||||
Some workflows use companion reference files for depth that does not need to load on every invocation. The orchestrator (main workflow file) loads them via `Read` directives during execution.
|
||||
|
||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`)
|
||||
**Pattern:** `src/<source-filename-without-extension>-references/` (e.g., `plan2code-review-references/`). A file several skills read lives in `src/shared-references/` instead and ships to each through `additionalReferences` (e.g., `building-habits.md` into Quick Task, Implement and Implement + Review).
|
||||
|
||||
**How the installer handles them:** the directory is copied verbatim to `skills/<skill-name>/references/`, so `Read references/<file>.md` resolves consistently for every agent. There is one output format, with no flat-file sibling directory or path rewrite.
|
||||
|
||||
@@ -142,20 +153,20 @@ Anything a workflow step decides with one correct answer (parsing a spec's check
|
||||
|
||||
| Script | Skills | Does |
|
||||
|---|---|---|
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/lib.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
|
||||
| `specs.mjs` | plan, revise-plan, document, implement, implement-review, review, quick-task, finalize, handoff | `list` / `status` (Phase Checklist, groups, task markers, numbering, the implement selection verdict, consistency checks) / `metrics` / `mark` / `archive`. Imports `scanProject()` from the bundled `web-console/scan.mjs`, so the dashboard and the skills share one spec classifier |
|
||||
| `commit-msg.mjs` | implement(-review), review, quick-task, finalize, init-update, git | The `<subject>` / `AI Assisted` commit command (two `-m` flags), with optional `git add` |
|
||||
| `review-scope.mjs` | review, implement(-review), quick-task | Review Mode's git fallback: files, lines, doc share, base branch |
|
||||
| `agents-md.mjs` | init, init-update | AGENTS.md structure, budget, orphans, broken links, always-inline sections |
|
||||
| `agent-files.mjs` | init, init-update | Detect and replace other agents' config files with AGENTS.md pointers |
|
||||
| `pathfinder.mjs` (own) | 0-pathfinder | `reconcile`, `frontier`, `claim`, `resolve`, `rule-out`, `trail`, `gate`, `lint`, `brief-data` |
|
||||
| `feedback-payload.mjs` (own) | 4-finalize | STEP 6.5's payload (real sha256 prompt hashes) and the gh / browser / print submission tiers |
|
||||
| `handoff-path.mjs` (own) | handoff | Timestamped path, OS temp dir, git ignore check |
|
||||
| `xray.mjs` (own) | xray | `hotspots` (churn, files changed together, often-changed files with no test, from `git log` over a capped window) and `history <path>` (commits following renames, a blame summary, PR titles and first paragraphs through `gh` when signed in, and which sources were used). Read-only |
|
||||
| `changelog-state.mjs` (own) | changelog | `state`, `bump`, `set-package-version`: the default branch's version, whether the branch's entry can be extended (not released, not on another branch), the file's heading style, the gap since the entry was last touched; only `set-package-version` writes, and only the version field |
|
||||
| `git-state.mjs` (own) | git-commit | `state`, `branch-check`, `init-check`: the repo snapshot, branch-name check and git init safety check, read-only |
|
||||
| `git.mjs` (own) | git | `state`, `plan`, `branch-check`, `init-check`, `delete-check`, `cleanup-list`, `conflicts`, `pr-url`, `classify-error`: the repo snapshot, each action's exact command and confirm text (shared by the terminal and the board), branch-name, delete, cleanup and git init checks, a stopped rebase's conflicts, the pull-request link and git's errors sorted into kinds with a next step. Read-only: the agent runs every command it prints, and `guard()` refuses force push, hook skipping, amend, remote delete and blanket add |
|
||||
|
||||
**Conventions** (`common.mjs`): Node 18+ built-ins only; one JSON object on stdout (`ok: false` plus `error`, `message`, `next` on a handled failure, the same line on stderr); exit 0 ok, 1 crash, 2 bad arguments, 3 not found, 4 invalid or check failed, 5 refused; `--help` documents commands and exit codes; writes take `--dry-run`; `PLAN2CODE_NOW` pins the clock for tests. A SKILL.md names a script as `node "<S>/<name>.mjs"`, where `<S>` is `scripts/` beside it.
|
||||
|
||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own), with fixtures from `scripts/skill-script-helpers.mjs`. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
||||
**Tests:** `scripts/test-skill-scripts.mjs` (installer plumbing and the shared scripts), `scripts/test-script-<skill>.mjs` (a skill's own), with fixtures from `scripts/skill-script-helpers.mjs`. Importing that module rebuilds `skills/` unless `npm_lifecycle_event` is `test` (`npm test` has just built it). Git fixtures go through `copyFixture()` (`scripts/fixture-helpers.mjs`): built once per test file, copied per test, since every `git` process costs a few hundred milliseconds on Windows; a remote inside the fixture is added with `slashed()` so the copy's `.git/config` can be pointed at its own origin. They run the built `skills/` tree, and one test fails if any SKILL.md or shipped reference names a `<S>/<name>.mjs` that skill does not ship. The per-skill scripts import `./common.mjs`, which only sits beside them in the built tree, so run them from `skills/`, not `src/`.
|
||||
|
||||
## Repo-Local Skills (`.claude/skills/`)
|
||||
|
||||
@@ -170,87 +181,162 @@ Do not run `skills add` against the repository root: recursive discovery also fi
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. The list of skills with a console is duplicated as `CONSOLE_WORKFLOWS` in `public/answers.js` (it decides whether a copied hand-off asks the next session for the console); a test fails if the two disagree.
|
||||
Optional local browser UI shipped with **every** skill. Source lives in `src/web-console/` and is fanned into each skill by an `additionalReferences: [{ source: 'web-console', target: 'web-console' }]` entry in `SOURCE_PROMPTS`, landing at `skills/<skill>/references/web-console/`. The bare `plan2code` skill is the hub: it opens the console as `--workflow dashboard`, the page draws the skill menu itself (from each `SKILLS` entry's `card` in `public/skills.js`, through `SKILL_CATALOG` in `public/answers.js`, kept in sync with the install set by a test), and a card click reaches the agent as a `{ "i": "__launch", "skill": ..., "workflow": ... }` send — the dashboard then **resumes its own session** under the launched skill's workflow (`open --resume <sid> --workflow <w>` restates `workflow`/`title`/`specDir` on the live server) and runs that skill's file. `plan2code-review` now has a console of its own AND still runs inside builds on the page (a `review` verdict on Implementation's sign-off card, or the **Review it now** button on a finished quick task), so `plan2code-3-implement` and `plan2code-quick-task` also carry `review.md` and the review references, the same way `implement-review` does. `CONSOLE_WORKFLOWS` in `public/answers.js`, built from the same `SKILLS` list, decides whether a copied hand-off asks the next session for the console.
|
||||
|
||||
| File | Role |
|
||||
|---|---|
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `delete-spec`, `handoff new`, `delete-handoff` (both on `handoffs.mjs`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`; `help <topic>` prints one contract file, `help topics` lists them). `post --wait <N>` posts and waits in one command |
|
||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (17 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `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 build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
|
||||
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/` (other files) | `index.html`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server and the tests import the pure modules) parses them as ES modules without a reparse warning. The stylesheet is the files in `public/styles/`, joined by the server into the one `/app.css` the page asks for |
|
||||
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; 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` |
|
||||
| `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 |
|
||||
| `inbox.mjs` | the Quick question chat's inbox beside the card slot |
|
||||
| `patches.mjs` | checking and merging an agent's patch into the session state: `validate()` (the house rules; allows `templates` only as `"idea"` on a `text` item, anything else exits 3), the patch merge, `resolveDocFiles()` and `applyPatch()` |
|
||||
| `routes.mjs` | every URL the page can call, in one ordered list (`ROUTES`, walked by `handle()`); `server.mjs` hands each request to it |
|
||||
| `scan.mjs` | what the dashboard knows about the repo: `scanProject()`, `classifySpec()` (a folder's files to a spec state), `TASK_LINE_RE` (re-exported from `spec-files.mjs`) and `removeSpec()` |
|
||||
| `sessions.mjs` | a session's roots and handle files (`repoRoots()`, `healthOk()`, `attachmentName()`: the kept-file name `<slug>-<id8>.<ext>`, the same upload always gets the same name, `readOverview()`) and the console folder's housekeeping: the three sweeps `open` runs fire-and-forget after it prints (`sweepUploads()`, `staleSessions()` / `removeSessions()`, `staleScratch()` / `removeScratch()`) and `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `settings.mjs` | the person's saved console settings: Subagents and pull-request hosts |
|
||||
| `spec-files.mjs` | no imports: how a spec's markdown files are read, `MARKERS`, `TASK_LINE_RE`, `TASK_ID_RE`, `CHECKBOX_RE`, `STATUS_RE`, `statusOf()` and `countTasks()`; shared by `scan.mjs`, `patches.mjs` and `src/skill-scripts/specs.mjs` (through `consoleModule()`) |
|
||||
| `static.mjs` | serving the page's own files: `SERVABLE` (the allow-list), `TYPES`, caching and ETags, the accent colors, and `CSS_ORDER` + `joinedStyles()`, the one place the cascade order is stated |
|
||||
| `workspace.mjs` | the session's extra folders, and the folders remembered per project and spec |
|
||||
| `public/app.js` | the page's entry and the only page file that starts anything: the start-up block. `index.html` loads it; it imports `screens/core.js` and the screens beside it |
|
||||
| `public/doc-files.js` | a document as the page shows it, and as a file: blocks, Markdown and HTML download |
|
||||
| `public/hops.js` | no imports: the hop rule, `startsClean(from, to)`, which says whether a hop from one workflow to another starts the new skill on a clean page (to or from the dashboard, 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` |
|
||||
| `public/looks.js` | how the page looks and sounds: the saved looks, their sync, and the preferences dialog's swatches |
|
||||
| `public/mention-box.js` | the @name suggestions popover under a text box |
|
||||
| `public/net.js` | the page talking to its own server |
|
||||
| `public/palette.js` | the highlight colors, the sound events and the card widths, as data (importable by Node so a test can check every shade in both themes) |
|
||||
| `public/render.js` | Markdown to DOM, safely: no HTML string is ever produced, only nodes built with `createElement` and `textContent`; also the shared page helpers (`el`, `md`, `copyButton`, `lightDismiss`) |
|
||||
| `public/selectors.js` | what the page reads off its state: the questions, the finish, the scan, who has the ball |
|
||||
| `public/send-state.js` | whether Send is available, and what its button says |
|
||||
| `public/skills.js` | the skill list: every per-skill fact the console uses (card, order, start pose, launch scoring, subagent opt-in, which spec states light its card), data only, imported by the page and by Node; the older tables (`SKILL_CATALOG`, `START_POSES`, `CONSOLE_WORKFLOWS` and the rest, in `answers.js`) are lookups on it. Each entry also carries `weight` (what its launch and `run` score on the meter, or null), `started` and `ran` (the meter's labels for them, or null), `resume` (`"overview"`, `"folder"` or null: what the resume command takes after the skill's command) and an optional `card.help` (Help's line for the card when it differs from `blurb`). `WORKFLOWS` (every entry's workflow, in order) and `isWorkflow()` are what the CLI checks a `--workflow` against. The meter's `WEIGHTS`, `LAUNCH_LABELS` and `RUN_LABELS`, `resumeCommand()`, Help's card list and `cmd-help`'s workflow list are all derived from it, so a new skill is one entry here, not an edit to each of those |
|
||||
| `public/sound.js` | the sound cues: which plays, one at a time, held until the first click |
|
||||
| `public/spec-states.js` | the spec states (`diagnosed`, `fixed`, `exploring`, `mapped`, `planned`, `documented`, `building`, `built`, `unrecognized`): each one's picker label, the card it is the natural next step for and its recommendation, data only; which cards a state lights lives in `skills.js`, how a folder maps to a state in `classifySpec()` in `scan.mjs` |
|
||||
| `public/state.js` | the page's shared state (`page.S` the server's truth, `page.local` what is staged) and the `redraw()` / save hooks every screen calls; defines only |
|
||||
| `public/uploads.js` | pictures and documents attached to a note: chips, trays, re-encoding, upload, retry |
|
||||
| `public/screens/ask.js` | the Ask chat, the Subagents tab, and attaching files to notes |
|
||||
| `public/screens/cards.js` | question cards: every kind, the pager, settled and in-flight records |
|
||||
| `public/screens/cleanup.js` | User Preferences, Cleanup tab |
|
||||
| `public/screens/core.js` | the core every screen sits inside: connection, the render loop, the page chrome and Send; the only file that imports the screens, and only `app.js` imports it |
|
||||
| `public/screens/dashboard.js` | the dashboard: cards, the spec picker, handoff chips, delete, and the first-open wake-up |
|
||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
|
||||
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js) |
|
||||
| `public/screens/looks.js` | User Preferences: looks, sounds and the launcher's model menus |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
|
||||
| `public/styles/ask.css` | The Ask pane and its Quick question chat |
|
||||
| `public/styles/dashboard.css` | The dashboard: the menu, the spec picker, its confirm and the launching pane |
|
||||
| `public/styles/docs.css` | Documents and the doc tools |
|
||||
| `public/styles/ending.css` | The end of a session: the hand-off and the stopping screen |
|
||||
| `public/styles/git.css` | The git board |
|
||||
| `public/styles/help.css` | The help dialog, its diagrams and its tabs |
|
||||
| `public/styles/looks.css` | The looks button and the highlight swatches |
|
||||
| `public/styles/pieces.css` | Shared pieces: cards, options, settled answers, pager, forms, checklist, markdown and the modal |
|
||||
| `public/styles/planny.css` | Planny the mascot: the flight, his moods and variants, and the wake-up |
|
||||
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
|
||||
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
|
||||
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
|
||||
| `public/styles/tokens.css` | Colours, type, sizes and the light and dark themes: the variables every other file reads |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `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` |
|
||||
| `public/pr-url.js` | PURE, no imports: `prUrl()`, the "open a pull request" link for the GitHub, GitLab, Azure DevOps and Bitbucket shapes (`null` for an unknown kind, no web address, or a non-https result). `git-repo.mjs` re-exports it, and the board's base picker rebuilds the link in the browser with the same code |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `cmd-chat.mjs`, `cmd-post-wait.mjs`, `workspace.mjs` and the page |
|
||||
| `public/meter.js` | PURE, 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, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
| `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/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 |
|
||||
| `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 |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network. The `plan2code` launcher reads the same cache for its terminal release notice (a copy of this module sits in `~/.plan2code/bin/`) |
|
||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. `scripts/test-web-console.mjs` imports this directly. |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by the page's looks and screens and by the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Kept out of the page's entry because `app.js` cannot be imported outside a browser, so anything left in it is untestable. The `scripts/test-web-console-*.mjs` tests import it directly. |
|
||||
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `console.md` | the agent-facing contract, which is what every console prompt points at. Its **Workflow notes** section holds the per-workflow detail (Dashboard, Init and Init Update, Document, Review, Handoff, Pathfinder, Planning, Revision, Finalize), which keeps the prompts themselves to a one-line pointer |
|
||||
| `building.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`), the sign-off (with the review offer as a verdict), the finish, and running the review on the page mid-session |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `screens/dashboard.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of the screens' render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
| `console.md` | the core of the agent-facing contract, read once per conversation (every skill ships the same copy, so a dashboard hop never re-reads it): starting, the turn (`post --wait`, the exit codes, handling a send, `settle`), posting, the payload and its kinds, documents (including `file` blocks), the house rules, and an index of the topic files below with the moment each is read. A test caps it at 24,000 characters |
|
||||
| `console-finish.md` · `console-stop.md` · `console-chat.md` · `console-workspace.md` · `console-subagents.md` · `console-launches.md` · `console-meter.md` · `console-attachments.md` · `console-trouble.md` | topic files, each read only when its moment first comes: finishing (the finish and its buttons), stop requests (the way home mid-workflow, `stopWarning`, resuming a pause), Quick questions, the Workspace, standing instructions and helper reports, dashboard launches and the menu payload, the session meter's `run` events (read only when a `run` is refused: the notes inline every `run`), keeping a cited note attachment, and recovery |
|
||||
| `notes/<workflow>.md` | per-workflow notes (`init` for both inits, `pathfinder` with Briefs, `plan`, `revise-plan`, `document`, `implement` for both builds, `quick-task`, `review`, `finalize`, `handoff`, `changelog`, `git`, `xray`, `diagnose`). Each skill's Interface line reads `<D>/console.md` and its own notes file right after `open`; a test checks every skill names one that exists |
|
||||
| `building.md` · `building-review.md` | the build half of the contract, for `implement`, `implement-review` and `quick-task`: progress posts (`agent.activity`, `agent.quietMinutes`, `file` blocks re-read with `refresh`), the chat check between tasks, questions mid-build and stop requests; `building-review.md` is the review run on the page (the sign-off's `review` verdict, **Review it now**, Implement + Review's Stage 2), read only when asked for |
|
||||
|
||||
Key design points:
|
||||
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `app.js`.
|
||||
- **First-run Welcome.** The first dashboard a person sees (after the wake-up finishes) opens `#welcome-modal`. Any close (button, Esc, backdrop) saves `looks.welcomeSeen: true` to `looks.json`, which survives "Back to default". Help's first tab has a **Show the welcome again** link (`data-action="welcome"`). Logic: `maybeWelcome()` / `openWelcome()` in `screens/help-dialog.js`.
|
||||
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (`server.mjs` `/version` route). `renderHelpVersion()` in `app.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `server.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `lib.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
|
||||
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
|
||||
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `console.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch }` when it found anything to clean.
|
||||
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`). 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`), `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.
|
||||
- **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). When it is `false` the Git commit card stays clickable and shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `lib.mjs`: one `git status --porcelain -z` (3 second timeout, `null` when git cannot say) counting modified, staged, deleted and untracked paths. At `0` the card greys out with `GIT_CLEAN_REASON`; above it the detail line is `pendingNote(n)` ("3 files to commit"); `null` leaves it clickable. 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-commit` in the same session. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
||||
- **No git process.** `repoRoots()` in `lib.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `lib.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `server.mjs` renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to `app.css`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
|
||||
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
|
||||
- **The first paint needs no fetch.** `routes.mjs` (`renderIndex()`) renders `index.html` with the session's title, badge and saved theme (`data-theme`, `data-looks-accent`, matched by accent rules generated from `palette.js` and appended to the joined stylesheet by `static.mjs`) and the whole first state as an inline `<script type="application/json" id="boot">` (every `<` escaped; data blocks are not executed, so the CSP is unchanged). `modulepreload` hints fetch every module in parallel, the page draws in the same task as the script runs, and `/events?have=<key>` skips the opening frame when the page already holds that exact state. The chimes load on first use, not at start-up.
|
||||
- **Reads are stat-gated.** `fileStamp()` (mtime:size:ino) decides whether `state.json`, `result.json` and `looks.json` changed before anything reads or parses them — per request, per heartbeat and in the 1s poll; the parsed state is cached (`readState()` returns it; `/submit` clones before editing). `wait` stats `result.json` every 50ms instead of parsing it every 400ms. Static assets are held in memory for the server's life and revalidate by ETag.
|
||||
- **The Workspace and the session meter live beside `state.json`, one writer each, and outlive every hop.** Three session files, none of which `switchWorkflow()` ever touches, so both survive dashboard → skill → dashboard (a new console session starts with a count of 0, and with the folders remembered for its folder and spec, below):
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `workspace.json` | `server.mjs` | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()`, now in `lib.mjs`, computed by the server at boot) |
|
||||
| `workspace.json` | the server (`workspace.mjs`) | the folders (`id`, `path`, `name`, `description`, `original`, `nested`), `version`, the `changes` log, `missing` ids, and `remote` (`remoteWarning()` in `sessions.mjs`, computed by the server at boot) |
|
||||
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
|
||||
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
||||
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `workspace.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console-workspace.md` and `console-meter.md`, and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
|
||||
| `<session>/subagents-setting.json` | `server.mjs` | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`syncSubagentSetting()`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-setting.json` | the server (`settings.mjs`) | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`serverSubagents().sync` in `settings.mjs`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
|
||||
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
|
||||
|
||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console.md` → Standing instructions.
|
||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console-subagents.md`.
|
||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `routes.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `sessions.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||
- **A build tells the page how long silence is normal.** The page calls a working agent stuck after two minutes without a post, which is right for a conversation and wrong for a twenty-minute build task. `agent.quietMinutes` (1 to 60, counted only while `working`) stretches the stuck, adrift and Send-grace thresholds; `quietLimitMs()` in `answers.js` is the one rule.
|
||||
- **A finished quick task's review button is a request through the wait loop**, like the brief: `{ "i": "__review" }` or `{ "i": "__done" }`. The agent keeps waiting after posting a finish that carries `review`, and takes the review up by posting `"finish": null`, which puts the session back to work. Implementation's review needs no such machinery: it is a verdict on the sign-off card, asked before approval, so the session never left work to take it up.
|
||||
- **Back to the dashboard is the same kind of post-finish request.** A finish with `finish.dashboard: true` shows the button; a press arrives as `{ "i": "__dashboard", "type": "dashboard" }`, and the agent runs `open --resume <sid> --no-open --workflow dashboard` then posts `"finish": null` with a fresh `menu`. The agent waits ~10 minutes after the finish for it (alongside `__review` / `__done` on a quick task); after that the page swaps the button for the `/plan2code` command. `finish.command` is optional — without one the page shows the "All done" line — and `validate()` rejects a `<placeholder>` command and a non-boolean `dashboard`. The session-level actions are therefore `__brief`, `__stop`, `__launch`, `__review`, `__done` and `__dashboard`; a new post-finish button should copy this precedent.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console.md → Stop requests → "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.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
|
||||
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
|
||||
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
|
||||
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notebook for <folder>"Line truncated
|
||||
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **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.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 18 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed (except the dashboard topic's card list: `buildHelp()` fills its `.help-cards` from `SKILL_CATALOG` and `CATALOG_GROUPS` at that moment, in the dashboard's order), so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `screens/help-dialog.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Stuck sessions are explained twice, in Help and on the status line.** `stuck` ("When something looks stuck") is the second tab in `HELP_TABS`; its panel opens with a `help-callout` ("Check this first": Plan2Code often waits for a permission in the terminal, which the page cannot see) and four You see / Likely cause / Do this rows before the diagram. The quiet and Not running status lines carry a "What to check" button (`openHelpOn("stuck")`) inside the existing `role="status"` element, so it exists only while the symptom shows. Every finished and paused screen gets a "Before you close this" panel from `renderCloseGuide()` in `renderHandoff()` (Safe to close, Start fresh, Carry on). Tests in `scripts/test-web-console-source.mjs` check the tab order, the callout and rows, and the `renderCloseGuide` call.
|
||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-getting-started.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs scripts/test-script-git-commit.mjs scripts/test-script-changelog.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --build-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then one `node --test` over the skill-script tests (`test-skill-scripts.mjs`, `test-script-*.mjs`, `test-git-repo.mjs`), `test-launcher.mjs`, `test-getting-started.mjs` and the web console's `test-web-console-*.mjs`, so they run in parallel, one process each. The console tests are split by area (`-session`, `-lifecycle`, `-logic`, `-server`, `-chat`, `-chat-stress`, `-workspace`, `-subagents`, `-concurrency`, `-source`, `-git`, `-qa`, `-speed`, `-hardening`). Their shared setup is `scripts/web-console-test-helpers.mjs`: importing it gives the file its own console home (so `workspaces.json`, `subagents.json`, `looks.json` and sessions never collide across files) and registers the `stop --all` cleanup. `-session` and `-lifecycle` each run an ordered chain of tests on one session of their own; everything else opens a session per test. A new test goes in the file for its area, after the tests it depends on. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
|
||||
**Adding a file under `public/` needs three edits, not one:** the file itself, the `SERVABLE` allow-list in `server.mjs`, and (for a module the page imports) a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a new module missing from it 404s and the page dies at import with no useful error (a test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint.
|
||||
**Adding a file under `public/`:** a page module needs `SERVABLE` in `static.mjs` and a `<link rel="modulepreload">` in `index.html`. The set is hardcoded rather than a directory lookup so there is nothing to traverse; a module missing from it 404s and the page dies at import with no useful error (the import-fetch test fetches every import and fails naming the file). A module missing its preload still works, but loads serially after `app.js` and slows the first paint. A screen goes in `public/screens/`, imports only `state.js` and the pure modules (never another screen), and is imported by `screens/core.js`; the import guard in `scripts/test-web-console-shape.mjs` fails naming a screen that breaks either rule. A stylesheet goes in `public/styles/` and on `CSS_ORDER` in `static.mjs`, never on `SERVABLE`; the joined-stylesheet test fails when the folder and the list disagree. Every new file also needs its row in the files table above, which the docs-table test (same file) checks.
|
||||
|
||||
## Status Line
|
||||
|
||||
@@ -286,10 +372,10 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
| 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) |
|
||||
|
||||
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 the same steps after its error. `--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=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. 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. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
|
||||
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.
|
||||
|
||||
**Design constraints:**
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice) and a `version.json` (the installed version). (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
- **npm-style shims** — written into npm's global bin (`npm config get prefix`; `<prefix>/bin` off Windows): an sh shim everywhere, plus `.cmd` and `.ps1` on Windows, so cmd.exe, PowerShell and Git Bash all resolve it. On macOS/Linux, when the npm bin isn't writable (system Node), it falls back to `~/.local/bin`.
|
||||
- **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`.
|
||||
@@ -306,4 +392,4 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
|
||||
|
||||
The macOS and Linux shortcuts carry the `plan2code-launcher` marker as a comment line. A `.lnk` has nowhere to hide one (its Description is the hover tooltip), so it's recognized by what it runs: the UTF-16 strings `plan2code.ps1` and `--pick-folder` stored in the file (`plan2code.cmd` also matches, so shortcuts from before the PowerShell switch get refreshed). `uninstallLauncher()` removes only a recognized shortcut, plus the icons (`plan2code.ico`, `plan2code.png`), `bin/models.json` and `launcher.json` (never the user's `~/.plan2code/models.json`). A shortcut failure prints a warning and never fails the command install.
|
||||
|
||||
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
|
||||
**Installer integration** lives in `install.js` under the `PLAN2CODE COMMAND` section (`installLauncher`, `uninstallLauncher`, plus the shortcut helpers). `install()` awaits it after a successful skills install (so `I` and Advanced → `E` get it), `U` removes it, and Advanced → `D` installs it alone. Every global install writes `~/.plan2code/install.json`, the install record listing the pieces installed (skills, launcher, statusline, loop, metrics, bot); `install.js --update` (what `plan2code update` runs) reinstalls exactly those, with no menu and never uninstalling, or with no record the skills and the `plan2code` command. After an install, `printGettingStarted()` prints the three steps (cd into the project, start Plan2Code, pick a card) and, when no agent CLI is on `PATH`, how to get one.
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
## Gotchas / Pitfalls
|
||||
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` and `docs/index.html` (footer `Version X.Y.Z`) also carry the version. `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.
|
||||
@@ -26,12 +26,12 @@
|
||||
- **Metrics internal prompts have no char limit:** Files in `plan2code-metrics/src/prompts/` are NOT subject to the 20,000 char limit — only `src/plan2code-*.md` consumer-facing prompts are.
|
||||
- **User Feedback table format:** The `## User Feedback` markdown table in `overview.md` has a strict format the collector regex depends on. Field names must be exactly `Rating`, `Reason`, `Went Well`, `Went Poorly`. Pipe characters in values must be escaped as `\|`.
|
||||
- **PLAN-DRAFT confidence numbers are scraped by regex:** `collector.ts` scrapes the latest `specs/<feature>/PLAN-DRAFT-*.md` prose. Overall confidence falls back to prose only when `<!-- METRICS_JSON ... -->` lacks `confidence` (`collector.ts:186-196`): `Confidence: 95%`, or a table row `| Confidence | 95` with no `%`. The four *breakdown* patterns (`collector.ts:200-203`) run on every draft, METRICS_JSON or not: `/[Rr]equirements?[:\s|]+(\d{1,2})/` and its siblings match a bare dimension word followed by whitespace, a colon, or a pipe and then digits. So a PLAN-DRAFT written by anything other than `/plan2code-1-plan` Phase 7 must keep `Confidence` followed by a number (with `%`, or as a table row) **and** bare `Requirements` / `Feasibility` / `Integration` / `Risk` followed by a number off the page — including innocent table rows like `| Requirements | 11 |`. Otherwise the metrics pipeline records a planning-step confidence that no planning step produced. `/plan2code-0-pathfinder` works around this by hyphenating the labels (`Requirements-clarity 22/25`), which breaks the character class.
|
||||
- **Web console result-handoff invariant:** `result.json` holds answers a person pressed Send on. **An uncollected result (no `consumedAt`) is never overwritten and never deleted.** `/submit` and `/cancel` return 409 while one is pending, `open` clears the file only when it is already consumed, and `wait` stamps `consumedAt` **after** printing the result, never before, and exits by setting `process.exitCode` rather than calling `process.exit()`. That ordering is deliberate: an agent harness that kills a long shell command must not be able to land between "marked collected" and "handed over", and `process.exit()` can truncate an unflushed pipe. A repeat delivery is recoverable, a lost one is not. Two separate data-loss bugs came from breaking this in different places, and both were silent: the person sees "Sent", the agent never receives it. Any new code path that touches `result.json` must preserve the invariant, and `scripts/test-web-console.mjs` guards it. Related: the server writes each submitted answer onto its item as `submitted`, and `validate()` in `lib.mjs` must keep excluding that field from the completion-marker and metrics-scraper scans, which are meant for agent-authored text only. A person who typed `TASK_COMPLETE` into an answer would otherwise make every later patch unpostable.
|
||||
- **Web console oversized bodies:** `readBody()` in `server.mjs` calls `req.destroy()` past `MAX_BODY`, so an oversized JSON body gets no response at all: the client sees a connection reset, never a status code. A route that must answer 413 has to stop buffering and drain the rest of the body instead, as `readRaw()` (the `POST /upload` reader) does; memory still stays capped.
|
||||
- **Web console commands are tied to the directory `open` ran in:** `console.mjs` finds a running server through a handle file under a hash of the project directory (`handleFile(project, sid)` → `runtimeDirFor(project)` → `<RUNTIME_DIR>/<cwdHash(project)>/<sid>.json` in `lib.mjs`, with `RUNTIME_DIR` = `os.tmpdir()/plan2code-console`, or `$PLAN2CODE_CONSOLE_HOME/runtime`), and the project is the working directory of `open` / `open --resume`. Run `status`, `chat`, `wait` and `stop` from that same directory. From anywhere else `status` says `live: false`, `chat` / `wait` report `server-gone` (exit 20) and `stop` stops nothing, while the server is in fact still running. It is easy to mistake for a crash when a scratch session is opened from the repo and then driven from its session folder; check `server.log` and `events.ndjson` (a real exit writes an `exit` event or a stack) before chasing one.
|
||||
- **Web console 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.
|
||||
- **Web console assets:** `computeExpectedSkills()` copies references as `Buffer`s, so binary files are fine. Adding a `public/` file needs the three edits in Architecture → Web Console. The vendored `marked.esm.js` sha256 is in `.readme/web-console.md`.
|
||||
- **The default highlight color lives in two places:** changing it means editing `DEFAULT_ACCENT` in `public/palette.js` and the light, system-dark and explicit-dark `--accent*` values in `public/app.css`. No test ties them together.
|
||||
- **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.
|
||||
- **The splitting guideline has a hard ceiling — reference files cannot always be split:** each new reference costs the orchestrator a `Read references/<file>.md` line plus its fallback blockquote (~150-200 chars), which adds up across a prompt's 20,000-char budget. When a reference legitimately exceeds 300 lines (e.g. `plan2code-0-pathfinder-references/chart.md`), that is an accepted trade-off, not an oversight. Nested folders under `-references/` work: `references/` is the real path on every agent.
|
||||
- **Windows global bins for loop, metrics and bot are wrappers, not `npm link`:** on win32 the installer writes `<name>.cmd` and `<name>.ps1` into `npm config get prefix`, each running `node <package>/dist/bin/<name>.js` (`install.js:1302-1323` for the loop; the metrics and bot installers do the same). After a source change, `npm run build` in the package is enough; no reinstall.
|
||||
|
||||
@@ -5,7 +5,8 @@
|
||||
|
||||
```bash
|
||||
# Install dev dependencies (sets up husky pre-commit hooks only; each sub-package
|
||||
# below needs its own npm install, Node 18+)
|
||||
# below needs its own npm install. Running `npm test` needs Node 20+; users of
|
||||
# the installed skills still need only Node 18+)
|
||||
npm install
|
||||
|
||||
# Run the interactive installer
|
||||
@@ -19,18 +20,24 @@ npm run build:skills
|
||||
npm test
|
||||
|
||||
# One web console or launcher test
|
||||
node --test --test-name-pattern "<regex>" scripts/test-web-console.mjs
|
||||
node --test --test-name-pattern "<regex>" scripts/test-web-console-<area>.mjs
|
||||
|
||||
# Web console start-up benchmark (puppeteer-core optional)
|
||||
# Web console start-up benchmark (the paint columns use a local Chrome or Edge through
|
||||
# playwright-core, which `npm install` already provides)
|
||||
node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
|
||||
|
||||
# Refresh the web console screenshots in docs/screenshots/ (needs a local Chrome or Edge).
|
||||
# Rerun after any change a person would see on the console page, and open every image
|
||||
# before committing: right screen, both themes, no username or home path in frame.
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
# PLAN2CODE_TEST_BROWSER=chrome|msedge forces which browser the page tests and these scripts use
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen (dashboard-utilities scrolls to the utility cards)
|
||||
|
||||
# Compare every element's computed style on every screen before and after a stylesheet change
|
||||
# (dev-only, not in npm test): take a baseline first, then compare after each move
|
||||
node scripts/css-snapshot.mjs --out before.json
|
||||
node scripts/css-snapshot.mjs --compare before.json
|
||||
|
||||
# Plan2Code Loop
|
||||
cd plan2code-loop && npm install # First time setup
|
||||
cd plan2code-loop && npm run build # Build the CLI
|
||||
@@ -45,13 +52,13 @@ 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/test-web-console.mjs:191`), so they never open a browser or touch your real console home. Almost all of the ~70s is the web console suite.
|
||||
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.
|
||||
|
||||
## Test/Dev Env Vars
|
||||
|
||||
| Variable | Effect |
|
||||
|----------|--------|
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/lib.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_CONSOLE_HOME` | Replaces `~/.plan2code/console`: sessions, `looks.json` and the runtime handle dir all move under it (`src/web-console/files.mjs`). Always set it for scratch runs so `stop --all` cannot reach real sessions. |
|
||||
| `PLAN2CODE_NO_BROWSER` | `open` does not launch a browser (`NO_BROWSER` also works). |
|
||||
| `PLAN2CODE_BROWSER` | Browser command line to run with the link appended, instead of the system default. |
|
||||
| `PLAN2CODE_MODELS_DIR` | Moves the launcher model menus (`bin/models.json`, `models.json`) away from `~/.plan2code`, for tests. |
|
||||
@@ -84,12 +91,13 @@ The root `npm test` does not run the metrics or bot vitest suites; run them in t
|
||||
|
||||
## Non-Interactive Flags
|
||||
|
||||
`install.js` takes no arguments for normal use, but exposes two build hooks. Any argument other than these two (when neither is present) exits 1 with usage; extra arguments beside either flag are ignored.
|
||||
`install.js` takes no arguments for normal use, but exposes two build hooks and the non-interactive update. Any argument other than these three (when none is present) exits 1 with usage; extra arguments beside `--build-skills` or `--verify-skills` are ignored, while `--update` must be the only argument.
|
||||
|
||||
| Flag | Action |
|
||||
|------|--------|
|
||||
| `--build-skills` | Regenerate `skills/` from `src/`, pruning stale skills and reference files |
|
||||
| `--verify-skills` | Diff local `skills/` against `src/`; exits 1 on drift. Diagnostic only, the installer rebuilds anyway |
|
||||
| `--update` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, statusline, loop, metrics, bot), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||
|
||||
## How the Installer Works
|
||||
|
||||
@@ -134,6 +142,15 @@ See the `skills/` build-artifact gotcha in [Code Style & Gotchas](./AGENTS-code-
|
||||
## Adding a New Workflow Prompt / Skill
|
||||
|
||||
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/`. Add it to the skill/workflow table and the "What each skill reads and writes" table in `src/plan2code.md` (the latter is checked by `scripts/check-skill-table.mjs`), and to the workflow lists in `src/web-console/public/answers.js`, `public/meter.js` and the `console.mjs` usage text.
|
||||
3. Update command inventories in `README.md`, `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md`, and `CHANGELOG.md`. Update `docs/index.html` only for core pipeline steps.
|
||||
4. Run `npm run build:skills` and `npm test`.
|
||||
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/index.html`: its start pose, an `<svg class="pose pose-<workflow>" data-pose="<workflow>">` in `<template id="start-poses">` (pose CSS in `public/styles/poses.css`), unless its `pose` borrows an existing one (as Implement + Review borrows Implement's).
|
||||
- Its help topic: a `src/web-console/notes/<workflow>.md` (named in the skill's Interface line) or a `HELP_TOPICS` alias in `src/web-console/cmd-help.mjs`.
|
||||
- `src/plan2code.md`: the skill/workflow table and "What each skill reads and writes" (`scripts/check-skill-table.mjs`: every backticked token must appear in the skill's prompt).
|
||||
- `console.md` (the `open --workflow` list and the `notes/<workflow>.md` row).
|
||||
- Optional: `STARTER_SET_FOR` in `public/starters.js` (unlisted gets "general").
|
||||
|
||||
**Adding a spec state** is shorter: one entry in `src/web-console/public/spec-states.js`, the detection in `classifySpec()` in `src/web-console/scan.mjs`, the `states` of each card in `skills.js` that takes it, and a line in the dashboard skill (`src/plan2code.md`); then `npm test`.
|
||||
4. Update command inventories in `README.md` (dashboard-card and command tables), `QUICK-REFERENCE.md`, `.agents-docs/AGENTS-architecture.md` (prompt table, own-script rows, notes list), and `CHANGELOG.md`. Update `docs/index.html` for core pipeline steps, and for a utility only when it is a headline change (its `.utils` block).
|
||||
5. Run `npm run build:skills` and `npm test`.
|
||||
@@ -1 +1 @@
|
||||
U0VOQwHlDc6GXsacM1cljlQP8y5A2pfARxFGNkmxiK3VxP1nQ9BIp3Z9PZAvB/qlVfrIGc7bCpdtmhsc42H0uveWo+th315m1M0PZWI9GzUWFTL5kShCH6ffFbL3oZpZwdz8l/+oncjsGShQMy0tUp+46YIPBJZGbF6SLG8/O5MC9IcsJfIob7WQUDca0IuSbxPkqC5WqN9PiZNM5P0tXayc3ARK+tUmpO3ywLT+0AJi0m1HWxNMNr3jCqCbwfMzpv5AMZR8jwkJHnCfUZ2DlfmTptnRFx7BjbPIDE8O3nlzOzQj2IFF5CNkPFM+uHvWcd/vUYgqCeBzG51Hi+urt6gW9Q/geoDR8AfioqNeVjakuH3pSjE4kBFsvyO7RSO8wXlwgc/nZHW5BIzHKWVUB12THRtIA0kOmnf/Tk5Da20dRENuCP35KZvBXu1KKn/BQ4hJ/dCB1K4FqKOnqHKE8+CoYCTvlursoAC0rphfufcwXvuAysmtPZGgrOTM7x3z825I8HY6K2Y1dh6h0kxwZ9UDbMzrSH/3WP/jMywD76Ep2qMFMdXKRsypxvIkwJCsptq0NilJN9hALdGwq5G5nRvBCP+nxy6brdCknbKxb8XHkcS8fDAUSifBD4/K9EbDDkXrykKFnA1Vh82LC9tU8o6Uwi99EzpZeWkoZCLHMqJlXPu+FEKvBQYiVa4pDQ/XHSu6lUvUFbdQlRL0vHjNfOq5hjF1kqHj4B+cCiD/FNMqAu9N57+UQNgjI2KzvdlOUAySqp22Bg9sTWa4Nj1ObWRqEx2WH+d4BLkd8N3RgA8OAlOPfF1BCUrDQAnhFoWZmyiPkfm8nCx1eHGFBB/Q4uLloBvhwv2EAoPy2U2pCqO723/C/NJNc4BFK0iuvBaoCNYm1P8mDpzX/fYRQq7kMLlQ+/5urLNfDclPJaJ0bCEHYfcssnrcpt+xshHfNhrLnQ6Ns/ULS8queCAJeNaxe7fOZ+WE1AiSWdXeXFdjnQbFgl0A91zntdfsB0wVW1X4q5sGzQo1NUOYHWi53M+ROBszKXpp4GHSML1OpJQixydcRpQIfNPg2j96RfFOXrJZWc05QSEnjckj3b6sIJLNATEKLY9314CunAG70y/GryqOoLtQmLwXTBRgTx/et7/ItKsvUaK3Z3cEFLflEU5Ny9iHA7Yuxs0rmdn6NjV+IXA9eEf+Uc+2eSHmVCaUgJuhDtnyaO6RpqCJkbs5wf7c/udW2G5QfWZCTLHG80p/7BsA3q2VvEvbQnC+LLPgnyJJpDKL+q/x8KdZ1x/iY4P1J3B5nehEztoMHi8dgUsL3NkItdnJMKf5VQsyW1vnv4kZo7qZ+6+Z/IuqZZNy0aT3N1hJZWDPboFRmcGpTE8ShwblGnrTdnIZlhyk0m951creqltUp13bPWSFOj1zt/yDmW1yBUkkOmpnbJzmzxd9G4kpzHsV6NvGE4JsFVAQnGHgMI6zxMwKM7He+As/+FlwJgdmAPeIZ+PtciZMv+ySi9/xSXMwpJHSXFo2NkkWj8QJke5l9BsDGj66ZTjkW5R1RmYNhVAPTrP32a02kPj2JYgDOAIAGcz0q1Somb4LqVNAp6/Y6DFY3iniC3bV6vZagVLcgQFngHRgZ3HzILWcytJZwhVoMpE18DXpTBuubqytM/bnVFRZ6GxLJtcRCt24RnMRYipuR19kq+ncxEN7Xl7LkPdpsfFPelS9srxAWbivtD32SjCxsIKte+vns2lU6J12UoXP86LVDtTZCRkh/bmCDs4ecks02NVu2htm47UjPMVx1KDqTGPlPGZA+Vuj/eaWdoqvpEJzeOCgcrhUehDqQCpm0ZfCPJ924eGdfZGQZaaO4CZ6H4asHTTabWpu1cuLqVQkO030VAHJaDNE8fqxiPN3rsXmRjxTTSuc/N2i5OyGdqJdXbItMdmaWOU7p5XkmkUDVhhKiHBBcGsUekx0TSMmNkkbLJBy0DK2wkMP9utLDAxAzT5v0uTKKbPPpMYqGbhveN9+HClsD3cHGZ1xT3ag8Xg3s04zwoOhmXNvoDOOtcDaqbJacrMBhj8Hj6PUKGd2JlaU8M6GuBRXHzbmfPlDL7eQLhvRuwDAlVTfePRFs/L7i45xQ40t2z+Mxu1h+eQRuw3ePVscNX7xe7h+l+6MddyT7XuR2hiP4CapOJQ8uYgjdIUDDTAblNhIh99KvM4mevwzcZ+K6J/Kc3MFCeJzOIGYL0xCSKKnrvdihkYiw02U9okgkfz2eVwtmGHWl4iu/ymPc89d/4kmwflIIL3aYNCIyO7UaZHyRHLg8MrCZOZk4p/cY9CecHQStTZ2pnii7CeXzrckFa0JFwU6DKI192FbthJ3/F/9DZFWb10CIYVxzjWM7EwQtCzP9BAZQ2v89CxMh82arb6BgOnTWr55vH7UJFeKDQYSc/MT/VNnzhWCJZaLiJcB7RXwL2HFI6K/d7a5frcEEBGWhVACJjjqnFGBBlrOT1QMLeJX1Ru1sXqVsEYte8hg5/WzKs2LFmJcp/FqapQmpXa5vSKzgqD14GLij/LHA/2tTnS3Idb42A3rMDvm6ekrv/3gv/KFg+udrZv5cWLgX9QNktHBEUJNEQWVR1R7xAvdIo5SPrQxj7mu+wRsu8JXm8wXvTZFw9wJADOPUPrim6fU5JbGKhOVlIgePXisGYuh6doIl7ZKfdvwaFzOT2Fp+8KHmlmK6FPEGNEG9QaltbjIwg/XXmzjjTUfrSmgOeWay7e+MABTPnc2OUk+moSYKO1fhEgynVtd9xeeX7w+Rpcy6QL9Ut6Mz77/vLkZD0QviJReItBKajsIoKtrOGgHJ/R/z/XcdMsdbEwFweb3bp43B83jFKb0GeuWxhzzjtqIBeXnJvL8kGv3dXmDNM6BWi/JBs9r0Cyx1KCHSPDc3UIhk1FAOkKiu4a043D064M+IC+JqMcQT62eUw+uZ/dPh8x6rJIWSCRldOondtJDvKfsVYU/7gC73i31RD2SRZCj67JB8wFpXkOS+EjDFtkNvN8c2BJ0W8bMXE1UwKrPktOV6O/XpY6tsj+BqzaeU6DMPP7WVlrQ5NjLCUerxwTKXCcUqH00b8pkkvRZoBTz/nuhdBTsQWE9YZ2L/UTX38Y+eTNPOdBeBHkyTc/GHbvDOM5xsw8/Y4Mx4+NSDdrdWd0EL3uc9W16QmQKTzozRYJbSmat2xQNbGlOJRCUoX1FZoQXFJQfFNLjg3VzlhzFusAkxEICXS/6nOESDTH3xIw44vkegypd3xiizZ9RrhdEYiaU+0zfJp6p91v5czqUqRfnyKbLS9bv8/nHUq5HGz/AfumZKS2yXjHxSxYD/zbKc1Z88BsMvFXhOFD4GnN2Y5W0RP02XBwWDxP5BdWTfXB6dkgVw4HFDFnbmgeZWfc0AgRzZTuua5gCjGc0kmDYayJrojW7mGMTJYQJzwLCrKp2pDr5A6n8bNPCbCdp2RK6I8sgTyJjrX+2TbkMlulE/Vne1yKOdtdzkMeQ7jcO3rEK77pRymnmRtBxcp4DUEhkSHyfedXwr/9UewQPZ8eXWJOQPzJng3IrvY+L1diu0NBYu4qYCtNscNfkju52+wnluL2I8kOUWVPuDfRtF3tloaohl0nEnnXjyMuC+53+2F4MKNJRsE2eiPTVV1lfRuBgFfIcEI8q+E+GN3vXZ2lr3ouVt5bI5y1xZW8Sjt7zmPmSiyKkU3NZsL65b1PA718YO8i9+YBemw8VYfGfDn3JEc3f1P5WFYl0POYWWnCwlPe13J4ErZ8k3PBIuPGAqaE6W1d5yIkrLUnthDIOREghCve5L0HfguZZt+TUuHoq7iYLeJpYDYhGawnINJfUiZJH1MzYPixy+GZKyVBqZdr/dxPpdt/BVOsZ6WDNifkRrHaN18QrOJ4zFUAvFJDYq/1jYkLVflaoyxDlviOwAX/geIMRRTeDyZM9ucc0FG5h8qyeqoJQErMqaQT9BfvrvBI3JuRQiH5XuXRbz+uQMJljvhqs/lRhkeTWtMu9BdkEqlnyJskehE9qBzfLIw6lHYrtGs0NAPwN1m2Es+c502RAUp5nlIinJUR5/f7q2p7jgqVWuj1ifD7N2XoWFdMqM2+kb7suSYlY+gUPYK/Uz7T2as77U9OVzqS+udjWgdy3v/gfZOhuXhs0zrP/hBxswvSrpyhTq61bAAH7xOQGO3+IMxW4G4OgrfArNDMCflsFAgpktwmjkyTfM1YrZSEC9/65b1WE5lUi7r1Vx2PF0gogexigbz//Dp5MlfTsQkjRlLVv0rb6tnLXriCW9rdt2c491XRTMPR+348A9ckMYBbgRebXsfxVNrHK1ehgFT3C/vDbp4fXKGTNMITfvneJEN+RvfJFJW2JCNeAGwdqmpZJ5by+xlMP5a1K6eZNxnyqEhad/hfkvWMmBZo7dbuiDksFZm9iyaXJARGUsu+laEJClYyjEfhP9YvVdAs/5sL0NPCAw9OfqgUB+ZpFOFvtRun8E4Vmu4k4EZHgdW3bIrOmtUxFkkpOVQN+5EqmeiiB39dpOb8pn7KhhDLgnG8CTwA0Q9+WI3QtLA7BouOO49Y45K/7RrmKy1dgknDkv2Pe+7axcyI87UnY6XlpEaWrebS8YPlCpiAF8ZASKV93VDIx83RmhMe8SP6iiF2jYvXR6N7na6B9LW9/waV8U/1O8thqf45UgJ2LprQjjGYyXJ51VeFn0iRPEkyIygzdW02hq3COIWW2CAPIqxmtT3SuG7tqFb6Oa/QN2XS1d4ilSuEU7jIxkrvTVjQGtptVXFPxVylBLYVc6rsM+5gPHvQRpeg4t7OwbAJBPWvwa9dPIB01GdK0ppG6rTtNWvdtdzME1PSExjw035fI0OIC2AnMKqIufE0AkYYFO48ugN0Lg5SKSllypChiI2m80+wFDhe+X3AfX8t4pldQhdW84sV0mfWllfwqYhGU4LWOuIMYiK2Clx+9F2s8VwjSwRs7102mxu8f0vQoIq5A+7/Line truncated
|
||||
U0VOQwFCLraZiofXGk3ma3rfAp+AwimbD2xmPARjOXLQKQDASKq6WUdAn5Xu24Z6rJgFAocX+aoaxr7aEcSFrlFujCdvGz8V8xc24n8bf5xsAEXkLEYouPry356TXt0FXr6hMN0uJvih1b0zJQI2g0NP0Nqjb6W3QsusKfvxJdVSWCC6fXd8YVGjqXIBBB0TnReajLcbE6innfSbpK9bPioIuychW0VEPtytUTo/+z8xxIwZphis8Wx4zVUUm2b6CZVgbh/Uhxq54dkicULYd58KfsBgRaUscASNvjwgw6ggjvo7R1Wj47xm0L0nSFDPoERuOomxW0lI4ib5wfJ+3j2hBoueX5dHVMpVaGOZpL7RLvJf0AbBE8kwCL4hLxjBuatt95R+sfCpxHXu8hga1AzFKa2gL/IE6nzq5GMC5UKJ9JIhjmM6GxekM3c5yh+AbBgUxfv4Fa2OnRzNBvICB+xJfDSP3G0lE+OwkenYURIzMrW+gS24NXJ12rzhlyhEp0iAvr6wGAskcTpe9nXShyL9M69FXmCJuNZdenQv8pPr9zuw0M5b6BdKG9Tcp8j1Qm4BBA8J22Vd0uF7D6ByjpKkknbPdQMh3A/s09qix7t20eP/OGTh1JBZkOXxbSt5N/mjYUeLXAzqCYN0c3GsX6Za45OU618l4PO+kC223EdAjD4dWbN1CW65uJY0m2XckZr+2p3f9ow00BHnfzIZVG+aMSicaIJdGGudWdABVCsb7zvFr/Pv2pRWZjSOtSh2OrIkFeobEuqOFra1ifRCn6Y2/LChsPJBUqDwV4qDNjFouWL1JR59XntCn/Vcn94S9HmeP1gFS0ceOWGDDnaocbqCF3RL6SW9PN7GZCORjiyYhVZn6i7gIBIvmlg8mqmYYAaTGm9abwB278V2UJEn/YD/Hbr2krnVZEoEG73pk+oFGDRiY+G+cA2bpWhVt0bXKluanQJV1UTby0/RhbGGjhFMr+dPqHLRoeuLbnYkvcvLbdjz3vRXRbJdO3GARy81hWjPEZnvEaT0SR0683uMsCzCz3pWqL8BMIN2GuMIIsn7D0lZwb5eKrDjEZIkyVZhYiwX1kSsjK+JfIweRvxRoa2fCZ20tP5alIozh6m+Q2eWyzdxyRqXCHZkd8kUUT+XbLj5cw9tl3oINfwRUFYxAPwq/bhJS3bpl5ElPdo/ZKOKQuHpjt2nLdyXDYjXtpY9nUMKDO5in/bkqzSnSM52Va++1vaaYBtZnYx0v1HFoPtepx34pwkX0yjKIqIsHOzQVNNAYL5cQlzATMNISYsmne8c8ioRRuK07nyHGZhLroVaxJ2fgL6VQVjlxWmyeI9b+tBf3fRGtYwP3SwS1B4SYySFZ70bNZyROaQdE8Rin8mH7Pw8WquuCEE+LR63KLdC0QnV3iAr8d4aJSsYlDjqMXMASgtqof/jKCE2KZtCR+T2DrnXMhvgsRVwZ18Iufd9clv8hxrEUYx8D0sP+Ao9LJYAWGJ0Kt7GSfdwDLaRjL4jkToeFIImwIZPDpckCsraOcWD+vuR+kuuOBCtSxN+rm9pZ1VulMAG0KkkpydTeNPlbRuLbgfmwk8o7QQnmjcWL96sLQszm0JnYlQDHLRfAmaBj7L4JbsiGhCe5+2SfIrfqDCZhUYF+OwILtwXbhBGl5DcbCeRUSz9NUrz3ywF8TZa8TgBM89PiJb/pvMNrE7m+SmDJugiQ6UWcoYD9eC/katecM+b7KLGBYpO5qFx2+QpJff/YRhmHpz5O8UjJVKJK+xLAbvyiVs44OL+yJ5MIq8TUB7ojZDaTkpuwLKeezycktpzUENMbona5GbjvSaJWmD97TgBgAY9iP38h6lOHzKh0Mda5aVSWVn1Rq1pJ3IsZBPSC9QQe/p4DItw5aXeiMQwdozY5j95qICXfxvfnZP/MSIAyj9SZWKhNIuCDvOUxDHj2h4EZ6X+sCBAvhQG4YFAIzPqS8nnUIdgBtbStZBkQoY+n+m8qPsaYf7QdWeGPRI2vcfcCXyR9DvePV6ER3sTI2GKUUr61peCejc+cBwIWvqacr7Xl5QqTgTXGYvgu/Sh3FMws9iEPNScfd9K/hRbqTpJv4CeDu4fyFwTzuP/BHRQuv5pqJvzHdmTppwAfqAmo5pAWig9WpglQc+rWmlJYAtUvF7SIop/uXcH3r0xmlMilpc4PDMzaw3gu6kLIec63jrS0+cX5CD0DjfuT9nSgsdR8plkFi7UwtIRGhFO3B0gCIG+frznPAFUpm5KtnjjG1jIKsAXcfB1ZViS7/yHVcC4FeO4XOOJyVZSAImWKJ7ljGtpjLCK8BtiqrCuf26wlj3iw9jMm8wS5f+G+INg7bFgnlNRfqId2EeYJ21q9rODCCLMf2DUjJmVEuqk/grPparL3OgIV579+RUhXMUechv3zwkSdk/w5zyKyCc4j6tbAERg2KJP3CEQnCrdUeqMSdy06/prdkHnByPAX+7tx3JzVjOPxv3L7FNmahhTW6lWSJX2IR2VRwsP1UL6kf4pPeT9T5Ou47mmRy3CP+JLFDYt+3cQs9qYry+Xz2MfTJnyNJb7vGfPaQv/rPfJZyOmlFhQSzXfGtAPVF8srKnUNgdX6EJsw08rDZQhr0pCcu92VkNvNigzDtxIb+u+WYNprGb+sJFT+rtPQbP5v9+akyBw1Op7+Kek+S1XgK4PF+29QiEHKfPq4pgYnO5BLaUvNJVEImZV4nXM1ve2+YRDjtxRB0f2zBau0CfI+QpSfAHPk/COZojZU5Pdd/IiVPttEaSo7dvlhINIbmvTmHIA/XcHuOERmTpIZycVumSeKhDXxnahJzEeWZwDoxIkxIhFM94hLH6rc13fcAUvo3T+jKt7d9k13rF6dw+rd63+Bq83bBDHFero8tZmWdQ0Tpnv231EbSwv4L16N7J7ALtvPbnyNWR5wWzN9bc2/xglGys4txTcBt32P/dBR8QsBQ26CISfoElUR+vWQyo+OTOMP9sXyWPN0q2jC+EA/j+xg0TT2dW7RtkpjLR9uEMZpvJSMYnep+HtWw+6fns+W8kTV8zjv9cwod0TOA+qLbd3VCaQr/TDImqHigciRLV4NCLOTWGYuZiWbHCfikIyG4HBJlRgFumVTlgGKsVPRtdx5gqZBvZqaE2CSAtESC/O7q6ocoGx7cyLEs5Oq9sp2JZQPfxyLTtfG77OdAsr4KFFwGvgjH1Laz6rqw+DL15Ysj/WTl7yJ6toQ0KaRVTUf+3pNhpyCsqfWOLy4A8bMWAoPTdvh4sN+lOgNmHfe5Wym/UfR/UTz6cDGSrQgbSN3PXFzzSBM/Lm77MRljbBbFp0qXJAsteajVeXJX2JVFhGhQ8TzAUL3jhblbY0psVHuBoW9oyQ+UREc5/fH9hbRSDVcCr/5BWnY3Og3YOESOhHFx+lNFT+v96QU5lkat8b80llUwM/aJ8t+tzK+nyKhQwGgXpek6hVwnDhAFuwGXbxaCJNR5XJWrvChcn+m/5TDEm/U7mRblkiwEBm+i3mBDEioH9vHcRTu7wB+FoR6Q0FJbr1tm2lG3tvBg05pEglHkXrz//3iH61NjH251++zW93BFzngQLoRRBcreFfdiEP6VoHsVC5cFjzcnymLEdUtBp/ihbDZ3Tzn72c0oOzV8td4lgDDzxlJLZglwqj2Yx0yJLAPUAG7hJCWk+NbvyDsYSLWxn+ywOMH2onyh3pnPV7S3nKuJ3k6o52gdLmBOM6kHZvDmyTl4yua5zABGr6UWSHlgtCS1BRs8bH+RV79irRp1F8LUl8C+aENK1OlvD37kRRrlbZlqUV0cFib1ItRy2I69E2H1MfjgPE8gwksVmvX/JSGR6GC1SOFEqRRaGQtVAgSNrZ9W+qVpevtsK7Eytg2HVo8ZmPifWRZe5YOawhE7fFaih0/4gEoegRa6hDGK+X0uWao+95Vgtf1DosETrxlICRbDZT6oyqqWjGrIHi4X3ZSAgXF7VsZ+EeYRLRbJ84H8l552PnjXXPufQkOP3o6fFJYCMEnqowtqRhTIl5stzBbHLWVmQ6UCKPlhUHePsjI5snYy8/zuw6HRxYY+p6odEi0sn31PXO3RCeRBMtNQ5xWhddJK2KX33Ygc+qXBLSe3LG1PcbTCCf1H+E8x06JM5tVGG1WsmZnEIBxCpQUZN3/fUe65B37QYyxBwZDFwxetjthnT2E4WR1INRVUgJySBYrgHJr9PJF84dAdyrbXJsh2TckR4rCRYpOC4Yf4p/GqQim69YA09EIHA+9PgywDyiZ3lSKYHwrLgGZliiJx0envl2YlL9udzPcLzpjGOLzwTj2vpOAe3cDgscYGLPSUK76yqS1cPCXfz+xpmrvVFgUxRSx5i/hj4TFQotyI9sTfHTSXBJBvywpxC2GMoZrTSR+4ksLv2kLatRtVGnUHSAA/Lx6fbFKQleOqN3sFn9exSQAo3EWEA1wT/Uep6uSBWAg12Laf8l9hgoIniThbqv3D1AgfRth3aXfY5sK0S7HQfwCfbMWr2HSU0JydhxufKFV3z6aV1fCpXAgkXoZ151Brrpgi4urtwgFWfD4Cvlrq1SXM8aW2F84EpvOkADhrEvpzf2ZJ8w7mOzZxZCxoQ3CbBhjHjyfnoPMUMldvYctLobZxOBUqfwxC2SlcCyQCvlRLDs+M6z/qONNOhg29pZK368WHEbzUNmevtq7cleE4MGk2NU88Br99YPFc0qaxY+xDSaZKFDhERe+2QRNY3jTC07aK8tfoChkK4uahAghWDImK50i3DCLnUI5TlOaxkOaujA40QtEmnt5CNQuLeSCKtduT4rmDn2zDdep+BCCJlS1lJfonIhtDl/fCUT1Zj4Q/JWOlwUJDs+3yalPC78fqWTgHrNOREN/o5VRkOegZDz36eE6sFr4cpKfjSdeeojMb8MMKAFRAJce3MR6HflkKqEpTyVPMkeB/u48Z2wANGcYDwhqzi9c54DDjbSh1Vw4BbkuxgFUgdREipn1NJLine truncated
|
||||
@@ -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/
|
||||
@@ -90,12 +90,12 @@ Both are cheap to enforce mechanically in the server's write path.
|
||||
```
|
||||
src/web-console/
|
||||
console.mjs CLI: open | post | wait | status | stop
|
||||
server.mjs the HTTP server (spawned detached by `open`)
|
||||
lib.mjs paths, atomic writes, patch merge, validate()
|
||||
server.mjs the HTTP server (spawned detached by `open`); routes.mjs lists its URLs
|
||||
files.mjs, sessions.mjs, patches.mjs, scan.mjs, ... paths, atomic writes, patch merge, validate(), the repo scan
|
||||
console.md the agent-facing contract
|
||||
public/index.html markup shell only
|
||||
public/app.js the client (no inline script, see CSP below)
|
||||
public/app.css
|
||||
public/app.js the client's entry (no inline script, see CSP below); screens/ and state.js hold the rest
|
||||
public/styles/ the stylesheet, joined by the server into /app.css
|
||||
public/render.js markdown tokens to DOM nodes
|
||||
public/vendor/marked.esm.js pinned 15.0.7, MIT, lexer only
|
||||
```
|
||||
@@ -223,7 +223,7 @@ Recovery matrix:
|
||||
}
|
||||
```
|
||||
|
||||
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation; the `.gitignore` question in handoff explicitly does not ("present it, don't force it").
|
||||
Note `recommended` is **optional per option**. Handoff explicitly wants its inferred task offered as the recommendation.
|
||||
|
||||
### 4.2 Primitives
|
||||
|
||||
@@ -308,7 +308,7 @@ Three panes, plus view tabs, closer to pathfinder's own vocabulary than to a gri
|
||||
|
||||
Built for a mixed product and engineering room reading one screen together.
|
||||
|
||||
- **One width variable.** `--card-width` on `:root` in `app.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 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.
|
||||
- **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.
|
||||
|
||||
@@ -15,7 +15,8 @@ inside it, or add `--web` to a skill (`/plan2code-1-plan --web plan a lunch voti
|
||||
- **Tabs** show the document taking shape, the build progress and, always last, **Ask**, where you can
|
||||
put a quick question to the running agent.
|
||||
- **Sign-off** asks for your approval at the end of a phase. You can run the code review first from
|
||||
the same card.
|
||||
the same card, or press **Show me it working** to have the agent start the app and show you
|
||||
screenshots of the change right on the page.
|
||||
|
||||
**Where next.** [walkthrough.md](walkthrough.md) follows one feature from the first idea to the
|
||||
last phase. The rest of this file is the reference: every card, button and rule. Prefer the terminal?
|
||||
@@ -50,11 +51,11 @@ it opens on the page without asking.
|
||||
<img src="../docs/screenshots/dashboard-light.webp" alt="The Plan2Code dashboard: a Set up card, then the steps in order as cards, one of them marked Suggested.">
|
||||
</picture>
|
||||
|
||||
Scroll down for the utilities. Outside a git repository the **Git commit** card says so and still offers to start one:
|
||||
Scroll down for the utilities. Outside a git repository the **Git** card says so and still offers to start one:
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/dashboard-utilities-dark.webp">
|
||||
<img src="../docs/screenshots/dashboard-utilities-light.webp" alt="The utility cards: Quick task, Review, Handoff and Git commit, which notes that the folder is not a git repository yet and offers to start one.">
|
||||
<img src="../docs/screenshots/dashboard-utilities-light.webp" alt="The utility cards: Quick task, Review, Handoff and Git, which notes that the folder is not a git repository yet and offers to start one.">
|
||||
</picture>
|
||||
|
||||
---
|
||||
@@ -145,6 +146,9 @@ Scroll down for the utilities. Outside a git repository the **Git commit** card
|
||||
- **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 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,7 +164,7 @@ Scroll down for the utilities. Outside a git repository the **Git commit** card
|
||||
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 17 topics,
|
||||
- **Help.** The **?** at the top right opens a Help dialog with 18 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.
|
||||
@@ -176,6 +180,8 @@ review has already reviewed the code, so its card has no review button.
|
||||
</picture>
|
||||
|
||||
The **Ask** tab is a chat beside the cards, for a quick question at any point.
|
||||
When a question is really a new task, the answer ends with a ready-to-paste
|
||||
prompt in a block with a Copy button, to take into a new conversation.
|
||||
|
||||
<picture>
|
||||
<source media="(prefers-color-scheme: dark)" srcset="../docs/screenshots/ask-dark.webp">
|
||||
@@ -193,12 +199,39 @@ The easy way in is the dashboard:
|
||||
A page opens with every skill laid out as cards — the setup pair, the pipeline
|
||||
in order, and the utilities alongside — with a note about what it made of your
|
||||
project (no AGENTS.md yet, a spec waiting on Phase 2) and a *Suggested* flag on
|
||||
the card it would pick. **Git commit** is among the utilities, always available; in a
|
||||
folder that is not a git repository its card says *Not a git repository yet: it offers to
|
||||
start one*, and clicking it still works. Click one and Planny flies while it gets ready; a few
|
||||
seconds later the same page is that skill's console, already running. No
|
||||
the card it would pick. **Git** is among the utilities, always available: it opens
|
||||
the git board, three tabs — Changes, Branches and Sync — that open on the
|
||||
likely next step (Help's *The git board* topic walks through it), and asks
|
||||
before every push, publish and delete. In a folder that is not a git
|
||||
repository its card says *Not a git repository yet: it offers to start one*,
|
||||
and clicking it still works. **Codebase X-ray** is always available too: it
|
||||
explains how and why an area works, or ranks its rough spots into
|
||||
`specs/<name>/ARCHITECTURE-BRIEF-<date>.md`, and never changes code.
|
||||
**Diagnose a bug** sits beside it, also always
|
||||
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
|
||||
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
|
||||
**Delete** button in place of the hover ✕ other specs carry, and one confirm
|
||||
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.
|
||||
|
||||
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
|
||||
cards give way to a preview: when it was written, its spec, the skill it came
|
||||
from and its Next task. **Pick it up here** carries on in that skill and spec
|
||||
in this same session (Quick Task takes over, and says so, when the skill or
|
||||
spec is gone), and the chip is gone from the next dashboard. **Read it all**
|
||||
opens the whole document, **Copy for a new conversation** copies a one-line
|
||||
prompt that points a fresh conversation at the file, and **Delete** removes it
|
||||
for good after one confirm. Handoffs from *Stop with a handoff* (below) and
|
||||
from the Handoff skill land in the same place, `~/.plan2code/handoffs/`.
|
||||
|
||||
A freshly opened dashboard starts with Planny asleep in the middle of the page.
|
||||
Click to wake him: he snores once while he gets a gentle shake side to side,
|
||||
then about five seconds of him powering on to a boot-up sound (arms lifting
|
||||
@@ -378,6 +411,48 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||
they show in the tab too.
|
||||
|
||||
### Your notebook
|
||||
|
||||
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.
|
||||
|
||||
- **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
|
||||
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 notebook, in
|
||||
`~/.plan2code/notepads/<folder-name>-<12 hex>/`: `meta.json` (which folder it
|
||||
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.
|
||||
- **Removed only when you say.** No automatic cleanup touches it. Once the
|
||||
newest file in a notebook is 30 days old or more, *User Preferences →
|
||||
Cleanup* offers it as one item named after its folder's full path
|
||||
(*Notebook for /home/sam/code/shop*),
|
||||
and deleting it removes the whole notebook, every tab's text and pictures.
|
||||
|
||||
### Session meter
|
||||
|
||||
A small ring pill in the top bar — **Session: fresh** (green), **Session:
|
||||
@@ -453,6 +528,23 @@ A finished session says so, and ends in one of three shapes:
|
||||
- **Paused.** You pressed *Stop session*. The card names what was saved and
|
||||
gives the command that picks it up later. Nothing else is offered.
|
||||
|
||||
*Stop session* offers two ways to stop (on the dashboard, where nothing has
|
||||
started, it is a plain Stop). **Stop with a handoff**, the suggested one,
|
||||
saves your place as usual and also has the agent write a handoff: where the
|
||||
work stands and the next task, kept in `~/.plan2code/handoffs/` rather than in
|
||||
your project. The paused card names the file, and the dashboard offers it as a
|
||||
chip until it is picked up. **Just stop and save** saves your place and gives
|
||||
the resume command, nothing more; where the step has nothing saved yet it reads
|
||||
*Stop anyway*, under a warning about what is lost.
|
||||
|
||||
When the next step is another Plan2Code skill, the screen also has a
|
||||
**Continue here** button beside it: one press starts that skill in the same
|
||||
conversation, as a dashboard card would. It disappears once the session meter is
|
||||
red, when a fresh conversation is the better choice. A finished Quick Task or
|
||||
Finalize that ends on a commit can also offer **Update CHANGELOG first**, beside
|
||||
**Commit it now**: it opens Changelog right there, and Changelog's yes to
|
||||
*Commit this now?* carries on to Git.
|
||||
|
||||
The first two also carry a **Back to the dashboard** button (beside the next
|
||||
step, or as the main button under "All done"). Press it and the same page turns
|
||||
back into the skill menu, in the same conversation, so the next skill starts
|
||||
@@ -566,9 +658,19 @@ chimes once (if sounds are on).
|
||||
|
||||
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
|
||||
AVAILABLE** banner at the top. Click it for the details: the version you
|
||||
have, the new one (linked to its Releases page) and the exact command that
|
||||
updates you, with a Copy button. **×** hides the banner for this session; the
|
||||
next dashboard shows it again until you update.
|
||||
have, the new one (linked to its Releases page) and the command that updates
|
||||
you, `plan2code update`, with a Copy button. It updates everything that was
|
||||
installed (the skills, the `plan2code` command and any extras you added), with
|
||||
no menu, and never uninstalls anything. If the `plan2code` command is not
|
||||
installed, the dialog also shows the install command,
|
||||
`npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git`, to run
|
||||
instead. **×** hides the banner for this session; the next dashboard shows it
|
||||
again until you update.
|
||||
|
||||
The `plan2code` command tells you too: before it starts your agent it prints
|
||||
one line, `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`.
|
||||
It reads the same saved check, so it never waits on the network; when that
|
||||
check is missing or old, it refreshes it in the background for next time.
|
||||
|
||||
The check uses your own git login to read the repo's release tags, once an
|
||||
hour at most. If git cannot reach the repo (no git, no access, offline), you
|
||||
@@ -590,7 +692,7 @@ keyboard-only navigation work.
|
||||
|
||||
## Models in User Preferences
|
||||
|
||||
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin 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.
|
||||
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.
|
||||
|
||||
---
|
||||
|
||||
@@ -659,6 +761,8 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.plan2code/console/sessions/<id>/` | the questions, your draft, your answers | 30 days after the session was last touched |
|
||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||
| `~/.plan2code/handoffs/<id>.md`, `<id>.json` | each handoff's document, and which checkout, spec and skill it belongs to and whether it was picked up (`handoffs.mjs` is their one owner) | 30 days after it was last touched, picked up or not |
|
||||
| `~/.plan2code/notepads/<folder-name>-<12 hex>/` | your notebook for one folder: `meta.json`, `tabs.json` and, per tab, `tabs/<id>/note.md` and `tabs/<id>/images/` (`notepads.mjs` is their one owner; the agent never reads them) | until you delete it through Cleanup, which offers it once its newest file is 30 days old |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||
| `~/.plan2code/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 |
|
||||
@@ -678,7 +782,8 @@ reads), `public/meter.js` and `public/mentions.js` (the `@name` popover) — and
|
||||
**Old sessions clean themselves up.** Each time a session opens, whole session
|
||||
folders nobody has touched for 30 days are deleted — questions, drafts,
|
||||
answers, uploads and all, paused or not — along with stray scratch files
|
||||
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long.
|
||||
(`.json` / `.mjs`) left at the top of `~/.plan2code/console/` for as long, and
|
||||
handoffs in `~/.plan2code/handoffs/` untouched for as long, both files each.
|
||||
Your `looks.json` and the `console-dir` pointer are never touched, and neither
|
||||
is the session being opened. Nothing of value goes with them: the page is
|
||||
never the record, `specs/` in your project is.
|
||||
@@ -688,7 +793,14 @@ clean up** lists, with sizes, everything in `~/.plan2code/` that is not
|
||||
needed: sessions untouched for 30 days (never the one you are in), anything at
|
||||
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||
`console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed once
|
||||
`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 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:
|
||||
`specs--completed/` is usually gitignored, so git can't restore it. A stray is listed once
|
||||
it has sat untouched for an hour, so a lock or temp file another session is
|
||||
writing right now is never caught. **Delete these** removes
|
||||
that list and nothing else. A console running from another home
|
||||
@@ -724,7 +836,7 @@ this:
|
||||
|
||||
### Routes
|
||||
|
||||
The upload routes, the send, the overview read and the workspace. Like every page route, they are on `127.0.0.1`
|
||||
The upload routes, the send, the overview and handoff reads, the workspace and the 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.
|
||||
|
||||
@@ -737,25 +849,37 @@ origin.
|
||||
| `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 /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[?tab=<id>]` | The notepad for the folder this session runs in: `{ tabs: [{ id, name }], last, tab: { id, text, savedAt, images: [{ id, url, thumb }] } | null }`, with the tab's `text`, `savedAt` and `images` repeated at the top. Without `tab` it answers the last one used; 404 `no-such-tab` for an id it does not have. A notepad in the first shape answers one virtual tab, Notes. Reading never creates or moves a file. |
|
||||
| `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`. |
|
||||
| `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
|
||||
|
||||
| | |
|
||||
| --- | --- |
|
||||
| Source | `src/web-console/` |
|
||||
| Source | `src/web-console/` (one row per file in the files table of `.agents-docs/AGENTS-architecture.md`; a test keeps it complete) |
|
||||
| Ships as | `skills/<every skill>/references/web-console/` |
|
||||
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/answers.js` (`SKILL_CATALOG`) |
|
||||
| Agent contract | `src/web-console/console.md`, plus `building.md` for the build steps |
|
||||
| Tests | `node --test scripts/test-web-console.mjs`, also run by `npm test` |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs `puppeteer-core` and a local Chrome or Edge for the paint columns; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs `puppeteer-core` and a local Chrome or Edge) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only |
|
||||
| Wiring | one `additionalReferences` entry per skill in `install.js`; the dashboard's menu lives in `public/skills.js` (each entry's `card`; `SKILL_CATALOG` in `public/answers.js` is a lookup on it) |
|
||||
| Agent contract | `src/web-console/console.md` (read once), its topic files (`console-*.md`), `notes/<workflow>.md`, and `building.md` / `building-review.md` for the builds; `console.mjs help <topic>` prints any of them |
|
||||
| Tests | `node --test scripts/test-web-console-*.mjs` (split by area, shared setup in `scripts/web-console-test-helpers.mjs`), also run by `npm test` |
|
||||
| Start-up benchmark | `node scripts/bench-web-console.mjs` (needs a local Chrome or Edge for the paint columns, driven through `playwright-core` from `npm install`; `--browser-delay 900` models a real browser launch, `--roundtrip` times Send→agent and post→page) |
|
||||
| Screenshots | `node scripts/capture-screenshots.mjs` (needs a local Chrome or Edge, driven through `playwright-core` from `npm install`; `PLAN2CODE_TEST_BROWSER=chrome|msedge` forces one) |
|
||||
| Dependencies | none at runtime. `marked` 15.0.7 (MIT) is vendored for its lexer only, 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`
|
||||
@@ -827,7 +951,6 @@ after any change a person would see on the page: a new layout, a renamed
|
||||
button, a different colour.
|
||||
|
||||
```bash
|
||||
npm i --no-save puppeteer-core # once; never added to package.json
|
||||
node scripts/capture-screenshots.mjs # every screen
|
||||
node scripts/capture-screenshots.mjs --only dashboard # one screen
|
||||
```
|
||||
|
||||
@@ -42,8 +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 built-in 17-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 (off by default, 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.md` → Standing instructions). The agent-facing contract is `console.md` / `building.md`; the server never writes into a project.
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; the server never writes into a project.
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -68,7 +67,7 @@ Details: [Code Style & Gotchas](./.agents-docs/AGENTS-code-style.md)
|
||||
|
||||
The project has a mascot called "Planny": a box with a star for an eye, stick arms and two small feet. He appears in installer output, workflow prompts, the loop, the Claude Code status line (box, star and feet, no arms) and the web console. ASCII variants are defined in the `MASCOT` constant in `install.js` (and `plan2code-loop/src/utils/logger.ts`) and appear in workflow markdown files: arms down at rest, one arm waving when he is asking something, both arms up when he is celebrating. The eye is always the star.
|
||||
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `app.js` switches mood with a single class, so the drawing stays in the markup and the styling in `app.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
The web console draws him as inline SVG in `src/web-console/public/index.html`, where he doubles as the page's state indicator: his star lights in the highlight colour and he waves when something is yours to do, the star turns and his feet walk while the agent works, it goes green when all is done, he shows no arms at all when the agent is not answering, and he fades with his star shut when the connection drops. The parts are classed (`shell`, `eye`, `smile`, `foot`, and one `arms a-<mood>` set per mood) and `screens/core.js` switches mood with a single class, so the drawing stays in the markup and the styling in `styles/planny.css`. The nine skill start poses, the dashboard wake-up, `favicon.svg` / `favicon.js` and `src/launcher/plan2code.ico` all use the same design.
|
||||
|
||||
```
|
||||
╭───╮
|
||||
@@ -87,6 +86,9 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
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.
|
||||
5. A skill rule broken twice becomes a script check (a `scripts/` test or a skill-script check), not more prose.
|
||||
6. Before adding a line, look for one on the same topic: sharpen or extend that one rather than adding a near-duplicate.
|
||||
7. Keep the log to 17 entries at most. Over the cap, first merge entries that share a cause, then drop the lowest-value ones: one-offs unlikely to recur, rules a test or script now enforces, and entries about code that no longer exists.
|
||||
|
||||
## Failure log
|
||||
|
||||
@@ -94,6 +96,14 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- Sync upstream only through `/sync-repo`, and verify its baseline against the real tree before porting: an earlier sync silently skipped a whole upstream release (the `3-implement-review` skill) while the recorded version froze. Update the baseline with `.claude/skills/sync-repo/set-synced.mjs`, never with a shell pipe over the decrypted body.
|
||||
- After a sync merge, run `npm test` before trusting a "clean" file: when upstream and plan2code fixed the same bug, `git merge-file` keeps both copies without a conflict (a sync once left `let pattern` declared twice in `app.js`, caught only by `parse-check`).
|
||||
- When extracting upstream files in Git Bash, run `git show <ref>:<path>` with `MSYS_NO_PATHCONV=1` and `C:/` style paths (never `/c/`): path conversion rewrites `origin/main:.readme/x.md` into `origin\main;.readme\x.md`, the show fails, and the merge silently runs against an empty "theirs". Check every extracted file is non-empty before merging.
|
||||
- After a sync, grep the result for the upstream owner slug and company name in any case (the `/sync-repo` body lists them): the rebrand map only rewrites URLs, so a bare owner slug once slipped through into `feedback-payload.mjs` (and its test) until it was fixed by hand to `jparkerweb/plan2code`. No upstream name may appear in plain text anywhere in this repo.
|
||||
- After a sync, grep the result for every upstream name the rebrand map can miss (the `/sync-repo` body lists them): the owner slug and company name in any case, the bare brand word inside identifiers and fixtures, and the ticket key followed by anything, not only digits. Each slipped through once: an owner slug in `feedback-payload.mjs` and its test (fixed by hand to `jparkerweb/plan2code`); in v2.7.0 a `KEPT_<BRAND>_ENTRIES` constant, a `<brand>Dir` option, a `"<brand>"` test folder and an owner slug in a git remote URL; in v2.8.0 git board fixtures built as `` `feature/<KEY>-${11000 + i}-…` `` template literals, which a digits-only rewrite to `ABC-<n>` misses. No upstream name may appear in plain text anywhere in this repo.
|
||||
- Keep plan2code's ticket-free `commit-msg.mjs` (`<subject>`, `AI Assisted`) in every `/sync-repo`: upstream's ticket-from-branch rule was ported by mistake once and removed in v2.6.0.
|
||||
- When a new first-run dialog is added to the web console, set its seen flag in `scripts/capture-screenshots.mjs`'s `looks.json` too: the Welcome dialog once covered the regenerated dashboard screenshots until `welcomeSeen: true` was added.
|
||||
- Import `scripts/skill-script-helpers.mjs` in any test that builds git fixtures for a skill script or `git-repo.mjs`: it scrubs the whole test process's git config, so fixtures, imported modules and spawned scripts agree. Mixed configs broke `git plan switch` once (a global `core.autocrlf=true` checked fixtures out with CRLF the scrubbed script read as changed).
|
||||
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
|
||||
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
|
||||
- When 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`.
|
||||
- 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.
|
||||
@@ -2,6 +2,192 @@
|
||||
|
||||
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 **Restart** 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**: a context meter in the bar reads how full the running agent's context window is: a real-ish number from Claude's own transcript or Codex's session log (labeled best-effort, since both formats are undocumented), a clearly labeled estimate for Devin or any agent with no documented signal, and a gentle nudge near 70% suggesting Restart, shown only for a real or best-effort reading.
|
||||
- **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 **Restart 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.
|
||||
- `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.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **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/`).
|
||||
|
||||
## 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
|
||||
|
||||
- **web console**: a private **Notepad** in the top bar, on every screen. It opens a modal with a Markdown editor that styles as you type (OverType 2.6.1, vendored, MIT) and saves as you go, with pictures: paste, drag and drop or **Add image**, each shrunk to JPEG in the browser, shown as a thumbnail strip with an X that asks before deleting, and a full-screen preview. There is one notepad per project folder, kept in `~/.plan2code/notepads/` (`notepads.mjs`) and never shown to the agent. User Preferences → Cleanup offers a notepad for removal only when its newest file is 30 days old or more, as one item that removes the whole folder; the automatic sweep at open never touches it.
|
||||
|
||||
- **web console**: a finished screen whose next step is a Plan2Code skill has a **Continue here** button beside the Next step block. One press starts that skill in the same session, as a dashboard card would, on a clean page. It is hidden when the session meter is red (a fresh conversation is the better choice), on a pause and for a git command. The page does it alone: the agent only handles the `__launch` the dashboard already sends, and posts `finish: null` first when the next step is the same skill (Implement to Implement).
|
||||
- **web console**: a finished Quick Task or Finalize can offer **Update CHANGELOG first** beside **Commit it now** (`finish.changelog: true`, refused on any other workflow). It hops into Changelog in the same session, and Changelog's yes to *Commit this now?* carries on to Git. The press arrives as `__changelog`.
|
||||
- **web console**: the Ask contract (`console-chat.md`, *Prompts to carry away*) tells the agent to answer a new-task question, or a request for a prompt, with the explanation and one self-contained prompt in a fenced block. The page already gave every fenced block a Copy button, so there is no page change.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web console**: the dashboard has one Implement card instead of Implement and Implement + Review. Its confirm pane has a Review checkbox, ticked by default, that launches Implement + Review when ticked and plain Implement when not; the command shown follows the box.
|
||||
- **web console**: `open` and `handoff new` refuse a `--workflow` the console does not know (exit 2, naming the valid ones), instead of opening a session no skill answers. `open` with no `--workflow` still opens Pathfinder.
|
||||
- **web console**: Help's list of dashboard cards is built from the cards themselves, so it can never name a card the dashboard lacks: it follows the dashboard's order (Handoff last under *Useful any time*), and X-ray's line is its card's.
|
||||
- **web console**: a hop into Git from any skill now starts the page clean on both sides. The server always cleared it; the page kept the last skill's tab and staged answers.
|
||||
- **contributors**: the per-skill tables that were still kept by hand now come from `public/skills.js`: the meter's weights and labels (`WEIGHTS`, `LAUNCH_LABELS`, `RUN_LABELS` in `meter.js`), `resumeCommand()`'s switch in `answers.js`, Help's card list in `index.html` (now filled by `buildHelp()` in `screens/help-dialog.js`) and `cmd-help.mjs`'s workflow list. Each entry gains `weight`, `started`, `ran`, `resume` and an optional `card.help`, and `skills.js` exports `WORKFLOWS` and `isWorkflow()`. A test fails, naming the file and the name, when `console.md`, `src/plan2code.md` or the CLI's help drift from the list.
|
||||
- **contributors**: two new shared modules. `src/web-console/spec-files.mjs` holds the task markers and the task-line, checkbox and Status-line patterns with `statusOf()` and `countTasks()`, read by `scan.mjs` and the `specs.mjs` skill script, which no longer keep copies of their own; `patches.mjs` now takes `TASK_LINE_RE` from it instead of from `scan.mjs`. `src/web-console/public/hops.js` holds `startsClean()`, the rule for which hops start the page clean, called by `cmd-open.mjs`, `server.mjs` and `screens/core.js`.
|
||||
- **contributors**: for the upstream port, these moved: the meter tables, `resumeCommand()`'s switch, Help's card markup and `cmd-help`'s workflow list into `skills.js` fields; the markers and patterns in `scan.mjs` and `specs.mjs` into `spec-files.mjs` (and `TASK_LINE_RE` tightened on the way: exactly one space before the box and a case-sensitive `Task`, matching `TASK_ID_RE`; keep that when porting); the hop test in `cmd-open.mjs`, `server.mjs` and `screens/core.js` into `hops.js`. Port upstream's changes to those tables into `skills.js` and the two modules, not back into the old files.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: Workspace's Browse… folder picker (and the launcher's) no longer opens behind the browser on Windows. Windows refused the picker's `SetForegroundWindow`, because the picker is spawned by the detached console server and is not the process that last had input; the existing topmost flag is ignored by that dialog. It now waits until the dialog is visible, taps Alt (which lifts the foreground lock for the next call), and takes the foreground.
|
||||
- **dashboard**: an assumed task (`[?]`) counts as done and is named in the spec's line ("3 of 4 tasks done, 1 assumed"). It used to be left out of the count altogether, so that phase read "2 of 3 tasks done", and a spec whose tasks were all assumed read as not started. Numbered task lines (`1. [x] **Task ...`) count too, on the dashboard and in the `specs.mjs` skill script.
|
||||
|
||||
## v2.9.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **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.
|
||||
- **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.
|
||||
- **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.
|
||||
- **launcher**: `plan2code` prints one line before it starts your agent when a newer release is out: `Plan2Code v<latest> is out (you have v<installed>). Run: plan2code update`. It reads the web console's saved release check, so it never waits on the network; when that check is missing or old it refreshes it in the background for the next start.
|
||||
- **web console**: **Stop session** gains a second way to stop, **Stop with a handoff**. It saves the skill's place as before and also writes a Handoff document, so a quick task, a review or a half-done changelog keeps its context; the paused screen names the file.
|
||||
- **dashboard**: this checkout's unused handoffs show as chips in the spec picker. **Pick it up here** carries on in the skill that stopped (a handoff from the Handoff skill carries on in Quick Task), in the same session, and the chip is gone afterwards; **Read it all**, **Copy for a new conversation** and **Delete** sit beside it.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **implement**, **quick-task**, **plan**, **document**: tightened as they took on the habits, so each stays well under 15,000 characters.
|
||||
- **pathfinder**: tightened to stay under 15,000 characters as it took on the X-ray pointer.
|
||||
- **quick-task**, **implement**: when the cause is unclear or the fix big, they stop and suggest `/plan2code-diagnose`.
|
||||
- **finalize**: its archive confirmation now reads "yes / no / show me", the last chance to look at the whole feature running before the spec moves.
|
||||
- **dashboard**: Handoff is now the last card in *Useful any time*, after Git.
|
||||
- **contributors**: the add-a-skill checklist in `.agents-docs/AGENTS-development-commands.md` now lists every place a new skill must be registered (it missed about a dozen).
|
||||
- **contributors**: `AGENTS.md` gains a rule that a skill rule broken twice becomes a script check, not more prose.
|
||||
- **web console**: the UPDATE AVAILABLE dialog now gives `plan2code update` as the command, keeping the install command beside it for a machine without the `plan2code` command. User Preferences → Cleanup never lists `~/.plan2code/install.json`.
|
||||
- **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.
|
||||
- **init**, **init-update**: the *Keeping this file current* section they write into `AGENTS.md` gains three rules: a rule broken twice becomes an automated check, a new Failure log line first looks for one on the same topic to sharpen instead, and the log holds 17 entries at most (over the cap, merge entries that share a cause, then drop the lowest-value ones). Init update offers the missing rules to an existing section and tidies the log on every run, showing each merge and removal for a yes before it writes.
|
||||
- **contributors**: this repo's `AGENTS.md` follows the same Failure log rules, and its three post-sync grep entries are merged into one.
|
||||
- **contributors**: the web console's source is split by job: `lib.mjs`, `server.mjs`, `console.mjs`, `app.js` and `app.css` become `routes.mjs`, `static.mjs`, `cmd-*.mjs`, the by-job Node files, `public/screens/` and `public/styles/`. Nothing a person sees changes, and the page starts faster (ready in about 280 ms, was 450 ms).
|
||||
- **contributors**: the per-skill and per-spec-state tables live in two data files, `public/skills.js` and `public/spec-states.js`, so adding a skill or a state is a short list in `.agents-docs/AGENTS-development-commands.md` and `npm test` names anything missed. This replaces the long add-a-skill checklist noted above.
|
||||
- **contributors**: page tests drive the real console in Chrome or Edge through `playwright-core` inside `npm test` (running it needs Node 20 or newer; installed skills still need only Node 18). The screenshot and speed scripts use it too, with no hand install, and `scripts/css-snapshot.mjs` compares every computed style across a stylesheet change.
|
||||
- **contributors**: a test keeps the files table in `.agents-docs/AGENTS-architecture.md` complete: every console file needs a one-line row.
|
||||
- **contributors**: `post` now refuses a `finish` (exit 3) while any reported helper still shows `running`, so a finished page never keeps a spinning row. The agent contract in `console-finish.md` says to mark each helper `done` or `failed` first.
|
||||
|
||||
### 🗑️ Removed
|
||||
|
||||
- **handoff**: the Handoff skill's `handoff-path.mjs` script is retired in favour of `console.mjs handoff new`, which every skill can reach.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: a short card on the git board (a confirm such as *Delete 2 branches?*) fills the board's width instead of sitting narrow in the middle.
|
||||
- **web console**: a redraw no longer throws you back to the top of the finished screen, a doc tab, the Overview or the dashboard menu (pressing **Review it now**, or an agent update landing while you read). The page kept your place only on question cards; it now keeps it for whatever is scrolling, as long as the same thing is still on screen.
|
||||
- **dashboard**: a bug folder whose diagnosis Quick Task had marked `Fixed` no longer sits on the dashboard forever as *Files on disk*, pre-selected as the most recent spec with no card to clear it. The scan reports it as a new spec state, **Bug fixed**: no pipeline card lights for it, the picker never opens on it (it opens on the most recent spec still in play, or *Start from scratch*), and it is hidden while *Hide unavailable workflows* is on, dimmed otherwise. Quick Task, right after marking a diagnosis-only folder `Fixed`, offers to archive it to `specs--completed/<bug>/` with the same `specs.mjs archive` Finalize uses (a confirm card on the web console).
|
||||
|
||||
## v2.8.1
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- **docs**: the docs site now shows the git board, with a light and dark screenshot under the pipeline's "Any time" cards: the Changes, Branches and Sync tabs, opening on the likely next step, the tab badges, the single block for a stopped rebase or merge, and asking before every push, publish or delete.
|
||||
- **docs**: `scripts/capture-screenshots.mjs` gains a `git` shot. It builds a sample repository with a pushed feature branch and three changes to commit, so `node scripts/capture-screenshots.mjs --only git` regenerates the images.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **tests**: `npm test` no longer fails `git plan switch` on a machine with a global `core.autocrlf=true`. `scripts/skill-script-helpers.mjs` now strips back the git config for the whole test process, so test fixtures, imported modules and the scripts under test always use the same settings.
|
||||
|
||||
## v2.8.0
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **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 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.
|
||||
- **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.
|
||||
|
||||
## v2.7.1
|
||||
|
||||
### 🐛 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.
|
||||
|
||||
## v2.7.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **git**: a new `/plan2code-git` skill and dashboard card that puts branches, pull, push and commits on one board in the web console. The board shows the branch you are on with what is ahead or behind, when the remotes were last refreshed, and every local and remote branch: current and default first, **Merged** and **Remote copy deleted** marked, remote-only branches folded after 50, and a search box. Every click is one action the agent runs, and the bar locks until it is done.
|
||||
- **git**: branch actions on the board: switch (asking first when you have changes: **Switch and bring them**, **Commit first** or **Cancel**), create `<type>/<description>` branches from any branch, delete local branches (a red confirm when unmerged) and **Clean up** merged and remote-deleted ones in one go. A remote branch is never deleted.
|
||||
- **git**: pull with conflict help. A pull that stops on conflicts offers to resolve them, shows each stop's files with a reason and a diff, and waits for **Continue**, **Change it** or **Abort pull**. Files it cannot resolve with confidence are named and left alone.
|
||||
- **git**: push and publish, each asking first with the exact command, never a force-push. After a push or publish the board links to the host's new pull request page (GitHub, GitLab, Bitbucket, Azure DevOps); an unknown host is asked about once and remembered in `~/.plan2code/console/pr-hosts.json`. Bitbucket PR links are unverified.
|
||||
- **git**: plain instructions in the terminal, such as `/plan2code-git switch to main` or `/plan2code-git commit and push`, run at once with the same confirms the board shows. Commits keep the `<subject>` / `AI Assisted` format.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web-console**: agents get through each turn faster. The agent instructions are split: a short `console.md` (21 KB, was 86 KB) is read once per conversation, and every skill copy is the same, so a dashboard hop doesn't re-read it. Topic files (ending a session, Quick questions, Workspace, helpers, launches, the meter, troubleshooting, each workflow's notes, the in-page review) are read only when they're needed. `console.mjs help <topic>` prints any of them.
|
||||
- **web-console**: one command per turn. `post --wait <N>` posts and then waits. Collecting a send marks the agent working, and a new question (or a wait with one open) hands the turn back, so agents no longer post a status first. `"settle": true` records the cards just answered from what was sent.
|
||||
- **web-console**: builds no longer retype the phase file after every task. A doc block can name a file (`{ "file": "specs/x/phase-3.md" }`, `"select": "tasks"` for the task lines) that the console reads from the project. `"refresh": true` re-reads it, and a doc's version moves up by itself when its content changes. A hop (dashboard launch, Back to the dashboard, Commit it now) comes with the exact resume command and the skill file to read. A chat reply's id defaults to `r<seq>`, and `fallbackText` is no longer asked for (nothing read it).
|
||||
- **web-console**: a send is picked up without delay. The wait loop's server health check no longer holds the 50 ms polling for up to 4 s. A working agent's timer now restarts with each new turn instead of counting from when the session opened. The git board unlocks when a working agent stops checking in.
|
||||
- **web-console**: **Commit it now** on a finished Finalize, phase build or quick task now opens Git in the same session, which commits every changed file (risky ones left out and named) and leaves the board open with Push lit.
|
||||
- **changelog**: its closing "Commit this now?" hands the session to Git to commit the result.
|
||||
- **web-console**: Help has an 18th topic, **The git board**, right after **Watching a build**, and a Git session opens Help on it. The dashboard topic's Git line points to it.
|
||||
- **web-console**: a Quick Task build now ticks the steps on the **Plan** tab one by one as each finishes, alongside the "Task x of y" line beside Planny. The separate Build progress tab is gone. The plan is posted as Summary, Files to change, Steps and Verify blocks, and each step's post resends only the `steps` checklist. The waiting pane's "follow along" link opens the Plan tab.
|
||||
- **web-console**: User Preferences → Cleanup also lists this project's `specs--completed/<feature>/` folders that nobody has touched for 30 days. Deleting one is permanent, since that folder is usually gitignored, and the help text says so.
|
||||
- **web-console**: the **Subagents** tab shows the small spinner left of its label, like **Ask**, while any helper is Running.
|
||||
- **web-console**: User Preferences is wider (880px). Only its body scrolls, so **Back to default** and **Done** stay in view.
|
||||
- **installer**: the finish screen no longer ends with "Update later with: `npx skills update -g`" (the README sentence is gone too). Re-running the install command is the update path.
|
||||
- **tests**: `npm test` runs much faster with the same tests. The web console's tests are split by area into `scripts/test-web-console-*.mjs` so `node --test` runs them in parallel, git fixtures are built once per test file and copied for each test, and the skill-script tests no longer rebuild `skills/` when `npm test` has just built it. The hardening tests that were only in plan2code moved to `scripts/test-web-console-hardening.mjs`.
|
||||
- **docs**: wherever the install command is printed (README, quick reference, docs site, the console's Update modal), a line explains that no output at all means npm couldn't reach the repository and hid the reason, and that `git ls-remote https://github.com/jparkerweb/plan2code.git` shows why.
|
||||
|
||||
### 🗑️ Removed
|
||||
|
||||
- **git-commit**: `/plan2code-git-commit` was replaced by `/plan2code-git`; a terminal commit no longer offers a push, so say `commit and push` to do both.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **git**: a new repository now starts on `main` rather than git's legacy `master`, unless you set `init.defaultBranch` yourself. `init-check` returns the `branch` and the `commands` to run (`git init`, then `git symbolic-ref HEAD refs/heads/main`, which works on every supported git), and the init card names the branch.
|
||||
- **web-console**: answers are never lost or misfiled. `settle: true` records the send `wait` handed over, never a later one still waiting to be collected. A thread reply on a sent list, text or multi card puts what was sent back on the form. A card asked again keeps the note sent with its answer in its thread. A card the agent left open after collecting it no longer stays locked as "sent". Multi-line answers and notes are indented in `reply`, so typed text never passes for a console line. A list's `reply` names renames, additions and removals, and its first click after a rename works. A skipped card settles as skipped, and a note on a finished card reads "Your last note".
|
||||
- **web-console**: builds and the git board report the right state. A build's progress bar trusts `cleared: 0`, and a review between counts shows its stage. A later phase can ask for its own sign-off. After a commit hop the Ask tab no longer shows answered questions as pending. The board locks while an agent question is open above it, sends Publish without a remote when there are several, always offers Continue during a conflict, shows "main · rebasing" mid-rebase, updates the footer branch, keeps the last good refresh time after a failed one, and disables New branch mid-rebase or before the first commit. A `notice` no longer takes a question slot. `pr-url` refuses a pull request from the default branch into itself, deleting a branch with no unique commits is no longer a red confirm, and `classify-error` knows more network failures and a new `diverged` kind.
|
||||
- **web-console**: a send made before the last collection, or a skip, never stays locked as "with Plan2Code". A card left open by a partial settle keeps the person's edits, and a plain reopen frees the card and keeps the note in its thread. A list rename is kept while typing. Two dashboard tabs on different specs no longer trade the workspace back and forth. A branch whose remote copy was deleted offers Publish, not Pull. Refresh works with no remote, picking up edits made outside. The cleanup confirm is red only when commits would be lost. A stop past a warning no longer promises a saved place. `post` refuses a patch that is not one JSON object. A spec with no `overview.md` no longer logs a failed request.
|
||||
- **web-console**: the CLI is sturdier. `post --file` reads a BOM or UTF-16 patch (PowerShell's), `wait`, `chat` and `stop --session` find a session's server from any folder, `open --resume` gives a busy server a second look rather than starting another, `keep` refuses a `--from` outside the project and keeps one copy per upload, `agent.status` accepts only `working` or `waiting`, and the dashboard refuses question cards.
|
||||
- **web-console**: the page reads right. Doc images and links to kept attachments load, and other relative links show their path. HTML comments are hidden, blocked, in-progress and assumed tasks get markers, and long doc tab titles are cut. Cards with more below the fold fade at their bottom edge. Back on the dashboard the picker starts on the most recent spec, and the agent's note shows only for that spec. Pauses read as paused, the hand-off wording matches the `--web` flag and git commands, stop and leave dialogs with a warning no longer promise a saved place, and the "still being picked up" banner clears. Smaller fixes cover the Brief button and dates, the decision line, Workspace and Cleanup messages, the role banner, the Subagents dialog, the welcome dialog, the tab title, dialog links and the chips.
|
||||
- **web-console**: on the git board, a card with a note box (the proposed `.gitignore`, a split's review) no longer shrinks under the board with its buttons and note box drawn behind it; the card keeps its full height and the column scrolls. A note box there grows with what you type instead of scrolling inside itself, and before the first question lands, a folder with no repository says a question is coming rather than pointing at an empty space "above". A task line holding a code block or a long word no longer widens a doc tab past the page, the branch table scrolls on its own on a phone instead of pushing the board off screen, and the Ask tab's Send button wraps rather than being clipped on a narrow screen.
|
||||
- **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**: 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
|
||||
|
||||
### ✨ Added
|
||||
|
||||
@@ -15,11 +15,16 @@ The web console is the main way in: a local page where questions, documents, bui
|
||||
| ------------------------- | ------------------------------------ | -------------------------------------------------------------------------------------- |
|
||||
| From your project (shell) | `plan2code` | Opens Claude Code, Devin or Codex on the dashboard (`--cli claude` / `devin` / `codex` to choose) |
|
||||
| Inside any agent | `/plan2code` (`$plan2code` in Codex) | Opens the dashboard: a card for every skill, launched on the same page |
|
||||
| Install / update | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command; re-run it to update |
|
||||
| Install | `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git` | Installs the skills and the `plan2code` command (re-run it to update without the `plan2code` command) |
|
||||
| Update | `plan2code update` | Updates everything that was installed, with no menu; never uninstalls anything |
|
||||
| Straight into a skill | `/plan2code-1-plan --web` (any step) | Skips the "web console or terminal?" question and opens the page |
|
||||
|
||||
The install command always opens a menu. Back at your prompt with no output at all? npm could not reach the repository and hid the reason: run `git ls-remote https://github.com/jparkerweb/plan2code.git` to see it (usually the network, a proxy or the VPN).
|
||||
|
||||
Pick a skill on the dashboard and the same page becomes that session. Details: [.readme/web-console.md](.readme/web-console.md) · worked example: [.readme/walkthrough.md](.readme/walkthrough.md).
|
||||
|
||||
The **Notebook** icon in the top bar opens a private scratch pad for the folder you are in (Markdown and pictures, kept in `~/.plan2code/notepads/`, never shown to the agent).
|
||||
|
||||
## Commands
|
||||
|
||||
Every command below is what a dashboard card runs. Typed on its own, each one asks "web console or terminal?" first.
|
||||
@@ -39,8 +44,10 @@ Every command below is what a dashboard card runs. Typed on its own, each one as
|
||||
| 3+review | /plan2code-3-implement-review | overview.md | Reviewed implementation ready for approval (alternative to `/plan2code-3-implement`) |
|
||||
| 4 | /plan2code-4-finalize | overview.md | Archived specs |
|
||||
| handoff | /plan2code-handoff | Conversation | Self-contained handoff doc (OS temp dir by default, or a folder you pick such as `handoffs/`) |
|
||||
| xray | /plan2code-xray | An area, or none | An explanation citing files and commits, or `ARCHITECTURE-BRIEF-<date>.md` with the rough spots you picked |
|
||||
| diagnose | /plan2code-diagnose | A bug, or none | `DIAGNOSIS-<date>.md` with the cause and its evidence, then Quick Task (or Plan for a big fix) to fix it |
|
||||
| changelog | /plan2code-changelog | Your branch | `CHANGELOG.md` entries and the `package.json` version, from the default branch's latest version |
|
||||
| git-commit | /plan2code-git-commit | Your changes | A commit (`<subject>` / `AI Assisted`): suggested splits, a branch offer on the default branch, optional push |
|
||||
| git | /plan2code-git | Your repo | Commits (`<subject>` / `AI Assisted`), branches, pull with conflict help, push, publish |
|
||||
|
||||
**Terminal instead:** run any command without `--web` and answer the interface question with **terminal**. Nothing is lost: same questions, same gates, same files under `specs/`. You can switch between the two mid-feature.
|
||||
|
||||
|
||||
@@ -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.6.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 2.11.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -37,7 +37,7 @@ The dashboard, in a project halfway through a build. It suggests the next step f
|
||||
- **Ways in.** `plan2code` (Claude Code, Devin or Codex), or type `/plan2code` in your agent (`$plan2code` in Codex).
|
||||
- **No agent yet?** Install Claude Code, Codex or Devin first.
|
||||
|
||||
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, re-run the install command.
|
||||
Installation needs network access and runs through the [skills CLI](https://skills.sh). To update, run `plan2code update` (or re-run the install command).
|
||||
|
||||
```bash
|
||||
npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git
|
||||
@@ -47,6 +47,11 @@ This fetches the installer to a temp directory, builds the workflow as Agent Ski
|
||||
installation to `skills add`, and cleans up after itself. The installed skills work independently
|
||||
from then on.
|
||||
|
||||
**Back at your prompt with no output at all?** The installer always opens the menu below, so nothing
|
||||
means npm could not reach the repository and hid the reason. Run
|
||||
`git ls-remote https://github.com/jparkerweb/plan2code.git` to see it: usually the network, a proxy
|
||||
or the VPN.
|
||||
|
||||
The installer opens this menu (cloning and running `node install.js`, below, opens the same one):
|
||||
|
||||
```
|
||||
@@ -83,12 +88,34 @@ Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permiss
|
||||
which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>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 bottom or right 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 opt-in tick (off by default); a **Restart** button then replaces the
|
||||
agent with a fresh one on a brief built from the session, and a status strip below the top bar shows
|
||||
the agent, the page open and a context meter that nudges you toward Restart once Claude's or Codex's
|
||||
context is getting full. 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, still starts with checks off by default). 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.
|
||||
|
||||
The installer keeps one canonical copy of each skill under `~/.agents/skills/` and links it into
|
||||
agents that maintain their own directory. To update, re-run the install command.
|
||||
agents that maintain their own directory. To update, run `plan2code update` (or re-run the install command).
|
||||
|
||||
Use the installer rather than calling `skills add` against the repository root: recursive discovery
|
||||
would also find maintainer-only skills under `.claude/skills/`. The installer targets `skills/`
|
||||
@@ -145,7 +172,8 @@ 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 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 never sees. 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.
|
||||
@@ -179,17 +207,19 @@ The dashboard's cards, and when each one lights up for the spec you pick:
|
||||
| Set up this project | Reads your project and writes AGENTS.md, the guide every later step works from. | The project has no AGENTS.md yet |
|
||||
| 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 or a drafted plan |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
|
||||
| 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, 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 |
|
||||
| Finalize | Checks the work, writes the summary, files the specs away and suggests the commit message. | Every task in the spec is done |
|
||||
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always |
|
||||
| Quick task | Too small for the full process? A quick plan, then it just builds it. | Always (suggested when the spec is a diagnosed bug) |
|
||||
| Review | A second opinion on the changes. Problems ranked, and you pick what gets fixed. | Always |
|
||||
| Handoff | Pack this conversation into a document a fresh session can pick up cold. | Always |
|
||||
| Handoff | Pack this conversation into a document a fresh session can pick up cold. Any skill's **Stop with a handoff** writes one too, and the dashboard lists them to pick up. | Always |
|
||||
| Codebase X-ray | Explain how and why an area works, or find the rough spots worth fixing. | Always |
|
||||
| Diagnose a bug | Find a bug's cause and write it up, without fixing it. | Always |
|
||||
| Changelog | Checks the CHANGELOG version against the main branch and suggests entries for what is new. | Always |
|
||||
| Git commit | Commits your changes with a clear message, suggests a split when it is really two jobs, and offers to push. | Always (offers to start a repository outside one) |
|
||||
| Git | Branches, pull, push and commits on one board, asking before anything leaves your machine. | Always (offers to start a repository outside one) |
|
||||
|
||||
---
|
||||
|
||||
@@ -355,9 +385,11 @@ console or the terminal; add `--web` to skip the question and go straight to the
|
||||
| `/plan2code-init-update` | Fold what you learned this session back into `AGENTS.md` |
|
||||
| `/plan2code-quick-task` | A small change that doesn't warrant the full sequence |
|
||||
| `/plan2code-1b-revise-plan` | Requirements moved mid-build. Revise the specs, not the code |
|
||||
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from |
|
||||
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then offer Git commit |
|
||||
| `/plan2code-git-commit` | Commit with a clear message, suggested splits, a branch offer on the default branch, and an optional push |
|
||||
| `/plan2code-handoff` | Compact this conversation into a doc the next one resumes from, saved in `~/.plan2code/handoffs/` and listed on the dashboard to pick up |
|
||||
| `/plan2code-xray` | Explain how and why an area of the code works (citing files, commits and PRs), or rank the rough spots worth fixing into a brief for Pathfinder or Plan; never edits code |
|
||||
| `/plan2code-diagnose` | Find a bug's cause and write it up as `specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it, then offer `/plan2code-quick-task` to fix it, or `/plan2code-1-plan` when the fix is big |
|
||||
| `/plan2code-changelog` | Check the CHANGELOG version against the default branch, suggest entries for new work you can edit, keep `package.json` aligned, then hand off to Git to commit |
|
||||
| `/plan2code-git` | Branches, pull, push and commits on one board (or plain instructions in the terminal); asks before every push, publish and delete |
|
||||
|
||||
---
|
||||
|
||||
@@ -408,7 +440,7 @@ edits out through the skills CLI.
|
||||
|
||||
Core reference:
|
||||
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off
|
||||
- **[.readme/web-console.md](.readme/web-console.md)**: the full guide to the web console, from the dashboard to the last sign-off, including the private Notebook 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,109 @@
|
||||
# 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 **Restart**
|
||||
button that replaces the agent with a fresh one on a brief the app builds from its own record of the
|
||||
session. 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.
|
||||
|
||||
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 (Claude, Devin or Codex), model and effort (Claude and Codex
|
||||
only) to start on. Permission checks off is its own tick, unchanged unless you choose it (Restart
|
||||
keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of
|
||||
just being greyed out. The card is skipped when the launcher already passed an agent to start.
|
||||
|
||||
Once an agent is running, a slim top bar holds the project name, **Restart** and **Change project**,
|
||||
and a status strip beneath it shows the page the agent opened (not only the dashboard — every console
|
||||
page, including Ask, Workspace, Notebook, Help, Preferences and Git, opens inside the window), the
|
||||
agent's name and status, a context meter once one is readable, and the permission mode in use. 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** asks first if an agent is running,
|
||||
then stops it and the console before opening the new folder.
|
||||
|
||||
## 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, if you choose it
|
||||
|
||||
The launch card's permission-mode tick is off by default: leave it off and the agent keeps its normal
|
||||
approval prompts. Turn it on and the agent starts with checks off instead
|
||||
(`--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 status strip says so while that agent runs. Restart keeps the same
|
||||
choice. Work in a folder you are happy for the agent to change, and keep it under version control,
|
||||
before turning checks off.
|
||||
|
||||
## 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.
|
||||
@@ -11,7 +11,7 @@
|
||||
<link rel="icon" href="favicon.svg" type="image/svg+xml">
|
||||
<link rel="apple-touch-icon" href="apple-touch-icon.png">
|
||||
<style>
|
||||
/* The web console's palette and type (src/web-console/public/app.css), so the
|
||||
/* The web console's palette and type (src/web-console/public/styles/tokens.css), so the
|
||||
site and the product look like one thing, with the Plan2Code blue as the
|
||||
accent: #2455a4 in light, and the console's Ocean highlight (palette.js),
|
||||
which the screenshots use, in dark. System fonts only, like the console. */
|
||||
@@ -225,6 +225,7 @@ footer a { color: inherit; }
|
||||
<ul>
|
||||
<li><strong>Node.js 18 or newer.</strong> Check with <code>node --version</code>. No Node? Get it from <a href="https://nodejs.org/">nodejs.org</a> (the LTS download), or run <code>winget install OpenJS.NodeJS.LTS</code> on Windows, <code>brew install node</code> on macOS, or use <code>nvm</code> on Linux. Then open a new terminal.</li>
|
||||
<li><strong>Start from your project.</strong> Open your terminal in the project you want to work on (<code>cd</code> into it) before you run anything. Plan2Code works on the folder you start it in.</li>
|
||||
<li><strong>Ways in.</strong> <code>plan2code</code> (Claude Code, Devin or Codex), or type <code>/plan2code</code> in your agent (<code>$plan2code</code> in Codex).</li>
|
||||
<li><strong>No agent yet?</strong> Install Claude Code, Codex or Devin first.</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -237,6 +238,7 @@ footer a { color: inherit; }
|
||||
</button>
|
||||
</div>
|
||||
<p class="then">then, from your project, run <code>plan2code</code> (Claude Code, Devin or Codex), or type <code>/plan2code</code> in your agent (<code>$plan2code</code> in Codex).</p>
|
||||
<p class="then">It always opens a menu; no output at all means npm could not reach the repository and hid the reason: <code>git ls-remote https://github.com/jparkerweb/plan2code.git</code> shows why.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
@@ -304,7 +306,22 @@ footer a { color: inherit; }
|
||||
<div class="utils">
|
||||
<div class="util"><span class="chip">Any time</span><h3>Quick task</h3><p>Too small for the full process? A quick plan, then it just builds it.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Review</h3><p>A second opinion on the changes. Problems ranked, and you pick what gets fixed.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Handoff</h3><p>Pack this conversation into a document a fresh session can pick up cold.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Handoff</h3><p>Pack the current session into a document a fresh session can pick up cold.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Codebase X-ray</h3><p>Explains how and why an area works, or ranks the rough spots worth fixing into a brief for planning.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Diagnose a bug</h3><p>Finds a bug's cause and writes it up without fixing it, then hands the fix to Quick task, or to Plan when it is big.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Changelog</h3><p>Picks the next version and drafts the entries, which you edit before Git commits them.</p></div>
|
||||
<div class="util"><span class="chip">Any time</span><h3>Git</h3><p>A board for branches, pull, push and commits that opens on the likely next step.</p></div>
|
||||
</div>
|
||||
|
||||
<div class="row" id="git-board">
|
||||
<picture class="shot">
|
||||
<source media="(prefers-color-scheme: dark)" srcset="screenshots/git-dark.webp">
|
||||
<img src="screenshots/git-light.webp" width="2560" height="1600" loading="lazy" alt="The git board on feature/task-endpoints: the Changes tab, badged 3, opens on a Next step card reading Commit 3 files, above the three changed files ticked for the commit. Branches and Sync tabs and a Done with git button sit beside it.">
|
||||
</picture>
|
||||
<div>
|
||||
<h3>The git board</h3>
|
||||
<p>Three tabs, <strong>Changes</strong>, <strong>Branches</strong> and <strong>Sync</strong>, and it opens on the one holding your likely next step: commit, pull, push, publish, open a pull request or tidy up branches. That step is one main button. Each tab badges what is waiting on it, a stopped rebase or merge gets one block with every file marked, and nothing is pushed, published or deleted without asking. It never force-pushes.</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -318,6 +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 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>
|
||||
@@ -337,6 +355,13 @@ footer a { color: inherit; }
|
||||
</picture>
|
||||
<figcaption>Every ending says what to run next.</figcaption>
|
||||
</figure>
|
||||
<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 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 notebook, private to the folder.</figcaption>
|
||||
</figure>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -375,6 +400,7 @@ footer a { color: inherit; }
|
||||
<ul>
|
||||
<li><strong>Node.js 18 or newer.</strong> Check with <code>node --version</code>. No Node? Get it from <a href="https://nodejs.org/">nodejs.org</a> (the LTS download), or run <code>winget install OpenJS.NodeJS.LTS</code> on Windows, <code>brew install node</code> on macOS, or use <code>nvm</code> on Linux. Then open a new terminal.</li>
|
||||
<li><strong>Start from your project.</strong> Open your terminal in the project you want to work on (<code>cd</code> into it) before you run anything. Plan2Code works on the folder you start it in.</li>
|
||||
<li><strong>Ways in.</strong> <code>plan2code</code> (Claude Code, Devin or Codex), or type <code>/plan2code</code> in your agent (<code>$plan2code</code> in Codex).</li>
|
||||
<li><strong>No agent yet?</strong> Install Claude Code, Codex or Devin first.</li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -387,6 +413,7 @@ footer a { color: inherit; }
|
||||
</button>
|
||||
</div>
|
||||
<p class="then">then, from your project, run <code>plan2code</code> (Claude Code, Devin or Codex), or type <code>/plan2code</code> in your agent (<code>$plan2code</code> in Codex).</p>
|
||||
<p class="then">It always opens a menu; no output at all means npm could not reach the repository and hid the reason: <code>git ls-remote https://github.com/jparkerweb/plan2code.git</code> shows why.</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
|
||||
|
Before Width: | Height: | Size: 95 KiB After Width: | Height: | Size: 99 KiB |
|
Before Width: | Height: | Size: 104 KiB After Width: | Height: | Size: 107 KiB |
|
Before Width: | Height: | Size: 106 KiB After Width: | Height: | Size: 110 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 114 KiB |
|
Before Width: | Height: | Size: 81 KiB After Width: | Height: | Size: 89 KiB |
|
Before Width: | Height: | Size: 87 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 92 KiB After Width: | Height: | Size: 109 KiB |
|
Before Width: | Height: | Size: 99 KiB After Width: | Height: | Size: 119 KiB |
|
Before Width: | Height: | Size: 109 KiB After Width: | Height: | Size: 115 KiB |
|
Before Width: | Height: | Size: 115 KiB After Width: | Height: | Size: 122 KiB |
|
Before Width: | Height: | Size: 94 KiB After Width: | Height: | Size: 97 KiB |
|
Before Width: | Height: | Size: 100 KiB After Width: | Height: | Size: 103 KiB |
|
After Width: | Height: | Size: 73 KiB |
|
After Width: | Height: | Size: 78 KiB |
|
After Width: | Height: | Size: 62 KiB |
|
After Width: | Height: | Size: 67 KiB |
|
Before Width: | Height: | Size: 103 KiB After Width: | Height: | Size: 106 KiB |
|
Before Width: | Height: | Size: 113 KiB After Width: | Height: | Size: 117 KiB |
|
Before Width: | Height: | Size: 86 KiB After Width: | Height: | Size: 96 KiB |
|
Before Width: | Height: | Size: 95 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' };
|
||||
@@ -174,6 +175,7 @@ const SOURCE_PROMPTS = [
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -216,6 +218,7 @@ const SOURCE_PROMPTS = [
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -230,6 +233,7 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [
|
||||
{ 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: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -263,6 +267,29 @@ const SOURCE_PROMPTS = [
|
||||
scripts: ['specs.mjs'],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-xray.md',
|
||||
stepNumber: 'xray',
|
||||
name: 'xray',
|
||||
displayName: 'X-ray Mode',
|
||||
description: 'Explain how and why an area of the code works, or find the rough spots worth fixing',
|
||||
isUtility: true,
|
||||
scripts: [],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-diagnose.md',
|
||||
stepNumber: 'diagnose',
|
||||
name: 'diagnose',
|
||||
displayName: 'Diagnose Mode',
|
||||
description: 'Find and write up a bug\'s cause without fixing it',
|
||||
isUtility: true,
|
||||
scripts: ['specs.mjs'],
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-changelog.md',
|
||||
stepNumber: 'changelog',
|
||||
@@ -274,11 +301,11 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-git-commit.md',
|
||||
stepNumber: 'git-commit',
|
||||
name: 'git-commit',
|
||||
displayName: 'Git Commit Mode',
|
||||
description: 'Commit changes with a clear message, suggest splits, offer a branch and a push',
|
||||
source: 'plan2code-git.md',
|
||||
stepNumber: 'git',
|
||||
name: 'git',
|
||||
displayName: 'Git Mode',
|
||||
description: 'Branches, pull, push and commits on one board that stays open while you work',
|
||||
isUtility: true,
|
||||
scripts: ['commit-msg.mjs'],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
@@ -308,7 +335,9 @@ function generateStepLabel(prompt) {
|
||||
if (prompt.stepNumber === 'update') return 'Update';
|
||||
if (prompt.stepNumber === 'review') return 'Review';
|
||||
if (prompt.stepNumber === 'handoff') return 'Handoff';
|
||||
if (prompt.stepNumber === 'git-commit') return 'Git Commit';
|
||||
if (prompt.stepNumber === 'git') return 'Git';
|
||||
if (prompt.stepNumber === 'xray') return 'X-ray';
|
||||
if (prompt.stepNumber === 'diagnose') return 'Diagnose';
|
||||
if (prompt.stepNumber === 'changelog') return 'Changelog';
|
||||
if (prompt.stepNumber === 'quick') return 'Quick Task';
|
||||
return `Step ${prompt.stepNumber}`;
|
||||
@@ -900,9 +929,10 @@ function removeInstalledSkills(scope, { quiet = false } = {}) {
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* Execute installation
|
||||
* Execute installation. `unattended` (plan2code update) asks nothing and skips the getting-started
|
||||
* steps; `outcome` receives `skills` and `launcher` as true or false for update's per-piece report.
|
||||
*/
|
||||
async function install() {
|
||||
async function install({ unattended = false, outcome = {} } = {}) {
|
||||
displaySectionHeader(' INSTALLING SKILLS ');
|
||||
if (!buildSkills(true)) {
|
||||
console.log(`${COLORS.RED}${SYMBOLS.ERROR} Failed to build ${SKILLS_DIR_NAME}/ from src/${COLORS.RESET}`);
|
||||
@@ -946,10 +976,16 @@ async function install() {
|
||||
console.log('');
|
||||
reportSkillsOutput(result);
|
||||
const failed = !result.ok;
|
||||
outcome.skills = !failed;
|
||||
if (!failed) recordInstalled('skills');
|
||||
|
||||
// The `plan2code` command opens the dashboard skill, so it's only worth adding once the
|
||||
// skills themselves are in place.
|
||||
const launcherFailed = failed ? false : (await installLauncher({ quiet: true })) !== 0;
|
||||
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}`);
|
||||
@@ -977,14 +1013,12 @@ async function install() {
|
||||
}
|
||||
|
||||
// The steps come first: where to start, the ways in, and what to do without an agent.
|
||||
printGettingStarted({ commandInstalled: !launcherFailed });
|
||||
if (!unattended) printGettingStarted({ commandInstalled: !launcherFailed });
|
||||
console.log(`${COLORS.GREEN} ╭───╮${COLORS.RESET} ${COLORS.BRIGHT}All done! Happy coding!${COLORS.RESET}`);
|
||||
console.log(`${COLORS.GREEN} ╲│ ${COLORS.CYAN}★${COLORS.GREEN} │╱${COLORS.RESET}`);
|
||||
console.log(`${COLORS.GREEN} │ ${COLORS.BRIGHT}◡${COLORS.GREEN} │${COLORS.RESET}`);
|
||||
console.log(`${COLORS.GREEN} ╰┬─┬╯${COLORS.RESET} ${COLORS.DIM}Docs:${COLORS.RESET} ${COLORS.BRIGHT}https://github.com/jparkerweb/plan2code${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.DIM} Update later with:${COLORS.RESET} ${COLORS.CYAN}npx skills update -g${COLORS.RESET}`);
|
||||
console.log('');
|
||||
|
||||
return launcherFailed ? 1 : 0;
|
||||
}
|
||||
@@ -1051,6 +1085,7 @@ function uninstallSkills() {
|
||||
} else {
|
||||
errors++;
|
||||
}
|
||||
if (errors === 0) forgetInstalled('skills');
|
||||
|
||||
console.log(`\n${COLORS.YELLOW}${SYMBOLS.ACTIVE} CLEANING LEGACY PATHS${COLORS.RESET}\n`);
|
||||
const legacy = cleanLegacyPaths();
|
||||
@@ -1181,6 +1216,7 @@ 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 {
|
||||
@@ -1522,6 +1558,7 @@ function installPlan2CodeLoop() {
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('loop');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
@@ -1541,6 +1578,7 @@ function uninstallPlan2CodeLoop() {
|
||||
displaySectionHeader('PLAN2CODE-LOOP', '[ UNINSTALL ]');
|
||||
|
||||
removeGlobalSymlink();
|
||||
forgetInstalled('loop');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-loop uninstalled${COLORS.RESET}`);
|
||||
@@ -1758,6 +1796,7 @@ function installPlan2CodeMetrics() {
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('metrics');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-metrics installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
@@ -1774,6 +1813,7 @@ function uninstallPlan2CodeMetrics() {
|
||||
displaySectionHeader('PLAN2CODE-METRICS', '[ UNINSTALL ]');
|
||||
|
||||
removeMetricsGlobalSymlink();
|
||||
forgetInstalled('metrics');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-metrics uninstalled${COLORS.RESET}`);
|
||||
@@ -1797,9 +1837,10 @@ function getStatusLineSrcDir() {
|
||||
|
||||
/**
|
||||
* Install status line (copy + configure settings).
|
||||
* Async because it may prompt when a custom (non-plan2code) statusLine exists.
|
||||
* Async because it may prompt when a custom (non-plan2code) statusLine exists. `unattended`
|
||||
* (plan2code update) never prompts: a custom statusLine is kept as it is.
|
||||
*/
|
||||
async function installStatusLine({ quiet = false } = {}) {
|
||||
async function installStatusLine({ quiet = false, unattended = false } = {}) {
|
||||
if (!quiet) {
|
||||
displaySectionHeader('CLAUDE STATUS LINE', '[ INSTALL ]');
|
||||
} else {
|
||||
@@ -1875,6 +1916,13 @@ async function installStatusLine({ quiet = false } = {}) {
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} Existing statusLine detected in settings.json:`);
|
||||
console.log(` ${COLORS.DIM} ${existingCmd}${COLORS.RESET}`);
|
||||
|
||||
// The person chose that status line when they last installed; an update keeps it.
|
||||
if (unattended) {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Kept it: scripts updated, settings.json unchanged${COLORS.RESET}`);
|
||||
recordInstalled('statusline');
|
||||
return 0;
|
||||
}
|
||||
|
||||
const rl2 = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
const answer = await new Promise(resolve => {
|
||||
rl2.question(` ${COLORS.CYAN}Replace with Plan2Code status line?${COLORS.RESET} (Y/n): `, resolve);
|
||||
@@ -1884,6 +1932,7 @@ async function installStatusLine({ quiet = false } = {}) {
|
||||
if (answer.trim().toLowerCase() === 'n') {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Skipped — scripts installed but settings.json unchanged${COLORS.RESET}`);
|
||||
console.log('');
|
||||
recordInstalled('statusline');
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -1921,6 +1970,7 @@ async function installStatusLine({ quiet = false } = {}) {
|
||||
}
|
||||
|
||||
if (settingsOk) {
|
||||
recordInstalled('statusline');
|
||||
if (!quiet) {
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Claude Status Line installed successfully!${COLORS.RESET}`);
|
||||
@@ -2002,6 +2052,7 @@ function uninstallStatusLine() {
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No status line files found${COLORS.RESET}`);
|
||||
}
|
||||
|
||||
forgetInstalled('statusline');
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} Preserved: statusline-config.json${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Status line uninstalled${COLORS.RESET}`);
|
||||
@@ -2219,6 +2270,7 @@ function installPlan2CodeBot() {
|
||||
}
|
||||
|
||||
console.log('');
|
||||
recordInstalled('bot');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot installed successfully!${COLORS.RESET}`);
|
||||
console.log('');
|
||||
console.log(`${COLORS.CYAN}Usage:${COLORS.RESET}`);
|
||||
@@ -2235,6 +2287,7 @@ function uninstallPlan2CodeBot() {
|
||||
displaySectionHeader('PLAN2CODE-BOT', '[ UNINSTALL ]');
|
||||
|
||||
removeBotGlobalSymlink();
|
||||
forgetInstalled('bot');
|
||||
|
||||
console.log('');
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} plan2code-bot uninstalled${COLORS.RESET}`);
|
||||
@@ -2262,7 +2315,67 @@ const MODELS_SRC = path.join(__dirname, 'src', 'launcher', 'models.json');
|
||||
const MODELS_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'models.json');
|
||||
const LAUNCHER_DEST = path.join(os.homedir(), '.plan2code', 'bin', 'plan2code.js');
|
||||
const LAUNCHER_STATE = path.join(os.homedir(), '.plan2code', 'launcher.json');
|
||||
// The release notice: the launcher reads the console's cached check through this copy, and
|
||||
// compares it with the version.json written beside it.
|
||||
const UPDATE_CHECK_SRC = path.join(__dirname, 'src', 'web-console', 'update-check.mjs');
|
||||
const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.mjs');
|
||||
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', '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.
|
||||
* `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'));
|
||||
if (record && typeof record === 'object' && Array.isArray(record.pieces)) return record;
|
||||
} catch {}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Temp file, then rename, so a crash never leaves a half-written record. A failure only skips the record. */
|
||||
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 });
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2) + '\n');
|
||||
fs.renameSync(tmp, INSTALL_RECORD);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/** Add a piece after a successful global install. */
|
||||
function recordInstalled(piece) {
|
||||
const record = readInstallRecord();
|
||||
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();
|
||||
if (record) writeInstallRecord(record.pieces.filter((p) => p !== piece));
|
||||
}
|
||||
const SHORTCUT_NAME = 'Plan2Code';
|
||||
const SHORTCUT_ICON_SRC = path.join(__dirname, 'src', 'launcher', 'plan2code.ico');
|
||||
const SHORTCUT_ICON_DEST = path.join(path.dirname(LAUNCHER_DEST), 'plan2code.ico');
|
||||
@@ -2443,6 +2556,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.
|
||||
*/
|
||||
@@ -2479,7 +2594,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,
|
||||
}
|
||||
);
|
||||
@@ -2499,7 +2614,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',
|
||||
@@ -2541,9 +2656,10 @@ async function offerDesktopShortcut(binDir) {
|
||||
|
||||
/**
|
||||
* Install the global `plan2code` command, then offer the desktop shortcut. `quiet` prints
|
||||
* compact lines for use inside the skills install instead of a section of its own.
|
||||
* compact lines for use inside the skills install instead of a section of its own;
|
||||
* `unattended` (plan2code update) skips the shortcut offer and leaves any shortcut as it is.
|
||||
*/
|
||||
async function installLauncher({ quiet = false } = {}) {
|
||||
async function installLauncher({ quiet = false, unattended = false } = {}) {
|
||||
if (quiet) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING THE ${LAUNCHER_COMMAND.toUpperCase()} COMMAND${COLORS.RESET}`);
|
||||
} else {
|
||||
@@ -2561,6 +2677,8 @@ async function installLauncher({ quiet = false } = {}) {
|
||||
// The curated model menu is the authors' source of truth, so it is overwritten on every install.
|
||||
// Models the user added in User Preferences live in ~/.plan2code/models.json and are untouched.
|
||||
fs.copyFileSync(MODELS_SRC, MODELS_DEST);
|
||||
fs.copyFileSync(UPDATE_CHECK_SRC, UPDATE_CHECK_DEST);
|
||||
fs.writeFileSync(LAUNCHER_VERSION_DEST, JSON.stringify(projectVersion, null, 2) + '\n');
|
||||
if (process.platform !== 'win32') fs.chmodSync(LAUNCHER_DEST, 0o755);
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${LAUNCHER_DEST}`);
|
||||
} catch (error) {
|
||||
@@ -2594,8 +2712,9 @@ async function installLauncher({ quiet = false } = {}) {
|
||||
if (!isDirOnPath(binDir)) {
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} ${binDir} is not on your PATH — add it to use ${COLORS.BRIGHT}${LAUNCHER_COMMAND}${COLORS.RESET} from any directory`);
|
||||
}
|
||||
recordInstalled('launcher');
|
||||
// The shortcut is a convenience on top of the command, so a failure here only warns.
|
||||
await offerDesktopShortcut(binDir);
|
||||
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.
|
||||
@@ -2629,7 +2748,8 @@ function uninstallLauncher() {
|
||||
}
|
||||
const shortcut = getShortcutFile();
|
||||
if (isOurShortcut(shortcut)) remove(shortcut);
|
||||
for (const file of [LAUNCHER_DEST, MODELS_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE]) {
|
||||
forgetInstalled('launcher');
|
||||
for (const file of [LAUNCHER_DEST, MODELS_DEST, UPDATE_CHECK_DEST, LAUNCHER_VERSION_DEST, SHORTCUT_ICON_DEST, SHORTCUT_PNG_DEST, LAUNCHER_STATE, INSTALL_RECORD]) {
|
||||
if (fs.existsSync(file)) remove(file);
|
||||
}
|
||||
try {
|
||||
@@ -2644,26 +2764,308 @@ 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)
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* The install function for each recorded piece, in the order update runs them. Install
|
||||
* functions only: an update never uninstalls anything. install() covers the skills and the
|
||||
* plan2code command together.
|
||||
*/
|
||||
const UPDATE_STEPS = {
|
||||
skills: install,
|
||||
launcher: installLauncher,
|
||||
app: installDesktopApp,
|
||||
statusline: installStatusLine,
|
||||
loop: installPlan2CodeLoop,
|
||||
metrics: installPlan2CodeMetrics,
|
||||
bot: installPlan2CodeBot,
|
||||
};
|
||||
|
||||
/**
|
||||
* Reinstall whatever ~/.plan2code/install.json lists, without the menu or any prompt. Returns
|
||||
* the exit code: 0 when every piece updated, 1 naming the pieces that failed.
|
||||
*/
|
||||
async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
displaySectionHeader(' UPDATING PLAN2CODE ');
|
||||
console.log(`${COLORS.BLUE}${COLORS.BRIGHT}Installing:${COLORS.RESET} ${projectVersion.name} ${projectVersion.version}`);
|
||||
console.log('');
|
||||
|
||||
const record = readInstallRecord();
|
||||
const pieces = record ? record.pieces : ['skills', 'launcher'];
|
||||
if (!record) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.INFO}${COLORS.RESET} No install record found (installed before v${projectVersion.version}); updating the skills and the plan2code command.`);
|
||||
console.log('');
|
||||
}
|
||||
|
||||
const results = {};
|
||||
for (const piece of INSTALL_PIECES) {
|
||||
if (!pieces.includes(piece) || piece in results) continue;
|
||||
const outcome = {};
|
||||
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}`;
|
||||
}
|
||||
// install() returns 1 when only the command failed, so its outcome says how the skills
|
||||
// themselves went; a command it put in place has updated the launcher too, and one it
|
||||
// could not is retried on its own as the next piece.
|
||||
if (piece === 'skills' && typeof outcome.skills === 'boolean') {
|
||||
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' || 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]}`);
|
||||
}
|
||||
console.log('');
|
||||
if (failed.length > 0) {
|
||||
console.log(`${COLORS.RED}${SYMBOLS.ERROR} Update failed for: ${failed.join(', ')}${COLORS.RESET}\n`);
|
||||
return 1;
|
||||
}
|
||||
console.log(`${COLORS.GREEN}${SYMBOLS.SUCCESS} Plan2Code is up to date (v${projectVersion.version})${COLORS.RESET}\n`);
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// MAIN
|
||||
// ============================================================================
|
||||
|
||||
// Non-interactive build hooks for the generated skills/ artifact.
|
||||
const argv = process.argv.slice(2);
|
||||
// Run only when invoked directly; requiring the file (the update tests do) is load-only.
|
||||
if (require.main === module) {
|
||||
// Non-interactive build hooks for the generated skills/ artifact.
|
||||
const argv = process.argv.slice(2);
|
||||
|
||||
if (argv.includes('--build-skills')) {
|
||||
process.exit(buildSkills() ? 0 : 1);
|
||||
if (argv.includes('--build-skills')) {
|
||||
process.exit(buildSkills() ? 0 : 1);
|
||||
} else if (argv.includes('--verify-skills')) {
|
||||
process.exit(verifySkillsSync() ? 0 : 1);
|
||||
} else if (argv.length === 1 && argv[0] === '--update') {
|
||||
update().then((code) => process.exit(code));
|
||||
} else if (argv.length > 0) {
|
||||
console.error(`Unknown option(s): ${argv.join(' ')}`);
|
||||
console.error('Usage: node install.js [--build-skills | --verify-skills | --update]');
|
||||
console.error('Run with no options for the interactive installer.');
|
||||
process.exit(1);
|
||||
} else {
|
||||
runInteractive();
|
||||
}
|
||||
}
|
||||
|
||||
if (argv.includes('--verify-skills')) {
|
||||
process.exit(verifySkillsSync() ? 0 : 1);
|
||||
}
|
||||
|
||||
if (argv.length > 0) {
|
||||
console.error(`Unknown option(s): ${argv.join(' ')}`);
|
||||
console.error('Usage: node install.js [--build-skills | --verify-skills]');
|
||||
console.error('Run with no options for the interactive installer.');
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
runInteractive();
|
||||
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.6.0",
|
||||
"version": "3.0.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -8,9 +8,10 @@
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"build:skills": "node install.js --build-skills",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-getting-started.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs scripts/test-script-git-commit.mjs scripts/test-script-changelog.mjs"
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0"
|
||||
"husky": "^9.0.0",
|
||||
"playwright-core": "1.64.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
[workspace]
|
||||
resolver = "2"
|
||||
members = ["src-tauri", "fake-agent"]
|
||||
@@ -0,0 +1,34 @@
|
||||
# plan2code-app
|
||||
|
||||
The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a Restart 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.
|
||||
|
||||
## 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
|
||||
cargo test --workspace
|
||||
```
|
||||
|
||||
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,105 @@
|
||||
# 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.
|
||||
|
||||
## 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 test --workspace` passes 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 Restart 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 and the context meter; the permission note appears only
|
||||
while an agent started with checks off is running, never otherwise
|
||||
- [ ] 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
|
||||
(off is an explicit tick, never the default); 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 **Expand** it back; its size from
|
||||
before collapsing is remembered
|
||||
- [ ] 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
|
||||
- [ ] **Change project** in the top bar, with an agent running: it asks first, then the folder
|
||||
picker opens; cancelling 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 offers **Update skills**, and
|
||||
nothing updates until it is pressed
|
||||
|
||||
## 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 bar says it ended and offers Restart
|
||||
|
||||
## Agent lifecycle
|
||||
|
||||
- [ ] Start, then **Restart**: it confirms once, 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 Restart or **Change agent**
|
||||
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 Restart; check Task
|
||||
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
||||
|
||||
## Context meter
|
||||
|
||||
- [ ] Claude Code and Codex: the meter moves during a long session and the nudge appears once
|
||||
- [ ] Devin: the meter is labeled as an estimate
|
||||
- [ ] `~/.claude/settings.json` and your own status line are byte-identical before and after a session
|
||||
|
||||
## 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,130 @@
|
||||
//! 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",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten"]
|
||||
}
|
||||
|
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,409 @@
|
||||
//! 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::{launch_spec, AgentKind, 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<AgentKind>,
|
||||
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: AgentKind,
|
||||
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` 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: AgentKind,
|
||||
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),
|
||||
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 =
|
||||
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,473 @@
|
||||
//! The agents the app can run and the command line each one starts with. The
|
||||
//! flags are the ones `src/launcher/plan2code.js` uses today, so the app and
|
||||
//! `plan2code` start an agent the same way. Knows nothing about Tauri.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
/// Tests only: run this program instead of the real agent, for any `AgentKind`,
|
||||
/// so the fake agent stands in for Claude, Devin and Codex.
|
||||
pub const AGENT_BIN_ENV: &str = "PLAN2CODE_APP_AGENT_BIN";
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum AgentKind {
|
||||
Claude,
|
||||
Devin,
|
||||
Codex,
|
||||
}
|
||||
|
||||
impl AgentKind {
|
||||
pub const ALL: [AgentKind; 3] = [AgentKind::Claude, AgentKind::Devin, AgentKind::Codex];
|
||||
|
||||
/// The id the page and the settings file use.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
AgentKind::Claude => "claude",
|
||||
AgentKind::Devin => "devin",
|
||||
AgentKind::Codex => "codex",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<AgentKind> {
|
||||
AgentKind::ALL.into_iter().find(|kind| kind.id() == id)
|
||||
}
|
||||
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
AgentKind::Claude => "Claude Code",
|
||||
AgentKind::Devin => "Devin",
|
||||
AgentKind::Codex => "Codex",
|
||||
}
|
||||
}
|
||||
|
||||
/// What a first start types: the skill that opens the dashboard. Codex
|
||||
/// mentions a skill with `$name`.
|
||||
pub fn default_prompt(self) -> &'static str {
|
||||
match self {
|
||||
AgentKind::Codex => "$plan2code",
|
||||
_ => "/plan2code",
|
||||
}
|
||||
}
|
||||
|
||||
/// The program this agent runs as, before any PATH resolution.
|
||||
pub fn program_name(self) -> &'static str {
|
||||
match self {
|
||||
AgentKind::Claude => "claude",
|
||||
AgentKind::Devin => "devin",
|
||||
AgentKind::Codex => "codex",
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether this agent takes a separate reasoning effort. Devin's model
|
||||
/// ids already carry effort (`swe-2-high`), so it has none of its own.
|
||||
pub fn has_effort(self) -> bool {
|
||||
matches!(self, AgentKind::Claude | AgentKind::Codex)
|
||||
}
|
||||
|
||||
/// Where to install this agent: an npm command or, with no package of its
|
||||
/// own, the site to install from. The same text `src/launcher/plan2code.js`
|
||||
/// shows for a missing CLI.
|
||||
pub fn install_hint(self) -> &'static str {
|
||||
match self {
|
||||
AgentKind::Claude => "npm i -g @anthropic-ai/claude-code",
|
||||
AgentKind::Devin => "https://devin.ai",
|
||||
AgentKind::Codex => "npm i -g @openai/codex",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether permission checks run while the agent works. Bypass is always an
|
||||
/// explicit pick, shown with a banner while it runs; it is never the silent
|
||||
/// default.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(rename_all = "lowercase")]
|
||||
pub enum PermissionMode {
|
||||
/// The agent's own approval flow: it asks before a sensitive action.
|
||||
Checked,
|
||||
/// Permission checks are off.
|
||||
Bypass,
|
||||
}
|
||||
|
||||
impl PermissionMode {
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
PermissionMode::Checked => "checked",
|
||||
PermissionMode::Bypass => "bypass",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_id(id: &str) -> Option<PermissionMode> {
|
||||
match id {
|
||||
"checked" => Some(PermissionMode::Checked),
|
||||
"bypass" => Some(PermissionMode::Bypass),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `program` exists on `path_var`: an exact file on macOS and Linux,
|
||||
/// or with `.exe`, `.cmd` or `.bat` on Windows (as `windows_command` resolves
|
||||
/// a program to run).
|
||||
pub fn find_on_path(program: &str, path_var: &str) -> Option<PathBuf> {
|
||||
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[""] };
|
||||
path_var.split(if cfg!(windows) { ';' } else { ':' }).filter(|dir| !dir.is_empty()).find_map(|dir| {
|
||||
exts.iter().find_map(|ext| {
|
||||
let name = if ext.is_empty() { program.to_string() } else { format!("{program}.{ext}") };
|
||||
let candidate = Path::new(dir).join(name);
|
||||
candidate.is_file().then_some(candidate)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Where `kind`'s CLI runs from: the test override when it is set, else its
|
||||
/// program name on PATH. `None` means it cannot be run.
|
||||
pub fn installed_at(kind: AgentKind) -> Option<PathBuf> {
|
||||
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
|
||||
let program = bin.unwrap_or_else(|| kind.program_name().to_string());
|
||||
find_on_path(&program, crate::node_check::resolved_path())
|
||||
}
|
||||
|
||||
/// Whether `kind`'s CLI can be run at all.
|
||||
pub fn is_installed(kind: AgentKind) -> bool {
|
||||
installed_at(kind).is_some()
|
||||
}
|
||||
|
||||
/// A command to run in the pseudo-terminal.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct LaunchSpec {
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
pub env: Vec<(String, String)>,
|
||||
pub cwd: PathBuf,
|
||||
}
|
||||
|
||||
/// How to start `kind` in `folder`. An empty `prompt` starts the agent with
|
||||
/// nothing typed. `PLAN2CODE_APP_AGENT_BIN` replaces the program (tests only).
|
||||
pub fn launch_spec(
|
||||
kind: AgentKind,
|
||||
folder: &Path,
|
||||
model: Option<&str>,
|
||||
effort: Option<&str>,
|
||||
mode: PermissionMode,
|
||||
prompt: &str,
|
||||
) -> LaunchSpec {
|
||||
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty());
|
||||
let mut spec = launch_spec_with(kind, folder, model, effort, mode, prompt, bin.as_deref());
|
||||
// The override names a program to run as it is; a real agent is looked up on PATH.
|
||||
if cfg!(windows) && bin.is_none() {
|
||||
let (program, args) = windows_command(&spec.program, spec.args, &std::env::var("PATH").unwrap_or_default());
|
||||
spec.program = program;
|
||||
spec.args = args;
|
||||
}
|
||||
spec
|
||||
}
|
||||
|
||||
fn launch_spec_with(
|
||||
kind: AgentKind,
|
||||
folder: &Path,
|
||||
model: Option<&str>,
|
||||
effort: Option<&str>,
|
||||
mode: PermissionMode,
|
||||
prompt: &str,
|
||||
bin_override: Option<&str>,
|
||||
) -> LaunchSpec {
|
||||
let cwd = folder.to_path_buf();
|
||||
if let Some(bin) = bin_override {
|
||||
return LaunchSpec { program: bin.to_string(), args: vec![], env: vec![], cwd };
|
||||
}
|
||||
|
||||
let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
let model_args = |args: &mut Vec<String>| {
|
||||
if let Some(model) = model {
|
||||
args.push("--model".to_string());
|
||||
args.push(model.to_string());
|
||||
}
|
||||
};
|
||||
let bypass = mode == PermissionMode::Bypass;
|
||||
let mut args = Vec::new();
|
||||
let program = match kind {
|
||||
AgentKind::Claude => {
|
||||
if !prompt.is_empty() {
|
||||
args.push(prompt.to_string());
|
||||
}
|
||||
if bypass {
|
||||
args.extend(strings(&["--permission-mode", "bypassPermissions"]));
|
||||
}
|
||||
model_args(&mut args);
|
||||
if let Some(effort) = effort {
|
||||
args.push("--effort".to_string());
|
||||
args.push(effort.to_string());
|
||||
}
|
||||
"claude"
|
||||
}
|
||||
AgentKind::Devin => {
|
||||
if bypass {
|
||||
args.extend(strings(&["--permission-mode", "bypass"]));
|
||||
}
|
||||
model_args(&mut args);
|
||||
if !prompt.is_empty() {
|
||||
args.push("--".to_string());
|
||||
args.push(prompt.to_string());
|
||||
}
|
||||
"devin"
|
||||
}
|
||||
AgentKind::Codex => {
|
||||
if bypass {
|
||||
args.extend(strings(&["--dangerously-bypass-approvals-and-sandbox"]));
|
||||
}
|
||||
model_args(&mut args);
|
||||
if let Some(effort) = effort {
|
||||
args.push("-c".to_string());
|
||||
args.push(format!("model_reasoning_effort={effort}"));
|
||||
}
|
||||
if !prompt.is_empty() {
|
||||
args.push(prompt.to_string());
|
||||
}
|
||||
"codex"
|
||||
}
|
||||
};
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
// directories (Task 9.9): the agent CLI itself, and anything it shells
|
||||
// out to, needs a PATH that finds them anyway.
|
||||
let env = vec![("PATH".to_string(), crate::node_check::resolved_path().to_string())];
|
||||
LaunchSpec { program: program.to_string(), args, env, cwd }
|
||||
}
|
||||
|
||||
/// An agent installed with npm is, on Windows, a `.cmd` shim beside an
|
||||
/// extensionless script, and `CreateProcess` cannot run the script. Look the
|
||||
/// program up on `path_var` for an `.exe` (run as is), `.cmd` or `.bat` (run
|
||||
/// through `cmd /c`); a program found as none of them is left alone.
|
||||
pub fn windows_command(program: &str, args: Vec<String>, path_var: &str) -> (String, Vec<String>) {
|
||||
for dir in path_var.split(';').filter(|dir| !dir.is_empty()) {
|
||||
for ext in ["exe", "cmd", "bat"] {
|
||||
let candidate = Path::new(dir).join(format!("{program}.{ext}"));
|
||||
if !candidate.is_file() {
|
||||
continue;
|
||||
}
|
||||
if ext == "exe" {
|
||||
return (candidate.to_string_lossy().into_owned(), args);
|
||||
}
|
||||
// The bare file name, not the full path: a path with a space gets
|
||||
// quoted, and `cmd /c` mangles a command line that starts with a quote.
|
||||
// `cmd` finds the shim on PATH itself.
|
||||
let mut wrapped = vec!["/c".to_string(), format!("{program}.{ext}")];
|
||||
wrapped.extend(args);
|
||||
return ("cmd".to_string(), wrapped);
|
||||
}
|
||||
}
|
||||
(program.to_string(), args)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn folder() -> PathBuf {
|
||||
PathBuf::from("project")
|
||||
}
|
||||
|
||||
fn args(kind: AgentKind, model: Option<&str>, mode: PermissionMode, prompt: &str) -> Vec<String> {
|
||||
launch_spec_with(kind, &folder(), model, None, mode, prompt, None).args
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_puts_the_prompt_first() {
|
||||
let spec = launch_spec_with(AgentKind::Claude, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None);
|
||||
assert_eq!(spec.program, "claude");
|
||||
assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions"]);
|
||||
assert_eq!(spec.cwd, folder());
|
||||
// A PATH that can still find nvm, Homebrew or Volta's directories (Task 9.9).
|
||||
assert_eq!(spec.env.iter().filter(|(k, _)| k == "PATH").count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_with_a_model() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Claude, Some("sonnet"), PermissionMode::Bypass, "/plan2code"),
|
||||
["/plan2code", "--permission-mode", "bypassPermissions", "--model", "sonnet"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_checked_mode_skips_the_bypass_flag() {
|
||||
assert_eq!(args(AgentKind::Claude, None, PermissionMode::Checked, "/plan2code"), ["/plan2code"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_with_an_effort() {
|
||||
let spec =
|
||||
launch_spec_with(AgentKind::Claude, &folder(), None, Some("high"), PermissionMode::Bypass, "/plan2code", None);
|
||||
assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions", "--effort", "high"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_full_launch_card_choice_carries_model_effort_and_mode_together() {
|
||||
let spec = launch_spec_with(
|
||||
AgentKind::Claude,
|
||||
&folder(),
|
||||
Some("opus"),
|
||||
Some("xhigh"),
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["/plan2code", "--permission-mode", "bypassPermissions", "--model", "opus", "--effort", "xhigh"]
|
||||
);
|
||||
let checked = launch_spec_with(
|
||||
AgentKind::Codex,
|
||||
&folder(),
|
||||
Some("gpt-5"),
|
||||
Some("medium"),
|
||||
PermissionMode::Checked,
|
||||
"$plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(checked.args, ["--model", "gpt-5", "-c", "model_reasoning_effort=medium", "$plan2code"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_puts_the_prompt_after_a_double_dash() {
|
||||
let spec = launch_spec_with(AgentKind::Devin, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None);
|
||||
assert_eq!(spec.program, "devin");
|
||||
assert_eq!(spec.args, ["--permission-mode", "bypass", "--", "/plan2code"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_with_a_model_keeps_the_prompt_last() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Devin, Some("opus"), PermissionMode::Bypass, "/plan2code"),
|
||||
["--permission-mode", "bypass", "--model", "opus", "--", "/plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_checked_mode_skips_the_bypass_flag() {
|
||||
assert_eq!(args(AgentKind::Devin, None, PermissionMode::Checked, "/plan2code"), ["--", "/plan2code"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_uses_its_own_flag_and_dollar_prompt() {
|
||||
let prompt = AgentKind::Codex.default_prompt();
|
||||
let spec = launch_spec_with(AgentKind::Codex, &folder(), None, None, PermissionMode::Bypass, prompt, None);
|
||||
assert_eq!(spec.program, "codex");
|
||||
assert_eq!(spec.args, ["--dangerously-bypass-approvals-and-sandbox", "$plan2code"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_with_a_model() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Codex, Some("gpt-5"), PermissionMode::Bypass, "$plan2code"),
|
||||
["--dangerously-bypass-approvals-and-sandbox", "--model", "gpt-5", "$plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_with_an_effort_uses_a_config_override() {
|
||||
let spec =
|
||||
launch_spec_with(AgentKind::Codex, &folder(), None, Some("low"), PermissionMode::Bypass, "$plan2code", None);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["--dangerously-bypass-approvals-and-sandbox", "-c", "model_reasoning_effort=low", "$plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_checked_mode_skips_the_bypass_flag() {
|
||||
assert_eq!(args(AgentKind::Codex, None, PermissionMode::Checked, "$plan2code"), ["$plan2code"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_prompt_means_nothing_typed() {
|
||||
assert_eq!(args(AgentKind::Claude, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypassPermissions"]);
|
||||
assert_eq!(args(AgentKind::Devin, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypass"]);
|
||||
assert_eq!(args(AgentKind::Codex, None, PermissionMode::Bypass, ""), ["--dangerously-bypass-approvals-and-sandbox"]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_prompt_is_passed_through() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Claude, None, PermissionMode::Bypass, "/plan2code pick up the brief"),
|
||||
["/plan2code pick up the brief", "--permission-mode", "bypassPermissions"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_has_no_effort_of_its_own() {
|
||||
assert!(!AgentKind::Devin.has_effort());
|
||||
assert!(AgentKind::Claude.has_effort());
|
||||
assert!(AgentKind::Codex.has_effort());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permission_mode_ids_round_trip() {
|
||||
for mode in [PermissionMode::Checked, PermissionMode::Bypass] {
|
||||
assert_eq!(PermissionMode::from_id(mode.id()), Some(mode));
|
||||
}
|
||||
assert_eq!(PermissionMode::from_id("nope"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_override_replaces_the_program_for_every_kind() {
|
||||
for kind in AgentKind::ALL {
|
||||
let spec = launch_spec_with(
|
||||
kind,
|
||||
&folder(),
|
||||
Some("m"),
|
||||
Some("high"),
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
Some("fake-agent"),
|
||||
);
|
||||
assert_eq!(spec.program, "fake-agent");
|
||||
assert!(spec.args.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn find_on_path_sees_only_what_is_really_there() {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-findonpath-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let name = if cfg!(windows) { "tool.exe" } else { "tool" };
|
||||
std::fs::write(dir.join(name), "").unwrap();
|
||||
let path = dir.to_string_lossy().into_owned();
|
||||
assert_eq!(find_on_path("tool", &path), Some(dir.join(name)));
|
||||
assert_eq!(find_on_path("missing-tool", &path), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_cmd_shim_runs_through_cmd_and_the_extensionless_script_is_ignored() {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-shim-{}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("tool"), "#!/bin/sh").unwrap();
|
||||
std::fs::write(dir.join("tool.cmd"), "@echo off").unwrap();
|
||||
std::fs::write(dir.join("real.exe"), "").unwrap();
|
||||
let path = dir.to_string_lossy().into_owned();
|
||||
let args = vec!["--flag".to_string()];
|
||||
|
||||
let (program, wrapped) = windows_command("tool", args.clone(), &path);
|
||||
assert_eq!(program, "cmd");
|
||||
assert_eq!(wrapped, ["/c".to_string(), "tool.cmd".to_string(), "--flag".to_string()]);
|
||||
|
||||
let (program, same) = windows_command("real", args.clone(), &path);
|
||||
assert_eq!(program, dir.join("real.exe").to_string_lossy());
|
||||
assert_eq!(same, args);
|
||||
|
||||
assert_eq!(windows_command("missing", args.clone(), &path), ("missing".to_string(), args));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ids_round_trip() {
|
||||
for kind in AgentKind::ALL {
|
||||
assert_eq!(AgentKind::from_id(kind.id()), Some(kind));
|
||||
}
|
||||
assert_eq!(AgentKind::from_id("nope"), None);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
//! 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,
|
||||
}
|
||||
|
||||
pub type OnPage = Arc<dyn Fn(PageNotice) + 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 let Ok(mut slot) = shared.lock() {
|
||||
*slot = Some(notice.clone());
|
||||
}
|
||||
on_page(notice);
|
||||
(204, 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())
|
||||
}
|
||||
|
||||
/// 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).unwrap())).unwrap();
|
||||
let b = AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).unwrap())).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(|_| {})).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(|_| {})).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");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,461 @@
|
||||
//! 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,373 @@
|
||||
//! 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;
|
||||
|
||||
/// 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);
|
||||
|
||||
/// 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 {
|
||||
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, HEALTH_TIMEOUT) else {
|
||||
return false;
|
||||
};
|
||||
let _ = stream.set_read_timeout(Some(HEALTH_TIMEOUT));
|
||||
let _ = stream.set_write_timeout(Some(HEALTH_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() {
|
||||
return Ok(false);
|
||||
}
|
||||
// The same session first, so the page and a skill's place in it survive;
|
||||
// a session that cannot be resumed (gone from disk) starts a new one.
|
||||
let sid = self.session.sid.clone();
|
||||
self.session = Self::open_session(&self.console_dir, &self.project_dir, &self.embed_origin, Some(&sid))
|
||||
.or_else(|_| Self::open_session(&self.console_dir, &self.project_dir, &self.embed_origin, None))?;
|
||||
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(())
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
#[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,228 @@
|
||||
//! Claude's context, read from its own transcript: the last `assistant` message's
|
||||
//! token usage, as a fraction of its context window. Claude Code writes one file
|
||||
//! per session under `~/.claude/projects/<cwd, every non-alphanumeric character
|
||||
//! replaced with `-`>/<session id>.jsonl` (relocatable via `CLAUDE_CONFIG_DIR`),
|
||||
//! and names it after the session's own id, so a project folder's newest file
|
||||
//! since the agent started is this run's transcript (Task 10.1's spike; the
|
||||
//! same approach `codex.rs` uses for Codex's log). The entry format is
|
||||
//! undocumented ("internal and may change between versions" per Claude's own
|
||||
//! docs), so a usable reading is `BestEffort`, never `Real`. An unreadable line
|
||||
//! is skipped, and a transcript with no usable line, or no transcript at all,
|
||||
//! is `Unknown`.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{ContextReader, ContextReading};
|
||||
|
||||
/// How much of a transcript's end is read; the newest usage is near the end.
|
||||
pub const TAIL_BYTES: u64 = 256 * 1024;
|
||||
|
||||
pub struct ClaudeReader {
|
||||
pub projects_dir: PathBuf,
|
||||
pub folder: PathBuf,
|
||||
/// Only a transcript written at or after this moment belongs to the running agent.
|
||||
pub since: SystemTime,
|
||||
/// The context window to read the usage against (`super::window_for`).
|
||||
pub window: u64,
|
||||
}
|
||||
|
||||
impl ContextReader for ClaudeReader {
|
||||
fn read(&self) -> ContextReading {
|
||||
match newest_transcript(&self.projects_dir.join(encode(&self.folder)), self.since) {
|
||||
Some(file) => reading_from_file(&file, self.window),
|
||||
None => ContextReading::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `folder` with every non-alphanumeric character replaced by `-`, the way
|
||||
/// Claude Code names a project's transcripts directory.
|
||||
fn encode(folder: &Path) -> String {
|
||||
folder.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
|
||||
}
|
||||
|
||||
/// The newest `*.jsonl` file directly under `dir` that was written at or after `since`.
|
||||
fn newest_transcript(dir: &Path, since: SystemTime) -> Option<PathBuf> {
|
||||
let entries = fs::read_dir(dir).ok()?;
|
||||
let mut newest: Option<(SystemTime, PathBuf)> = None;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
|
||||
continue;
|
||||
}
|
||||
let Ok(modified) = entry.metadata().and_then(|m| m.modified()) else { continue };
|
||||
if modified < since {
|
||||
continue;
|
||||
}
|
||||
if newest.as_ref().is_none_or(|(best, _)| modified > *best) {
|
||||
newest = Some((modified, path));
|
||||
}
|
||||
}
|
||||
newest.map(|(_, path)| path)
|
||||
}
|
||||
|
||||
/// The percent of `window` the last usable `assistant` usage line in `text` used.
|
||||
pub fn reading_from_text(text: &str, window: u64) -> ContextReading {
|
||||
for line in text.lines().rev() {
|
||||
if let Some(percent) = percent_from_line(line, window) {
|
||||
return ContextReading::BestEffort { percent };
|
||||
}
|
||||
}
|
||||
ContextReading::Unknown
|
||||
}
|
||||
|
||||
fn percent_from_line(line: &str, window: u64) -> Option<u8> {
|
||||
if window == 0 {
|
||||
return None;
|
||||
}
|
||||
let value: Value = serde_json::from_str(line).ok()?;
|
||||
if value.get("type")?.as_str()? != "assistant" {
|
||||
return None;
|
||||
}
|
||||
let usage = value.get("message")?.get("usage")?;
|
||||
let input = usage.get("input_tokens")?.as_u64()?;
|
||||
let cache_read = usage.get("cache_read_input_tokens").and_then(Value::as_u64).unwrap_or(0);
|
||||
let cache_creation = usage.get("cache_creation_input_tokens").and_then(Value::as_u64).unwrap_or(0);
|
||||
let used = input.saturating_add(cache_read).saturating_add(cache_creation);
|
||||
Some((used.saturating_mul(100) / window).min(100) as u8)
|
||||
}
|
||||
|
||||
/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`.
|
||||
fn reading_from_file(file: &Path, window: u64) -> ContextReading {
|
||||
let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown };
|
||||
let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown };
|
||||
if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
if handle.read_to_end(&mut bytes).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
// The first line of a partial tail is cut short; it fails to parse and is skipped.
|
||||
reading_from_text(&String::from_utf8_lossy(&bytes), window)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
const GOOD: &str = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":724,"cache_read_input_tokens":205907}}}"#;
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-claude-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn epoch_plus(secs: u64) -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
fn write_transcript(dir: &Path, name: &str, body: &str, modified: SystemTime) -> PathBuf {
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
let file = dir.join(format!("{name}.jsonl"));
|
||||
fs::write(&file, body).unwrap();
|
||||
File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_assistant_usage_gives_the_percent_of_the_window() {
|
||||
assert_eq!(reading_from_text(GOOD, 206_633), ContextReading::BestEffort { percent: 100 });
|
||||
assert_eq!(reading_from_text(GOOD, 1_000_000), ContextReading::BestEffort { percent: 20 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_normal_transcript_is_read_from_the_newest_assistant_line() {
|
||||
let early = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":99998}}}"#;
|
||||
let text = format!("{early}\n{GOOD}");
|
||||
assert_eq!(reading_from_text(&text, 206_633), ContextReading::BestEffort { percent: 100 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_last_line_is_skipped_in_favour_of_the_line_before_it() {
|
||||
let text = format!("{GOOD}\n{{\"type\":\"assistant\",\"mess");
|
||||
assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_assistant_and_malformed_lines_are_skipped() {
|
||||
let text = format!("not json\n{{bad\n{{\"type\":\"user\",\"message\":{{}}}}\n{GOOD}");
|
||||
assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_with_no_usable_usage_is_unknown() {
|
||||
assert_eq!(reading_from_text("", 1_000_000), ContextReading::Unknown);
|
||||
assert_eq!(reading_from_text(r#"{"type":"assistant","message":{}}"#, 1_000_000), ContextReading::Unknown);
|
||||
assert_eq!(reading_from_text(GOOD, 0), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_unknown() {
|
||||
let reader = ClaudeReader {
|
||||
projects_dir: temp_dir("missing").join("projects"),
|
||||
folder: PathBuf::from(r"C:\git\project"),
|
||||
since: epoch_plus(0),
|
||||
window: 200_000,
|
||||
};
|
||||
assert_eq!(reader.read(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_transcript_is_read_from_its_end() {
|
||||
let dir = temp_dir("long");
|
||||
let file = write_transcript(&dir, "long", &format!("{}\n{GOOD}", "x".repeat(TAIL_BYTES as usize + 100)), epoch_plus(0));
|
||||
assert_eq!(reading_from_file(&file, 206_633), ContextReading::BestEffort { percent: 100 });
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_transcript_for_this_folder_is_read() {
|
||||
let root = temp_dir("newest");
|
||||
let projects = root.join("projects");
|
||||
let dir = projects.join(encode(Path::new(r"C:\git\project")));
|
||||
write_transcript(&dir, "a-old", GOOD, epoch_plus(100));
|
||||
let newest = write_transcript(&dir, "b-new", &GOOD.replace("205907", "500000"), epoch_plus(200));
|
||||
let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 };
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
|
||||
let _ = fs::remove_dir_all(root);
|
||||
let _ = newest;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_file_is_read_from_the_new_one() {
|
||||
let root = temp_dir("rotated");
|
||||
let projects = root.join("projects");
|
||||
let dir = projects.join(encode(Path::new(r"C:\git\project")));
|
||||
write_transcript(&dir, "first", GOOD, epoch_plus(100));
|
||||
let reader = ClaudeReader { projects_dir: projects.clone(), folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 };
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 20 });
|
||||
write_transcript(&dir, "second", &GOOD.replace("205907", "500000"), epoch_plus(200));
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transcript_from_before_the_agent_started_is_ignored() {
|
||||
let root = temp_dir("since");
|
||||
let projects = root.join("projects");
|
||||
let dir = projects.join(encode(Path::new(r"C:\git\project")));
|
||||
write_transcript(&dir, "old", GOOD, epoch_plus(100));
|
||||
let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(200), window: 1_000_000 };
|
||||
assert_eq!(reader.read(), ContextReading::Unknown);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cwd_is_encoded_the_way_claude_code_names_its_projects_folder() {
|
||||
assert_eq!(encode(Path::new(r"C:\git\plan2code")), "C--git-plan2code");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! Codex's context, read from its session log. Codex writes each run to
|
||||
//! `sessions/YYYY/MM/DD/rollout-*.jsonl` under its home folder (`CODEX_HOME`,
|
||||
//! or `~/.codex`). The app reads the newest log for its project folder, from
|
||||
//! its end, and never writes there. The format is undocumented, so the reading
|
||||
//! is `BestEffort`: an unrecognised line is skipped, and a log with no usable
|
||||
//! line, or no log at all, is `Unknown`. Nothing here is an error.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{ContextReader, ContextReading};
|
||||
|
||||
/// How much of a log's end is read. The newest token count is near the end,
|
||||
/// so a long log is never read whole.
|
||||
pub const TAIL_BYTES: u64 = 256 * 1024;
|
||||
|
||||
/// How deep the sessions folder is searched: year, month, day, file.
|
||||
const SEARCH_DEPTH: u32 = 4;
|
||||
|
||||
pub struct CodexReader {
|
||||
pub sessions_dir: PathBuf,
|
||||
pub folder: PathBuf,
|
||||
/// Only logs written at or after this moment belong to the running agent.
|
||||
pub since: SystemTime,
|
||||
}
|
||||
|
||||
impl ContextReader for CodexReader {
|
||||
fn read(&self) -> ContextReading {
|
||||
match newest_log(&self.sessions_dir, &self.folder, self.since) {
|
||||
Some(file) => reading_from_file(&file),
|
||||
None => ContextReading::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The percent of the model's window the newest request used, from the last
|
||||
/// usable `token_count` line in `text`.
|
||||
pub fn reading_from_text(text: &str) -> ContextReading {
|
||||
for line in text.lines().rev() {
|
||||
if let Some(percent) = percent_from_line(line) {
|
||||
return ContextReading::BestEffort { percent };
|
||||
}
|
||||
}
|
||||
ContextReading::Unknown
|
||||
}
|
||||
|
||||
fn percent_from_line(line: &str) -> Option<u8> {
|
||||
let value: Value = serde_json::from_str(line).ok()?;
|
||||
if value.get("type")?.as_str()? != "event_msg" {
|
||||
return None;
|
||||
}
|
||||
let payload = value.get("payload")?;
|
||||
if payload.get("type")?.as_str()? != "token_count" {
|
||||
return None;
|
||||
}
|
||||
let info = payload.get("info")?;
|
||||
let used = info.get("last_token_usage")?.get("input_tokens")?.as_u64()?;
|
||||
let window = info.get("model_context_window")?.as_u64()?;
|
||||
if window == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((used.saturating_mul(100) / window).min(100) as u8)
|
||||
}
|
||||
|
||||
/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`.
|
||||
fn reading_from_file(file: &Path) -> ContextReading {
|
||||
let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown };
|
||||
let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown };
|
||||
if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
if handle.read_to_end(&mut bytes).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
// The first line of a partial tail is cut short; it fails to parse and is skipped.
|
||||
reading_from_text(&String::from_utf8_lossy(&bytes))
|
||||
}
|
||||
|
||||
/// The newest log under `sessions_dir` that was written since `since` and
|
||||
/// whose first line names `folder` as its working directory.
|
||||
pub fn newest_log(sessions_dir: &Path, folder: &Path, since: SystemTime) -> Option<PathBuf> {
|
||||
let mut logs = Vec::new();
|
||||
collect_logs(sessions_dir, SEARCH_DEPTH, since, &mut logs);
|
||||
let mut recent: Vec<(SystemTime, PathBuf)> = logs
|
||||
.into_iter()
|
||||
.filter_map(|file| {
|
||||
let modified = fs::metadata(&file).ok()?.modified().ok()?;
|
||||
(modified >= since).then_some((modified, file))
|
||||
})
|
||||
.collect();
|
||||
recent.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
recent.into_iter().map(|(_, file)| file).find(|file| names_folder(file, folder))
|
||||
}
|
||||
|
||||
// A day folder not touched since `since` holds no log of this run (creating a
|
||||
// log updates its own folder, and only that one), so it is skipped: the walk
|
||||
// stays short however many old logs Codex has kept. Year and month folders are
|
||||
// always entered, as their own times say nothing about the logs below them.
|
||||
// `depth` is 2 while the entries of a month folder are listed.
|
||||
fn collect_logs(dir: &Path, depth: u32, since: SystemTime, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
let touched = fs::metadata(&path).and_then(|m| m.modified()).is_ok_and(|m| m >= since);
|
||||
if depth > 0 && (depth != 2 || touched) {
|
||||
collect_logs(&path, depth - 1, since, out);
|
||||
}
|
||||
} else if is_rollout(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_rollout(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl"))
|
||||
}
|
||||
|
||||
/// True when the log's first line is a `session_meta` for `folder`.
|
||||
fn names_folder(file: &Path, folder: &Path) -> bool {
|
||||
let Ok(handle) = File::open(file) else { return false };
|
||||
let mut first = String::new();
|
||||
if BufReader::new(handle).read_line(&mut first).is_err() {
|
||||
return false;
|
||||
}
|
||||
let Ok(value) = serde_json::from_str::<Value>(&first) else { return false };
|
||||
if value.get("type").and_then(Value::as_str) != Some("session_meta") {
|
||||
return false;
|
||||
}
|
||||
value
|
||||
.get("payload")
|
||||
.and_then(|payload| payload.get("cwd"))
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|cwd| same_folder(cwd, folder))
|
||||
}
|
||||
|
||||
/// Compares two folder paths the way Windows does: case, slash style and a
|
||||
/// trailing separator do not count.
|
||||
fn same_folder(cwd: &str, folder: &Path) -> bool {
|
||||
let norm = |s: &str| {
|
||||
s.trim_start_matches(r"\\?\").trim_end_matches(['\\', '/']).replace('/', "\\").to_ascii_lowercase()
|
||||
};
|
||||
norm(cwd) == norm(&folder.to_string_lossy())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
const GOOD: &str = r#"{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":21839},"model_context_window":258400}}}"#;
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-codex-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
// A log whose first line names `cwd`, then `body` lines, dated `modified`.
|
||||
fn write_log(sessions: &Path, name: &str, cwd: &str, body: &str, modified: SystemTime) -> PathBuf {
|
||||
let day = sessions.join("2026").join("10").join("22");
|
||||
fs::create_dir_all(&day).unwrap();
|
||||
let file = day.join(format!("rollout-{name}.jsonl"));
|
||||
let meta = serde_json::json!({ "type": "session_meta", "payload": { "cwd": cwd } });
|
||||
fs::write(&file, format!("{meta}\n{body}")).unwrap();
|
||||
// `meta` is a JSON value, so its text is escaped for the log.
|
||||
fs::File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
fn epoch_plus(secs: u64) -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_token_count_gives_the_percent_of_the_window() {
|
||||
assert_eq!(reading_from_text(GOOD), ContextReading::BestEffort { percent: 8 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrecognised_and_malformed_lines_are_skipped() {
|
||||
let text = format!("not json\n{{bad\n{GOOD}\n{}", r#"{"type":"event_msg","payload":{"type":"other"}}"#);
|
||||
assert_eq!(reading_from_text(&text), ContextReading::BestEffort { percent: 8 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_with_no_usable_line_is_unknown() {
|
||||
assert_eq!(reading_from_text(""), ContextReading::Unknown);
|
||||
assert_eq!(reading_from_text("garbage\n{}"), ContextReading::Unknown);
|
||||
let zero_window = GOOD.replace("258400", "0");
|
||||
assert_eq!(reading_from_text(&zero_window), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_early_token_count_without_info_is_skipped() {
|
||||
let early = r#"{"type":"event_msg","payload":{"type":"token_count","info":null}}"#;
|
||||
assert_eq!(reading_from_text(&format!("{GOOD}\n{early}")), ContextReading::BestEffort { percent: 8 });
|
||||
assert_eq!(reading_from_text(early), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_session_meta_with_this_folder_names_it() {
|
||||
let root = temp_dir("names");
|
||||
let folder = Path::new(r"C:\git\project");
|
||||
let verbatim = serde_json::json!({ "type": "session_meta", "payload": { "cwd": r"\\?\C:\git\project" } });
|
||||
let cases = [
|
||||
("not json".to_string(), false),
|
||||
(r#"{"type":"other","payload":{"cwd":"x"}}"#.to_string(), false),
|
||||
(r#"{"type":"session_meta","payload":{}}"#.to_string(), false),
|
||||
(verbatim.to_string(), true),
|
||||
];
|
||||
for (i, (line, expected)) in cases.iter().enumerate() {
|
||||
let file = root.join(format!("rollout-{i}.jsonl"));
|
||||
fs::write(&file, format!("{line}\n{GOOD}\n")).unwrap();
|
||||
assert_eq!(names_folder(&file, folder), *expected, "{line}");
|
||||
}
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_log_is_read_from_its_end() {
|
||||
let dir = temp_dir("long");
|
||||
let file = dir.join("long.jsonl");
|
||||
fs::write(&file, format!("{}\n{GOOD}\n", "x".repeat(TAIL_BYTES as usize + 100))).unwrap();
|
||||
assert_eq!(reading_from_file(&file), ContextReading::BestEffort { percent: 8 });
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_log_is_unknown() {
|
||||
assert_eq!(reading_from_file(Path::new("no-such-dir/rollout-x.jsonl")), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_sessions_folder_is_unknown() {
|
||||
let reader = CodexReader {
|
||||
sessions_dir: temp_dir("none").join("sessions"),
|
||||
folder: PathBuf::from(r"C:\git\project"),
|
||||
since: epoch_plus(0),
|
||||
};
|
||||
assert_eq!(reader.read(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_log_for_this_folder_is_read() {
|
||||
let root = temp_dir("newest");
|
||||
let sessions = root.join("sessions");
|
||||
write_log(&sessions, "a-old", r"C:\git\project", GOOD, epoch_plus(100));
|
||||
write_log(&sessions, "b-other", r"C:\git\elsewhere", GOOD, epoch_plus(300));
|
||||
let newest = write_log(&sessions, "c-new", r"c:\git\project\", &GOOD.replace("21839", "129200"), epoch_plus(200));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(0)), Some(newest));
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
// Sets a folder's modified time; Windows needs the backup-semantics flag to open one.
|
||||
fn set_dir_modified(dir: &Path, time: SystemTime) {
|
||||
let mut options = fs::OpenOptions::new();
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
options.write(true).custom_flags(0x0200_0000);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
options.read(true);
|
||||
options.open(dir).unwrap().set_modified(time).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_year_and_month_folders_do_not_hide_todays_log() {
|
||||
let root = temp_dir("parents");
|
||||
let sessions = root.join("sessions");
|
||||
let log = write_log(&sessions, "today", r"C:\git\project", GOOD, epoch_plus(500));
|
||||
// Creating a log touches only its day folder: the parents keep their old times.
|
||||
set_dir_modified(&sessions.join("2026"), epoch_plus(10));
|
||||
set_dir_modified(&sessions.join("2026").join("10"), epoch_plus(20));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), Some(log));
|
||||
// A day folder untouched since the agent started is skipped.
|
||||
set_dir_modified(&sessions.join("2026").join("10").join("22"), epoch_plus(30));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), None);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_from_before_the_agent_started_is_ignored() {
|
||||
let root = temp_dir("since");
|
||||
let sessions = root.join("sessions");
|
||||
write_log(&sessions, "old", r"C:\git\project", GOOD, epoch_plus(100));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(200)), None);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_log_is_read_from_the_new_file() {
|
||||
let root = temp_dir("rotated");
|
||||
let sessions = root.join("sessions");
|
||||
write_log(&sessions, "first", r"C:\git\project", GOOD, epoch_plus(100));
|
||||
let reader = CodexReader {
|
||||
sessions_dir: sessions.clone(),
|
||||
folder: PathBuf::from(r"C:\git\project"),
|
||||
since: epoch_plus(0),
|
||||
};
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 8 });
|
||||
write_log(&sessions, "second", r"C:\git\project", &GOOD.replace("21839", "129200"), epoch_plus(200));
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,313 @@
|
||||
//! How full the agent's context is. A reader says one of four things: a real
|
||||
//! number (`Real`, documented by the agent and verified), a best-effort number
|
||||
//! (`BestEffort`, works today but undocumented), a labeled estimate (`Estimate`)
|
||||
//! or `Unknown`. Knows nothing about Tauri: the page asks for a reading and
|
||||
//! draws what it gets.
|
||||
|
||||
pub mod claude;
|
||||
pub mod codex;
|
||||
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
/// A rough token window used only by the estimate, and by `claude.rs` when no
|
||||
/// window comes with the signal it reads. The estimate is labeled as one
|
||||
/// everywhere it is shown, so the exact size does not have to be right.
|
||||
pub const ESTIMATE_TOKEN_WINDOW: u64 = 200_000;
|
||||
|
||||
/// The window for a model whose id names it a long-context one (Claude Code's
|
||||
/// `[1m]` model id suffix).
|
||||
pub const LONG_CONTEXT_TOKEN_WINDOW: u64 = 1_000_000;
|
||||
|
||||
/// The usual rule of thumb: about four characters of text per token.
|
||||
pub const BYTES_PER_TOKEN: u64 = 4;
|
||||
|
||||
/// The context window to read `kind`'s usage against, or `None` when no
|
||||
/// window is documented for it at all (Devin today), in which case a byte
|
||||
/// count is not even a meaningful guess. `model` is the id the person picked,
|
||||
/// if any; one naming a long-context model (Claude Code's `[1m]` suffix) gets
|
||||
/// the bigger window.
|
||||
pub fn window_for(kind: Option<AgentKind>, model: Option<&str>) -> Option<u64> {
|
||||
match kind {
|
||||
Some(AgentKind::Claude) | Some(AgentKind::Codex) => {
|
||||
let long_context = model.is_some_and(|m| m.to_ascii_lowercase().contains("[1m]"));
|
||||
Some(if long_context { LONG_CONTEXT_TOKEN_WINDOW } else { ESTIMATE_TOKEN_WINDOW })
|
||||
}
|
||||
Some(AgentKind::Devin) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum ContextReading {
|
||||
Real { percent: u8 },
|
||||
BestEffort { percent: u8 },
|
||||
Estimate { percent: u8 },
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// One agent's way of reading its context. The estimate is the fallback every
|
||||
/// agent has; a reader for an agent that documents its usage returns `Real`.
|
||||
pub trait ContextReader {
|
||||
fn read(&self) -> ContextReading;
|
||||
}
|
||||
|
||||
/// The percent of `window` that `bytes` of text fills, capped at 100 and
|
||||
/// rounded up: any text at all reads as at least 1 percent, never a flat 0
|
||||
/// while the agent is working.
|
||||
pub fn estimate_percent(bytes: u64, window: u64) -> u8 {
|
||||
let tokens = bytes / BYTES_PER_TOKEN;
|
||||
if tokens == 0 || window == 0 {
|
||||
return 0;
|
||||
}
|
||||
tokens.saturating_mul(100).div_ceil(window).min(100) as u8
|
||||
}
|
||||
|
||||
/// Where the output scan is inside a terminal control sequence.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum Escape {
|
||||
#[default]
|
||||
None,
|
||||
Esc,
|
||||
Intermediate,
|
||||
Csi,
|
||||
Osc,
|
||||
OscEnd,
|
||||
}
|
||||
|
||||
/// Counts the text an agent run has produced and been given. A new agent
|
||||
/// (a new `generation`) starts the count over, and nothing is counted while
|
||||
/// no agent runs.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Meter {
|
||||
generation: u64,
|
||||
seen: bool,
|
||||
running: bool,
|
||||
bytes: u64,
|
||||
escape: Escape,
|
||||
kind: Option<AgentKind>,
|
||||
// When the current agent run began: its own log must be written after this.
|
||||
since: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl Meter {
|
||||
/// Called on every agent state change: a new generation resets the count.
|
||||
pub fn observe(&mut self, generation: u64, running: bool) {
|
||||
if !self.seen || generation != self.generation {
|
||||
self.generation = generation;
|
||||
self.seen = true;
|
||||
self.bytes = 0;
|
||||
self.escape = Escape::None;
|
||||
self.since = Some(SystemTime::now());
|
||||
}
|
||||
self.running = running;
|
||||
}
|
||||
|
||||
pub fn set_kind(&mut self, kind: Option<AgentKind>) {
|
||||
self.kind = kind;
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> Option<AgentKind> {
|
||||
self.kind
|
||||
}
|
||||
|
||||
pub fn since(&self) -> Option<SystemTime> {
|
||||
self.since
|
||||
}
|
||||
|
||||
/// Output from the agent, or text typed to it, while it runs.
|
||||
/// Output from the agent. Terminal control sequences (colours, cursor
|
||||
/// moves, window titles) are not text the agent holds, so only the visible
|
||||
/// bytes count. A sequence cut across two chunks is still skipped whole.
|
||||
pub fn add_output(&mut self, chunk: &[u8]) {
|
||||
let mut visible = 0usize;
|
||||
for &byte in chunk {
|
||||
self.escape = match self.escape {
|
||||
Escape::None => match byte {
|
||||
0x1b => Escape::Esc,
|
||||
b'\n' | b'\t' => {
|
||||
visible += 1;
|
||||
Escape::None
|
||||
}
|
||||
0x20..=0x7e | 0x80..=0xff => {
|
||||
visible += 1;
|
||||
Escape::None
|
||||
}
|
||||
_ => Escape::None,
|
||||
},
|
||||
Escape::Esc => match byte {
|
||||
b'[' => Escape::Csi,
|
||||
// OSC, and the other strings that end the same way: DCS, SOS, PM, APC.
|
||||
b']' | b'P' | b'X' | b'^' | b'_' => Escape::Osc,
|
||||
// `ESC ( B` and the like: intermediate bytes, then one final byte.
|
||||
0x20..=0x2f => Escape::Intermediate,
|
||||
_ => Escape::None,
|
||||
},
|
||||
Escape::Intermediate => match byte {
|
||||
0x20..=0x2f => Escape::Intermediate,
|
||||
_ => Escape::None,
|
||||
},
|
||||
Escape::Csi => match byte {
|
||||
0x40..=0x7e => Escape::None,
|
||||
_ => Escape::Csi,
|
||||
},
|
||||
Escape::Osc => match byte {
|
||||
0x07 => Escape::None,
|
||||
0x1b => Escape::OscEnd,
|
||||
_ => Escape::Osc,
|
||||
},
|
||||
Escape::OscEnd => Escape::None,
|
||||
};
|
||||
}
|
||||
self.add(visible);
|
||||
}
|
||||
|
||||
/// Text typed to the agent, or any count of visible bytes.
|
||||
pub fn add(&mut self, bytes: usize) {
|
||||
if self.running {
|
||||
self.bytes = self.bytes.saturating_add(bytes as u64);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reading(&self) -> ContextReading {
|
||||
if !self.seen || !self.running {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
match window_for(self.kind, None) {
|
||||
Some(window) => ContextReading::Estimate { percent: estimate_percent(self.bytes, window) },
|
||||
None => ContextReading::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextReader for Meter {
|
||||
fn read(&self) -> ContextReading {
|
||||
self.reading()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_text_is_zero_percent() {
|
||||
assert_eq!(estimate_percent(0, ESTIMATE_TOKEN_WINDOW), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_the_window_is_fifty_percent() {
|
||||
assert_eq!(estimate_percent(ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 2, ESTIMATE_TOKEN_WINDOW), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_the_window_caps_at_one_hundred() {
|
||||
assert_eq!(estimate_percent(u64::MAX / 2, ESTIMATE_TOKEN_WINDOW), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_text_at_all_rounds_up_instead_of_reading_zero() {
|
||||
assert_eq!(estimate_percent(BYTES_PER_TOKEN, ESTIMATE_TOKEN_WINDOW), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_context_model_gets_the_bigger_window() {
|
||||
assert_eq!(window_for(Some(AgentKind::Claude), Some("claude-sonnet-4-5-20250929[1m]")), Some(LONG_CONTEXT_TOKEN_WINDOW));
|
||||
assert_eq!(window_for(Some(AgentKind::Claude), Some("sonnet")), Some(ESTIMATE_TOKEN_WINDOW));
|
||||
assert_eq!(window_for(Some(AgentKind::Claude), None), Some(ESTIMATE_TOKEN_WINDOW));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_and_an_unknown_agent_have_no_basis_for_a_window() {
|
||||
assert_eq!(window_for(Some(AgentKind::Devin), None), None);
|
||||
assert_eq!(window_for(None, None), None);
|
||||
}
|
||||
|
||||
fn counted(chunks: &[&[u8]]) -> u64 {
|
||||
let mut meter = Meter::default();
|
||||
meter.observe(1, true);
|
||||
for chunk in chunks {
|
||||
meter.add_output(chunk);
|
||||
}
|
||||
meter.bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_counts_and_control_sequences_do_not() {
|
||||
assert_eq!(counted(&[b"hello\n"]), 6);
|
||||
assert_eq!(counted(&[b"\x1b[31mred\x1b[0m"]), 3);
|
||||
assert_eq!(counted(&[b"\x1b[2K\x1b[1A\x1b[Gx"]), 1);
|
||||
assert_eq!(counted(&[b"\x1b]0;a title\x07ok"]), 2);
|
||||
assert_eq!(counted(&[b"\x1b]0;a title\x1b\\ok"]), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn charset_and_string_sequences_are_skipped() {
|
||||
assert_eq!(counted(&[b"\x1b(Bok"]), 2);
|
||||
assert_eq!(counted(&[b"\x1bPq#0;2;0;0;0\x1b\\ok"]), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sequence_split_across_chunks_is_still_skipped() {
|
||||
assert_eq!(counted(&[b"ab\x1b[3", b"1mcd"]), 4);
|
||||
assert_eq!(counted(&[b"\x1b", b"[0m", b"z"]), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_running_is_unknown() {
|
||||
let mut meter = Meter::default();
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
meter.observe(1, false);
|
||||
meter.add(10_000);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_agent_is_an_estimate_of_what_it_has_seen() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Claude));
|
||||
meter.observe(1, true);
|
||||
meter.add((ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 4) as usize);
|
||||
assert_eq!(meter.reading(), ContextReading::Estimate { percent: 25 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_agent_starts_the_count_over() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Claude));
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
meter.observe(2, true);
|
||||
assert_eq!(meter.reading(), ContextReading::Estimate { percent: 0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_agent_is_unknown_again() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Claude));
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
meter.observe(1, false);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_with_no_documented_window_is_unknown_not_a_guess() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Devin));
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_kind_set_yet_is_unknown_not_a_guess() {
|
||||
let mut meter = Meter::default();
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,224 @@
|
||||
//! 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 brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod context;
|
||||
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,746 @@
|
||||
// Hide the extra console window on Windows release builds.
|
||||
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use plan2code_app_lib::announce::AnnounceServer;
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, Sink};
|
||||
use plan2code_app_lib::agents::{self, AgentKind, PermissionMode};
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, ConsoleSupervisor};
|
||||
use plan2code_app_lib::context::claude::ClaudeReader;
|
||||
use plan2code_app_lib::context::codex::CodexReader;
|
||||
use plan2code_app_lib::context::{self, ContextReader, ContextReading, Meter};
|
||||
use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::restart_brief;
|
||||
use plan2code_app_lib::settings;
|
||||
use plan2code_app_lib::versions;
|
||||
use tauri::ipc::{Channel, InvokeResponseBody};
|
||||
use tauri::{Emitter, Manager, State};
|
||||
use tauri_plugin_dialog::{DialogExt, MessageDialogButtons, MessageDialogKind};
|
||||
|
||||
type PageChannel = Arc<Mutex<Option<Channel<InvokeResponseBody>>>>;
|
||||
|
||||
// The project the app is working on, the console it supervises for it and the
|
||||
// agent it runs there.
|
||||
#[derive(Default)]
|
||||
struct AppState {
|
||||
project: Mutex<Option<ProjectDir>>,
|
||||
// The agent and model the launcher chose, from its arguments.
|
||||
launch: project::LaunchChoice,
|
||||
console: Arc<Mutex<Option<ConsoleSupervisor>>>,
|
||||
agent: Mutex<Option<Arc<AgentManager>>>,
|
||||
// Where the agent's output and state changes go: the page's latest channel.
|
||||
page: PageChannel,
|
||||
// How much text the running agent has produced and been given, for the meter.
|
||||
context: Arc<Mutex<Meter>>,
|
||||
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
|
||||
announce: Mutex<Option<AnnounceServer>>,
|
||||
// The Node version `main()` found before opening the window (Task 1.7 exits
|
||||
// cleanly on anything else, so this is always a passing version once the
|
||||
// window exists), and which binary that was, with `resolved_path`'s PATH
|
||||
// (Task 9.9): the first-run checklist's Node row names both.
|
||||
node_version: Option<String>,
|
||||
node_binary: Option<String>,
|
||||
}
|
||||
|
||||
// The operating system and, on Windows, the build number xterm needs for ConPTY.
|
||||
#[tauri::command]
|
||||
fn platform_info() -> serde_json::Value {
|
||||
let build = if cfg!(windows) { windows_build() } else { None };
|
||||
serde_json::json!({ "os": std::env::consts::OS, "windowsBuild": build })
|
||||
}
|
||||
|
||||
// What the launch card offers per agent: whether its CLI is on PATH (else how
|
||||
// to install it), and whether it takes its own reasoning effort.
|
||||
#[tauri::command]
|
||||
fn agent_availability() -> serde_json::Value {
|
||||
let entries: Vec<_> = AgentKind::ALL
|
||||
.iter()
|
||||
.map(|&kind| {
|
||||
let at = agents::installed_at(kind);
|
||||
serde_json::json!({
|
||||
"id": kind.id(),
|
||||
"label": kind.label(),
|
||||
"installed": at.is_some(),
|
||||
// Which binary was used (Task 9.9), when one was found.
|
||||
"path": at.map(|p| p.to_string_lossy().into_owned()),
|
||||
"installHint": kind.install_hint(),
|
||||
"hasEffort": kind.has_effort(),
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
serde_json::json!(entries)
|
||||
}
|
||||
|
||||
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
|
||||
fn windows_build() -> Option<u32> {
|
||||
let out = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let version = text.split("Version ").nth(1)?;
|
||||
version.split('.').nth(2)?.trim().parse().ok()
|
||||
}
|
||||
|
||||
// Sends the agent's output as raw bytes and its state changes as JSON, on the
|
||||
// page's latest channel. Nothing is sent while no page has registered one.
|
||||
// The meter sees every output and state change too, page or no page.
|
||||
fn page_sink(page: PageChannel, meter: Arc<Mutex<Meter>>) -> Sink {
|
||||
Arc::new(move |event| {
|
||||
if let Ok(mut meter) = meter.lock() {
|
||||
match &event {
|
||||
AgentEvent::Output(bytes) => meter.add_output(bytes),
|
||||
AgentEvent::State(snapshot) => {
|
||||
let running = snapshot.state == AgentState::Running;
|
||||
meter.observe(snapshot.generation, running);
|
||||
meter.set_kind(snapshot.kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Ok(guard) = page.lock() else { return };
|
||||
let Some(channel) = guard.as_ref() else { return };
|
||||
let body = match event {
|
||||
AgentEvent::Output(bytes) => InvokeResponseBody::Raw(bytes),
|
||||
AgentEvent::State(snapshot) => match serde_json::to_string(&snapshot) {
|
||||
Ok(json) => InvokeResponseBody::Json(json),
|
||||
Err(_) => return,
|
||||
},
|
||||
};
|
||||
let _ = channel.send(body);
|
||||
})
|
||||
}
|
||||
|
||||
// The manager for the current project, made on first use. A manager for a
|
||||
// different folder replaces an idle one.
|
||||
fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||
let dir = {
|
||||
let project = state.project.lock().map_err(|e| e.to_string())?;
|
||||
project.as_ref().map(|p| p.dir.clone()).ok_or("no project folder chosen")?
|
||||
};
|
||||
let mut guard = state.agent.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(agent) = guard.as_ref() {
|
||||
// Only the same folder's manager is reused: an active agent for a
|
||||
// folder the project has since moved away from must not be handed
|
||||
// back as if it belonged to the new one.
|
||||
if agent.folder() == &dir {
|
||||
return Ok(Arc::clone(agent));
|
||||
}
|
||||
}
|
||||
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.context));
|
||||
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||
// A Restart leaves the brief for the dashboard, from the console that is running now.
|
||||
let console = Arc::clone(&state.console);
|
||||
agent.set_before_fresh(Arc::new(move || {
|
||||
let sid = console.lock().ok()?.as_ref()?.session().sid.clone();
|
||||
restart_brief::note_for_restart(&sid)
|
||||
}));
|
||||
*guard = Some(Arc::clone(&agent));
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
||||
state.agent.lock().ok().and_then(|guard| guard.clone())
|
||||
}
|
||||
|
||||
// The origin the app page has, which the console must allow as its frame
|
||||
// parent. In a release build that is a constant, but `tauri dev` serves the
|
||||
// page from a loopback dev server, so the window is asked for its real URL.
|
||||
fn window_origin(app: &tauri::AppHandle) -> String {
|
||||
app.get_webview_window("main")
|
||||
.and_then(|window| window.url().ok())
|
||||
.and_then(|url| origin_of(url.as_str()))
|
||||
.unwrap_or_else(|| app_origin().to_string())
|
||||
}
|
||||
|
||||
// Gives the agent the in-app signal: this window's announce endpoint and the
|
||||
// origin its console must allow. The agent's own `open` then shows its pages
|
||||
// here (it asks the window which session is current). Without an endpoint the
|
||||
// agent gets nothing and opens pages the plain way.
|
||||
fn sync_agent_env(app: &tauri::AppHandle) {
|
||||
let state = app.state::<AppState>();
|
||||
let Some(agent) = current_agent(&state) else { return };
|
||||
let env = match state.announce.lock().ok() {
|
||||
Some(guard) => guard
|
||||
.as_ref()
|
||||
.map(|server| server.agent_env(&window_origin(app), &app.package_info().version.to_string()))
|
||||
.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
agent.set_env(env);
|
||||
}
|
||||
|
||||
// `on_output` is deliberately not a parameter here: `agent_reattach` already
|
||||
// registered `state.page` when the page mounted (`main()` on the frontend
|
||||
// calls it before this), and that registration must stay the only one. Every
|
||||
// Channel argument Tauri deserializes for an invoke is a fresh wrapper around
|
||||
// the same frontend id; dropping one (as happened here when it replaced the
|
||||
// reattach registration) sends the frontend an "end" message that
|
||||
// unregisters that id for good, breaking all future sends through it.
|
||||
#[tauri::command]
|
||||
fn agent_start(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
kind: String,
|
||||
model: Option<String>,
|
||||
effort: Option<String>,
|
||||
mode: String,
|
||||
cols: u16,
|
||||
rows: u16,
|
||||
) -> Result<(), String> {
|
||||
let kind = AgentKind::from_id(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
|
||||
let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
|
||||
let agent = agent_for_project(&state)?;
|
||||
agent.resize(cols, rows)?;
|
||||
sync_agent_env(&app);
|
||||
agent.start(kind, model, effort, mode, None)?;
|
||||
// A settings file that cannot be written must not stop the agent.
|
||||
if let Some(file) = settings::settings_file() {
|
||||
let _ = settings::save_last_agent(&file, kind);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_input(state: State<'_, AppState>, data: String) -> Result<(), String> {
|
||||
if let Ok(mut meter) = state.context.lock() {
|
||||
meter.add(data.len());
|
||||
}
|
||||
match current_agent(&state) {
|
||||
Some(agent) => agent.input(data.as_bytes()),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(), String> {
|
||||
match current_agent(&state) {
|
||||
Some(agent) => agent.resize(cols, rows),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
|
||||
current_agent(&state).ok_or("no agent has been started")?.restart()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
match current_agent(&state) {
|
||||
Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(),
|
||||
None => idle_snapshot_json(),
|
||||
}
|
||||
}
|
||||
|
||||
fn idle_snapshot_json() -> serde_json::Value {
|
||||
serde_json::json!({ "state": "idle", "kind": null, "mode": null, "generation": 0 })
|
||||
}
|
||||
|
||||
/// A page that just mounted (a reload, or this window's first paint while an
|
||||
/// agent survived it) registers its output channel here instead of through
|
||||
/// `agent_start`, which would try to start a second agent. Replays the
|
||||
/// current generation's recent output on it at once, so the terminal does
|
||||
/// not come up blank, and returns the same shape `agent_state` does.
|
||||
#[tauri::command]
|
||||
fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseBody>) -> Result<serde_json::Value, String> {
|
||||
let agent = current_agent(&state);
|
||||
*state.page.lock().map_err(|e| e.to_string())? = Some(on_output.clone());
|
||||
if let Some(agent) = &agent {
|
||||
let replay = agent.replay();
|
||||
if !replay.is_empty() {
|
||||
let _ = on_output.send(InvokeResponseBody::Raw(replay));
|
||||
}
|
||||
}
|
||||
Ok(match &agent {
|
||||
Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(),
|
||||
None => idle_snapshot_json(),
|
||||
})
|
||||
}
|
||||
|
||||
// The bar's meter, polled at most every two seconds: how full the running
|
||||
// agent's context looks, labeled by how it was read.
|
||||
#[tauri::command]
|
||||
fn agent_context(state: State<'_, AppState>) -> serde_json::Value {
|
||||
let (estimate, kind, since) = match state.context.lock() {
|
||||
Ok(meter) => (meter.read(), meter.kind(), meter.since()),
|
||||
Err(_) => (ContextReading::Unknown, None, None),
|
||||
};
|
||||
let agent = current_agent(&state);
|
||||
let model = agent.as_ref().and_then(|agent| agent.model_and_effort().0);
|
||||
// Claude's own transcript, or Codex's own log, is read when there is one;
|
||||
// an unknown reading from either falls back to the labeled estimate.
|
||||
// Nothing is read while no agent runs.
|
||||
let reading = match (estimate, kind, agent, since) {
|
||||
(ContextReading::Unknown, _, _, _) => ContextReading::Unknown,
|
||||
(_, Some(AgentKind::Claude), Some(agent), Some(since)) => {
|
||||
// `window_for` always has a window for Claude; the fallback here only
|
||||
// guards against a future change to that rule.
|
||||
let window = context::window_for(kind, model.as_deref()).unwrap_or(context::ESTIMATE_TOKEN_WINDOW);
|
||||
let claude = ClaudeReader { projects_dir: claude_projects_dir(), folder: agent.folder().clone(), since, window };
|
||||
match claude.read() {
|
||||
ContextReading::Unknown => estimate,
|
||||
read => read,
|
||||
}
|
||||
}
|
||||
(_, Some(AgentKind::Codex), Some(agent), Some(since)) => {
|
||||
let codex = CodexReader {
|
||||
sessions_dir: codex_sessions_dir(),
|
||||
folder: agent.folder().clone(),
|
||||
since,
|
||||
};
|
||||
match codex.read() {
|
||||
ContextReading::Unknown => estimate,
|
||||
read => read,
|
||||
}
|
||||
}
|
||||
_ => estimate,
|
||||
};
|
||||
serde_json::to_value(reading).unwrap_or_default()
|
||||
}
|
||||
|
||||
// Claude Code's transcripts folder: `CLAUDE_CONFIG_DIR` when it is set, else `~/.claude`.
|
||||
fn claude_projects_dir() -> std::path::PathBuf {
|
||||
let home = std::env::var_os("CLAUDE_CONFIG_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::home_dir().map(|home| home.join(".claude")))
|
||||
.unwrap_or_default();
|
||||
home.join("projects")
|
||||
}
|
||||
|
||||
// Codex's sessions folder: `CODEX_HOME` when it is set, else `~/.codex`.
|
||||
fn codex_sessions_dir() -> std::path::PathBuf {
|
||||
let home = std::env::var_os("CODEX_HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::home_dir().map(|home| home.join(".codex")))
|
||||
.unwrap_or_default();
|
||||
home.join("sessions")
|
||||
}
|
||||
|
||||
// Asks before quitting while an agent runs; "no" keeps the app open.
|
||||
fn confirm_quit(app: &tauri::AppHandle) {
|
||||
let app = app.clone();
|
||||
app.dialog()
|
||||
.message("An agent is still running. Quit and stop it?")
|
||||
.title("Quit Plan2Code")
|
||||
.kind(MessageDialogKind::Warning)
|
||||
.buttons(MessageDialogButtons::YesNo)
|
||||
.show({
|
||||
let app = app.clone();
|
||||
move |quit| {
|
||||
if quit {
|
||||
quit_app(&app);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn agent_is_active(app: &tauri::AppHandle) -> bool {
|
||||
current_agent(&app.state::<AppState>()).is_some_and(|agent| agent.is_active())
|
||||
}
|
||||
|
||||
// Stops the agent, then the console, then exits.
|
||||
fn quit_app(app: &tauri::AppHandle) {
|
||||
let state = app.state::<AppState>();
|
||||
if let Some(agent) = current_agent(&state) {
|
||||
agent.stop();
|
||||
}
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
if let Some(mut console) = guard.take() {
|
||||
let _ = console.stop();
|
||||
}
|
||||
}
|
||||
app.exit(0);
|
||||
}
|
||||
|
||||
/// What the page draws its bar from: the folder (or that none is chosen yet)
|
||||
/// and the agent the picker starts on.
|
||||
#[tauri::command]
|
||||
fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
let project = state.project.lock().ok().and_then(|p| p.clone());
|
||||
let settings_file = settings::settings_file();
|
||||
// The agent picked in the launcher starts the bar's picker, ahead of the app's own last one.
|
||||
let last_agent = state
|
||||
.launch
|
||||
.agent
|
||||
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)))
|
||||
.or_else(project::remembered_agent);
|
||||
let nudge = settings_file
|
||||
.as_ref()
|
||||
.map_or(settings::DEFAULT_NUDGE_PERCENT, |file| settings::load_nudge_percent(file));
|
||||
let term_panel = settings_file.as_ref().map_or(
|
||||
settings::TermPanelSettings {
|
||||
dock: settings::DEFAULT_TERM_DOCK.to_string(),
|
||||
fraction: settings::DEFAULT_TERM_FRACTION,
|
||||
collapsed: false,
|
||||
},
|
||||
|file| settings::load_term_panel(file),
|
||||
);
|
||||
let first_run_done = settings_file.as_ref().is_some_and(|file| settings::load_first_run_done(file));
|
||||
serde_json::json!({
|
||||
"projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()),
|
||||
"projectDirSource": project.as_ref().map(|p| p.source),
|
||||
"lastAgent": last_agent.map(|kind| kind.id()),
|
||||
"launchModel": state.launch.model,
|
||||
"contextNudgePercent": nudge,
|
||||
// Task 1.7 already exits before the window opens on a missing or too-old
|
||||
// Node, so this is always a pass; the checklist's Node row just names it.
|
||||
"nodeVersion": state.node_version,
|
||||
"nodeBinary": state.node_binary,
|
||||
"skillsVersion": versions::installed_skills_version(),
|
||||
"firstRunDone": first_run_done,
|
||||
// The launcher always passes `--project` alongside `--agent`, so an
|
||||
// explicit `--agent` means skip straight to starting it, no checklist
|
||||
// or launch card shown.
|
||||
"autoStart": state.launch.agent.map(|kind| kind.id()),
|
||||
"termPanel": term_panel,
|
||||
})
|
||||
}
|
||||
|
||||
/// The terminal pane's toolbar remembers its shape here: dock side, size and
|
||||
/// whether it was left collapsed. A settings file that cannot be written is
|
||||
/// reported to the caller; the pane itself keeps working either way.
|
||||
#[tauri::command]
|
||||
fn save_term_panel(dock: String, fraction: f64, collapsed: bool) -> Result<(), String> {
|
||||
let file = settings::settings_file().ok_or("no home folder found")?;
|
||||
settings::save_term_panel(&file, &dock, fraction, collapsed)
|
||||
}
|
||||
|
||||
/// The first-run checklist passed once: later launches go straight to the
|
||||
/// launch card (Task 9.4).
|
||||
#[tauri::command]
|
||||
fn save_first_run_done() -> Result<(), String> {
|
||||
let file = settings::settings_file().ok_or("no home folder found")?;
|
||||
settings::save_first_run_done(&file)
|
||||
}
|
||||
|
||||
/// The app's version (`tauri.conf.json`'s, which Tauri puts in the package info) beside the
|
||||
/// installed skills' version. The bar shows its Update line when they differ (FR-14).
|
||||
#[tauri::command]
|
||||
fn version_status(app: tauri::AppHandle) -> versions::VersionStatus {
|
||||
versions::status(&app.package_info().version.to_string(), versions::installed_skills_version())
|
||||
}
|
||||
|
||||
/// What `update_skills` resolves with: the installer's last line, and the version status
|
||||
/// re-read afterwards, so the bar can say plainly whether the mismatch is actually gone.
|
||||
#[derive(serde::Serialize)]
|
||||
struct UpdateOutcome {
|
||||
message: String,
|
||||
status: versions::VersionStatus,
|
||||
}
|
||||
|
||||
/// Run the existing installer's update, pinned to this app's own release tag. Only the bar's
|
||||
/// button asks for it: never silently. `progress` carries each line of the installer's own
|
||||
/// output live, for the bar to show while it runs.
|
||||
#[tauri::command]
|
||||
async fn update_skills(app: tauri::AppHandle, progress: Channel<String>) -> Result<UpdateOutcome, String> {
|
||||
let version = app.package_info().version.to_string();
|
||||
let message = tauri::async_runtime::spawn_blocking(move || {
|
||||
versions::run_update(&version, |line| {
|
||||
let _ = progress.send(line.to_string());
|
||||
})
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let status = versions::status(&app.package_info().version.to_string(), versions::installed_skills_version());
|
||||
Ok(UpdateOutcome { message, status })
|
||||
}
|
||||
|
||||
/// The OS folder picker, shown when no folder is known; a choice becomes the
|
||||
/// launcher's remembered folder.
|
||||
#[tauri::command]
|
||||
fn pick_project_folder(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
.blocking_pick_folder()
|
||||
.and_then(|p| p.as_path().map(|dir| dir.to_path_buf()));
|
||||
let Some(dir) = picked else {
|
||||
return Ok(None);
|
||||
};
|
||||
let choice = project::remember_folder(&dir)?;
|
||||
let text = choice.dir.to_string_lossy().into_owned();
|
||||
*state.project.lock().map_err(|e| e.to_string())? = Some(choice);
|
||||
Ok(Some(text))
|
||||
}
|
||||
|
||||
/// Stops the old project's agent and console and clears both from state, so
|
||||
/// neither `agent_for_project` nor `console_start` can hand either back once
|
||||
/// the project has moved on (Task 9.5). `state.page` is deliberately left
|
||||
/// alone: it is the page's own output channel, not the project's, and it must
|
||||
/// stay the single live registration for `agentChannel`'s id for the page's
|
||||
/// whole lifetime. Dropping it here (even briefly, to `None`) sends the
|
||||
/// frontend an "end" message that unregisters that id for good — no later
|
||||
/// command can ever re-register the same frontend `Channel` object after
|
||||
/// that, whatever it passes, so a project switch would silently and
|
||||
/// permanently cut the new agent's output off from the page.
|
||||
fn teardown_project(state: &AppState) -> Result<(), String> {
|
||||
if let Some(agent) = current_agent(state) {
|
||||
agent.stop();
|
||||
}
|
||||
*state.agent.lock().map_err(|e| e.to_string())? = None;
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
if let Some(mut sup) = guard.take() {
|
||||
let _ = sup.stop();
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Switch to a different project folder, picked fresh: a clean teardown of
|
||||
/// the old one (its agent stopped, its console stopped) before the new
|
||||
/// folder is remembered, so `agent_for_project` and `console_start` start
|
||||
/// fresh for it rather than reusing anything from the one just left. Picking
|
||||
/// nothing (cancelled) leaves the current project untouched. One project per
|
||||
/// window stays; this replaces it, it does not add a second.
|
||||
#[tauri::command]
|
||||
fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
.blocking_pick_folder()
|
||||
.and_then(|p| p.as_path().map(|dir| dir.to_path_buf()));
|
||||
let Some(dir) = picked else {
|
||||
return Ok(None);
|
||||
};
|
||||
|
||||
teardown_project(&state)?;
|
||||
|
||||
let choice = project::remember_folder(&dir)?;
|
||||
let text = choice.dir.to_string_lossy().into_owned();
|
||||
*state.project.lock().map_err(|e| e.to_string())? = Some(choice);
|
||||
Ok(Some(text))
|
||||
}
|
||||
|
||||
/// The console the agent opened, alive and as it is now, or restarted on the
|
||||
/// same session when it died. The app never starts a dashboard of its own:
|
||||
/// the agent does, by running the skill, and announces it. Nothing to show yet
|
||||
/// is an error the page words for the person.
|
||||
#[tauri::command]
|
||||
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
|
||||
console_start_impl(&state)
|
||||
}
|
||||
|
||||
fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
let sup = guard.as_mut().ok_or("The agent has not opened the dashboard yet.")?;
|
||||
if !sup.health() {
|
||||
sup.restart_if_dead()?;
|
||||
}
|
||||
serde_json::to_value(sup.session()).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
/// The bar's poll: none (never started or stopped on purpose), running, or
|
||||
/// dead (started but not answering).
|
||||
#[tauri::command]
|
||||
fn console_status(state: State<'_, AppState>) -> serde_json::Value {
|
||||
let Ok(guard) = state.console.lock() else {
|
||||
return serde_json::json!({ "state": "none", "url": null });
|
||||
};
|
||||
match guard.as_ref() {
|
||||
Some(sup) if sup.stopped() => serde_json::json!({ "state": "none", "url": null }),
|
||||
Some(sup) if sup.health() => serde_json::json!({ "state": "running", "url": sup.session().url }),
|
||||
Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }),
|
||||
None => serde_json::json!({ "state": "none", "url": null }),
|
||||
}
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(mut sup) = guard.take() {
|
||||
sup.stop()?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
// Without Node 18+ the console and skills cannot run: say so and stop (FR-13).
|
||||
let status = node_check::check_node();
|
||||
let node_problem = node_check::problem_message(&status);
|
||||
let node_version = match &status {
|
||||
node_check::NodeStatus::Ok(version) => Some(version.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let node_binary = node_version.as_ref().and_then(|_| node_check::node_binary_path());
|
||||
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
tauri::Builder::default()
|
||||
.plugin(tauri_plugin_dialog::init())
|
||||
.manage(AppState {
|
||||
project: Mutex::new(project::resolve(&args)),
|
||||
launch: project::launch_choice(&args),
|
||||
node_version,
|
||||
node_binary,
|
||||
..AppState::default()
|
||||
})
|
||||
.invoke_handler(tauri::generate_handler![
|
||||
platform_info,
|
||||
agent_availability,
|
||||
agent_start,
|
||||
agent_input,
|
||||
agent_resize,
|
||||
agent_restart,
|
||||
agent_state,
|
||||
agent_reattach,
|
||||
agent_context,
|
||||
app_state,
|
||||
save_term_panel,
|
||||
save_first_run_done,
|
||||
version_status,
|
||||
update_skills,
|
||||
pick_project_folder,
|
||||
change_project,
|
||||
console_start,
|
||||
console_status,
|
||||
console_stop
|
||||
])
|
||||
.on_window_event(|window, event| {
|
||||
// Closing with an agent running asks first; "no" keeps the window open.
|
||||
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
|
||||
let app = window.app_handle().clone();
|
||||
if agent_is_active(&app) {
|
||||
api.prevent_close();
|
||||
confirm_quit(&app);
|
||||
}
|
||||
}
|
||||
})
|
||||
.setup(move |app| {
|
||||
// Pages the agent's `open` announces: the supervisor and the agent's
|
||||
// environment follow the console, and the page frame shows it.
|
||||
let handle = app.handle().clone();
|
||||
let server = AnnounceServer::start(Arc::new(move |notice| {
|
||||
let state = handle.state::<AppState>();
|
||||
if let Ok(mut guard) = state.console.lock() {
|
||||
match guard.as_mut() {
|
||||
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
||||
// The agent started the console: the app owns its stop from here.
|
||||
None => {
|
||||
let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone()));
|
||||
if let Some(dir) = dir {
|
||||
if let Ok(sup) =
|
||||
ConsoleSupervisor::adopt(dir, window_origin(&handle), ¬ice.url, ¬ice.sid)
|
||||
{
|
||||
*guard = Some(sup);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = handle.emit("console-page", ¬ice);
|
||||
}));
|
||||
match server {
|
||||
Ok(server) => {
|
||||
if let Ok(mut slot) = app.state::<AppState>().announce.lock() {
|
||||
*slot = Some(server);
|
||||
}
|
||||
}
|
||||
// Without it the agent opens pages the plain way; nothing else breaks.
|
||||
Err(error) => eprintln!("plan2code: no announce endpoint: {error}"),
|
||||
}
|
||||
if let Some(message) = &node_problem {
|
||||
app.dialog()
|
||||
.message(message)
|
||||
.title("Plan2Code needs Node.js")
|
||||
.kind(MessageDialogKind::Error)
|
||||
.blocking_show();
|
||||
std::process::exit(1);
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.build(tauri::generate_context!())
|
||||
.expect("error while building the Plan2Code app")
|
||||
.run(|app, event| {
|
||||
// Cmd+Q and the app menu's Quit on macOS end the app without closing the
|
||||
// window first. An exit asked for in code (`code` is set) is `quit_app`'s own.
|
||||
if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event {
|
||||
if agent_is_active(app) {
|
||||
api.prevent_exit();
|
||||
confirm_quit(app);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn state_for(dir: &str) -> AppState {
|
||||
AppState {
|
||||
project: Mutex::new(Some(ProjectDir { dir: PathBuf::from(dir), source: project::ProjectSource::Picked })),
|
||||
..AppState::default()
|
||||
}
|
||||
}
|
||||
|
||||
// Covers the folder-matching rule itself (Task 9.5's fix); a genuinely
|
||||
// *active* agent for the old folder needs a real spawned process to
|
||||
// prove against, which only the `tests/agent_manager.rs` harness (the
|
||||
// fake agent) can build — out of reach for an inline test here. The
|
||||
// by-hand "Change project" check (RELEASE-CHECKLIST.md) covers that case.
|
||||
#[test]
|
||||
fn a_different_folder_never_gets_the_old_manager_back() {
|
||||
let state = state_for("project-a");
|
||||
let first = agent_for_project(&state).expect("a manager for project-a");
|
||||
assert_eq!(first.folder(), &PathBuf::from("project-a"));
|
||||
|
||||
// The project moved on; the slot still holds project-a's manager
|
||||
// until a fresh call replaces it.
|
||||
*state.project.lock().unwrap() = Some(ProjectDir { dir: PathBuf::from("project-b"), source: project::ProjectSource::Picked });
|
||||
let second = agent_for_project(&state).expect("a manager for project-b");
|
||||
assert_eq!(second.folder(), &PathBuf::from("project-b"));
|
||||
assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_folder_reuses_the_same_manager() {
|
||||
let state = state_for("project-a");
|
||||
let first = agent_for_project(&state).unwrap();
|
||||
let second = agent_for_project(&state).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &second), "the same folder should not make a second manager");
|
||||
}
|
||||
|
||||
fn have_node() -> bool {
|
||||
std::process::Command::new("node").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)
|
||||
}
|
||||
|
||||
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
||||
/// up: `PLAN2CODE_CONSOLE_DIR` points at the repo's own console source,
|
||||
/// `PLAN2CODE_CONSOLE_HOME` keeps its session files out of the real one.
|
||||
fn real_console() -> Option<plan2code_app_lib::console_supervisor::ConsoleSupervisor> {
|
||||
if !have_node() {
|
||||
eprintln!("skipping: node is not on PATH");
|
||||
return None;
|
||||
}
|
||||
let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||
if !console_dir.join("console.mjs").is_file() {
|
||||
eprintln!("skipping: console source missing at {}", console_dir.display());
|
||||
return None;
|
||||
}
|
||||
let pid = std::process::id();
|
||||
let project = std::env::temp_dir().join(format!("p2c-main-test-project-{pid}"));
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_HOME", std::env::temp_dir().join(format!("p2c-main-test-home-{pid}")));
|
||||
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
|
||||
Some(
|
||||
plan2code_app_lib::console_supervisor::ConsoleSupervisor::start(
|
||||
project,
|
||||
plan2code_app_lib::console_supervisor::app_origin().to_string(),
|
||||
)
|
||||
.expect("start a real console for the test"),
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn teardown_clears_the_console_so_console_start_refuses_not_reconnects() {
|
||||
let Some(sup) = real_console() else { return };
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(sup);
|
||||
assert!(console_start_impl(&state).is_ok(), "console_start should work before the project changes");
|
||||
|
||||
teardown_project(&state).unwrap();
|
||||
|
||||
let err = console_start_impl(&state).expect_err("console_start must refuse, not reconnect to the old session");
|
||||
assert!(err.contains("has not opened the dashboard"), "unexpected message: {err:?}");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! 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::OnceLock;
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
/// The PATH every process this app spawns should run with: an explicit
|
||||
/// `--node`'s directory first, then (macOS and Linux) the login shell's own
|
||||
/// PATH, then this process's own PATH, each included only once. Resolved
|
||||
/// once per launch: none of these change while the app runs.
|
||||
pub fn resolved_path() -> &'static str {
|
||||
static PATH: OnceLock<String> = OnceLock::new();
|
||||
PATH.get_or_init(|| {
|
||||
let args: Vec<String> = std::env::args().collect();
|
||||
let inherited = std::env::var("PATH").unwrap_or_default();
|
||||
let mut parts = Vec::new();
|
||||
if let Some(dir) = node_override_dir(&args) {
|
||||
parts.push(dir);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
if let Some(login) = login_shell_path() {
|
||||
parts.push(login);
|
||||
}
|
||||
if !inherited.is_empty() {
|
||||
parts.push(inherited);
|
||||
}
|
||||
parts.join(if cfg!(windows) { ";" } else { ":" })
|
||||
})
|
||||
}
|
||||
|
||||
/// 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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,191 @@
|
||||
//! 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::AgentKind;
|
||||
|
||||
/// 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 agent the launcher last ran. The bar's picker starts on it until the
|
||||
/// app has a choice of its own (`settings.rs`).
|
||||
pub fn remembered_agent() -> Option<AgentKind> {
|
||||
AgentKind::from_id(read_launcher().get("lastCli")?.as_str()?)
|
||||
}
|
||||
|
||||
/// `--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 {
|
||||
pub agent: Option<AgentKind>,
|
||||
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 {
|
||||
let agent = flag_value(args, "--agent").and_then(|id| AgentKind::from_id(&id.to_lowercase()));
|
||||
let model = agent.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::*;
|
||||
|
||||
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), 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), 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), model: None }
|
||||
);
|
||||
}
|
||||
|
||||
#[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,280 @@
|
||||
//! 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 colour.
|
||||
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,182 @@
|
||||
//! 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);
|
||||
|
||||
/// The skill named on a handoff record for a workflow `brief::skill_for_workflow`
|
||||
/// does not map, such as `dashboard`: the console's own name for that pseudo-skill.
|
||||
const UNMAPPED_SKILL: &str = "plan2code";
|
||||
|
||||
/// Write the brief for session `sid` as a handoff. A workflow with no mapped
|
||||
/// skill (a dashboard, or one not yet known) still gets a short, honest chip
|
||||
/// rather than nothing. Returns the handoff's id, or `None` when there is
|
||||
/// truly nothing to write (the session 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 skill = brief::skill_for_workflow(workflow);
|
||||
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 skill {
|
||||
Some(skill) => match spec {
|
||||
Some(spec) => format!("Restart of {skill} on {spec}"),
|
||||
None => format!("Restart of {skill}"),
|
||||
},
|
||||
None => format!("Restart while on {workflow}"),
|
||||
};
|
||||
let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill: skill.unwrap_or(UNMAPPED_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())
|
||||
}
|
||||
|
||||
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_still_leaves_a_chip() {
|
||||
let (home, _, handoffs) = session("dashboard", "dashboard", None);
|
||||
let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff");
|
||||
let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap();
|
||||
assert_eq!(record["title"], "Restart while on dashboard");
|
||||
assert_eq!(record["skill"], "plan2code");
|
||||
assert_eq!(record["workflow"], "dashboard");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("- Workflow: `dashboard`"));
|
||||
assert!(doc.contains("## Next task\n\nOpen the dashboard"));
|
||||
}
|
||||
|
||||
#[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,217 @@
|
||||
//! 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,242 @@
|
||||
//! 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};
|
||||
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
const LAST_AGENT_KEY: &str = "lastAgent";
|
||||
const NUDGE_KEY: &str = "CONTEXT_NUDGE_PERCENT";
|
||||
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";
|
||||
|
||||
/// The context percent at which the bar suggests a Restart, when the file
|
||||
/// names no other.
|
||||
pub const DEFAULT_NUDGE_PERCENT: u8 = 70;
|
||||
|
||||
/// 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 saved in `file`, when it still names one the app can run.
|
||||
pub fn load_last_agent(file: &Path) -> Option<AgentKind> {
|
||||
AgentKind::from_id(read(file).get(LAST_AGENT_KEY)?.as_str()?)
|
||||
}
|
||||
|
||||
/// The context percent that triggers the Restart suggestion. A value outside
|
||||
/// 1 to 100, or one that is not a number, means the default.
|
||||
pub fn load_nudge_percent(file: &Path) -> u8 {
|
||||
read(file)
|
||||
.get(NUDGE_KEY)
|
||||
.and_then(|value| value.as_u64())
|
||||
.filter(|percent| (1..=100).contains(percent))
|
||||
.map_or(DEFAULT_NUDGE_PERCENT, |percent| percent as u8)
|
||||
}
|
||||
|
||||
/// Save the pick, keeping any other key the file holds.
|
||||
pub fn save_last_agent(file: &Path, kind: AgentKind) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(kind.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)
|
||||
}
|
||||
|
||||
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, AgentKind::Devin).unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some(AgentKind::Devin));
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nudge_defaults_to_seventy() {
|
||||
assert_eq!(load_nudge_percent(&temp_file("nudge-missing")), 70);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nudge_reads_a_named_percent() {
|
||||
let file = temp_file("nudge-set");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"CONTEXT_NUDGE_PERCENT": 85}"#).unwrap();
|
||||
assert_eq!(load_nudge_percent(&file), 85);
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nudge_outside_one_to_one_hundred_or_not_a_number_is_the_default() {
|
||||
for text in [
|
||||
r#"{"CONTEXT_NUDGE_PERCENT": 0}"#,
|
||||
r#"{"CONTEXT_NUDGE_PERCENT": 150}"#,
|
||||
r#"{"CONTEXT_NUDGE_PERCENT": "high"}"#,
|
||||
] {
|
||||
let file = temp_file("nudge-bad");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, text).unwrap();
|
||||
assert_eq!(load_nudge_percent(&file), 70, "{text}");
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_agent_is_ignored() {
|
||||
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), 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 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,273 @@
|
||||
//! 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,36 @@
|
||||
{
|
||||
"$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,
|
||||
"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,301 @@
|
||||
//! 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::{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(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(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(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(AgentKind::Codex));
|
||||
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(AgentKind::Codex), "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();
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
//! 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,100 @@
|
||||
//! 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");
|
||||
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,154 @@
|
||||
//! 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, process_alive};
|
||||
|
||||
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 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,852 @@
|
||||
// The app page: the top bar, the console dashboard in an iframe, and the
|
||||
// agent's terminal panel docked at the bottom with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { nudgeDue } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
const projectDirEl = document.getElementById('project-dir');
|
||||
const agentNameEl = document.getElementById('agent-name');
|
||||
const agentStatusEl = document.getElementById('agent-status');
|
||||
const restartBtn = document.getElementById('agent-restart');
|
||||
const changeAgentBtn = document.getElementById('change-agent');
|
||||
const changeProjectBtn = document.getElementById('change-project');
|
||||
const launchCard = document.getElementById('launch-card');
|
||||
const launchAgentEl = document.getElementById('launch-agent');
|
||||
const launchMissingEl = document.getElementById('launch-missing');
|
||||
const launchModelEl = document.getElementById('launch-model');
|
||||
const launchEffortRow = document.getElementById('launch-effort-row');
|
||||
const launchEffortEl = document.getElementById('launch-effort');
|
||||
const launchBypassEl = document.getElementById('launch-bypass');
|
||||
const launchBypassWarningEl = document.getElementById('launch-bypass-warning');
|
||||
const launchStartBtn = document.getElementById('launch-start');
|
||||
const firstRunEl = document.getElementById('first-run');
|
||||
const firstRunListEl = document.getElementById('first-run-list');
|
||||
const firstRunStartBtn = document.getElementById('first-run-start');
|
||||
const meterSlot = document.getElementById('bar-slot-meter');
|
||||
const nudgeEl = document.getElementById('context-nudge');
|
||||
const nudgeRestartBtn = document.getElementById('context-restart');
|
||||
const versionEl = document.getElementById('version-update');
|
||||
const versionTextEl = document.getElementById('version-update-text');
|
||||
const versionBtn = document.getElementById('version-update-button');
|
||||
const versionRestartBtn = document.getElementById('version-update-restart');
|
||||
const consoleStatusEl = document.getElementById('console-status');
|
||||
const permissionsNoteEl = document.getElementById('permissions-note');
|
||||
const consoleAgainBtn = document.getElementById('console-again');
|
||||
const frame = document.getElementById('console-frame');
|
||||
const stateBox = document.getElementById('dashboard-state');
|
||||
const stateText = document.getElementById('dashboard-state-text');
|
||||
const stateButton = document.getElementById('dashboard-state-button');
|
||||
const stateCancelEl = document.getElementById('dashboard-state-cancel');
|
||||
const workspaceEl = document.getElementById('workspace');
|
||||
const termPanel = document.getElementById('term-panel');
|
||||
const termHandle = document.getElementById('term-handle');
|
||||
const termDockBtn = document.getElementById('term-dock');
|
||||
const termMaximizeBtn = document.getElementById('term-maximize');
|
||||
const termCollapseBtn = document.getElementById('term-collapse');
|
||||
const termBadgeEl = document.getElementById('term-badge');
|
||||
const currentPageEl = document.getElementById('current-page');
|
||||
|
||||
const STATUS_POLL_MS = 5000;
|
||||
const METER_POLL_MS = 2000;
|
||||
const BADGE_POLL_MS = 2000;
|
||||
const MIN_PANE = 0.10;
|
||||
const MAX_PANE = 0.60;
|
||||
const MAXIMIZED_PANE = 0.80;
|
||||
// Below this share of the window, a collapsed-or-small pane can hide a
|
||||
// question the agent is quietly waiting on.
|
||||
const SMALL_PANE = 0.15;
|
||||
const QUIET_BADGE_MS = 10000;
|
||||
|
||||
const AGENT_LABELS = { claude: 'Claude Code', devin: 'Devin', codex: 'Codex' };
|
||||
// Devin's model ids already carry their effort (`swe-2-high`); only these two
|
||||
// take a separate effort, at the levels their own CLI documents.
|
||||
const EFFORT_OPTIONS = {
|
||||
claude: ['low', 'medium', 'high', 'xhigh', 'max'],
|
||||
codex: ['low', 'medium', 'high'],
|
||||
};
|
||||
|
||||
// What the Rust agent host last said: idle, running or ended.
|
||||
let agent = { state: 'idle', kind: null, generation: 0 };
|
||||
const agentActive = () => agent.state === 'running';
|
||||
|
||||
// The context percent that triggers the Restart suggestion, from the app's
|
||||
// settings (main() reads it), and the agent run the suggestion was shown for:
|
||||
// it appears once per run, not again after it is dismissed by a Restart.
|
||||
let nudgePercent = 70;
|
||||
let nudgeShownFor = null;
|
||||
|
||||
const terminal = await mountTerminal(document.getElementById('term'), {
|
||||
onInput: (data) => {
|
||||
if (agentActive()) invoke('agent_input', { data });
|
||||
},
|
||||
onResize: (cols, rows) => {
|
||||
if (agentActive()) invoke('agent_resize', { cols, rows });
|
||||
},
|
||||
});
|
||||
|
||||
// One channel for the page's life: the agent's output arrives as bytes and its
|
||||
// state changes as objects, across restarts too.
|
||||
const agentChannel = new Channel();
|
||||
agentChannel.onmessage = (message) => {
|
||||
if (message instanceof ArrayBuffer) {
|
||||
terminal.write(new Uint8Array(message));
|
||||
lastOutputAt = Date.now();
|
||||
updateBadge();
|
||||
} else if (message && typeof message === 'object' && 'state' in message) {
|
||||
applyAgentState(message);
|
||||
}
|
||||
};
|
||||
|
||||
function applyAgentState(next, { skipReset } = {}) {
|
||||
const wasEnded = agent.state === 'ended';
|
||||
// A new generation is a fresh agent: it starts on a clean screen. Skipped
|
||||
// when catching up to an agent that was already running before this page
|
||||
// mounted (a reload): its replayed output, not a blank screen, belongs here,
|
||||
// and the channel that delivers it races this call, not waits for it.
|
||||
const freshScreen = next.generation !== agent.generation && !skipReset;
|
||||
if (freshScreen) {
|
||||
terminal.reset();
|
||||
lastOutputAt = Date.now();
|
||||
}
|
||||
agent = next;
|
||||
const label = AGENT_LABELS[agent.kind] || '';
|
||||
const active = agentActive();
|
||||
|
||||
agentNameEl.textContent = active ? label : '';
|
||||
if (active) {
|
||||
// Only ever auto-*hides* the card (the agent just started); it must
|
||||
// never auto-*show* it on 'ended' or 'idle' — that is Change agent's
|
||||
// job alone, so the card does not pop up over the dashboard uninvited.
|
||||
launchCard.hidden = true;
|
||||
hideFirstRun();
|
||||
}
|
||||
// One rule throughout: Restart while running or ended (it keeps the
|
||||
// previous agent, model, effort and mode); Change agent only once ended,
|
||||
// when there is a real choice to make again.
|
||||
restartBtn.hidden = !(active || agent.state === 'ended');
|
||||
changeAgentBtn.hidden = agent.state !== 'ended';
|
||||
// Checked mode needs no banner; bypass always gets one, naming the agent it
|
||||
// applies to, for exactly as long as that agent runs.
|
||||
const bypassActive = active && agent.mode === 'bypass';
|
||||
permissionsNoteEl.hidden = !bypassActive;
|
||||
permissionsNoteEl.textContent = bypassActive ? `Permission checks are off for ${label || 'the running agent'}` : '';
|
||||
restartBtn.title = agent.state === 'ended' ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window';
|
||||
if (freshScreen || agent.state !== 'running') nudgeEl.hidden = true;
|
||||
if (!agentActive()) renderMeter({ kind: 'unknown' });
|
||||
// The agent is back (a fresh generation, running): the restart message stays
|
||||
// on screen (restarting() below) until its dashboard page is announced.
|
||||
if (restarting && freshScreen && agent.state === 'running') {
|
||||
terminal.write('\r\n\r\n[Fresh agent started. Waiting for the dashboard...]\r\n\r\n');
|
||||
}
|
||||
|
||||
if (agent.state === 'ended') {
|
||||
agentStatusEl.textContent = `${label || 'The agent'} ended: ${agent.reason}. Nothing starts until you press Restart.`;
|
||||
// A failed Restart clears the screen too, so it says so again.
|
||||
if (!wasEnded || freshScreen) {
|
||||
terminal.write(`\r\n[${label || 'The agent'} ended: ${agent.reason}. Press Restart in the bar to start a fresh one.]\r\n`);
|
||||
}
|
||||
} else {
|
||||
// After a Restart the bar says what it left for the dashboard, if anything.
|
||||
agentStatusEl.textContent = agent.briefNote || '';
|
||||
}
|
||||
agentStatusEl.title = agentStatusEl.textContent;
|
||||
updateBadge();
|
||||
}
|
||||
|
||||
// True from a confirmed Restart until the fresh agent's dashboard page is
|
||||
// announced (showAnnounced below): the frame stays blanked with a message the
|
||||
// whole time, since the restarted agent must boot and run the skill again
|
||||
// before anything can show.
|
||||
let restarting = false;
|
||||
|
||||
function confirmRestart(onYes) {
|
||||
if (agent.state !== 'running') {
|
||||
onYes();
|
||||
return;
|
||||
}
|
||||
showState(
|
||||
'Restart the agent on a fresh context window? What it was doing is not saved.',
|
||||
'Restart',
|
||||
() => {
|
||||
restarting = true;
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
currentPageEl.textContent = '';
|
||||
showState('The agent is restarting on a fresh context window. Please wait for the dashboard to load.');
|
||||
onYes();
|
||||
},
|
||||
() => (frameReady ? hideState() : showState('No dashboard has loaded yet.'))
|
||||
);
|
||||
}
|
||||
|
||||
// What the launch card offers for each agent: whether its CLI was found on
|
||||
// PATH (else how to install it) and whether it takes its own effort.
|
||||
let agentAvailability = {};
|
||||
|
||||
async function loadAgentAvailability() {
|
||||
try {
|
||||
const list = await invoke('agent_availability');
|
||||
agentAvailability = Object.fromEntries(list.map((entry) => [entry.id, entry]));
|
||||
} catch {
|
||||
// Nothing to show is not a reason to block the card: Start just tries it.
|
||||
agentAvailability = {};
|
||||
}
|
||||
}
|
||||
|
||||
function refreshLaunchCard() {
|
||||
const kind = launchAgentEl.value;
|
||||
const info = agentAvailability[kind];
|
||||
const installed = info ? info.installed : true;
|
||||
launchStartBtn.disabled = !installed;
|
||||
launchMissingEl.hidden = installed;
|
||||
launchMissingEl.replaceChildren();
|
||||
if (!installed) {
|
||||
const label = (info && info.label) || AGENT_LABELS[kind] || kind;
|
||||
launchMissingEl.append(`${label} was not found on PATH. Install it: `);
|
||||
const code = document.createElement('code');
|
||||
code.textContent = (info && info.installHint) || '';
|
||||
launchMissingEl.append(code);
|
||||
}
|
||||
const levels = EFFORT_OPTIONS[kind] || [];
|
||||
launchEffortRow.hidden = levels.length === 0;
|
||||
launchEffortEl.replaceChildren();
|
||||
const def = document.createElement('option');
|
||||
def.value = '';
|
||||
def.textContent = 'Default';
|
||||
launchEffortEl.append(def);
|
||||
for (const level of levels) {
|
||||
const option = document.createElement('option');
|
||||
option.value = level;
|
||||
option.textContent = level[0].toUpperCase() + level.slice(1);
|
||||
launchEffortEl.append(option);
|
||||
}
|
||||
}
|
||||
|
||||
launchAgentEl.onchange = refreshLaunchCard;
|
||||
launchBypassEl.onchange = () => {
|
||||
launchBypassWarningEl.hidden = !launchBypassEl.checked;
|
||||
};
|
||||
|
||||
function showLaunchCard() {
|
||||
hideState();
|
||||
hideFirstRun();
|
||||
refreshLaunchCard();
|
||||
launchCard.hidden = false;
|
||||
}
|
||||
|
||||
function hideLaunchCard() {
|
||||
launchCard.hidden = true;
|
||||
}
|
||||
|
||||
// One row of the first-run checklist: a pass/fail mark, a title and a detail
|
||||
// line (plain text or a built node, such as the CLI-by-CLI list).
|
||||
function firstRunRow(pass, title, detail) {
|
||||
const row = document.createElement('li');
|
||||
row.className = `first-run-row ${pass ? 'is-pass' : 'is-fail'}`;
|
||||
const mark = document.createElement('span');
|
||||
mark.className = 'first-run-mark';
|
||||
mark.textContent = pass ? '✓' : '!';
|
||||
const body = document.createElement('div');
|
||||
body.className = 'first-run-body';
|
||||
const titleEl = document.createElement('div');
|
||||
titleEl.className = 'first-run-title';
|
||||
titleEl.textContent = title;
|
||||
body.append(titleEl);
|
||||
if (detail) {
|
||||
const detailEl = document.createElement('div');
|
||||
detailEl.className = 'first-run-detail';
|
||||
if (typeof detail === 'string') detailEl.textContent = detail;
|
||||
else detailEl.append(detail);
|
||||
body.append(detailEl);
|
||||
}
|
||||
row.append(mark, body);
|
||||
return row;
|
||||
}
|
||||
|
||||
// Node is always a pass here: `main()` on the Rust side already exits before
|
||||
// the window opens on anything else (Task 1.7), so this row is a confirmation,
|
||||
// never a way to recover from a real failure.
|
||||
function renderFirstRun(state) {
|
||||
firstRunListEl.replaceChildren();
|
||||
const nodeDetail = `${state.nodeVersion || 'found'} (18 or newer)${state.nodeBinary ? ` — ${state.nodeBinary}` : ''}`;
|
||||
firstRunListEl.append(firstRunRow(true, 'Node.js', nodeDetail));
|
||||
|
||||
const agentsKnown = Object.values(agentAvailability);
|
||||
const anyAgentInstalled = agentsKnown.length === 0 || agentsKnown.some((a) => a.installed);
|
||||
const agentsDetail = document.createElement('span');
|
||||
if (agentsKnown.length === 0) {
|
||||
agentsDetail.textContent = 'Could not check.';
|
||||
} else {
|
||||
agentsKnown.forEach((a, i) => {
|
||||
if (i > 0) agentsDetail.append(', ');
|
||||
agentsDetail.append(`${a.label}: ${a.installed ? a.path : 'not found'}`);
|
||||
});
|
||||
}
|
||||
firstRunListEl.append(firstRunRow(anyAgentInstalled, 'An agent CLI', agentsDetail));
|
||||
|
||||
firstRunListEl.append(firstRunRow(Boolean(state.projectDir), 'Project folder', state.projectDir || 'not chosen yet'));
|
||||
|
||||
const skillsOk = Boolean(state.skillsVersion);
|
||||
const skillsDetail = skillsOk ? `v${state.skillsVersion}` : 'not found; run `plan2code update`';
|
||||
firstRunListEl.append(firstRunRow(skillsOk, 'Plan2Code skills', skillsDetail));
|
||||
|
||||
firstRunStartBtn.disabled = !(anyAgentInstalled && state.projectDir && skillsOk);
|
||||
}
|
||||
|
||||
function showFirstRun(state) {
|
||||
hideState();
|
||||
hideLaunchCard();
|
||||
renderFirstRun(state);
|
||||
firstRunEl.hidden = false;
|
||||
}
|
||||
|
||||
function hideFirstRun() {
|
||||
firstRunEl.hidden = true;
|
||||
}
|
||||
|
||||
firstRunStartBtn.onclick = async () => {
|
||||
hideFirstRun();
|
||||
try {
|
||||
await invoke('save_first_run_done');
|
||||
} catch {
|
||||
// Not remembered is not fatal: the checklist just shows again next launch.
|
||||
}
|
||||
showLaunchCard();
|
||||
};
|
||||
|
||||
async function startAgent(event) {
|
||||
if (event) event.preventDefault();
|
||||
const kind = launchAgentEl.value;
|
||||
const model = launchModelEl.value.trim() || null;
|
||||
const effort = (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
|
||||
const mode = launchBypassEl.checked ? 'bypass' : 'checked';
|
||||
agentStatusEl.textContent = '';
|
||||
showState('Waiting for the agent to open the dashboard');
|
||||
const { cols, rows } = terminal.size();
|
||||
try {
|
||||
await invoke('agent_start', { kind, model, effort, mode, cols, rows });
|
||||
terminal.focus();
|
||||
} catch (error) {
|
||||
agentStatusEl.textContent = `Could not start the agent: ${error}`;
|
||||
showLaunchCard();
|
||||
}
|
||||
}
|
||||
|
||||
async function agentAction(command) {
|
||||
try {
|
||||
await invoke(command);
|
||||
terminal.focus();
|
||||
} catch (error) {
|
||||
agentStatusEl.textContent = String(error);
|
||||
}
|
||||
}
|
||||
|
||||
launchCard.addEventListener('submit', startAgent);
|
||||
restartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
|
||||
nudgeRestartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
|
||||
// Only ever enabled once the agent has ended: nothing active to lose, so no confirm.
|
||||
changeAgentBtn.onclick = () => showLaunchCard();
|
||||
|
||||
// The pane's shape: which edge it docks to, its share of the window when it
|
||||
// is neither collapsed nor maximized (dragging and the settings file both
|
||||
// deal in that share, never in pixels), and whether it is collapsed.
|
||||
// Maximized is a transient view, never saved: the pane comes back at its
|
||||
// last saved share on the next launch.
|
||||
let paneDock = 'bottom';
|
||||
let paneFraction = 0.25;
|
||||
let paneCollapsed = false;
|
||||
let paneMaximized = false;
|
||||
|
||||
const paneExtent = () => (paneDock === 'right' ? window.innerWidth : window.innerHeight);
|
||||
|
||||
function applyPaneLayout() {
|
||||
workspaceEl.classList.toggle('dock-right', paneDock === 'right');
|
||||
termPanel.classList.toggle('collapsed', paneCollapsed);
|
||||
termHandle.hidden = paneCollapsed;
|
||||
const sizeProp = paneDock === 'right' ? 'width' : 'height';
|
||||
const otherProp = paneDock === 'right' ? 'height' : 'width';
|
||||
termPanel.style[otherProp] = '';
|
||||
if (paneCollapsed) {
|
||||
termPanel.style[sizeProp] = '';
|
||||
} else {
|
||||
const fraction = paneMaximized ? MAXIMIZED_PANE : paneFraction;
|
||||
termPanel.style[sizeProp] = `${Math.round(paneExtent() * fraction)}px`;
|
||||
}
|
||||
termDockBtn.textContent = paneDock === 'right' ? 'Dock bottom' : 'Dock right';
|
||||
termMaximizeBtn.textContent = paneMaximized ? 'Restore' : 'Maximize';
|
||||
termMaximizeBtn.setAttribute('aria-pressed', String(paneMaximized));
|
||||
termCollapseBtn.textContent = paneCollapsed ? 'Expand' : 'Collapse';
|
||||
termCollapseBtn.setAttribute('aria-pressed', String(paneCollapsed));
|
||||
updateBadge();
|
||||
}
|
||||
|
||||
function savePaneSettings() {
|
||||
invoke('save_term_panel', { dock: paneDock, fraction: paneFraction, collapsed: paneCollapsed }).catch(() => {
|
||||
// A settings file that cannot be written must not stop the pane from working.
|
||||
});
|
||||
}
|
||||
|
||||
termDockBtn.onclick = () => {
|
||||
paneDock = paneDock === 'right' ? 'bottom' : 'right';
|
||||
applyPaneLayout();
|
||||
savePaneSettings();
|
||||
};
|
||||
termMaximizeBtn.onclick = () => {
|
||||
paneMaximized = !paneMaximized;
|
||||
applyPaneLayout();
|
||||
};
|
||||
termCollapseBtn.onclick = () => {
|
||||
paneCollapsed = !paneCollapsed;
|
||||
if (!paneCollapsed) terminal.focus();
|
||||
applyPaneLayout();
|
||||
savePaneSettings();
|
||||
};
|
||||
|
||||
// Dragging the handle sets the panel's share of the window, along whichever
|
||||
// edge it is docked to.
|
||||
termHandle.addEventListener('pointerdown', (event) => {
|
||||
event.preventDefault();
|
||||
termHandle.setPointerCapture(event.pointerId);
|
||||
});
|
||||
termHandle.addEventListener('pointermove', (event) => {
|
||||
if (!termHandle.hasPointerCapture(event.pointerId)) return;
|
||||
const extent = paneExtent();
|
||||
const wanted = paneDock === 'right' ? window.innerWidth - event.clientX : window.innerHeight - event.clientY;
|
||||
const clamped = Math.min(Math.max(wanted, extent * MIN_PANE), extent * MAX_PANE);
|
||||
paneFraction = clamped / extent;
|
||||
paneMaximized = false;
|
||||
applyPaneLayout();
|
||||
});
|
||||
termHandle.addEventListener('pointerup', (event) => {
|
||||
if (termHandle.hasPointerCapture(event.pointerId)) termHandle.releasePointerCapture(event.pointerId);
|
||||
savePaneSettings();
|
||||
});
|
||||
|
||||
// When the pane is collapsed or small, the agent's own status line can keep
|
||||
// redrawing while it is really waiting on a prompt no one is watching: a
|
||||
// stretch of no new output at all is the giveaway.
|
||||
let lastOutputAt = Date.now();
|
||||
|
||||
function updateBadge() {
|
||||
const small = paneCollapsed || (!paneMaximized && paneFraction < SMALL_PANE);
|
||||
const quiet = agentActive() && Date.now() - lastOutputAt >= QUIET_BADGE_MS;
|
||||
termBadgeEl.hidden = !(small && quiet);
|
||||
}
|
||||
|
||||
// The frame is "showing" only once the console page itself says so (it posts a
|
||||
// hello to its parent when it draws). The frame's own load event also fires for
|
||||
// an error page, so it proves nothing: a blocked or dead frame must not look
|
||||
// like a loaded one.
|
||||
const HELLO_WAIT_MS = 8000;
|
||||
let currentUrl = null;
|
||||
let frameReady = false;
|
||||
let helloTimer = null;
|
||||
// Nothing has shown here yet: no agent has opened the dashboard. No polling,
|
||||
// no "reconnect" button makes sense until that first page lands.
|
||||
let consoleKnown = false;
|
||||
|
||||
function loadFrame(url) {
|
||||
currentUrl = url;
|
||||
frameReady = false;
|
||||
clearTimeout(helloTimer);
|
||||
helloTimer = setTimeout(onNoHello, HELLO_WAIT_MS);
|
||||
frame.src = url;
|
||||
}
|
||||
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.source !== frame.contentWindow) return;
|
||||
if (!event.data || event.data.plan2code !== 'console-ready') return;
|
||||
frameReady = true;
|
||||
clearTimeout(helloTimer);
|
||||
hideState();
|
||||
});
|
||||
|
||||
// No hello in time: ask the console why, and say so with a way forward.
|
||||
async function onNoHello() {
|
||||
if (frameReady || !consoleKnown || restarting) return;
|
||||
let status = null;
|
||||
try {
|
||||
status = await invoke('console_status');
|
||||
} catch {
|
||||
// The status check itself failed; treat it as a console that is not answering.
|
||||
}
|
||||
if (!status || status.state !== 'running') {
|
||||
showState('The console stopped, so the page could not show.', 'Restart the console', reconnectConsole);
|
||||
} else {
|
||||
showState('The console is running but its page did not show in this window.', 'Reload the page', () => {
|
||||
showState('Reloading the page');
|
||||
loadFrame(currentUrl);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function showState(text, buttonLabel, onButton, onCancel) {
|
||||
hideLaunchCard();
|
||||
hideFirstRun();
|
||||
stateText.textContent = text;
|
||||
stateButton.hidden = !buttonLabel;
|
||||
stateButton.textContent = buttonLabel || '';
|
||||
stateButton.onclick = onButton || null;
|
||||
stateCancelEl.hidden = !onCancel;
|
||||
stateCancelEl.onclick = onCancel || null;
|
||||
stateBox.hidden = false;
|
||||
}
|
||||
|
||||
function hideState() {
|
||||
stateBox.hidden = true;
|
||||
}
|
||||
|
||||
let pollTimer = null;
|
||||
|
||||
// Only once the agent has opened a page: brings an idle or dead console back
|
||||
// on its own session. The app never opens a dashboard on its own (the agent
|
||||
// does, by running the skill), so there is nothing to start before that.
|
||||
async function reconnectConsole() {
|
||||
markConsoleAlive();
|
||||
showState('Reconnecting to the console');
|
||||
try {
|
||||
const info = await invoke('console_start');
|
||||
loadFrame(info.url);
|
||||
} catch (error) {
|
||||
showState(`The console could not be reached: ${error}`, 'Retry', reconnectConsole);
|
||||
// An old console cannot be framed: the fix is the skills update, so offer it.
|
||||
if (String(error).includes('too old')) {
|
||||
versionTextEl.textContent = 'The installed console is too old for the app';
|
||||
versionEl.hidden = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Health check on a timer. A console that dies after its page showed (it idles
|
||||
// out, or something ended it) is brought back on the same session, a few times
|
||||
// at most; before the page ever showed, the person decides with a button.
|
||||
const RECONNECT_LIMIT = 3;
|
||||
let reconnects = 0;
|
||||
|
||||
async function pollConsole() {
|
||||
try {
|
||||
const status = await invoke('console_status');
|
||||
if (status.state === 'running') {
|
||||
markConsoleAlive();
|
||||
return;
|
||||
}
|
||||
markConsoleDead();
|
||||
if (frameReady && reconnects < RECONNECT_LIMIT) {
|
||||
reconnects += 1;
|
||||
showState('The console stopped. Reconnecting');
|
||||
await reconnectConsole();
|
||||
} else if (!frameReady) {
|
||||
onNoHello();
|
||||
}
|
||||
} catch {
|
||||
// A failed check is not proof the console died; look again next tick.
|
||||
}
|
||||
}
|
||||
|
||||
// The meter: a bar and a percent for a real or best-effort reading, a dashed
|
||||
// bar with "about N%" and an "estimate" tag for an estimate, "unknown" when
|
||||
// nothing is available. Built with DOM calls, never innerHTML.
|
||||
function renderMeter(reading) {
|
||||
meterSlot.replaceChildren();
|
||||
// Left empty, not even an "unknown" label: #bar-slot-meter:empty hides it,
|
||||
// so the bar carries nothing until the reading means something.
|
||||
if (reading.kind === 'unknown') return;
|
||||
const label = document.createElement('span');
|
||||
const track = document.createElement('span');
|
||||
track.className = `meter-track ${reading.kind}`;
|
||||
const fill = document.createElement('span');
|
||||
fill.className = 'meter-fill';
|
||||
fill.style.width = `${reading.percent}%`;
|
||||
track.append(fill);
|
||||
label.textContent = reading.kind === 'estimate' ? `about ${reading.percent}%` : `${reading.percent}%`;
|
||||
meterSlot.append(track, label);
|
||||
if (reading.kind === 'estimate') {
|
||||
const tag = document.createElement('span');
|
||||
tag.className = 'meter-tag';
|
||||
tag.textContent = 'estimate';
|
||||
meterSlot.append(tag);
|
||||
meterSlot.title = 'Estimated from the text so far: the agent does not report its context size';
|
||||
} else if (reading.kind === 'besteffort') {
|
||||
meterSlot.title = 'Read from the agent\'s session log: undocumented, so it may stop working after an update';
|
||||
} else {
|
||||
meterSlot.title = 'How full the agent context is, as the agent reports it';
|
||||
}
|
||||
}
|
||||
|
||||
// Every two seconds while an agent runs: draw the meter and, once per run,
|
||||
// suggest a Restart when the context reaches the nudge percent.
|
||||
async function pollMeter() {
|
||||
if (!agentActive()) return;
|
||||
try {
|
||||
// The reading may land after a Restart: only a reading for the same run counts.
|
||||
const { generation, state } = agent;
|
||||
const reading = await invoke('agent_context');
|
||||
if (agent.generation !== generation || agent.state !== state) return;
|
||||
renderMeter(reading);
|
||||
if (nudgeDue(reading, nudgePercent) && state === 'running' && nudgeShownFor !== generation) {
|
||||
nudgeShownFor = generation;
|
||||
nudgeEl.hidden = false;
|
||||
}
|
||||
} catch {
|
||||
// A failed read is not a reading: look again on the next tick.
|
||||
}
|
||||
}
|
||||
|
||||
// Once, at start: when the app and the installed skills are on different versions the bar
|
||||
// says so and offers Update skills. Nothing runs until that button is pressed.
|
||||
async function checkVersions() {
|
||||
try {
|
||||
const status = await invoke('version_status');
|
||||
if (!status.mismatch) return;
|
||||
if (status.skills_ahead) {
|
||||
// The skills are ahead of this app: another Update skills run cannot help.
|
||||
versionTextEl.textContent = `The installed skills are v${status.skills}, newer than this app (v${status.app}). Get the new app.`;
|
||||
versionBtn.hidden = true;
|
||||
} else {
|
||||
versionTextEl.textContent = `Skills are v${status.skills}, this app is v${status.app}`;
|
||||
versionBtn.hidden = false;
|
||||
}
|
||||
versionEl.hidden = false;
|
||||
} catch {
|
||||
// No version to compare is no reason to nag.
|
||||
}
|
||||
}
|
||||
|
||||
versionBtn.onclick = async () => {
|
||||
versionBtn.disabled = true;
|
||||
versionRestartBtn.hidden = true;
|
||||
versionTextEl.textContent = 'Updating Plan2Code...';
|
||||
const progress = new Channel();
|
||||
progress.onmessage = (line) => {
|
||||
if (line) versionTextEl.textContent = line;
|
||||
};
|
||||
try {
|
||||
const outcome = await invoke('update_skills', { progress });
|
||||
versionTextEl.textContent = outcome.status.mismatch
|
||||
? `Updated, but the mismatch remains (skills v${outcome.status.skills}, app v${outcome.status.app}).`
|
||||
: 'Updated. Restart the console to use the new version.';
|
||||
versionBtn.hidden = true;
|
||||
versionRestartBtn.hidden = outcome.status.mismatch;
|
||||
} catch (error) {
|
||||
versionTextEl.textContent = String(error);
|
||||
versionBtn.disabled = false;
|
||||
}
|
||||
};
|
||||
|
||||
versionRestartBtn.onclick = async () => {
|
||||
versionRestartBtn.disabled = true;
|
||||
try {
|
||||
await invoke('console_stop');
|
||||
} catch {
|
||||
// Nothing to stop is fine: reconnectConsole starts a fresh one either way.
|
||||
}
|
||||
versionEl.hidden = true;
|
||||
await reconnectConsole();
|
||||
};
|
||||
|
||||
// A page the agent's `console.mjs open` asked this window to show.
|
||||
const pageLabel = (workflow) => (workflow || '').replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
|
||||
|
||||
function showAnnounced(notice) {
|
||||
restarting = false;
|
||||
currentPageEl.textContent = pageLabel(notice.workflow);
|
||||
if (!consoleKnown) {
|
||||
consoleKnown = true;
|
||||
if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS);
|
||||
}
|
||||
markConsoleAlive();
|
||||
if (notice.url !== currentUrl) {
|
||||
showState('Opening the page');
|
||||
loadFrame(notice.url);
|
||||
}
|
||||
}
|
||||
|
||||
window.__TAURI__.event.listen('console-page', (event) => showAnnounced(event.payload));
|
||||
|
||||
function markConsoleAlive() {
|
||||
consoleStatusEl.textContent = '';
|
||||
consoleAgainBtn.hidden = true;
|
||||
}
|
||||
|
||||
function markConsoleDead() {
|
||||
consoleStatusEl.textContent = 'The console stopped.';
|
||||
consoleAgainBtn.hidden = false;
|
||||
}
|
||||
|
||||
consoleAgainBtn.onclick = () => reconnectConsole();
|
||||
|
||||
function setProjectDir(dir) {
|
||||
projectDirEl.textContent = dir;
|
||||
projectDirEl.title = dir;
|
||||
}
|
||||
|
||||
// The state `main()` read at startup: `pickFolder()` and the first-run
|
||||
// checklist both need it once a folder lands, after the fact.
|
||||
let appState = null;
|
||||
|
||||
// Opens the OS folder picker. A cancelled pick (or a failed one) lands on the
|
||||
// "No project folder chosen" state with a button that tries again.
|
||||
async function pickFolder() {
|
||||
try {
|
||||
const dir = await invoke('pick_project_folder');
|
||||
if (!dir) {
|
||||
showState('No project folder chosen', 'Choose folder', pickFolder);
|
||||
return;
|
||||
}
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
afterProjectKnown();
|
||||
} catch (error) {
|
||||
showState(`Could not open the folder picker: ${error}`, 'Choose folder', pickFolder);
|
||||
}
|
||||
}
|
||||
|
||||
// Once a project folder is known: the first-run checklist (once, until it
|
||||
// passes) or straight to the launch card.
|
||||
function afterProjectKnown() {
|
||||
if (appState && !appState.firstRunDone) {
|
||||
showFirstRun(appState);
|
||||
} else {
|
||||
showLaunchCard();
|
||||
}
|
||||
}
|
||||
|
||||
// Switches to a folder picked fresh: the Rust side tears the old project's
|
||||
// agent and console down before the new one is remembered, so nothing from
|
||||
// it carries over. Picking nothing (cancelled) leaves the current project as
|
||||
// it was.
|
||||
async function doChangeProject() {
|
||||
showState('Choose the new project folder...');
|
||||
try {
|
||||
const dir = await invoke('change_project');
|
||||
if (!dir) {
|
||||
if (agentActive()) hideState();
|
||||
else afterProjectKnown();
|
||||
return;
|
||||
}
|
||||
setProjectDir(dir);
|
||||
if (appState) appState.projectDir = dir;
|
||||
restarting = false;
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
currentPageEl.textContent = '';
|
||||
afterProjectKnown();
|
||||
} catch (error) {
|
||||
showState(`Could not switch project: ${error}`, 'Try again', doChangeProject);
|
||||
}
|
||||
}
|
||||
|
||||
function changeProject() {
|
||||
if (agentActive()) {
|
||||
showState(
|
||||
'Stop the running agent and switch to a different project? What it was doing is not saved.',
|
||||
'Change project',
|
||||
doChangeProject,
|
||||
() => (frameReady ? hideState() : showLaunchCard())
|
||||
);
|
||||
return;
|
||||
}
|
||||
doChangeProject();
|
||||
}
|
||||
|
||||
changeProjectBtn.onclick = changeProject;
|
||||
|
||||
// The launcher passed `--agent`: start it at once, on its model, with the
|
||||
// same bypass flags the terminal launcher itself always runs that agent with
|
||||
// (it offers no permission-mode choice of its own).
|
||||
async function autoStartAgent(state) {
|
||||
launchAgentEl.value = state.autoStart;
|
||||
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
|
||||
agentStatusEl.textContent = '';
|
||||
showState('Starting the agent...');
|
||||
const { cols, rows } = terminal.size();
|
||||
try {
|
||||
await invoke('agent_start', {
|
||||
kind: state.autoStart,
|
||||
model: state.launchModel || null,
|
||||
effort: null,
|
||||
mode: 'bypass',
|
||||
cols,
|
||||
rows,
|
||||
});
|
||||
terminal.focus();
|
||||
} catch (error) {
|
||||
agentStatusEl.textContent = `Could not start the agent: ${error}`;
|
||||
showLaunchCard();
|
||||
}
|
||||
}
|
||||
|
||||
// A page that just mounted registers its output channel and, if an agent
|
||||
// already ran before it (a reload, or this is the window's first paint
|
||||
// after one survived a restart), gets its recent output replayed onto a
|
||||
// clean xterm at once instead of starting blank.
|
||||
async function recoverAfterReload(snapshot) {
|
||||
applyAgentState(snapshot, { skipReset: true });
|
||||
terminal.focus();
|
||||
hideState();
|
||||
consoleKnown = true;
|
||||
if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS);
|
||||
try {
|
||||
const status = await invoke('console_status');
|
||||
if (status.state === 'running' && status.url) {
|
||||
loadFrame(status.url);
|
||||
} else {
|
||||
onNoHello();
|
||||
}
|
||||
} catch {
|
||||
onNoHello();
|
||||
}
|
||||
}
|
||||
|
||||
async function main() {
|
||||
let state;
|
||||
try {
|
||||
state = await invoke('app_state');
|
||||
} catch (error) {
|
||||
showState(`Could not read the app state: ${error}`, 'Retry', main);
|
||||
return;
|
||||
}
|
||||
appState = state;
|
||||
if (AGENT_LABELS[state.lastAgent]) launchAgentEl.value = state.lastAgent;
|
||||
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
|
||||
if (Number.isInteger(state.contextNudgePercent)) nudgePercent = state.contextNudgePercent;
|
||||
if (state.termPanel) {
|
||||
paneDock = state.termPanel.dock === 'right' ? 'right' : 'bottom';
|
||||
paneFraction = state.termPanel.fraction;
|
||||
paneCollapsed = Boolean(state.termPanel.collapsed);
|
||||
}
|
||||
applyPaneLayout();
|
||||
await loadAgentAvailability();
|
||||
refreshLaunchCard();
|
||||
setInterval(pollMeter, METER_POLL_MS);
|
||||
setInterval(updateBadge, BADGE_POLL_MS);
|
||||
checkVersions();
|
||||
|
||||
let reattach = null;
|
||||
try {
|
||||
reattach = await invoke('agent_reattach', { onOutput: agentChannel });
|
||||
} catch {
|
||||
// Nothing to reattach to is not fatal: carry on as a plain first paint.
|
||||
}
|
||||
if (reattach && reattach.state !== 'idle') {
|
||||
if (state.projectDir) setProjectDir(state.projectDir);
|
||||
await recoverAfterReload(reattach);
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.autoStart) {
|
||||
if (state.projectDir) setProjectDir(state.projectDir);
|
||||
await autoStartAgent(state);
|
||||
return;
|
||||
}
|
||||
if (state.projectDir) {
|
||||
setProjectDir(state.projectDir);
|
||||
afterProjectKnown();
|
||||
} else {
|
||||
pickFolder();
|
||||
}
|
||||
}
|
||||
|
||||
main();
|
||||
@@ -0,0 +1,211 @@
|
||||
<!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; }
|
||||
|
||||
#bar { flex: none; border-bottom: 1px solid #444; }
|
||||
#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-sep { flex: none; align-self: stretch; width: 1px; margin: 8px 0; background: #3a3a3a; }
|
||||
#title { font-weight: 600; font-size: 13px; }
|
||||
#project-dir { color: #9ab; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 220px; }
|
||||
#current-page { color: #8c8; }
|
||||
#current-page:not(:empty)::before { content: "page: "; color: #666; }
|
||||
#agent-name { color: #9ab; }
|
||||
#agent-name:not(:empty)::before { content: "agent: "; color: #666; }
|
||||
#console-status, #agent-status { color: #d7ba7d; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 260px; }
|
||||
#agent-restart[hidden], #change-agent[hidden] { display: none; }
|
||||
.bar-slot { flex: none; }
|
||||
#permissions-note { color: #888; }
|
||||
#context-nudge { display: flex; align-items: center; gap: 6px; color: #d7ba7d; }
|
||||
#context-nudge[hidden] { display: none; }
|
||||
#version-update { display: flex; align-items: center; gap: 6px; color: #d7ba7d; }
|
||||
#version-update[hidden], #version-update-button[hidden] { display: none; }
|
||||
#bar-slot-meter { display: flex; align-items: center; gap: 6px; color: #9ab; }
|
||||
#bar-slot-meter:empty { display: none; }
|
||||
.meter-track { display: inline-block; width: 64px; height: 8px; border: 1px solid #666; border-radius: 2px; overflow: hidden; background: #2a2a2a; }
|
||||
.meter-track.estimate { border-style: dashed; }
|
||||
.meter-fill { display: block; height: 100%; background: #6a9955; }
|
||||
.meter-track.estimate .meter-fill { background: repeating-linear-gradient(45deg, #6a9955 0 4px, transparent 4px 8px); }
|
||||
.meter-tag { color: #d7ba7d; font-style: italic; }
|
||||
|
||||
#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; }
|
||||
|
||||
#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-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; }
|
||||
#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">
|
||||
<span id="title">Plan2Code</span>
|
||||
<span id="project-dir"></span>
|
||||
<span id="bar-slot-restart" class="bar-slot"><button id="agent-restart" hidden>Restart</button></span>
|
||||
<span id="bar-slot-change-agent" class="bar-slot"><button id="change-agent" hidden>Change agent</button></span>
|
||||
<span id="bar-slot-change-project" class="bar-slot"><button id="change-project">Change project</button></span>
|
||||
<span id="bar-sep" aria-hidden="true"></span>
|
||||
<span id="current-page" title="The page the agent opened"></span>
|
||||
<span id="agent-name"></span>
|
||||
<span id="agent-status" role="status"></span>
|
||||
<span id="console-status"></span>
|
||||
<button id="console-again" hidden>Start it again</button>
|
||||
<span id="context-nudge" class="bar-slot" hidden>
|
||||
<span>Context is getting full: consider Restart</span>
|
||||
<button id="context-restart">Restart</button>
|
||||
</span>
|
||||
<!-- Shown only when the app and the installed skills are on different versions. -->
|
||||
<span id="version-update" class="bar-slot" hidden>
|
||||
<span id="version-update-text"></span>
|
||||
<button id="version-update-button">Update skills</button>
|
||||
<button id="version-update-restart" hidden>Restart the console</button>
|
||||
</span>
|
||||
<span id="bar-slot-meter" class="bar-slot"></span>
|
||||
<!-- Shown only while an agent is running, naming the real mode it started with. -->
|
||||
<span id="permissions-note" hidden></span>
|
||||
</div>
|
||||
</header>
|
||||
<div id="workspace">
|
||||
<main id="dashboard">
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard"></iframe>
|
||||
<div id="dashboard-state" hidden>
|
||||
<p id="dashboard-state-text"></p>
|
||||
<span>
|
||||
<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>
|
||||
<label for="launch-model">Model</label>
|
||||
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off">
|
||||
<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">
|
||||
Turn permission checks off for this agent
|
||||
</label>
|
||||
<p id="launch-bypass-warning" hidden>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,15 @@
|
||||
// The context meter'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).
|
||||
|
||||
/**
|
||||
* Whether `reading` (what the `agent_context` command returns) should fire
|
||||
* the Restart nudge at `nudgePercent`. Only a real or best-effort number
|
||||
* counts, per the context policy (pathfinder Question 11): an estimate is
|
||||
* not precise enough for "about 70%" to mean the window really is close to
|
||||
* full, so an estimate-only agent gets the meter but never the nudge.
|
||||
*/
|
||||
export function nudgeDue(reading, nudgePercent) {
|
||||
return (reading.kind === 'real' || reading.kind === 'besteffort') && reading.percent >= nudgePercent;
|
||||
}
|
||||
@@ -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(),
|
||||
};
|
||||
}
|
||||
@@ -10,10 +10,10 @@ An autonomous CLI tool that implements Plan2Code specs by looping through tasks
|
||||
# From the plan2code root directory:
|
||||
|
||||
# Option 1: Install everything (recommended)
|
||||
node install.js # Select option A
|
||||
node install.js # Select A (Advanced) → E (Everything)
|
||||
|
||||
# Option 2: Install loop only
|
||||
node install.js # Select option O
|
||||
node install.js # Select A (Advanced) → O (Loop CLI)
|
||||
|
||||
# Option 3: Manual build and link
|
||||
cd plan2code-loop
|
||||
|
||||
@@ -16,15 +16,17 @@
|
||||
// fcp first contentful paint: the person sees something
|
||||
// ready the session is drawn from real state (the menu, or a question)
|
||||
//
|
||||
// plus the bytes and request count the page cost. Needs puppeteer-core in
|
||||
// node_modules and a local Chrome or Edge for the browser columns; without
|
||||
// them it still reports url/cliExit and an HTTP-only waterfall.
|
||||
// plus the bytes and request count the page cost. The browser columns need
|
||||
// playwright-core (from `npm install`) and a local Chrome or Edge, picked by
|
||||
// scripts/browser.mjs; without a browser it still reports url/cliExit and an
|
||||
// HTTP-only waterfall.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -44,20 +46,6 @@ const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER
|
||||
// so a slow GitHub never colours the timings.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
function findBrowser() {
|
||||
if (args.browser === "none") return null;
|
||||
if (typeof args.browser === "string") return args.browser;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
// Resolves at the first stdout line carrying a url, and again at exit.
|
||||
// --launch hook (default): `open` launches "the browser" the way it would for
|
||||
// a person, through PLAN2CODE_BROWSER, and the hook just writes the link to
|
||||
@@ -211,18 +199,22 @@ async function roundtrip() {
|
||||
|
||||
async function main() {
|
||||
if (args.roundtrip) return roundtrip();
|
||||
const browserPath = findBrowser();
|
||||
let puppeteer = null;
|
||||
if (browserPath) {
|
||||
// --browser none: no launch at all. --browser <path>: that executable.
|
||||
// Otherwise the helper's pick; a browser problem is one line, then the
|
||||
// HTTP-only waterfall.
|
||||
let browser = null;
|
||||
let browserName = null;
|
||||
if (args.browser !== "none") {
|
||||
const custom = typeof args.browser === "string" ? args.browser : null;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
console.error("puppeteer-core not installed; browser columns skipped");
|
||||
browser = await launchBrowser(custom ? { executablePath: custom } : {});
|
||||
const found = custom ? null : findBrowser();
|
||||
browserName = found ? `${found.channel} (${found.path})` : custom;
|
||||
} catch (e) {
|
||||
if (!e.browserProblem) throw e;
|
||||
console.error(e.message);
|
||||
}
|
||||
}
|
||||
const browser = puppeteer
|
||||
? await puppeteer.launch({ executablePath: browserPath, headless: true, args: ["--no-first-run", "--no-default-browser-check"] })
|
||||
: null;
|
||||
|
||||
const rows = [];
|
||||
// One throwaway run so disk caches and the Node binary are warm; the person
|
||||
@@ -231,7 +223,7 @@ async function main() {
|
||||
stopAll();
|
||||
// The tab exists before the clock starts: a person's browser is already
|
||||
// running, and creating a context is the harness's cost, not the page's.
|
||||
const ctx = browser ? await browser.createBrowserContext() : null;
|
||||
const ctx = browser ? await browser.newContext() : null;
|
||||
const page = ctx ? await ctx.newPage() : null;
|
||||
const { t0, urlP, exitP, openP } = runOpen();
|
||||
const o = await openP;
|
||||
@@ -246,7 +238,7 @@ async function main() {
|
||||
page.on("response", async (res) => {
|
||||
requests++;
|
||||
try {
|
||||
bytes += (await res.buffer()).length;
|
||||
bytes += (await res.body()).length;
|
||||
} catch {}
|
||||
});
|
||||
if (BROWSER_DELAY) await new Promise((r) => setTimeout(r, Math.max(0, o.at + BROWSER_DELAY - Date.now())));
|
||||
@@ -303,7 +295,7 @@ async function main() {
|
||||
};
|
||||
const summary = Object.fromEntries(cols.map((k) => [k, stat(k)]));
|
||||
console.log(`web console start-up, ${RUNS} runs, workflow=${WORKFLOW}, cwd=${CWD}`);
|
||||
console.log(`browser: ${browser ? browserPath : "none (HTTP-only waterfall)"}`);
|
||||
console.log(`browser: ${browser ? browserName : "none (HTTP-only waterfall)"}`);
|
||||
console.log("metric".padEnd(10) + "median".padStart(9) + "min".padStart(9) + "max".padStart(9));
|
||||
for (const k of cols) {
|
||||
const s = summary[k];
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Picks and launches the browser for page tests and the dev scripts. Dev-only:
|
||||
// lives in scripts/ so it never ships inside a skill.
|
||||
//
|
||||
// The first installed of Chrome then Edge, through playwright-core (a root
|
||||
// devDependency); PLAN2CODE_TEST_BROWSER=chrome or msedge forces one. Every
|
||||
// failure is one line in our own words, never Playwright's install hint.
|
||||
|
||||
import fs from "node:fs";
|
||||
|
||||
// The fixed places each browser installs to, probed in order on every
|
||||
// platform (a path that cannot exist here is simply not found).
|
||||
export const BROWSER_PATHS = {
|
||||
chrome: [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/google-chrome-stable",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
],
|
||||
msedge: [
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/microsoft-edge",
|
||||
"/usr/bin/microsoft-edge-stable",
|
||||
],
|
||||
};
|
||||
|
||||
const CHANNELS = Object.keys(BROWSER_PATHS);
|
||||
|
||||
// Returns { channel, path } for the first browser found, or null. Either way
|
||||
// findBrowser.checked lists every path this call looked at.
|
||||
export function findBrowser({ env = process.env, exists = fs.existsSync } = {}) {
|
||||
const forced = env.PLAN2CODE_TEST_BROWSER;
|
||||
if (forced && !CHANNELS.includes(forced)) {
|
||||
throw new Error(`PLAN2CODE_TEST_BROWSER must be ${CHANNELS.join(" or ")} (it is "${forced}").`);
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
for (const channel of forced ? [forced] : CHANNELS) {
|
||||
for (const p of BROWSER_PATHS[channel]) {
|
||||
findBrowser.checked.push(p);
|
||||
if (exists(p)) return { channel, path: p };
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
findBrowser.checked = [];
|
||||
|
||||
// null when page tests can run here, otherwise the one line that says why
|
||||
// not. `checked` defaults to the paths the last findBrowser() call probed.
|
||||
export function browserProblem({ nodeVersion = process.versions.node, found, checked = findBrowser.checked } = {}) {
|
||||
if (Number(nodeVersion.split(".")[0]) < 20) {
|
||||
return `Page tests need Node 20 or newer (this is ${nodeVersion}). Users of Plan2Code still only need Node 18.`;
|
||||
}
|
||||
if (!found) {
|
||||
return `Page tests need Chrome or Edge. Looked in: ${checked.join(", ")}. Install either one, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Launches the browser findBrowser() picks, headless. `options` go to
|
||||
// Playwright's chromium.launch() as they are (an `executablePath` there skips
|
||||
// the pick); `find` hands findBrowser() its env and exists, for tests. A
|
||||
// problem rejects with an Error whose message is our one line and whose
|
||||
// `browserProblem` is true, never Playwright's own launch text.
|
||||
export async function launchBrowser(options = {}, find = {}) {
|
||||
const found = options.executablePath ? { channel: null, path: options.executablePath } : findBrowser(find);
|
||||
const problem = browserProblem({ found });
|
||||
if (problem) throw Object.assign(new Error(problem), { browserProblem: true });
|
||||
let chromium;
|
||||
try {
|
||||
({ chromium } = await import("playwright-core"));
|
||||
} catch (e) {
|
||||
throw Object.assign(new Error("Page tests need playwright-core: run npm install.", { cause: e }), { browserProblem: true });
|
||||
}
|
||||
try {
|
||||
return await chromium.launch({
|
||||
executablePath: found.path,
|
||||
headless: true,
|
||||
args: ["--no-first-run", "--no-default-browser-check"],
|
||||
...options,
|
||||
});
|
||||
} catch (e) {
|
||||
// Playwright's own text stays out of the message, but is kept as the
|
||||
// cause for whoever needs to debug a real launch failure.
|
||||
const line = `Page tests could not start the browser at ${found.path}. Install Chrome or Edge, or set PLAN2CODE_TEST_BROWSER.`;
|
||||
throw Object.assign(new Error(line, { cause: e }), { browserProblem: true });
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
// it never ships inside a skill.
|
||||
//
|
||||
// node scripts/capture-screenshots.mjs [--only <shot>] [--browser <path>]
|
||||
// [--out <dir>]
|
||||
// [--out <dir>] [--compare]
|
||||
//
|
||||
// Every shot is staged with no agent: a throwaway sample project called
|
||||
// `task-api`, a throwaway console home (PLAN2CODE_CONSOLE_HOME), then
|
||||
@@ -13,17 +13,28 @@
|
||||
// The shots use the console's Ocean highlight rather than its default orange:
|
||||
// it is the console's nearest to the Plan2Code blue the site and README use.
|
||||
//
|
||||
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask.
|
||||
// Shots: dashboard, dashboard-utilities, question, doc, build, signoff, finish, ask, git.
|
||||
// --compare adds workspace, stop, delete, help, prefs and cleanup: screens the
|
||||
// docs never show, for checking a change by eye against a "before" set. Its
|
||||
// --out must be outside docs/screenshots/, so the set is never published.
|
||||
//
|
||||
// Needs puppeteer-core (`npm i --no-save puppeteer-core`, never added to
|
||||
// package.json) and a local Chrome or Edge. Writes nothing outside its temp
|
||||
// folders and --out.
|
||||
// --snapshot <file> (used by scripts/css-snapshot.mjs) takes no pictures: it
|
||||
// writes every element's computed style, per screen, theme and width, to <file>.
|
||||
// It sees what these shots stage: choice, multi, text, review and confirm cards;
|
||||
// a checklist, list, recap or menu card is not staged, so a rule only they use
|
||||
// is not covered.
|
||||
//
|
||||
// Needs playwright-core (a root devDependency, so `npm install` brings it) and
|
||||
// a local Chrome or Edge, launched through scripts/browser.mjs. Playwright has
|
||||
// no WebP screenshots, so each shot is taken over CDP. Writes nothing outside
|
||||
// its temp folders and --out.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
@@ -53,13 +64,13 @@ const SHOTS = {
|
||||
scrollTo: ".dash-toggle",
|
||||
mustShow: ".dash-card:has(.pill.suggested)",
|
||||
},
|
||||
// The utility cards sit even lower: scroll until the Git commit card is the
|
||||
// The utility cards sit even lower: scroll until the Git card is the
|
||||
// last row in frame ("cmd:" picks a card by its command).
|
||||
"dashboard-utilities": {
|
||||
workflow: "dashboard",
|
||||
posts: ["dashboard"],
|
||||
scrollTo: "cmd:/plan2code-git-commit",
|
||||
mustShow: "cmd:/plan2code-git-commit",
|
||||
scrollTo: "cmd:/plan2code-git",
|
||||
mustShow: "cmd:/plan2code-git",
|
||||
},
|
||||
question: { workflow: "plan", posts: ["question"] },
|
||||
doc: { workflow: "plan", posts: ["doc"], tab: "What we've agreed" },
|
||||
@@ -67,6 +78,128 @@ const SHOTS = {
|
||||
signoff: { workflow: "implement", posts: ["signoff"] },
|
||||
finish: { workflow: "implement", posts: ["signoff", "finish"] },
|
||||
ask: { workflow: "plan", posts: ["question"], ask: "Where are tasks paged?" },
|
||||
// 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 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 });
|
||||
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);
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// --compare only: the screens the docs never show, shot so a change to the
|
||||
// console can be checked against a "before" set by eye. `open` runs on the
|
||||
// page after every load and clicks through to the screen. Never published.
|
||||
const COMPARE_SHOTS = {
|
||||
// The confirm dialog, with the handoff choice beside plain stop.
|
||||
stop: {
|
||||
workflow: "implement",
|
||||
posts: ["stop"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-stop");
|
||||
await page.waitForSelector("#stop-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// The first step of a spec chip's delete.
|
||||
delete: {
|
||||
workflow: "dashboard",
|
||||
posts: ["delete"],
|
||||
open: async (page) => {
|
||||
await page.locator(".spec-chip-del").first().click({ force: true });
|
||||
await page.waitForSelector("#delete-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Help on its first tab, whatever topic it opened on.
|
||||
help: {
|
||||
workflow: "plan",
|
||||
posts: ["help"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-about");
|
||||
await page.locator("#help-tabs .help-tab").first().click();
|
||||
await page.waitForSelector("#help-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
prefs: {
|
||||
workflow: "plan",
|
||||
posts: ["prefs"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
// Preferences scrolled to Cleanup once its scan has answered.
|
||||
cleanup: {
|
||||
workflow: "plan",
|
||||
posts: ["cleanup"],
|
||||
open: async (page) => {
|
||||
await page.click("#btn-looks");
|
||||
await page.waitForSelector("#looks-modal[open]", { timeout: 10000 });
|
||||
await page.locator(".looks-cleanup").scrollIntoViewIfNeeded();
|
||||
await page.click("#cleanup-scan");
|
||||
await page.waitForFunction(() => document.getElementById("cleanup-status").textContent.trim() !== "", null, { timeout: 15000 }).catch(() => {});
|
||||
},
|
||||
},
|
||||
// The panel open with two folders: the project and a sibling added once.
|
||||
// Last, since the console remembers the folder for the project and every
|
||||
// later shot's footer would count it.
|
||||
workspace: {
|
||||
workflow: "plan",
|
||||
posts: ["workspace"],
|
||||
open: async (page) => {
|
||||
const extra = makeExtraFolder();
|
||||
await page.evaluate(async (dir) => {
|
||||
const now = await (await fetch("/workspace", { cache: "no-store" })).json();
|
||||
if ((now.folders || []).length < 2) {
|
||||
await fetch("/workspace/add", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ path: dir, name: "task-web", description: "The web app that calls the API" }),
|
||||
});
|
||||
}
|
||||
}, extra);
|
||||
await page.click("#footer-where");
|
||||
await page.waitForSelector("#workspace-modal[open] #workspace-list li:nth-child(2)", { timeout: 10000 });
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
// On Windows the temp dir sits under the user's profile, and the page can
|
||||
@@ -86,21 +219,6 @@ function fail(message) {
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
function findBrowser() {
|
||||
if (typeof args.browser === "string") return fs.existsSync(args.browser) ? args.browser : null;
|
||||
const candidates = [
|
||||
"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe",
|
||||
"C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe",
|
||||
"/Applications/Google Chrome.app/Contents/MacOS/Google Chrome",
|
||||
"/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge",
|
||||
"/usr/bin/google-chrome",
|
||||
"/usr/bin/chromium",
|
||||
"/usr/bin/chromium-browser",
|
||||
];
|
||||
return candidates.find((p) => fs.existsSync(p)) || null;
|
||||
}
|
||||
|
||||
function phaseFile(n, name, tasks, done) {
|
||||
const lines = tasks.map((t, i) => `- [${done ? "x" : " "}] **Task ${n}.${i + 1}:** ${t}`).join("\n");
|
||||
return `# Phase ${n}: ${name}\n\n**Status:** ${done ? "Complete" : "Not Started"}\n\n## Tasks\n\n${lines}\n`;
|
||||
@@ -166,6 +284,54 @@ function makeSampleProject() {
|
||||
return project;
|
||||
}
|
||||
|
||||
// The Workspace shot's second folder, beside the sample project.
|
||||
function makeExtraFolder() {
|
||||
const dir = path.join(SCRATCH, "task-web");
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, "README.md"), "# task-web\n\nThe web app that lists and edits a team's tasks.\n");
|
||||
return dir;
|
||||
}
|
||||
|
||||
function git(cwd, ...gitArgs) {
|
||||
const r = spawnSync("git", gitArgs, { cwd, env: ENV, encoding: "utf8" });
|
||||
if (r.status !== 0) throw new Error(`git ${gitArgs.join(" ")} failed: ${(r.stderr || "").trim()}`);
|
||||
}
|
||||
|
||||
// The git shot's project: the same sample in a repository whose feature branch
|
||||
// is pushed to a local bare "origin" and has three changes to commit, so the
|
||||
// board opens on Changes with Commit as the next step. It sits in its own
|
||||
// folder so the other shots never see a repository.
|
||||
let GIT_PROJECT = null;
|
||||
function makeGitProject() {
|
||||
if (GIT_PROJECT) return GIT_PROJECT;
|
||||
const parent = path.join(SCRATCH, "git");
|
||||
fs.mkdirSync(parent, { recursive: true });
|
||||
const origin = path.join(parent, "origin.git");
|
||||
git(parent, "init", "--bare", "--initial-branch=main", origin);
|
||||
const prev = SCRATCH;
|
||||
SCRATCH = parent;
|
||||
const project = makeSampleProject();
|
||||
SCRATCH = prev;
|
||||
const id = ["-c", "user.name=Sam Rivera", "-c", "user.email=sam@example.com", "-c", "commit.gpgsign=false"];
|
||||
git(project, "init", "--initial-branch=main");
|
||||
git(project, "remote", "add", "origin", origin);
|
||||
git(project, "add", "-A");
|
||||
git(project, ...id, "commit", "-m", "Scaffold the task API and its specs");
|
||||
git(project, "push", "-u", "origin", "main");
|
||||
git(project, "switch", "-c", "feature/task-endpoints");
|
||||
fs.writeFileSync(path.join(project, "src", "tasks", "routes.js"), "// The /tasks routes.\nexport default async function routes(app) {}\n");
|
||||
git(project, "add", "-A");
|
||||
git(project, ...id, "commit", "-m", "Register the /tasks routes plugin");
|
||||
git(project, "push", "-u", "origin", "feature/task-endpoints");
|
||||
// A fetch stamps FETCH_HEAD, so the board says "Last refreshed" rather than "Never".
|
||||
git(project, "fetch", "origin");
|
||||
fs.appendFileSync(path.join(project, "src", "tasks", "paginate.js"), "\nexport const MAX_LIMIT = 50;\n");
|
||||
fs.writeFileSync(path.join(project, "src", "tasks", "schema.js"), "// The Zod schema for a task.\nexport const taskSchema = {};\n");
|
||||
fs.appendFileSync(path.join(project, "specs", "task-api", "phase-3.md"), "\n<!-- Task 3.1 in progress -->\n");
|
||||
GIT_PROJECT = project;
|
||||
return project;
|
||||
}
|
||||
|
||||
function cli(cwd, ...cliArgs) {
|
||||
const r = spawnSync(process.execPath, [CONSOLE_CLI, ...cliArgs], { cwd, env: ENV, encoding: "utf8" });
|
||||
const line = (r.stdout || "").trim().split("\n").pop() || "";
|
||||
@@ -182,8 +348,7 @@ function post(project, sid, name) {
|
||||
}
|
||||
|
||||
// Opens a session for the shot and posts its payloads. Returns { sid, url }.
|
||||
function stage(project, shot) {
|
||||
const spec = SHOTS[shot];
|
||||
function stage(project, spec) {
|
||||
const r = cli(project, "open", "--workflow", spec.workflow, "--no-open");
|
||||
if (r.code !== 0 || !r.out || !r.out.url) throw new Error(`open failed (${r.code}): ${r.err.trim()}`);
|
||||
for (const name of spec.posts) post(project, r.out.sid, name);
|
||||
@@ -193,9 +358,9 @@ function stage(project, shot) {
|
||||
// Waits for the page to draw real state, then lets the animations finish
|
||||
// (the dashboard's wake-up is the longest).
|
||||
async function settle(page) {
|
||||
await page.waitForNetworkIdle({ idleTime: 500, timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(3500);
|
||||
await page.waitForLoadState("networkidle", { timeout: 15000 }).catch(() => {});
|
||||
await page.waitForSelector(".dash-card, .card, .handoff, .ask-pane, .doc, .git-board", { timeout: 15000 }).catch(() => {});
|
||||
await sleep(args.snapshot ? 1800 : 3500);
|
||||
}
|
||||
|
||||
async function openTab(page, label) {
|
||||
@@ -208,7 +373,7 @@ async function openTab(page, label) {
|
||||
|
||||
async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const problem = await page.evaluate(
|
||||
(topSel, showSel) => {
|
||||
([topSel, showSel]) => {
|
||||
const find = (sel) =>
|
||||
sel.startsWith("cmd:")
|
||||
? [...document.querySelectorAll(".dash-card")].find((c) => c.querySelector(".dash-card-cmd")?.textContent.trim() === sel.slice(4))
|
||||
@@ -222,24 +387,95 @@ async function scrollTo(page, { scrollTo: top, mustShow }) {
|
||||
const r = show.getBoundingClientRect();
|
||||
return r.top >= 0 && r.bottom <= window.innerHeight ? null : `${showSel} is not wholly in view`;
|
||||
},
|
||||
top,
|
||||
mustShow || null
|
||||
[top, mustShow || null]
|
||||
);
|
||||
if (problem) console.log(` warning: ${problem}`);
|
||||
await sleep(300);
|
||||
}
|
||||
|
||||
// The properties that change how a stylesheet move would look.
|
||||
const SNAP_PROPS = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
// Recorded after the properties above, for every element: what names its animation.
|
||||
// A property a running animation is moving is recorded as "~" (it differs from run
|
||||
// to run), so a rule that adds or removes an animation shows in these fields instead.
|
||||
const SNAP_ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
const SNAP = {};
|
||||
|
||||
async function snapshotNow(page) {
|
||||
return page.evaluate(
|
||||
([props, animation]) => {
|
||||
const out = {};
|
||||
const seen = new Map();
|
||||
for (const el of document.querySelectorAll("*")) {
|
||||
const parent = el.parentElement;
|
||||
const key = parent ? (seen.get(parent) || "") : "";
|
||||
const sib = parent ? [...parent.children].indexOf(el) : 0;
|
||||
const cls = typeof el.className === "string" ? el.className.trim().split(/\s+/).filter(Boolean).slice(0, 3).join(".") : "";
|
||||
const path = (parent ? key + ">" : "") + el.tagName.toLowerCase() + (el.id ? "#" + el.id : "") + (cls ? "." + cls : "") + "[" + sib + "]";
|
||||
seen.set(el, path);
|
||||
const cs = getComputedStyle(el);
|
||||
const moving = new Set();
|
||||
for (const a of el.getAnimations ? el.getAnimations() : []) {
|
||||
for (const kf of a.effect && a.effect.getKeyframes ? a.effect.getKeyframes() : []) {
|
||||
for (const k of Object.keys(kf)) if (!["offset", "easing", "composite", "computedOffset"].includes(k)) moving.add(k.replace(/[A-Z]/g, (c) => "-" + c.toLowerCase()));
|
||||
}
|
||||
}
|
||||
out[path] = props.map((p) => (moving.has(p) ? "~" : cs.getPropertyValue(p))).concat(animation.map((p) => cs.getPropertyValue(p))).join("|");
|
||||
}
|
||||
return out;
|
||||
},
|
||||
[SNAP_PROPS, SNAP_ANIMATION]
|
||||
);
|
||||
}
|
||||
|
||||
async function snapshotShot(page, name, theme) {
|
||||
for (const [w, h] of [[1280, 800], [390, 844]]) {
|
||||
await page.setViewportSize({ width: w, height: h });
|
||||
await sleep(1500);
|
||||
SNAP[`${name}/${theme}/${w}`] = await snapshotNow(page);
|
||||
}
|
||||
await page.setViewportSize({ width: 1280, height: 800 });
|
||||
}
|
||||
|
||||
async function shoot(page, name) {
|
||||
const written = [];
|
||||
// Math.random picks Planny's mood variants; pinned so two runs draw the same page.
|
||||
if (args.snapshot) await page.addInitScript(() => { Math.random = () => 0.5; });
|
||||
for (const theme of THEMES) {
|
||||
await page.emulateMediaFeatures([{ name: "prefers-color-scheme", value: theme }]);
|
||||
await page.emulateMedia({ colorScheme: theme });
|
||||
// The theme is applied at load, so reload rather than trust a live switch.
|
||||
await page.reload({ waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
if (page.__tab) await openTab(page, page.__tab);
|
||||
if (page.__scroll && page.__scroll.scrollTo) await scrollTo(page, page.__scroll);
|
||||
if (page.__open) {
|
||||
await page.__open(page);
|
||||
await sleep(600);
|
||||
}
|
||||
if (args.snapshot) {
|
||||
await snapshotShot(page, name, theme);
|
||||
continue;
|
||||
}
|
||||
const file = path.join(OUT, `${name}-${theme}.webp`);
|
||||
await page.screenshot({ type: "webp", quality: QUALITY, path: file });
|
||||
const cdp = await page.context().newCDPSession(page);
|
||||
// Without a clip the capture comes out in CSS pixels; a clip of the
|
||||
// viewport at scale 2 is the twice-density shot (byte for byte what
|
||||
// Playwright's own PNG screenshot takes).
|
||||
const clip = { x: 0, y: 0, width: 1280, height: 800, scale: 2 };
|
||||
const { data } = await cdp.send("Page.captureScreenshot", { format: "webp", quality: QUALITY, captureBeyondViewport: false, clip });
|
||||
await cdp.detach();
|
||||
fs.writeFileSync(file, Buffer.from(data, "base64"));
|
||||
const kb = Math.round(fs.statSync(file).size / 1024);
|
||||
console.log(`${path.basename(file)} ${kb} KB`);
|
||||
if (kb > WARN_KB) console.log(` warning: ${path.basename(file)} is over ${WARN_KB} KB`);
|
||||
@@ -249,15 +485,15 @@ async function shoot(page, name) {
|
||||
}
|
||||
|
||||
// Opens the page for a staged session and saves both themes.
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
async function capture(browser, url, name, { tab, scrollTo: top, mustShow, open }) {
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
page.__tab = tab || null;
|
||||
page.__scroll = { scrollTo: top, mustShow };
|
||||
page.__open = open || null;
|
||||
return await shoot(page, name);
|
||||
} finally {
|
||||
await ctx.close();
|
||||
@@ -267,15 +503,14 @@ async function capture(browser, url, name, { tab, scrollTo: top, mustShow }) {
|
||||
// The Ask shot: a question typed and sent on the page, collected with `chat`
|
||||
// the way an agent would, and answered with a posted reply.
|
||||
async function captureAsk(browser, project, sid, url, question) {
|
||||
const ctx = await browser.createBrowserContext();
|
||||
const ctx = await browser.newContext({ viewport: { width: 1280, height: 800 }, deviceScaleFactor: 2 });
|
||||
try {
|
||||
const page = await ctx.newPage();
|
||||
await page.setViewport({ width: 1280, height: 800, deviceScaleFactor: 2 });
|
||||
await page.goto(url, { waitUntil: "domcontentloaded" });
|
||||
await settle(page);
|
||||
await openTab(page, "Ask");
|
||||
await page.waitForSelector("#ask-input:not([disabled])", { timeout: 10000 });
|
||||
await page.type("#ask-input", question);
|
||||
await page.locator("#ask-input").pressSequentially(question);
|
||||
await page.evaluate(() => {
|
||||
const send = [...document.querySelectorAll(".ask-composer button")].find((b) => b.textContent.trim() === "Send");
|
||||
if (send) send.click();
|
||||
@@ -317,21 +552,18 @@ async function captureAsk(browser, project, sid, url, question) {
|
||||
}
|
||||
|
||||
async function main() {
|
||||
const names = args.only ? [args.only] : Object.keys(SHOTS);
|
||||
for (const n of names) if (!SHOTS[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(SHOTS).join(", ")}`);
|
||||
|
||||
let puppeteer;
|
||||
try {
|
||||
puppeteer = (await import("puppeteer-core")).default;
|
||||
} catch {
|
||||
fail("puppeteer-core is not installed. Run: npm i --no-save puppeteer-core");
|
||||
const docs = path.join(ROOT, "docs", "screenshots");
|
||||
const fold = (p) => (process.platform === "win32" ? p.toLowerCase() : p);
|
||||
if (args.compare && (fold(OUT) === fold(docs) || fold(OUT).startsWith(fold(docs) + path.sep))) {
|
||||
fail(`--compare never writes into ${path.relative(ROOT, docs)}: pass --out with a folder outside it.`);
|
||||
}
|
||||
const browserPath = findBrowser();
|
||||
if (!browserPath) fail("No Chrome or Edge found. Pass one with --browser <path>.");
|
||||
const table = args.compare ? { ...SHOTS, ...COMPARE_SHOTS } : SHOTS;
|
||||
const names = args.only ? [args.only] : Object.keys(table);
|
||||
for (const n of names) if (!table[n]) fail(`Unknown shot "${n}". Shots: ${Object.keys(table).join(", ")}`);
|
||||
|
||||
SCRATCH = fs.mkdtempSync(path.join(SCRATCH_ROOT, "p2c-shots-"));
|
||||
HOME = path.join(SCRATCH, "console-home");
|
||||
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||
ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NOTEPADS_DIR: path.join(SCRATCH, "notepads"), PLAN2CODE_NO_BROWSER: "1" };
|
||||
fs.mkdirSync(HOME, { recursive: true });
|
||||
fs.mkdirSync(OUT, { recursive: true });
|
||||
let browser = null;
|
||||
@@ -342,20 +574,21 @@ async function main() {
|
||||
// and the Ocean highlight is the console's nearest to the Plan2Code blue
|
||||
// the landing page uses.
|
||||
fs.writeFileSync(path.join(HOME, "looks.json"), JSON.stringify({ looks: { role: "engineer", accent: "ocean", welcomeSeen: true } }));
|
||||
browser = await puppeteer.launch({
|
||||
executablePath: browserPath,
|
||||
headless: true,
|
||||
browser = await launchBrowser({
|
||||
...(typeof args.browser === "string" ? { executablePath: args.browser } : {}),
|
||||
args: ["--no-first-run", "--no-default-browser-check", "--mute-audio"],
|
||||
});
|
||||
for (const name of names) {
|
||||
const { sid, url } = stage(project, name);
|
||||
const where = table[name].repo ? makeGitProject() : project;
|
||||
const { sid, url } = stage(where, table[name]);
|
||||
try {
|
||||
if (SHOTS[name].ask) await captureAsk(browser, project, sid, url, SHOTS[name].ask);
|
||||
else await capture(browser, url, name, SHOTS[name]);
|
||||
if (table[name].ask) await captureAsk(browser, where, sid, url, table[name].ask);
|
||||
else await capture(browser, url, name, table[name]);
|
||||
} finally {
|
||||
cli(project, "stop", "--session", sid);
|
||||
cli(where, "stop", "--session", sid);
|
||||
}
|
||||
}
|
||||
if (args.snapshot) fs.writeFileSync(path.resolve(String(args.snapshot)), JSON.stringify(SNAP));
|
||||
} finally {
|
||||
if (browser) await browser.close();
|
||||
if (project) cli(project, "stop", "--all");
|
||||
|
||||
@@ -0,0 +1,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,10 @@
|
||||
// The console's stylesheet as the tests read it: the files under
|
||||
// public/styles/ joined in the server's own order, without the accent rules.
|
||||
// A rule moving between files never breaks a test; only a rule that changes
|
||||
// or vanishes does.
|
||||
|
||||
import { joinedStyles } from "../src/web-console/static.mjs";
|
||||
|
||||
export function joinedCss() {
|
||||
return joinedStyles().toString("utf8");
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
#!/usr/bin/env node
|
||||
// The cheapest check for a stylesheet move: every element's computed style, on
|
||||
// every screen the console has, in both themes, at desktop and phone width.
|
||||
// Dev-only, not in `npm test`. Stages the screens the way
|
||||
// scripts/capture-screenshots.mjs does (its --snapshot mode), so the sample
|
||||
// project and payloads are the same.
|
||||
//
|
||||
// node scripts/css-snapshot.mjs [--out <file>] write a snapshot
|
||||
// node scripts/css-snapshot.mjs --compare <file> take one now and print every difference
|
||||
//
|
||||
// Take a baseline before moving any rule, then compare after each move. Two
|
||||
// runs in a row on the same stylesheet report nothing: Math.random is pinned,
|
||||
// a property a running animation is moving is recorded as "~" (its animation
|
||||
// fields are still compared), and heights within 4px are ignored (see jitter).
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const CAPTURE = path.join(ROOT, "scripts", "capture-screenshots.mjs");
|
||||
|
||||
const args = {};
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
const a = process.argv[i];
|
||||
if (a.startsWith("--")) args[a.slice(2)] = process.argv[i + 1] && !process.argv[i + 1].startsWith("--") ? process.argv[++i] : true;
|
||||
}
|
||||
|
||||
function take(file) {
|
||||
// The screenshot script wants a folder to exist for --compare; nothing is written to it.
|
||||
const out = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-css-snap-"));
|
||||
try {
|
||||
const r = spawnSync(process.execPath, [CAPTURE, "--compare", "--snapshot", file, "--out", out], { stdio: ["ignore", "inherit", "inherit"] });
|
||||
if (r.status !== 0) {
|
||||
console.error("the snapshot run failed");
|
||||
process.exit(1);
|
||||
}
|
||||
} finally {
|
||||
fs.rmSync(out, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
const NAMES = [
|
||||
"display", "position", "top", "right", "bottom", "left", "width", "height", "min-width", "max-width", "min-height", "max-height",
|
||||
"margin-top", "margin-right", "margin-bottom", "margin-left", "padding-top", "padding-right", "padding-bottom", "padding-left",
|
||||
"color", "background-color", "background-image", "border-top-width", "border-right-width", "border-bottom-width", "border-left-width",
|
||||
"border-top-style", "border-top-color", "border-right-color", "border-bottom-color", "border-left-color", "border-top-left-radius",
|
||||
"font-family", "font-size", "font-weight", "font-style", "line-height", "letter-spacing", "text-align", "text-transform",
|
||||
"gap", "grid-template-columns", "grid-template-rows", "grid-column-start", "grid-column-end", "grid-row-start", "grid-row-end",
|
||||
"flex-direction", "flex-wrap", "flex-grow", "flex-shrink", "flex-basis", "align-items", "justify-content", "align-self",
|
||||
"overflow-x", "overflow-y", "opacity", "visibility", "transform", "z-index", "box-shadow", "cursor", "pointer-events", "white-space",
|
||||
"content", "outline-style", "transform-origin", "fill", "stroke",
|
||||
];
|
||||
const ANIMATION = ["animation-name", "animation-duration", "animation-delay", "animation-iteration-count", "animation-timing-function", "animation-direction", "animation-fill-mode"];
|
||||
|
||||
// A growing answer box at phone width settles a few pixels either way from one
|
||||
// run to the next with the same stylesheet; the heights it carries up the page
|
||||
// (and the transform origin, which is half of one) are not a stylesheet's doing.
|
||||
const JITTER = new Set(["height", "min-height", "transform-origin"]);
|
||||
function jitter(name, a, b) {
|
||||
if (!JITTER.has(name)) return false;
|
||||
const na = a.match(/-?\d+(?:\.\d+)?/g);
|
||||
const nb = b.match(/-?\d+(?:\.\d+)?/g);
|
||||
return !!na && !!nb && na.length === nb.length && na.every((n, i) => Math.abs(n - nb[i]) <= 4);
|
||||
}
|
||||
|
||||
function compare(before, after) {
|
||||
const diffs = [];
|
||||
for (const key of new Set([...Object.keys(before), ...Object.keys(after)])) {
|
||||
const a = before[key];
|
||||
const b = after[key];
|
||||
if (!a || !b) {
|
||||
diffs.push(`${key}: screen ${a ? "missing from the new run" : "is new"}`);
|
||||
continue;
|
||||
}
|
||||
for (const el of new Set([...Object.keys(a), ...Object.keys(b)])) {
|
||||
if (a[el] === b[el] || el.includes("p.dock-say")) continue; // the one line of Planny that types itself in, so its width moves
|
||||
if (a[el] === undefined || b[el] === undefined) {
|
||||
diffs.push(`${key} ${el}: element ${a[el] === undefined ? "added" : "gone"}`);
|
||||
continue;
|
||||
}
|
||||
const x = a[el].split("|");
|
||||
const y = b[el].split("|");
|
||||
const names = NAMES.concat(ANIMATION);
|
||||
x.forEach((v, i) => {
|
||||
if (v !== y[i] && v !== "~" && y[i] !== "~" && !jitter(names[i], v, y[i])) diffs.push(`${key} ${el} ${names[i] ?? i}: ${v} -> ${y[i]}`);
|
||||
});
|
||||
}
|
||||
}
|
||||
return diffs;
|
||||
}
|
||||
|
||||
if (args.compare === true) {
|
||||
console.error("usage: node scripts/css-snapshot.mjs --compare <snapshot file> (or --out <file> to take one)");
|
||||
process.exit(1);
|
||||
} else if (typeof args.compare === "string") {
|
||||
const tmp = path.join(os.tmpdir(), `p2c-css-snap-${process.pid}.json`);
|
||||
take(tmp);
|
||||
const diffs = compare(JSON.parse(fs.readFileSync(args.compare, "utf8")), JSON.parse(fs.readFileSync(tmp, "utf8")));
|
||||
fs.rmSync(tmp, { force: true });
|
||||
for (const d of diffs.slice(0, 200)) console.log(d);
|
||||
if (diffs.length > 200) console.log(`... and ${diffs.length - 200} more`);
|
||||
console.log(diffs.length ? `${diffs.length} difference(s)` : "no differences");
|
||||
process.exit(diffs.length ? 1 : 0);
|
||||
} else {
|
||||
const out = path.resolve(typeof args.out === "string" ? args.out : "css-snapshot.json");
|
||||
take(out);
|
||||
console.log(`wrote ${out} (${Math.round(fs.statSync(out).size / 1024)} KB)`);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
// Copy-on-use fixtures for the tests in scripts/.
|
||||
//
|
||||
// Building a git fixture means a run of git processes (init, config, add,
|
||||
// commit, remote, push), and on Windows each one costs a few hundred
|
||||
// milliseconds. copyFixture builds a fixture once per test file and hands
|
||||
// every caller its own copy of it, so a test can still change its repo freely.
|
||||
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
|
||||
const templates = new Map();
|
||||
const madeDirs = [];
|
||||
|
||||
const tempDir = (name) => {
|
||||
const dir = fs.mkdtempSync(path.join(fs.realpathSync.native(os.tmpdir()), `p2c-${name}-`));
|
||||
madeDirs.push(dir);
|
||||
return dir;
|
||||
};
|
||||
export const slashed = (p) => p.replace(/\\/g, "/");
|
||||
|
||||
/** Every .git/config in the copied tree, bounded two levels down (repo at the root or `repo/` + `origin.git/` beside it). */
|
||||
function gitConfigs(dir, depth = 2) {
|
||||
const out = [];
|
||||
const walk = (d, left) => {
|
||||
for (const entry of fs.readdirSync(d, { withFileTypes: true })) {
|
||||
const p = path.join(d, entry.name);
|
||||
if (entry.isDirectory() && entry.name === ".git") out.push(path.join(p, "config"));
|
||||
else if (entry.isDirectory() && left > 0) walk(p, left - 1);
|
||||
}
|
||||
};
|
||||
walk(dir, depth);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Remove the temp dirs copyFixture made. Suites call this in test.after. */
|
||||
export function fixtureCleanup() {
|
||||
for (const dir of madeDirs.splice(0)) fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
|
||||
/**
|
||||
* A fresh copy, in its own temp dir named for `name`, of the fixture `build`
|
||||
* makes. `build(dir)` runs once per `key` per process, into an empty dir.
|
||||
*
|
||||
* A remote that points inside the fixture (a bare origin beside the repo)
|
||||
* must be added with forward slashes, as `slashed()` gives it: every copied
|
||||
* .git/config (found by a bounded walk, so a repo a folder or two down still
|
||||
* gets it) has the template's path swapped for the copy's, so the copy pushes
|
||||
* to its own origin.
|
||||
*/
|
||||
export function copyFixture(name, key, build) {
|
||||
let template = templates.get(key);
|
||||
if (!template) {
|
||||
template = tempDir("template");
|
||||
build(template);
|
||||
templates.set(key, template);
|
||||
}
|
||||
const dir = tempDir(name);
|
||||
fs.cpSync(template, dir, { recursive: true, preserveTimestamps: true });
|
||||
for (const config of gitConfigs(dir)) {
|
||||
if (!fs.existsSync(config)) continue;
|
||||
const text = fs.readFileSync(config, "utf8");
|
||||
if (text.includes(slashed(template))) fs.writeFileSync(config, text.split(slashed(template)).join(slashed(dir)));
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
@@ -0,0 +1,360 @@
|
||||
// Git board fixture: canned state.git snapshots, one per journey step and edge case.
|
||||
//
|
||||
// A copy of specs/git-board-redesign/pathfinder/sketch-00/states.js, the repo
|
||||
// states every Pathfinder sketch moved between. Shape follows
|
||||
// src/web-console/git-repo.mjs snapshot(). `expect` is [primary op, secondary
|
||||
// op] under the agreed next-step rules (nextStep() in git-board.js), and
|
||||
// `expectTab` the tab that owns that step. Times are relative to a fixed NOW,
|
||||
// so ages read the same on every run.
|
||||
|
||||
export const NOW = Date.parse("2026-10-14T12:00:00Z");
|
||||
const ago = (mins) => new Date(NOW - mins * 60000).toISOString();
|
||||
|
||||
const ORIGIN = {
|
||||
name: "origin",
|
||||
url: "git@github.com:jparkerweb/plan2code.git",
|
||||
host: "github.com",
|
||||
web: "https://github.com/jparkerweb/plan2code",
|
||||
kind: "github",
|
||||
};
|
||||
|
||||
const pr = (head) => `https://github.com/jparkerweb/plan2code/compare/main...${head}?expand=1`;
|
||||
|
||||
const last = (subject, author, mins) => ({ subject, author, at: ago(mins) });
|
||||
|
||||
function local(name, extra = {}) {
|
||||
return {
|
||||
name,
|
||||
current: false,
|
||||
default: name === "main",
|
||||
remote: null,
|
||||
upstream: `origin/${name}`,
|
||||
upstreamRemote: "origin",
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
gone: false,
|
||||
merged: false,
|
||||
last: last("Update README", "Justin Parker", 60 * 24),
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
function remoteOnly(name, subject, author, mins) {
|
||||
return { name, current: false, default: false, remote: "origin", upstream: null, upstreamRemote: null, ahead: null, behind: null, gone: false, merged: false, last: last(subject, author, mins) };
|
||||
}
|
||||
|
||||
// The branches every journey shares; `current` and the current row's tracking are set per state.
|
||||
function branches(current, row = {}) {
|
||||
const rows = [
|
||||
local("main", { last: last("Release 4.12.0", "Justin Parker", 60 * 5) }),
|
||||
local("feature/ABC-12001-export-csv", { last: last("Add CSV export button to the audit view", "Justin Parker", 40) }),
|
||||
local("feature/ABC-11980-audit-filter", { last: last("Filter audit events by actor", "Priya Raman", 60 * 26) }),
|
||||
local("fix/ABC-11890-null-ticket", { merged: true, last: last("Guard against a null ticket id", "Sam Okafor", 60 * 24 * 6) }),
|
||||
local("chore/bump-deps", { merged: true, last: last("Bump dev dependencies", "Justin Parker", 60 * 24 * 9) }),
|
||||
remoteOnly("feature/ABC-12010-sso-banner", "Show SSO expiry banner", "Dana Whitfield", 60 * 3),
|
||||
remoteOnly("docs/readme-console", "Document the console's Ask tab", "Priya Raman", 60 * 24 * 2),
|
||||
];
|
||||
if (!rows.some((b) => b.name === current)) rows.splice(1, 0, local(current, { upstream: null, upstreamRemote: null, ahead: null, behind: null }));
|
||||
return rows.map((b) => (b.name === current && !b.remote ? { ...b, current: true, ...row } : b));
|
||||
}
|
||||
|
||||
const NO_CHANGES = { count: 0, heldBack: 0, files: [], untrackedDirs: [] };
|
||||
|
||||
const DIRTY_FEATURE = {
|
||||
count: 4,
|
||||
heldBack: 1,
|
||||
files: [
|
||||
{ path: "src/web-console/public/audit-export.js", state: "modified", staged: false, risky: false },
|
||||
{ path: "src/web-console/public/app.css", state: "modified", staged: false, risky: false },
|
||||
{ path: ".env.local", state: "new", staged: false, risky: true },
|
||||
],
|
||||
untrackedDirs: [{ path: "scripts/fixtures/audit/", files: 6 }],
|
||||
};
|
||||
|
||||
const DIRTY_MAIN = {
|
||||
count: 2,
|
||||
heldBack: 0,
|
||||
files: [
|
||||
{ path: "src/web-console/public/login.js", state: "modified", staged: false, risky: false },
|
||||
{ path: "scripts/test-login.mjs", state: "new", staged: false, risky: false },
|
||||
],
|
||||
untrackedDirs: [],
|
||||
};
|
||||
|
||||
function snap({ branch, ahead = 0, behind = 0, upstream, gone = false, changes = NO_CHANGES, inProgress = null, conflicted = [], lastFetch = ago(5), remotes = [ORIGIN], rows, prUrl = null, hasCommits = true, detached = null, rebasing }) {
|
||||
const up = upstream === undefined ? (branch ? `origin/${branch}` : null) : upstream;
|
||||
return {
|
||||
at: new Date(NOW).toISOString(),
|
||||
repo: true,
|
||||
hasCommits,
|
||||
head: { branch, detached, ...(rebasing ? { rebasing } : {}), upstream: up, gone, ahead: up ? ahead : null, behind: up ? behind : null },
|
||||
defaultBranch: "main",
|
||||
inProgress,
|
||||
conflicted,
|
||||
changes,
|
||||
remotes,
|
||||
lastFetch,
|
||||
refreshFailed: false,
|
||||
branches: rows || branches(branch, { upstream: up, upstreamRemote: up ? "origin" : null, ahead: up ? ahead : null, behind: up ? behind : null, gone }),
|
||||
prUrl,
|
||||
};
|
||||
}
|
||||
|
||||
const EXPORT = "feature/ABC-12001-export-csv";
|
||||
const LOGIN = "fix/ABC-12044-login-redirect";
|
||||
const FILTER = "feature/ABC-11980-audit-filter";
|
||||
|
||||
/** The three journeys, in click order. */
|
||||
export const JOURNEYS = [
|
||||
{ id: "commit-push", title: "Commit & push", states: ["cp-dirty", "cp-committing", "cp-ahead", "cp-pushing", "cp-pushed"] },
|
||||
{ id: "new-branch", title: "Start a new branch", states: ["nb-main-dirty", "nb-creating", "nb-unpublished", "nb-publishing", "nb-published"] },
|
||||
{ id: "pull-conflict", title: "Recover from a pull conflict", states: ["pc-diverged", "pc-pulling", "pc-conflict", "pc-resolved", "pc-continuing", "pc-rebased", "pc-pushing", "pc-pushed"] },
|
||||
];
|
||||
|
||||
/**
|
||||
* Every state: `git` (the snapshot), `journey` and `step` (or "edge"), `title`,
|
||||
* `expect` (primary op, secondary op or null), `expectTab` (the tab owning the
|
||||
* next step), `expectLine` where the line itself is pinned, `busy` (what is
|
||||
* running, when a git command is), `result` (the git-result notice after the
|
||||
* last action), and `on` (board op -> next state id) for the clicks a journey
|
||||
* takes.
|
||||
*/
|
||||
export const STATES = {
|
||||
/* Commit & push, on a published feature branch */
|
||||
"cp-dirty": {
|
||||
journey: "commit-push", step: 1, title: "4 changes on a feature branch (one held back)",
|
||||
git: snap({ branch: EXPORT, changes: DIRTY_FEATURE, prUrl: pr(EXPORT) }),
|
||||
expect: ["commit", "pr"],
|
||||
expectTab: "changes",
|
||||
on: { commit: "cp-committing" },
|
||||
},
|
||||
"cp-committing": {
|
||||
journey: "commit-push", step: 2, title: "Committing (busy)", busy: "Committing 3 files on feature/ABC-12001-export-csv",
|
||||
git: snap({ branch: EXPORT, changes: DIRTY_FEATURE, prUrl: pr(EXPORT) }),
|
||||
expect: ["commit", "pr"],
|
||||
expectTab: "changes",
|
||||
on: { done: "cp-ahead" },
|
||||
},
|
||||
"cp-ahead": {
|
||||
journey: "commit-push", step: 3, title: "Committed, 1 to push",
|
||||
result: { title: "Committed 3 files", body: "`9f3c2ab` Add CSV export button to the audit view. `.env.local` was held back." },
|
||||
git: snap({ branch: EXPORT, ahead: 1, changes: { count: 1, heldBack: 1, files: [DIRTY_FEATURE.files[2]], untrackedDirs: [] }, prUrl: pr(EXPORT) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { push: "cp-pushing" },
|
||||
},
|
||||
"cp-pushing": {
|
||||
journey: "commit-push", step: 4, title: "Pushing (busy)", busy: "Pushing 1 commit to origin",
|
||||
git: snap({ branch: EXPORT, ahead: 1, changes: { count: 1, heldBack: 1, files: [DIRTY_FEATURE.files[2]], untrackedDirs: [] }, prUrl: pr(EXPORT) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { done: "cp-pushed" },
|
||||
},
|
||||
"cp-pushed": {
|
||||
journey: "commit-push", step: 5, title: "Pushed, pull request ready",
|
||||
result: { title: "Pushed 1 commit to origin/feature/ABC-12001-export-csv", body: `\`9f3c2ab\`. [Open pull request](${pr(EXPORT)})` },
|
||||
git: snap({ branch: EXPORT, changes: { count: 1, heldBack: 1, files: [DIRTY_FEATURE.files[2]], untrackedDirs: [] }, prUrl: pr(EXPORT) }),
|
||||
expect: ["pr", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
|
||||
/* Start a new branch, from changes made on main */
|
||||
"nb-main-dirty": {
|
||||
journey: "new-branch", step: 1, title: "2 changes on main",
|
||||
git: snap({ branch: "main", changes: DIRTY_MAIN }),
|
||||
expect: ["create-commit", "commit"],
|
||||
expectTab: "changes",
|
||||
on: { "create-commit": "nb-creating", create: "nb-creating" },
|
||||
},
|
||||
"nb-creating": {
|
||||
journey: "new-branch", step: 2, title: "Creating the branch and committing (busy)", busy: "Creating fix/ABC-12044-login-redirect from origin/main, then committing 2 files",
|
||||
git: snap({ branch: "main", changes: DIRTY_MAIN }),
|
||||
expect: ["create-commit", "commit"],
|
||||
expectTab: "changes",
|
||||
on: { done: "nb-unpublished" },
|
||||
},
|
||||
"nb-unpublished": {
|
||||
journey: "new-branch", step: 3, title: "New branch with 1 commit, not published",
|
||||
result: { title: "Created fix/ABC-12044-login-redirect and committed 2 files", body: "`4e7d1c0` Redirect to the login page after SSO expiry." },
|
||||
git: snap({ branch: LOGIN, upstream: null }),
|
||||
expect: ["publish", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: { publish: "nb-publishing" },
|
||||
},
|
||||
"nb-publishing": {
|
||||
journey: "new-branch", step: 4, title: "Publishing (busy)", busy: "Publishing fix/ABC-12044-login-redirect to origin",
|
||||
git: snap({ branch: LOGIN, upstream: null }),
|
||||
expect: ["publish", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: { done: "nb-published" },
|
||||
},
|
||||
"nb-published": {
|
||||
journey: "new-branch", step: 5, title: "Published, pull request ready",
|
||||
result: { title: "Published fix/ABC-12044-login-redirect to origin", body: `[Open pull request](${pr(LOGIN)})` },
|
||||
git: snap({ branch: LOGIN, prUrl: pr(LOGIN) }),
|
||||
expect: ["pr", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
|
||||
/* Recover from a pull conflict */
|
||||
"pc-diverged": {
|
||||
journey: "pull-conflict", step: 1, title: "1 ahead, 3 behind",
|
||||
git: snap({ branch: FILTER, ahead: 1, behind: 3, prUrl: pr(FILTER) }),
|
||||
expect: ["pull", "push"],
|
||||
expectTab: "sync",
|
||||
on: { pull: "pc-pulling" },
|
||||
},
|
||||
"pc-pulling": {
|
||||
journey: "pull-conflict", step: 2, title: "Pulling (busy)", busy: "Pulling origin/feature/ABC-11980-audit-filter (rebase)",
|
||||
git: snap({ branch: FILTER, ahead: 1, behind: 3, prUrl: pr(FILTER) }),
|
||||
expect: ["pull", "push"],
|
||||
expectTab: "sync",
|
||||
on: { done: "pc-conflict" },
|
||||
},
|
||||
"pc-conflict": {
|
||||
journey: "pull-conflict", step: 3, title: "Rebase stopped on 2 conflicts, 1 with markers left",
|
||||
result: { title: "Pull stopped on 2 conflicts", body: "Replaying `b81e9d4` Filter audit events by actor (1 of 1). Plan2Code resolved `src/web-console/public/audit.js`; `src/web-console/public/audit.css` still has markers." },
|
||||
git: snap({
|
||||
branch: null, detached: "b81e9d4", rebasing: FILTER, upstream: null, inProgress: "rebase",
|
||||
conflicted: [
|
||||
{ path: "src/web-console/public/audit.js", markers: false },
|
||||
{ path: "src/web-console/public/audit.css", markers: true },
|
||||
],
|
||||
rows: branches(FILTER, { ahead: 1, behind: 3 }),
|
||||
}),
|
||||
expect: ["fix", "abort"],
|
||||
expectTab: "sync",
|
||||
on: { continue: "pc-conflict", abort: "pc-diverged", fix: "pc-resolved" },
|
||||
},
|
||||
"pc-resolved": {
|
||||
journey: "pull-conflict", step: 4, title: "Every conflict resolved",
|
||||
git: snap({
|
||||
branch: null, detached: "b81e9d4", rebasing: FILTER, upstream: null, inProgress: "rebase",
|
||||
conflicted: [
|
||||
{ path: "src/web-console/public/audit.js", markers: false },
|
||||
{ path: "src/web-console/public/audit.css", markers: false },
|
||||
],
|
||||
rows: branches(FILTER, { ahead: 1, behind: 3 }),
|
||||
}),
|
||||
expect: ["continue", "abort"],
|
||||
expectTab: "sync",
|
||||
on: { continue: "pc-continuing", abort: "pc-diverged" },
|
||||
},
|
||||
"pc-continuing": {
|
||||
journey: "pull-conflict", step: 5, title: "Continuing the rebase (busy)", busy: "Continuing the rebase",
|
||||
git: snap({
|
||||
branch: null, detached: "b81e9d4", rebasing: FILTER, upstream: null, inProgress: "rebase",
|
||||
conflicted: [
|
||||
{ path: "src/web-console/public/audit.js", markers: false },
|
||||
{ path: "src/web-console/public/audit.css", markers: false },
|
||||
],
|
||||
rows: branches(FILTER, { ahead: 1, behind: 3 }),
|
||||
}),
|
||||
expect: ["continue", "abort"],
|
||||
expectTab: "sync",
|
||||
on: { done: "pc-rebased" },
|
||||
},
|
||||
"pc-rebased": {
|
||||
journey: "pull-conflict", step: 6, title: "Rebased, 1 to push",
|
||||
result: { title: "Pull finished", body: "1 commit replayed on top of origin. Resolved `audit.js` (kept both filters) and `audit.css` (you fixed it). 1 commit ready to push." },
|
||||
git: snap({ branch: FILTER, ahead: 1, prUrl: pr(FILTER) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { push: "pc-pushing" },
|
||||
},
|
||||
"pc-pushing": {
|
||||
journey: "pull-conflict", step: 7, title: "Pushing (busy)", busy: "Pushing 1 commit to origin",
|
||||
git: snap({ branch: FILTER, ahead: 1, prUrl: pr(FILTER) }),
|
||||
expect: ["push", "pr"],
|
||||
expectTab: "sync",
|
||||
on: { done: "pc-pushed" },
|
||||
},
|
||||
"pc-pushed": {
|
||||
journey: "pull-conflict", step: 8, title: "Pushed, pull request ready",
|
||||
result: { title: `Pushed 1 commit to origin/${FILTER}`, body: `\`c42d7e1\`. [Open pull request](${pr(FILTER)})` },
|
||||
git: snap({ branch: FILTER, prUrl: pr(FILTER) }),
|
||||
expect: ["pr", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
|
||||
/* Edges that break layouts */
|
||||
"e-caught-up": {
|
||||
journey: "edge", title: "All caught up on main",
|
||||
git: snap({ branch: "main", rows: branches("main").map((b) => ({ ...b, merged: false })) }),
|
||||
expect: [null, "create"],
|
||||
expectTab: "sync",
|
||||
expectLine: "All caught up on main · checked 5 min. ago",
|
||||
on: {},
|
||||
},
|
||||
"e-stale": {
|
||||
journey: "edge", title: "All caught up, but last checked 3 hours ago",
|
||||
git: snap({ branch: "main", lastFetch: ago(180), rows: branches("main").map((b) => ({ ...b, merged: false })) }),
|
||||
expect: [null, "create"],
|
||||
expectTab: "sync",
|
||||
expectLine: "All caught up on main · checked 3 hr. ago",
|
||||
on: { refresh: "e-caught-up" },
|
||||
},
|
||||
"e-held-only": {
|
||||
journey: "edge", title: "Caught up except a held-back file",
|
||||
git: snap({ branch: "main", changes: { count: 1, heldBack: 1, files: [{ path: ".env.local", state: "new", staged: false, risky: true }], untrackedDirs: [] }, rows: branches("main").map((b) => ({ ...b, merged: false })) }),
|
||||
expect: [null, "ignore"],
|
||||
expectTab: "changes",
|
||||
on: {},
|
||||
},
|
||||
"e-gone": {
|
||||
journey: "edge", title: "Remote copy deleted",
|
||||
git: snap({ branch: "feature/ABC-11702-old-banner", gone: true }),
|
||||
expect: ["publish", "cleanup"],
|
||||
expectTab: "sync",
|
||||
on: {},
|
||||
},
|
||||
"e-no-remote": {
|
||||
journey: "edge", title: "No remote at all",
|
||||
git: snap({ branch: "main", upstream: null, remotes: [], lastFetch: null, rows: [local("main", { current: true, upstream: null, upstreamRemote: null, ahead: null, behind: null })] }),
|
||||
expect: [null, "create"],
|
||||
expectTab: "sync",
|
||||
expectLine: "Nothing to commit on main · no remote yet",
|
||||
on: {},
|
||||
},
|
||||
"e-first-commit": {
|
||||
journey: "edge", title: "No commits yet",
|
||||
git: snap({
|
||||
branch: "main", hasCommits: false, upstream: null, remotes: [], lastFetch: null, rows: [],
|
||||
changes: { count: 3, heldBack: 0, files: [{ path: "README.md", state: "new", staged: false, risky: false }, { path: "package.json", state: "new", staged: false, risky: false }], untrackedDirs: [{ path: "src/", files: 12 }] },
|
||||
}),
|
||||
expect: ["commit", null],
|
||||
expectTab: "changes",
|
||||
on: {},
|
||||
},
|
||||
"e-detached": {
|
||||
journey: "edge", title: "Detached at a commit",
|
||||
git: snap({ branch: null, detached: "a1b2c3d", upstream: null, rows: branches("main").map((b) => ({ ...b, current: false })) }),
|
||||
expect: ["create", "cleanup"],
|
||||
expectTab: "branches",
|
||||
on: {},
|
||||
},
|
||||
"e-many-branches": {
|
||||
journey: "edge", title: "300 branches, 40 merged",
|
||||
git: snap({
|
||||
branch: "main",
|
||||
rows: [
|
||||
local("main", { current: true }),
|
||||
...Array.from({ length: 120 }, (_, i) =>
|
||||
local(`feature/ABC-${11000 + i}-${["export", "filter", "banner", "login", "audit", "sso"][i % 6]}-${i}`, {
|
||||
merged: i < 40,
|
||||
ahead: i % 7 === 0 ? 2 : 0,
|
||||
behind: i % 5 === 0 ? 4 : 0,
|
||||
last: last(`Work on ABC-${11000 + i}`, ["Justin Parker", "Priya Raman", "Sam Okafor", "Dana Whitfield"][i % 4], 60 * (i + 1)),
|
||||
}),
|
||||
),
|
||||
...Array.from({ length: 179 }, (_, i) => remoteOnly(`feature/ABC-${12100 + i}-remote-${i}`, `Remote work ${i}`, "Dana Whitfield", 60 * 24 + i * 30)),
|
||||
],
|
||||
}),
|
||||
expect: ["cleanup", null],
|
||||
expectTab: "branches",
|
||||
on: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,127 @@
|
||||
// Start a real console and open its page in a real browser, for the page tests
|
||||
// (scripts/test-web-console-page-*.mjs).
|
||||
//
|
||||
// One browser per test file (pageSuite), a fresh console session and browser
|
||||
// context per test (openSession). Sessions run against the file's own console
|
||||
// home from web-console-test-helpers.mjs, in a temp project unless a test
|
||||
// names one. Any uncaught error on the page fails the test that opened it, so
|
||||
// a later split that breaks a screen shows as a named error, not a blank page.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { cli, payload, until, HOME, REMEMBERED } from "./web-console-test-helpers.mjs";
|
||||
import { launchBrowser } from "./browser.mjs";
|
||||
|
||||
// `test` is node:test's test function (or any context with .after): the
|
||||
// browser is launched the first time a test asks for it and closed once the
|
||||
// file is done.
|
||||
export function pageSuite(test) {
|
||||
let launching = null;
|
||||
test.after(async () => {
|
||||
if (launching) await (await launching).close();
|
||||
});
|
||||
return {
|
||||
browser: () => (launching ??= launchBrowser()),
|
||||
};
|
||||
}
|
||||
|
||||
let projects = 0;
|
||||
let payloads = 0;
|
||||
|
||||
// A fresh project folder under the file's console home, removed with it.
|
||||
export function tempProject(files = {}) {
|
||||
const dir = path.join(HOME, "projects", `p${++projects}`);
|
||||
for (const [rel, text] of Object.entries(files)) {
|
||||
fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true });
|
||||
fs.writeFileSync(path.join(dir, rel), text);
|
||||
}
|
||||
fs.mkdirSync(dir, { recursive: true });
|
||||
return dir;
|
||||
}
|
||||
|
||||
// Opens a console session the way an agent does (`console.mjs open`, then
|
||||
// `post`), and its page in a new browser context. Resolves once the page has
|
||||
// drawn from the session's real state, not the boot pane in the markup.
|
||||
// `t` is the test's context: stop() is registered with t.after, so a failing
|
||||
// test still cleans up, and a page error fails the test. `clock: true` gives
|
||||
// the page Playwright's fake clock before it loads (s.page.clock), so a test
|
||||
// can jump past the page's silence limits instead of sitting through them.
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
|
||||
fs.rmSync(REMEMBERED, { force: true });
|
||||
const cwd = project || tempProject();
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
|
||||
const s = {
|
||||
sid: opened.sid,
|
||||
session: opened.session,
|
||||
url: opened.url,
|
||||
project: cwd,
|
||||
errors: [],
|
||||
context: null,
|
||||
page: null,
|
||||
};
|
||||
|
||||
// The agent's side, run from the project like an agent would.
|
||||
s.post = (patch) => {
|
||||
const r = cli(["post", "--session", s.sid, "--file", payload(`page-post-${++payloads}.json`, patch)], { cwd });
|
||||
if (r.status !== 0) throw new Error(`post failed (${r.status}): ${r.stderr}`);
|
||||
return r.json;
|
||||
};
|
||||
s.wait = (seconds = 10) => {
|
||||
const r = cli(["wait", "--session", s.sid, "--seconds", String(seconds)], { cwd });
|
||||
return { code: r.status, ...(r.json || {}) };
|
||||
};
|
||||
// Whether the session's server still answers on its port.
|
||||
s.answers = async () => {
|
||||
try {
|
||||
await fetch(new URL("/health", s.url), { signal: AbortSignal.timeout(1000) });
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
let stopped = false;
|
||||
s.stop = async () => {
|
||||
if (stopped) return;
|
||||
stopped = true;
|
||||
cli(["stop", "--session", s.sid], { cwd });
|
||||
if (s.context) await s.context.close().catch(() => {});
|
||||
await until(async () => !(await s.answers()), 5000);
|
||||
};
|
||||
t.after(async () => {
|
||||
await s.stop();
|
||||
if (s.errors.length) throw new Error(`uncaught error on the page: ${s.errors[0]}`);
|
||||
});
|
||||
|
||||
if (first) s.post(first);
|
||||
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
if (clock) await s.context.clock.install();
|
||||
s.page = await s.context.newPage();
|
||||
s.page.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
return s;
|
||||
}
|
||||
|
||||
// The page has adopted a state frame: app.js has replaced the boot pane the
|
||||
// markup ships with.
|
||||
export async function drawn(page) {
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
|
||||
}
|
||||
|
||||
// Presses Send on the page and collects the send the way an agent's `wait`
|
||||
// does: the same JSON an agent receives.
|
||||
export async function sendAndCollect(s) {
|
||||
await s.page.click("#btn-send");
|
||||
const got = s.wait(10);
|
||||
if (got.code !== 0) throw new Error(`nothing was sent (wait exit ${got.code}): ${got.message || ""}`);
|
||||
return got;
|
||||
}
|
||||
|
||||
// The card for one item id.
|
||||
export const itemCard = (page, id) => page.locator(`[data-item="${id}"]`).first();
|
||||
|
||||
// A locator's visible text, trimmed.
|
||||
export const textOf = async (locator) => (await locator.innerText()).trim();
|
||||
|
||||
// The scroll offset of the first element matching `selector`.
|
||||
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
|
||||
@@ -10,7 +10,19 @@ import { fileURLToPath } from "node:url";
|
||||
|
||||
const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
const DIR = path.join(ROOT, "src", "web-console", "public");
|
||||
const FILES = ["app.js", "answers.js", "render.js", "palette.js", "starters.js", "favicon.js"];
|
||||
// Every page module (vendored code aside), found by walking public/ so a new
|
||||
// screen is guarded without editing a list.
|
||||
function pageModules(dir, rel = "") {
|
||||
const out = [];
|
||||
for (const e of fs.readdirSync(path.join(dir, rel), { withFileTypes: true })) {
|
||||
const p = rel ? `${rel}/${e.name}` : e.name;
|
||||
if (e.isDirectory()) {
|
||||
if (p !== "vendor") out.push(...pageModules(dir, p));
|
||||
} else if (e.name.endsWith(".js")) out.push(p);
|
||||
}
|
||||
return out.sort();
|
||||
}
|
||||
const FILES = pageModules(DIR);
|
||||
|
||||
let bad = 0;
|
||||
for (const name of FILES) {
|
||||
@@ -20,7 +32,7 @@ for (const name of FILES) {
|
||||
console.log(` ok ${name}`);
|
||||
} catch (err) {
|
||||
// A module that parses but cannot run here (app.js touches `document` at
|
||||
// import) is fine; only a parse failure is a real problem.
|
||||
// import, and relative imports cannot resolve from a data: URL) is fine; only a parse failure is a real problem.
|
||||
const parseFailure = err instanceof SyntaxError;
|
||||
if (parseFailure) {
|
||||
bad++;
|
||||
|
||||
@@ -13,6 +13,24 @@ and dark WebP images in `docs/screenshots/`.
|
||||
| `build.json` | A phase being built: the progress bar, the task list and the current task |
|
||||
| `signoff.json` | The completion report and the sign-off card |
|
||||
| `finish.json` | The finished screen after sign-off (posted after `signoff.json`) |
|
||||
| `git.json` | The git board, handed back to you in a sample repository with three changes to commit (the script builds the repository) |
|
||||
|
||||
Refresh every image with `node scripts/capture-screenshots.mjs`, or one with
|
||||
`--only <shot>`.
|
||||
|
||||
## Comparison-only shots
|
||||
|
||||
`--compare` adds the screens the docs never show, so a change to the console
|
||||
can be checked by eye against a "before" set. They are never published: the
|
||||
script refuses `--compare` with an `--out` inside `docs/screenshots/`.
|
||||
|
||||
| File | Stages |
|
||||
| --- | --- |
|
||||
| `stop.json` | A build with a question open, behind the Stop dialog and its handoff choice |
|
||||
| `delete.json` | The dashboard, behind the first step of a spec chip's Delete |
|
||||
| `help.json` | A Plan question, behind Help on its first tab |
|
||||
| `prefs.json` | A Plan question, behind User Preferences |
|
||||
| `cleanup.json` | A Plan question, behind User Preferences scrolled to Cleanup after a scan |
|
||||
| `workspace.json` | A Plan question, behind the Workspace panel with a second folder added (shot last: the console remembers the folder) |
|
||||
|
||||
`node scripts/capture-screenshots.mjs --compare --out <folder outside the repo>`
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"menu": {
|
||||
"note": "task-api is built up to Phase 2 of 4. Phase 3 is next.",
|
||||
"recommend": "plan2code-3-implement",
|
||||
"details": {
|
||||
"plan2code-3-implement": "Phase 3 of 4 is next"
|
||||
}
|
||||
},
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"reread": true,
|
||||
"board": { "describe": "task-schema-and-paging" },
|
||||
"agent": { "status": "waiting" }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 2 of 7: Who calls it",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q3",
|
||||
"kind": "text",
|
||||
"title": "Who calls the API",
|
||||
"body": "Which apps call the task API first, and what does each need from it?",
|
||||
"placeholder": "For example: the web app lists tasks, the mobile app only updates their status."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"workflow": "plan",
|
||||
"title": "Task API",
|
||||
"headline": {
|
||||
"stage": "Step 3 of 7: Signing in",
|
||||
"cleared": 2,
|
||||
"total": 7
|
||||
},
|
||||
"items": [
|
||||
{
|
||||
"id": "q4",
|
||||
"kind": "text",
|
||||
"title": "How callers sign in",
|
||||
"body": "Do callers sign in as a person, or as an app with a key?",
|
||||
"placeholder": "For example: apps use an API key per team."
|
||||
}
|
||||
],
|
||||
"agent": {
|
||||
"status": "waiting"
|
||||
}
|
||||
}
|
||||