mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 20:51:19 -08:00
Install and update from release tags so people never get unfinished work from main
AI Assisted
This commit is contained in:
1 parent
347831475d
commit
c07e679105
12 files changed
+2400
-519
No files matched your search
@@ -85,7 +85,7 @@ plan2code/
|
||||
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-launcher-update/
|
||||
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
|
||||
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, metrics.md, status-line.md, test-bot.md)
|
||||
├── .readme/ # User guides linked from README (README.md index, web-console.md, activities.md, web-console-internals.md, web-console-design.md, walkthrough.md, steps.md, launcher.md, metrics.md, status-line.md, test-bot.md)
|
||||
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
|
||||
│ └── screenshots/ # Web console screenshots, <shot>-light.webp and <shot>-dark.webp (generated)
|
||||
├── specs/ # Feature specs (if any in-progress)
|
||||
@@ -112,7 +112,7 @@ plan2code/
|
||||
| `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. The folder comes from `--project` alone: with none (a bare start of the app) the app shows its own picker, Choose a folder first and focused with the recent folders under it (`project::recent_folders`, the `recent_folders` and `open_recent_folder` commands), and Change project opens the same picker. The list is `recentFolders` in `~/.plan2code/launcher.json`, one rule written twice (`readRecent`, `pushRecent`, `listRecent` in the launcher, their twins in `project.rs`) and held to `scripts/fixtures/recent-folders-cases.json`. Its menu, lookup and no-agent flow come from `agents.json` through `agent-lookup.mjs`, loaded by dynamic `import()` from `~/.plan2code/bin/` (the launcher's one stated exception to its Node-built-ins-only rule; a missing copy falls back to the plain printed install steps) |
|
||||
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
|
||||
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
|
||||
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux use the plugin box with the same words, where Quit stays the default button (putting Stay first would make Esc quit). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
|
||||
| `plan2code-app/src-tauri/src/quit_prompt.rs`, `task_dialog.rs` | The quit check shown while an agent runs. `quit_prompt(last_signal)` is pure: the page's last taskbar signal `ready` or `plain` is the waiting case ("Done for now?", Info icon), and `busy`, `attention` or none yet is the working case ("Leave while your agent is busy?", Warning icon). `task_dialog.rs` (Windows only) draws it with `TaskDialogIndirect` through `winapi`: a heading, Stay as the default, and the app's icon in the title bar, since the dialog plugin has no heading and Windows copies its icon into the title bar (the warning once showed twice). `confirm_quit` in `main.rs` runs it on its own thread; macOS and Linux ask through the shell's own modal (`ui_confirm.rs`: `ask_in_window` emits `confirm-request`, the page's `confirmModal` answers with `confirm_answer`), where Stay comes first and has focus, so Stay is the default on every system; the plugin box with the same words is only the fallback while the page is not listening (`confirm_ready`), and there Quit stays the default button (putting Stay first would make Esc quit). The Implementation Loop's Start confirm goes through the same modal (`loop_driver::confirm_lines`: the quick check in a code block, the trunk warning as a callout). A page reload or an unanswered page clears the signal to none (`clear_attention`), so the box stays on the working words until the page reports again; `QUIT_OPEN` keeps a second box from stacking |
|
||||
| `plan2code-app/src-tauri/src/loop_driver.rs` | The Implementation Loop's driver. Its decisions are pure functions and carry the unit tests: `phase_prompt()` (the prompt each fresh phase session starts on), `judge_outcome()` (the skill's `loopOutcome` against the spec's marks and the setup), `expect_patch()` (the `loopExpect` judging criteria stamped into the session so the console refuses a bad report at post time), `silence_expired()`, `should_retry()` (one retry for a crash or silence, never for a real failure), `open_question()` and `stop_line()`. Around them sit the running record (app memory only), the watch thread and the stop and resume entry points. **The app, not the agent, marks a loop phase done and commits it**; the skill only builds and reports |
|
||||
| `plan2code-app/src-tauri/src/loop_commit.rs` | The loop's commit step, called by `handle_outcome` in a fixed order: prepare (subject, message), stage and check the staged names and sizes against a denylist (`.env*` except `.example`, `.sample`, `.template`; oversized files; a bad list unstages all and stops), save the phase file text, mark done, commit with its own limit, and on a failed commit restore the saved text only if the file still equals what the loop wrote (else stop with "marked, not committed", kept in the reports store). Stop now never commits; `judge_outcome` refuses missing task data and failed tests; the watcher runs under `catch_unwind` and counts unreadable sessions as silence; `loop_state` in `main.rs` redraws the strip after a reload |
|
||||
| `plan2code-app/src-tauri/src/loop_notify.rs` | The loop's notification: `NotifyKind` (query string, JSON body, Discord, Slack, Teams, Google Chat; its comment lists what a new service needs), `valid_url()`, `valid_param()` (mirrored in `loop-setup.mjs` and `screens/loop-setup.js`), `request_for()` (each kind's address and body) and `send()`, with a 10 second limit and errors that never hold the address. The driver writes the message and calls it from `observe()`, `stop_loop()` and `finish()`. |
|
||||
@@ -121,6 +121,10 @@ plan2code/
|
||||
| `plan2code-app/src-tauri/src/agents.rs` | Agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the shipped `agents.json` read at run time with the baked copy as fallback; `find_on_path`, the Rust twin of `agent-lookup.mjs`'s `findAgent` (PATH, PATHEXT, the saved PATH from `node_check::resolved_path()`, npm's global folder, the install folders), held to `scripts/fixtures/agent-lookup-cases.json`. The console side is `src/web-console/agents.mjs` |
|
||||
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
|
||||
|
||||
### Release channel
|
||||
|
||||
Install and update follow release tags, never `main`. `release-app.yml`'s `publish` job ends by fast-forwarding the `release` branch to the tag it just published (no force: a tag not ahead of the branch fails the job), and the README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`. `plan2code update` installs the newest `vX.Y.Z` tag (`newestReleaseTag()` in `src/launcher/plan2code.js`, using `latestTag()` and `runLsRemote()` from the copy of `update-check.mjs` beside it); `--main` installs the tip of `main`, `--tag <ref>` any ref (how to go back to a release); `--main` and a `--tag` naming a branch always pass `--force`, since unreleased work keeps the last release's version and the installer's `Already on` check would install nothing. `plan2code uninstall` runs the newest release's installer the same way, falling back to `main` only when no release tag can be found. The console's release check (`update-check.mjs`) and the app's notice (`versions.rs` `latest_tag()`) use the same rule: the highest plain `vX.Y.Z` in `git ls-remote --tags`, peeled and pre-release tags skipped. The app's Update skills still pins to the app's own tag.
|
||||
|
||||
### Agents file
|
||||
|
||||
`~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents & models, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first.
|
||||
@@ -151,11 +155,11 @@ plan2code/
|
||||
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
|
||||
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
|
||||
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
|
||||
| `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-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-pr-prep.md` | pr-prep | Get a branch ready for review: pick the checks its changes need from the project's `## Test map` (or its config files), let the person trim the plan, run it, give Ready, Ready with notes or Not ready, and write a PR description to copy (following the repo's template) with the create-a-PR link; offers to save `PR-READINESS-<date>.md` into the branch's spec folder; never commits, pushes or opens the PR |
|
||||
| `plan2code-test.md` | test | Write missing tests: ask where to look, find source files no test covers (matching, plus real coverage when the project already has a coverage tool, offered first), show a plan opening with how this project writes tests, then write and run unit and integration tests; escalates past 8 source files, 8 new test files or 2 runners to a PLAN-DRAFT for Plan, hands a real bug to Diagnose, never changes source code |
|
||||
| `plan2code-dead-code.md` | dead-code | Find unused code and dead code: use the project's own dead-code tools, one per language that has files (Knip, vulture, cargo check and others), or search by itself, check every item for callers across the project (`references/caller-search.md`), label each Safe to remove, Check first or Warning, remove only what the person picks, then run the tests and build and put back anything that breaks them, then offer a final review of the removals in the same session (Step 7.5, recommended yes; ships `review.md`, `review-in-build.md`, `test-runs.md` and the review references, as Finalize does); never commits, never installs a tool. Scripts: `dead-code.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs`, `specs.mjs`, `commit-msg.mjs`, `review-scope.mjs`, `lessons.mjs` |
|
||||
| `plan2code-deps.md` | deps | Update dependencies: scan every manifest (the npm family, Cargo, pip and uv, Go, .NET), label each available update Safe, Check first or Warning with a reason, show a pick list, apply the picks in batches, run the project's install and checks after each batch and put back whatever breaks (narrowing a failed batch to the breaking pick); a ticked Warning writes `specs/<package>-upgrade/UPGRADE-<YYYYMMDD>.md` instead. The dashboard scan reports such a folder as spec state `upgrade` ("Upgrade ready"), which lights Quick Task (suggested) and Plan; once Quick Task applies it and marks the brief `Done` the state is `upgraded` ("Upgrade done"), finished like `fixed`. Never commits or updates anything not picked; installs a scanner or fixes a small break in project code only after the person approves that exact change, and puts the fix back if it fails. Scripts: `deps.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs` |
|
||||
| `plan2code-deps.md` | deps | Update dependencies: scan every manifest (the npm family, Cargo, pip and uv, Go, .NET), label each available update Safe, Check first or Warning with a reason, show a pick list, apply the picks in batches, run the project's install and checks after each batch and put back whatever breaks (narrowing a failed batch to the breaking pick); a ticked Warning writes `specs/<package>-upgrade/UPGRADE-<YYYYMMDD>.md` instead. The dashboard scan reports such a folder as spec state `upgrade` ("Upgrade ready"), which lights Quick task (suggested) and Plan; once Quick task applies it and marks the brief `Done` the state is `upgraded` ("Upgrade done"), finished like `fixed`. Never commits or updates anything not picked; installs a scanner or fixes a small break in project code only after the person approves that exact change, and puts the fix back if it fails. Scripts: `deps.mjs` (own), `test-map.mjs`, `glob.mjs`, `test-commands.mjs`, `run-check.mjs` |
|
||||
| `plan2code-ui-prototype.md` | ui-prototype | Draw several versions of a screen or flow on one page with live dials (drafts under `~/.plan2code/prototypes/`), bring the pick back by Copy and paste for the next round, and save the pair into `specs/<spec>/prototypes/` only on a yes; never changes code |
|
||||
| `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 |
|
||||
@@ -176,7 +180,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/`). 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, and `lessons.md` into every skill that ships `lessons.mjs`).
|
||||
**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, and `lessons.md` into every skill that ships `lessons.mjs`).
|
||||
|
||||
**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.
|
||||
|
||||
@@ -209,7 +213,7 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
|
||||
The bracketed flags (each entry's `bypassArgs`; a custom agent's own `bypassArgs`) go in only when permission prompts are off. Right after the agent is chosen, and only when it has such a flag, `chooseBypass()` asks `Turn <CLI>'s permission prompts off?` (Codex: `approval prompts and its sandbox`, worded by `bypassQuestion()`) on every launch, with Yes as the default and no answer remembered; `--keep-permissions` answers no and `--bypass-permissions` answers yes (neither is forwarded; keep wins when both are given), and with no TTY on stdin the prompts stay on unless `--bypass-permissions` is given. When the desktop app will take over, the question is skipped (its launch card has its own tick) and asked only if the app fails to start. The installer prints no warning about it.
|
||||
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With more than one on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number or a CLI id also works); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with none it runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own 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`, `recentFolders` and `lastModels`. Then, at a terminal with recent folders to offer, it asks `Which project folder?` as a numbered menu in the style of the model menu: the current folder first (Enter keeps it), the recent folders (at most 5, newest first), then `Choose another folder...` for the native picker. With no recent folders other than the current one (the typed command leaves the current folder out of the list), or no TTY on stdin, there is no menu and it opens the current folder as before. The folder is recorded as `recentFolders` (with `lastFolder` always its first entry) only after the project check passes (`recordFolder()`), on every path including the global command; declining the check records nothing. 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` and `plan2code uninstall [--yes] [--purge]` are the two subcommands: neither is forwarded and neither opens an agent. Update runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists; uninstall runs the same npx line with `--uninstall` (an unknown flag exits 2 before npx runs), and `install.js` confirms, removes everything the menu's U option does, then asks about `~/.plan2code` (see `--uninstall` in Development Commands). 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.
|
||||
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 runs the setup flow when a person can see a page (`hasDisplay()` and a TTY or the shortcut; the desktop app first when it is installed, else the console's agent-less `setup` page in the browser) and otherwise prints the install steps (`printNoAgentGuidance()`: each built-in's install command and page, how to add another agent in `~/.plan2code/agents.json`, and to run `plan2code` again) and exits 127. An uninstalled `--cli` pick goes to the same setup flow on that agent when a page can open, else prints that CLI's own 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`, `recentFolders` and `lastModels`. Then, at a terminal with recent folders to offer, it asks `Which project folder?` as a numbered menu in the style of the model menu: the current folder first (Enter keeps it), the recent folders (at most 5, newest first), then `Choose another folder...` for the native picker. With no recent folders other than the current one (the typed command leaves the current folder out of the list), or no TTY on stdin, there is no menu and it opens the current folder as before. The folder is recorded as `recentFolders` (with `lastFolder` always its first entry) only after the project check passes (`recordFolder()`), on every path including the global command; declining the check records nothing. 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; a bare `--` ends the launcher's own arguments, and everything after it goes to the agent as it is (the separator dropped) and keeps the run in the terminal even with the app installed (`plan2code -- --help` shows the agent's help). When the app opens it takes only the folder, agent and model, so one dim line names any other argument it drops (`droppedForApp()`). `plan2code --help` (`-h`, `help`) prints `usageText()` and `plan2code --version` (`-v`) prints the version in `version.json` beside the launcher; both exit 0 before the banner or any question. `plan2code update` and `plan2code uninstall [--yes] [--purge]` are the two subcommands: neither is forwarded and neither opens an agent. The launcher and `install.js` both start with a Node guard (`nodeVersionProblem()`): below Node 18 they print one sentence and exit 1. Update runs `npx --yes --allow-git=all git+https://github.com/jparkerweb/plan2code.git --update`, so `install.js --update` reinstalls what `~/.plan2code/install.json` lists; uninstall runs the same npx line with `--uninstall` (an unknown flag exits 2 before npx runs), and `install.js` confirms, removes everything the menu's U option does, then asks about `~/.plan2code` (see `--uninstall` in Development Commands). 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. Beside it go `update-check.mjs` (the web console's release check, for the terminal notice), `agents.json` and `agent-lookup.mjs` (the shared agent list and lookup rule; `plan2code update` restores a missing copy) and a `version.json` (the installed version). (The metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
@@ -230,4 +234,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. 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 those (metrics and bot only when run from a git checkout), 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.
|
||||
**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 those (metrics and bot only when run from a git checkout), 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), the PATH line for the person's shell when the bin folder is off `PATH`, and, when `detectAgents()` finds no agent the launcher could run (the shared `agents.json` and `agent-lookup.mjs` rule, plus the custom agents read through the launcher's `customClis()`), how to get one. A `plan2code` already in the bin folder without the launcher marker is saved as `<file>.bak` by `writeLauncherShim()` before the shim is written.
|
||||
@@ -49,6 +49,11 @@ node scripts/bench-web-console.mjs [--runs 7] [--workflow dashboard]
|
||||
# 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)
|
||||
# After a full capture, rebuild what the landing page derives from it (hero 1280px variants, the 1200x630
|
||||
# social card) and, until the owner has real desktop app pictures, the labeled placeholders (never overwrites a real file)
|
||||
node scripts/make-site-images.mjs
|
||||
node scripts/make-social-card.mjs
|
||||
node scripts/make-app-placeholders.mjs
|
||||
|
||||
# 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
|
||||
@@ -137,14 +142,14 @@ 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 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.
|
||||
`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` takes only `--force` beside it.
|
||||
|
||||
| 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, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. `plan2code update` runs it through npx |
|
||||
| `--uninstall [--yes] [--purge]` | No menu: confirm y/N (`--yes` skips it), run `uninstallAll()` (the menu's U sequence: skills, dev tools, status line, `plan2code` command, desktop app), then ask whether to also delete `~/.plan2code` (`purgeData()`; `--purge` says yes without asking, `--yes` alone keeps the data). `plan2code uninstall [--yes] [--purge]` runs it through npx |
|
||||
| `--update [--force]` | No menu: reinstall what `~/.plan2code/install.json` lists (skills, launcher, app, statusline; metrics and bot only when run from a git checkout, since they run from the install folder, which npx's cache is not), never uninstalling; with no record, the skills and the `plan2code` command. Compact output: `Updating <old> -> <new>` from the record's version (or `Already on <new>`, which stops unless `--force`), each piece's own output held back (`captureOutput()`) and shown only for a warning or a failure, one summary with human piece names (`PIECE_LABELS`), the release notes link and the restart hint; a failed update also prints `plan2code update --tag v<old>`. A failed update, or one whose desktop app was kept because the release has no app file yet, puts the old version back on `install.json`, so the next update (the app's Update and restart included) runs instead of stopping at Already on. `plan2code update` runs it through npx, pinned to the newest `vX.Y.Z` tag the launcher finds with update-check.mjs's `git ls-remote` pick (`--main` takes the tip of `main`, `--tag <ref>` any ref, `--force` is passed on; `PLAN2CODE_LS_REMOTE_FILE` replaces the git call in tests) |
|
||||
| `--uninstall [--yes] [--purge]` | No menu: confirm y/N (`--yes` skips it), run `uninstallAll()`, then ask whether to also delete `~/.plan2code` (`purgeData()`; `--purge` says yes without asking, `--yes` alone keeps the data). `uninstallAll()` is driven by the pieces `install.json` records plus a quiet probe for strays (`UNINSTALL_STEPS`, `UNINSTALL_PROBES`), prints one line per piece actually removed, falls back to deleting the `plan2code*` folders under `~/.agents/skills` when the skills CLI is unreachable, and removes the versioned console folders and `console-dir` (`removeConsoleFolders()`, stopping a running console first). What stays in `~/.plan2code` is listed by name with its size (`listKeptData()`), and the run always ends with the Removed / Could not remove / To finish block (`printUninstallReport()`). Deleting the data also removes the app's webview data outside `~/.plan2code` (`appWebviewDirs()`, `purgeAppWebview()`), and a running app is named before anything is removed (`appRunning()`). `plan2code uninstall [--yes] [--purge]` runs it through npx |
|
||||
|
||||
## How the Installer Works
|
||||
|
||||
|
||||
@@ -97,10 +97,14 @@ Read the current `CHANGELOG.md` on the branch. Look for:
|
||||
|
||||
### Step 5 — Draft or fix the CHANGELOG entry
|
||||
|
||||
**If no entry exists**, draft a new one based on the commits and changed files. Match this repo's house format exactly — a bare `## vX.Y.Z` heading with **no date**, emoji `###` headings from the Step 2 table, and a blank line between bullets:
|
||||
**If no entry exists**, draft a new one based on the commits and changed files. Match this repo's house format exactly: a `## vX.Y.Z (YYYY-MM-DD)` heading with the release date (take it from `version.json`'s `releaseDate`, or today's date for an entry not yet released; older headings have no date and stay as they are), emoji `###` headings from the Step 2 table in the order Added, Changed, Fixed, and a blank line between bullets. The format going forward:
|
||||
|
||||
- A minor release opens with a `### Highlights` block of exactly three plain-language bullets, before Added.
|
||||
- Game changes sit under one `Activities` line.
|
||||
- Tooling and test lines go under a `**For contributors**` bullet group at the end of the section.
|
||||
|
||||
```markdown
|
||||
## {computed-version-with-v-prefix}
|
||||
## {computed-version-with-v-prefix} ({release-date})
|
||||
|
||||
### ✨ Added
|
||||
|
||||
@@ -142,7 +146,7 @@ This keeps `package.json`, `version.json`, and `CHANGELOG.md` in lockstep so `np
|
||||
|
||||
- Never create a version entry without checking main first — the whole point is to derive the version from main's current state
|
||||
- Always present changes before writing — the user should see and approve the CHANGELOG entry
|
||||
- Match the existing file's format — `## vX.Y.Z` with no date, emoji `###` headings. Do not introduce Keep a Changelog's `## [x.y.z] - date` style
|
||||
- Match the file's format: `## vX.Y.Z (YYYY-MM-DD)` (older headings carry no date; do not backfill them), emoji `###` headings. Do not introduce Keep a Changelog's `## [x.y.z] - date` style
|
||||
- Write for someone reading the release notes, not for someone reading the diff — say what the change lets them do
|
||||
- If multiple change types exist (Added + Changed), use multiple headings under the same version
|
||||
- `version.json`'s `releaseDate` is today's date, i.e. when the release is being prepared, not when the work started
|
||||
|
||||
@@ -21,7 +21,7 @@ Run from the repo root (the folder holding `install.js` and `src/launcher/`). Ru
|
||||
|
||||
### Step 2 — Read the current files
|
||||
|
||||
Read `src/launcher/models.json`. It has five keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`) and `strengths` (an object, see Step 4c). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
|
||||
Read `src/launcher/models.json`. It has five keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`) and `strengths` (an object, see Step 4c). A `label` is the description only, never the id or a name ahead of a gloss: `{ "id": "sonnet", "label": "latest Sonnet" }`, not `"Sonnet, latest Sonnet"` or `"sonnet (latest Sonnet)"`. The launcher's model menu prints the id in a padded column with the label beside it, and the console and the desktop app show the id next to it too, so a label that repeats the name shows it twice. Devin's and Codex's labels are the display name the vendor uses (`Claude Opus 5.5 Low`), which is their description. Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
|
||||
|
||||
Read `src/launcher/agents.json`. It has `schema` (currently `1`) and `agents`, a list of entries. Each entry carries `id`, `name`, `kind` (`builtin` or `template`), `command`, `prompt`, `args`, `bypassArgs`, `modelArgs`, and optional `note`. A `builtin` entry also carries `installUrl`, `install` (lists under `win`, `mac` and `linux`, each `{ label, run, note? }`) and `installDirs` (the same OS keys). Keep the file's shape and order exactly as read.
|
||||
|
||||
@@ -80,7 +80,7 @@ For `models.json`, compare the discovered list with the current one by `id` and
|
||||
|
||||
- **added:** offered by the CLI, not in the file.
|
||||
- **gone:** in the file, no longer offered.
|
||||
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
||||
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style: the description only (see Step 2), never repeating the id.
|
||||
|
||||
For `agents.json`, show one table with one row per changed field:
|
||||
|
||||
@@ -137,7 +137,7 @@ Check every rule before `npm test` (Step 10). They mirror the shipped-file tests
|
||||
- `_note` is present and unchanged from what Step 2 read.
|
||||
- `claude` and `devin` are both non-empty arrays; `codex` is an array (empty is allowed).
|
||||
- `devin` has at most 30 entries.
|
||||
- Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`.
|
||||
- Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`, and no label is a name followed by a gloss (`Sonnet, latest Sonnet`); `scripts/test-launcher.mjs` checks this too.
|
||||
- Ids are unique within each list, and labels are unique within each list.
|
||||
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
|
||||
- Every `strengths` row names a `model` that is in that agent's list in the same file, uses only the words `thrifty`, `balanced` and `best`, and no agent other than the ones already under `strengths` gains a mapping.
|
||||
|
||||
@@ -30,7 +30,7 @@ git pull origin main
|
||||
|
||||
Read all three files at the repo root and extract each version:
|
||||
|
||||
- `CHANGELOG.md` — parse the first `## vX.Y.Z` heading. Strip the leading `v` → `$CHANGELOG_VERSION`. Note: plan2code CHANGELOG headings are `## vX.Y.Z` (v-prefixed, **no** date and **no** brackets) — different from a `## [x.y.z] - YYYY-MM-DD` format.
|
||||
- `CHANGELOG.md` — parse the first `## vX.Y.Z` heading. Strip the leading `v` → `$CHANGELOG_VERSION`. Note: plan2code CHANGELOG headings are `## vX.Y.Z`, optionally followed by ` (YYYY-MM-DD)` (v-prefixed, **no** brackets; older headings have no date), different from a `## [x.y.z] - YYYY-MM-DD` format. The date is not part of the version.
|
||||
- `version.json` — the `version` field → `$VERSION_JSON`. Also read its `releaseDate` field → `$RELEASE_DATE` (informational only — shown at the confirm step, never part of the sync gate; use `(none)` if absent).
|
||||
- `package.json` (root) → the `version` field → `$PACKAGE_JSON`.
|
||||
|
||||
@@ -80,7 +80,30 @@ If `$CHANGELOG_VERSION` > `$RELEASE_VERSION`, compute:
|
||||
|
||||
- `tag = "v$CHANGELOG_VERSION"`
|
||||
- `title = "v$CHANGELOG_VERSION"` (plan2code keeps the `v` prefix in release titles)
|
||||
- `notes` = the header line `# What's New 🎉`, then one blank line, then `$SECTION` verbatim (`$SECTION` already starts with the `## vX.Y.Z` heading). Build this as a real multi-line string with **actual newlines** — the `\n\n` shorthand shown elsewhere means "a blank line," never the literal two-character sequence `\` + `n`. Getting this wrong would run the header and the first CHANGELOG heading together with a stray `\n\n` in the published body.
|
||||
- `notes` = the header line `# What's New 🎉`, one blank line, the **fixed header** below (with `$CHANGELOG_VERSION` filled in), one blank line, then the **highlights**, one blank line, then `$SECTION` verbatim (`$SECTION` already starts with the `## vX.Y.Z` heading). Build this as a real multi-line string with **actual newlines** — the `\n\n` shorthand shown elsewhere means "a blank line," never the literal two-character sequence `\` + `n`. Getting this wrong would run the header and the first CHANGELOG heading together with a stray `\n\n` in the published body.
|
||||
|
||||
**The fixed header** (the same on every release, so a visitor to the release page finds the install and update commands and the right file without reading the changelog):
|
||||
|
||||
````markdown
|
||||
**Install:** `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`
|
||||
**Update:** `plan2code update`
|
||||
|
||||
The installer downloads the right app for your system and puts it in place for you, so you only need the files below for a manual download.
|
||||
|
||||
| Your system | File |
|
||||
| --- | --- |
|
||||
| Windows (64-bit Intel or AMD) | `plan2code-app-$CHANGELOG_VERSION-windows-x64.exe` |
|
||||
| macOS (Apple silicon) | `plan2code-app-$CHANGELOG_VERSION-macos-arm64` |
|
||||
| macOS (Intel) | `plan2code-app-$CHANGELOG_VERSION-macos-x64` |
|
||||
| Linux (64-bit Intel or AMD) | `plan2code-app-$CHANGELOG_VERSION-linux-x64` |
|
||||
| Any system: check a download | `plan2code-app-$CHANGELOG_VERSION-SHA256SUMS.txt` |
|
||||
|
||||
The app files are not code-signed. See [the desktop app guide](https://github.com/jparkerweb/plan2code/blob/main/docs/desktop-app.md#the-app-is-not-code-signed) for what your system may ask and how to answer.
|
||||
````
|
||||
|
||||
Check the install command against the README's "See it" line before publishing; if it has changed, the README wins.
|
||||
|
||||
**The highlights** (written fresh for each release, from `$SECTION`): a `### Highlights` heading and exactly three bullets, each one plain sentence about what a person can now do or no longer trips over (no file names, no internal terms). The full list follows below them. When `$SECTION` already opens with its own `### Highlights` block (the changelog format from 3.1.0 on), reuse those bullets as they are: add no second Highlights block.
|
||||
|
||||
Present all three to the user and wait for an explicit answer before any write. Offer the optional decorative title suffix — a plain `vX.Y.Z` title is the default, but a release may append one (e.g. `v1.14.0 - 🔍 Review workflow`):
|
||||
|
||||
@@ -105,7 +128,7 @@ If the user supplies a suffix, set `title = "v$CHANGELOG_VERSION " + <suffix>` (
|
||||
|
||||
### Step 9 - Publish (on approval)
|
||||
|
||||
The release is created by the `release-app` workflow, **last**, not by this skill. The workflow builds the app on four systems, attaches every file to a draft release, and only then publishes it, so the `vX.Y.Z` tag (which the app's update check watches) never exists before its binaries do. Creating the release here with `gh release create` would put the tag up first and leave users offered an upgrade with nothing to download. Do not do that.
|
||||
The release is created by the `release-app` workflow, **last**, not by this skill. The workflow builds the app on four systems, attaches every file to a draft release, and only then publishes it, so the `vX.Y.Z` tag (which the app's update check watches) never exists before its binaries do; its last step then fast-forwards the `release` branch (what the README installs from) to the new tag, and fails loudly if the tag is not ahead of the branch. Creating the release here with `gh release create` would put the tag up first and leave users offered an upgrade with nothing to download. Do not do that.
|
||||
|
||||
On approval, write `$notes` to a temp file, never inline (multiline text on the command line is a quoting bug). `$notes` must already hold **real newlines** (per Step 8) because `printf '%s'` / `WriteAllText` write it byte-for-byte, and the file MUST be **UTF-8** because the notes contain emoji. Then start the workflow on `main`, passing the file as the `notes` input (`-F key=@file` reads the file's contents):
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@ name: release-app
|
||||
# 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
|
||||
# its WebKitGTK 4.1 dependency instead. The app is not code-signed: docs/desktop-app.md says
|
||||
# how to allow it.
|
||||
|
||||
on:
|
||||
@@ -187,3 +187,18 @@ jobs:
|
||||
if [ "$state" = "true" ]; then
|
||||
gh release edit "$TAG" --draft=false
|
||||
fi
|
||||
- name: Move the release branch to this tag
|
||||
# The README's first install is `npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git#release`, so new users
|
||||
# get the newest release and never a half-finished main. Last step, after the release is
|
||||
# public: a failure earlier leaves the branch on the previous release. Fast-forward only
|
||||
# (no --force), so a tag that is not ahead of the branch fails loudly instead of
|
||||
# rewinding what people install.
|
||||
run: |
|
||||
# The checkout is shallow, and git decides "fast-forward" locally: without the full
|
||||
# history the branch's old tip is unknown here and the push is refused as "fetch first".
|
||||
if [ "$(git rev-parse --is-shallow-repository)" = "true" ]; then
|
||||
git fetch --no-tags --unshallow origin
|
||||
fi
|
||||
git fetch --no-tags origin "refs/tags/${TAG}:refs/tags/${TAG}"
|
||||
sha="$(git rev-parse "refs/tags/${TAG}^{commit}")"
|
||||
git push origin "${sha}:refs/heads/release"
|
||||
+1029
-412
File diff suppressed because it is too large.
Load diff
@@ -46,6 +46,11 @@ file directly after checking it against the release's checksum list.
|
||||
`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)
|
||||
- [ ] **Update and restart** (bar, with a newer release out): the bar shows the installer's progress,
|
||||
the app reopens on the same project, and says **Updated to vX** once; with an agent running it
|
||||
asks first, and Stay leaves the app up with **Restart Plan2Code** offered; a failed update
|
||||
(try it offline) leaves the old app running with a readable reason; **What's new** opens the
|
||||
release page in the default browser
|
||||
|
||||
## The window (each system)
|
||||
|
||||
@@ -64,14 +69,24 @@ file directly after checking it against the release's checksum list.
|
||||
only) and permission mode (checks off is ticked by default, matching the plain `plan2code`
|
||||
launcher; untick it for an agent that keeps its normal approval prompts); a CLI it could
|
||||
not find is named, not just disabled
|
||||
- [ ] **Dock the terminal to the right**: the splitter becomes vertical, the toolbar stacks, and the
|
||||
dashboard keeps the rest of the width; dock it back to the bottom
|
||||
- [ ] **Collapse** the terminal to a thin strip (either dock) and **View Agent Terminal** brings it
|
||||
- [ ] **Dock the terminal to the right**: the splitter becomes vertical, and the
|
||||
dashboard keeps the rest of the width; dock it back to the bottom (the dock button is an icon with a tooltip and a label)
|
||||
- [ ] **Collapse** the terminal to a thin strip (either dock) and its expand button (**Show the terminal**) brings it
|
||||
back; its size from before collapsing is remembered
|
||||
- [ ] Docked right, collapsed: the **View Agent Terminal** label reads top-to-bottom and fits inside the strip,
|
||||
not sideways text running off the edge
|
||||
- [ ] Docked right, collapsed: the strip holds only the expand button (and the pill, reading top-to-bottom),
|
||||
with nothing running off the edge
|
||||
- [ ] Collapse the terminal (or shrink it small), let the agent go quiet for a while mid-answer: the
|
||||
"agent may need you" badge appears on the strip; expanding it clears the badge
|
||||
**Agent may need you** pill appears on the strip; pressing it expands the terminal and focuses it, and the pill clears
|
||||
- [ ] The splitter takes the keyboard (Tab to it, arrows step it 2%, Home and End go to the ends)
|
||||
and a double-click returns it to the default width; Ctrl or Cmd with plus, minus and 0 change the
|
||||
terminal's text size, and it is the same size after a relaunch
|
||||
- [ ] Switch the theme (and the highlight) in User Preferences: the bar, the terminal frame, the terminal's
|
||||
colors and the OS title bar all follow at once, and a relaunch opens in that theme with no flash of
|
||||
the other one (check WebView2 on Windows, and WebKit on macOS and Linux: scrollbars, fonts, title bar)
|
||||
- [ ] The window appears already painted (no white or blank frame), says "Starting Plan2Code" until the
|
||||
first screen, remembers its size and position, and opens maximized only on the very first launch
|
||||
- [ ] Narrow the window: the model text leaves the top bar first, then the status line (both then sit in
|
||||
the agent menu), and the bar never scrolls; **+N more** opens a list of the other steps
|
||||
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
|
||||
console frame and the terminal included) or Escape, and are not cut off by the bar
|
||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
||||
|
||||
@@ -19,11 +19,12 @@ function read(file) {
|
||||
// or the end of its container (HTML).
|
||||
function blockOf(file) {
|
||||
const text = read(file);
|
||||
const start = text.search(/^#{2,3} Before you start$|<h3>Before you start<\/h3>/m);
|
||||
const start = text.search(/^#{2,3} Before you start$|<h3>Before you start<\/h3>|<summary>Before you start<\/summary>/m);
|
||||
assert.ok(start >= 0, `${file} has no "Before you start" block`);
|
||||
const rest = text.slice(start);
|
||||
const body = rest.indexOf('\n') + 1;
|
||||
const next = file.endsWith('.html') ? rest.indexOf('</div>') : rest.slice(body).search(/^#{1,3} /m);
|
||||
const closers = ['</details>', '</div>'].map((tag) => rest.indexOf(tag)).filter((i) => i > 0);
|
||||
const next = file.endsWith('.html') ? Math.min(...closers) : rest.slice(body).search(/^#{1,3} /m);
|
||||
const end = file.endsWith('.html') ? next : next < 0 ? -1 : body + next;
|
||||
return end > 0 ? rest.slice(0, end) : rest;
|
||||
}
|
||||
@@ -40,11 +41,30 @@ for (const file of DOCS) {
|
||||
});
|
||||
|
||||
if (!WITH_INSTALL.has(file)) continue;
|
||||
test(`${file} puts the guidance before the install command`, () => {
|
||||
// The command leads (README's "See it" picture, the site's hero); the guidance follows in a
|
||||
// block of its own, and the line beside the command names the two requirements.
|
||||
test(`${file} leads with the install command and names what it needs`, () => {
|
||||
const text = read(file);
|
||||
const guide = text.indexOf('Before you start');
|
||||
const install = text.indexOf('npx --allow-git');
|
||||
assert.ok(guide >= 0 && install >= 0 && guide < install, `${file}: "Before you start" must come before the npx line`);
|
||||
assert.ok(install >= 0 && text.includes('Before you start'), `${file} is missing the install command or "Before you start"`);
|
||||
if (file === 'README.md') {
|
||||
const first = text.split('\n').slice(0, 60).join('\n');
|
||||
assert.ok(first.includes('**Plan it. Approve it. Let it build.**'), 'README.md: the tagline must open it');
|
||||
assert.ok(first.includes('npx --allow-git'), 'README.md: the install command must be in its first 60 lines, under "See it"');
|
||||
assert.ok(first.indexOf('## See it') >= 0 && first.indexOf('## See it') < first.indexOf('npx --allow-git'), 'README.md: the install command must sit under "See it"');
|
||||
assert.ok(first.includes('Needs Node.js 18+ and Git'), 'README.md: the first lines must name Node.js and Git');
|
||||
}
|
||||
if (file === 'docs/index.html') {
|
||||
assert.ok(install < text.indexOf('id="install"'), 'docs/index.html: the command must also be in the hero, before #install');
|
||||
assert.ok(text.includes('Needs Node 18+ and Git'), 'docs/index.html: #install must say what it needs in one line');
|
||||
}
|
||||
});
|
||||
|
||||
test(`${file} installs from the release branch, never from main`, () => {
|
||||
const text = read(file);
|
||||
const commands = text.match(/npx --allow-git=all git\+https:\/\/github\.com\/jparkerweb\/plan2code\.git\S*/g) || [];
|
||||
assert.ok(commands.length > 0, `${file} has no install command`);
|
||||
for (const command of commands) assert.match(command, /\.git#release(?![\w.-])/, `${file}: ${command} must end in #release`);
|
||||
});
|
||||
|
||||
test(`${file} says what a silent install means and how to see why`, () => {
|
||||
|
||||
+674
-21
@@ -104,11 +104,12 @@ test("update: with no record it says so and updates the skills and the plan2code
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, new RegExp(`No install record found \\(installed before v${VERSION.replace(/\./g, "\\.")}\\); updating the skills and the plan2code command\\.`));
|
||||
assert.match(out, /No install record found; updating the skills and the plan2code command\./);
|
||||
assert.doesNotMatch(out, /installed before v/);
|
||||
// install() covers the command with the skills, so the launcher step does not run again.
|
||||
assert.deepEqual(fake.ran(), ["skills"]);
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /launcher: updated/);
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /plan2code command: updated/);
|
||||
});
|
||||
|
||||
test("update: a partial record runs only the listed pieces, in order, unattended", async () => {
|
||||
@@ -119,7 +120,7 @@ test("update: a partial record runs only the listed pieces, in order, unattended
|
||||
assert.deepEqual(fake.ran(), ["statusline", "bot"]);
|
||||
for (const call of fake.calls) assert.equal(call.options.unattended, true, call.piece);
|
||||
assert.doesNotMatch(out, /No install record/);
|
||||
assert.doesNotMatch(out, /skills:/);
|
||||
assert.doesNotMatch(out, /Skills:/);
|
||||
});
|
||||
|
||||
test("update: a failing piece exits 1 naming it, and the others still run", async () => {
|
||||
@@ -128,10 +129,10 @@ test("update: a failing piece exits 1 naming it, and the others still run", asyn
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "statusline", "metrics", "bot"]);
|
||||
assert.match(out, /statusline: failed: /);
|
||||
assert.match(out, /metrics: failed: npm exploded/);
|
||||
assert.match(out, /bot: updated/);
|
||||
assert.match(out, /Update failed for: statusline, metrics/);
|
||||
assert.match(out, /Status line: failed: /);
|
||||
assert.match(out, /Metrics: failed: npm exploded/);
|
||||
assert.match(out, /Bot: updated/);
|
||||
assert.match(out, /Update failed for: Status line, Metrics/);
|
||||
});
|
||||
|
||||
test("update: when the skills install leaves the command out, the launcher step runs on its own", async () => {
|
||||
@@ -141,8 +142,8 @@ test("update: when the skills install leaves the command out, the launcher step
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(fake.ran(), ["skills", "launcher"]);
|
||||
// install() returned 1 for the command alone: the skills still read as updated.
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /launcher: updated/);
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /plan2code command: updated/);
|
||||
});
|
||||
|
||||
test("update: a command that fails on the retry is the only piece named", async () => {
|
||||
@@ -150,8 +151,165 @@ test("update: a command that fails on the retry is the only piece named", async
|
||||
const fake = fakeSteps({ launcherWithSkills: false, codes: { launcher: 1 } });
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.match(out, /skills: updated/);
|
||||
assert.match(out, /Update failed for: launcher\b/);
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /Update failed for: plan2code command\b/);
|
||||
// A failed update says how to go back (the record's old version here).
|
||||
assert.match(out, /To go back to a release, run: plan2code update --tag v1\.0\.0/);
|
||||
});
|
||||
|
||||
test("update: prints the version change, one line per piece by name, the release notes link and the restart hint", async () => {
|
||||
writeRecord(["skills", "launcher", "app", "statusline"]);
|
||||
const fake = fakeSteps();
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, new RegExp(`^Updating 1\\.0\\.0 -> ${VERSION.replace(/\./g, "\\.")}$`, "m"));
|
||||
// The compact summary: human names only, never the internal piece names.
|
||||
assert.match(out, /Skills: updated/);
|
||||
assert.match(out, /plan2code command: updated/);
|
||||
assert.match(out, /Desktop app: updated/);
|
||||
assert.match(out, /Status line: updated/);
|
||||
assert.doesNotMatch(out, /[✓✗] (skills|launcher|statusline|app|metrics|bot): /);
|
||||
assert.equal((out.match(/Update summary/g) || []).length, 1, "one summary");
|
||||
assert.match(out, new RegExp(`^What's new: https://github\\.com/jparkerweb/plan2code/releases/tag/v${VERSION.replace(/\./g, "\\.")}$`, "m"));
|
||||
assert.match(out, /Close any open Plan2Code console or app and start `plan2code` again\./);
|
||||
assert.doesNotMatch(out, /Happy coding|PARAMETERS|To go back to a release/);
|
||||
});
|
||||
|
||||
test("update: already on the new version it says so and stops, until --force", async () => {
|
||||
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: VERSION, scope: "global", pieces: ["skills", "launcher"] }));
|
||||
const idle = fakeSteps();
|
||||
const stopped = await runUpdate(idle.steps);
|
||||
assert.equal(stopped.code, 0, stopped.out);
|
||||
assert.match(stopped.out, new RegExp(`Already on ${VERSION.replace(/\./g, "\\.")}`));
|
||||
assert.match(stopped.out, /plan2code update --force/);
|
||||
assert.deepEqual(idle.ran(), [], "nothing was reinstalled");
|
||||
assert.doesNotMatch(stopped.out, /Update summary/);
|
||||
|
||||
const forced = fakeSteps();
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
let code;
|
||||
try {
|
||||
code = await installer.update({ steps: forced.steps, cleanShims: () => {}, force: true });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
const out = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "");
|
||||
assert.equal(code, 0, out);
|
||||
assert.deepEqual(forced.ran(), ["skills"]);
|
||||
assert.match(out, new RegExp(`Updating ${VERSION.replace(/\./g, "\\.")} -> ${VERSION.replace(/\./g, "\\.")}`));
|
||||
});
|
||||
|
||||
test("update: a step's own output stays out of the summary, except its warnings and its failures", async () => {
|
||||
writeRecord(["skills", "statusline", "bot"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.skills = async (options) => {
|
||||
console.log("Installing skills");
|
||||
console.log(" ✓ Built 23 skills from src/");
|
||||
console.log(" ! heads up from the skills step");
|
||||
options.outcome.skills = true;
|
||||
options.outcome.launcher = true;
|
||||
return 0;
|
||||
};
|
||||
fake.steps.statusline = async () => {
|
||||
console.log(" ✗ could not write settings.json");
|
||||
return 1;
|
||||
};
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 1, out);
|
||||
assert.doesNotMatch(out, /Installing skills|Built 23 skills/);
|
||||
assert.match(out, /! heads up from the skills step/);
|
||||
assert.match(out, /✗ could not write settings\.json/);
|
||||
});
|
||||
|
||||
test("update: a failed update puts the old version back in the record, so a retry runs instead of stopping at Already on", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps({ codes: { skills: 1 } });
|
||||
// As the real launcher step: it works, and recording it stamps the version being installed.
|
||||
fake.steps.launcher = async () => {
|
||||
installer.recordInstalled("launcher");
|
||||
return 0;
|
||||
};
|
||||
const failed = await runUpdate(fake.steps);
|
||||
assert.equal(failed.code, 1, failed.out);
|
||||
assert.match(failed.out, /To try again, run: plan2code update/);
|
||||
assert.match(failed.out, /To go back to a release, run: plan2code update --tag v1\.0\.0/);
|
||||
assert.equal(installer.readInstallRecord().version, "1.0.0", "the record stays on the old version");
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["launcher", "skills"], "and keeps every piece");
|
||||
|
||||
const retry = await runUpdate(fakeSteps().steps);
|
||||
assert.equal(retry.code, 0, retry.out);
|
||||
assert.doesNotMatch(retry.out, /Already on/);
|
||||
assert.match(retry.out, /Plan2Code is up to date/);
|
||||
});
|
||||
|
||||
test("update: an app kept because the release has no app file yet leaves the old version on the record, so the next update fetches it", async () => {
|
||||
writeRecord(["skills", "launcher", "app"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.app = async (options) => {
|
||||
installer.recordInstalled("app");
|
||||
options.outcome.appMissing = true;
|
||||
return 0;
|
||||
};
|
||||
const kept = await runUpdate(fake.steps);
|
||||
assert.equal(kept.code, 0, kept.out);
|
||||
assert.match(kept.out, /Desktop app: kept \(no new desktop app file yet\)/);
|
||||
assert.equal(installer.readInstallRecord().version, "1.0.0", "the record stays on the old version");
|
||||
|
||||
const next = await runUpdate(fakeSteps().steps);
|
||||
assert.equal(next.code, 0, next.out);
|
||||
assert.doesNotMatch(next.out, /Already on/);
|
||||
assert.match(next.out, /Desktop app: updated/);
|
||||
});
|
||||
|
||||
test("update: a failed desktop app install inside the skills step is shown, and does not fail the update", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.skills = async (options) => {
|
||||
console.log(" Built 23 skills from src/");
|
||||
console.log(" ✗ The desktop app was not installed: the download did not match its checksum.");
|
||||
options.outcome.skills = true;
|
||||
options.outcome.launcher = true;
|
||||
options.outcome.app = false;
|
||||
return 0;
|
||||
};
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, /✗ The desktop app was not installed: the download did not match its checksum\./);
|
||||
assert.doesNotMatch(out, /Built 23 skills/);
|
||||
});
|
||||
|
||||
test("update: the app's size is in its summary line when the skills step brought it in", async () => {
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const fake = fakeSteps();
|
||||
fake.steps.skills = async (options) => {
|
||||
options.outcome.skills = true;
|
||||
options.outcome.launcher = true;
|
||||
options.outcome.app = true;
|
||||
options.outcome.appSize = 3 * 1024 * 1024;
|
||||
return 0;
|
||||
};
|
||||
const { code, out } = await runUpdate(fake.steps);
|
||||
assert.equal(code, 0, out);
|
||||
assert.match(out, /Desktop app: updated \(3\.0 MB\)/);
|
||||
});
|
||||
|
||||
test("uninstall: printKeptData names the folder and lists each entry with its size", async () => {
|
||||
const data = path.join(HOME, ".plan2code");
|
||||
fs.mkdirSync(path.join(data, "handoffs"), { recursive: true });
|
||||
fs.writeFileSync(path.join(data, "handoffs", "h.md"), "y".repeat(3000));
|
||||
const { out } = await captured(() => installer.printKeptData());
|
||||
assert.match(out, /Your data in .* was kept/);
|
||||
assert.match(out, /Handoffs: 3 KB/);
|
||||
fs.rmSync(path.join(data, "handoffs"), { recursive: true, force: true });
|
||||
});
|
||||
|
||||
test("install.js --update: an option other than --force is refused", () => {
|
||||
const refused = spawnSync(process.execPath, [INSTALL, "--update", "--nope"], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(refused.status, 1);
|
||||
assert.match(refused.stderr, /Unknown option\(s\): --update --nope/);
|
||||
});
|
||||
|
||||
test("update: the real status line step keeps a custom statusLine without asking", async () => {
|
||||
@@ -186,7 +344,7 @@ test("update: every step is an install function, never an uninstall", () => {
|
||||
test("install.js: --update and --uninstall are in the usage line, and an unknown option still exits 1", () => {
|
||||
const result = spawnSync(process.execPath, [INSTALL, "--bogus"], { encoding: "utf8" });
|
||||
assert.equal(result.status, 1);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update | --uninstall [--yes] [--purge]]"), result.stderr);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update [--force] | --uninstall [--yes] [--purge]]"), result.stderr);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
@@ -207,7 +365,8 @@ async function releaseServer(files) {
|
||||
const name = decodeURIComponent(req.url.slice(1));
|
||||
hits.push(name);
|
||||
if (name in files) {
|
||||
res.writeHead(200);
|
||||
// As GitHub does, the size is sent, so the download can show it.
|
||||
res.writeHead(200, { "Content-Length": Buffer.byteLength(files[name]) });
|
||||
res.end(files[name]);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
@@ -282,7 +441,10 @@ test("app installed: the file is downloaded, verified, placed and recorded", { s
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)], "no temp or .old file is left");
|
||||
assert.match(out, /unsigned/);
|
||||
assert.match(out, /Downloading the desktop app \(1 KB\)\.\.\./, "piped: the size, on one plain line");
|
||||
assert.match(out, /not code-signed/);
|
||||
assert.ok(out.includes(`Installed: ${installer.APP_DEST}`), out);
|
||||
assert.ok(out.includes(installer.APP_GUIDE_URL), out);
|
||||
assert.deepEqual(server.hits, [`release/${SUMS}`, `release/${ASSET}`]);
|
||||
} finally {
|
||||
server.close();
|
||||
@@ -353,7 +515,7 @@ test("app update: plan2code update replaces an older app and reports it", { skip
|
||||
// The real app step, in the real update loop; the record lists only the app.
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: updated/);
|
||||
assert.match(out, /Desktop app: updated/);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]);
|
||||
} finally {
|
||||
@@ -368,7 +530,7 @@ test("app update: a checksum mismatch fails the update naming the app, nothing e
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /Update failed for: app/);
|
||||
assert.match(out, /Update failed for: Desktop app/);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
@@ -384,7 +546,7 @@ test("app update: a release with no app file yet keeps the installed app and doe
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS, cleanShims: () => {} }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: kept/);
|
||||
assert.match(out, /Desktop app: kept/);
|
||||
assert.doesNotMatch(out, /Update failed/);
|
||||
assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the installed app");
|
||||
} finally {
|
||||
@@ -621,6 +783,8 @@ async function runUninstall(options, answers = []) {
|
||||
},
|
||||
remove: () => (calls.push("remove"), 0),
|
||||
purgeIt: () => (calls.push("purge"), 0),
|
||||
purgeWebview: () => (calls.push("webview"), 0),
|
||||
running: () => false,
|
||||
...options,
|
||||
});
|
||||
return { code, asked, calls, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
@@ -648,7 +812,7 @@ test("uninstall: a yes removes everything, then asks about the data and keeps it
|
||||
|
||||
test("uninstall: a yes to the data question purges it", async () => {
|
||||
const r = await runUninstall({}, [true, true]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge"]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge", "webview"]);
|
||||
});
|
||||
|
||||
test("uninstall: --yes skips both questions and keeps the data", async () => {
|
||||
@@ -660,13 +824,13 @@ test("uninstall: --yes skips both questions and keeps the data", async () => {
|
||||
test("uninstall: --yes --purge deletes the data without a question", async () => {
|
||||
const r = await runUninstall({ yes: true, purge: true });
|
||||
assert.deepEqual(r.asked, []);
|
||||
assert.deepEqual(r.calls, ["remove", "purge"]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge", "webview"]);
|
||||
});
|
||||
|
||||
test("uninstall: --purge alone still confirms the uninstall but never asks about the data", async () => {
|
||||
const r = await runUninstall({ purge: true }, [true]);
|
||||
assert.equal(r.asked.length, 1);
|
||||
assert.deepEqual(r.calls, ["remove", "purge"]);
|
||||
assert.deepEqual(r.calls, ["remove", "purge", "webview"]);
|
||||
});
|
||||
|
||||
test("uninstall: a failing removal or purge makes the exit code non-zero", async () => {
|
||||
@@ -702,3 +866,492 @@ test("install.js --uninstall: with no terminal and no --yes it explains, exits 1
|
||||
assert.match(r.stdout, /Run plan2code uninstall --yes/);
|
||||
assert.ok(fs.existsSync(path.join(HOME, ".plan2code")));
|
||||
});
|
||||
|
||||
test("install: the Node guard names the version on Node older than 18", () => {
|
||||
assert.equal(installer.nodeVersionProblem("16.20.2"), "Plan2Code needs Node.js 18 or newer; you have v16.20.2. Get it from nodejs.org");
|
||||
assert.equal(installer.nodeVersionProblem("17.9.1").startsWith("Plan2Code needs Node.js 18 or newer"), true);
|
||||
assert.equal(installer.nodeVersionProblem("18.0.0"), null);
|
||||
assert.equal(installer.nodeVersionProblem("26.1.0"), null);
|
||||
});
|
||||
|
||||
test("install: an old Node fails fast with the guard's sentence before installing anything", () => {
|
||||
const code = `Object.defineProperty(process.versions, "node", { value: "16.20.2" }); require(${JSON.stringify(INSTALL)});`;
|
||||
const result = spawnSync(process.execPath, ["-e", code], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /Plan2Code needs Node\.js 18 or newer; you have v16\.20\.2\. Get it from nodejs\.org/);
|
||||
});
|
||||
|
||||
test("uninstall: --purge also removes the app's webview data, and a failure there is non-zero", async () => {
|
||||
assert.equal((await runUninstall({ yes: true, purge: true, purgeWebview: () => 1 })).code, 1);
|
||||
const kept = await runUninstall({ yes: true });
|
||||
assert.deepEqual(kept.calls, ["remove"]);
|
||||
});
|
||||
|
||||
test("uninstall: a running app is named before anything is removed", async () => {
|
||||
const r = await runUninstall({ yes: true, running: () => true });
|
||||
assert.match(r.out, /Plan2Code is running: close it first/);
|
||||
const quiet = await runUninstall({ yes: true });
|
||||
assert.doesNotMatch(quiet.out, /is running/);
|
||||
});
|
||||
|
||||
test("appWebviewDirs: the webview data folder for com.plan2code.desktop on each OS", () => {
|
||||
const home = path.join(path.sep, "h");
|
||||
// The last folder on each OS is the app's config folder, where the window-state file lives.
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "win32", home, env: { LOCALAPPDATA: path.join(home, "Local"), APPDATA: path.join(home, "Roaming") } }), [
|
||||
path.join(home, "Local", "com.plan2code.desktop"),
|
||||
path.join(home, "Roaming", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "win32", home, env: {} }), [
|
||||
path.join(home, "AppData", "Local", "com.plan2code.desktop"),
|
||||
path.join(home, "AppData", "Roaming", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "linux", home, env: {} }), [
|
||||
path.join(home, ".local", "share", "com.plan2code.desktop"),
|
||||
path.join(home, ".cache", "com.plan2code.desktop"),
|
||||
path.join(home, ".config", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "linux", home, env: { XDG_DATA_HOME: path.join(home, "d"), XDG_CACHE_HOME: path.join(home, "c"), XDG_CONFIG_HOME: path.join(home, "g") } }), [
|
||||
path.join(home, "d", "com.plan2code.desktop"),
|
||||
path.join(home, "c", "com.plan2code.desktop"),
|
||||
path.join(home, "g", "com.plan2code.desktop"),
|
||||
]);
|
||||
assert.deepEqual(installer.appWebviewDirs({ platform: "darwin", home, env: {} }), [
|
||||
path.join(home, "Library", "WebKit", "com.plan2code.desktop"),
|
||||
path.join(home, "Library", "WebKit", "plan2code-app"),
|
||||
path.join(home, "Library", "Caches", "com.plan2code.desktop"),
|
||||
path.join(home, "Library", "Caches", "plan2code-app"),
|
||||
path.join(home, "Library", "Application Support", "com.plan2code.desktop"),
|
||||
]);
|
||||
});
|
||||
|
||||
test("purgeAppWebview: removes the folders that exist and skips the rest", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-webview-"));
|
||||
const there = path.join(dir, "com.plan2code.desktop");
|
||||
fs.mkdirSync(path.join(there, "EBWebView"), { recursive: true });
|
||||
const log = console.log;
|
||||
console.log = () => {};
|
||||
try {
|
||||
assert.equal(installer.purgeAppWebview([there, path.join(dir, "missing")]), 0);
|
||||
assert.equal(fs.existsSync(there), false);
|
||||
} finally {
|
||||
console.log = log;
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("appRunning: asks tasklist on Windows and pgrep elsewhere by the program's name", () => {
|
||||
const seen = [];
|
||||
const run = (cmd, args) => (seen.push([cmd, ...args]), { status: 0, stdout: cmd === "tasklist" ? "plan2code-app.exe 1234 Console" : "" });
|
||||
assert.equal(installer.appRunning({ platform: "win32", run }), true);
|
||||
assert.equal(installer.appRunning({ platform: "win32", run: () => ({ status: 0, stdout: "INFO: No tasks are running" }) }), false);
|
||||
assert.equal(installer.appRunning({ platform: "linux", run }), true);
|
||||
assert.equal(installer.appRunning({ platform: "darwin", run: () => ({ status: 1 }) }), false);
|
||||
assert.equal(installer.appRunning({ platform: "linux", run: () => { throw new Error("no pgrep"); } }), false);
|
||||
assert.deepEqual(seen[1], ["pgrep", "-x", "plan2code-app"]);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The next steps after an install: on or off PATH, with or without the desktop app.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
/** printGettingStarted's output with colors stripped. */
|
||||
async function gettingStarted(options) {
|
||||
const { out } = await captured(() => installer.printGettingStarted({ commandInstalled: true, agents: { found: ["Claude Code"], builtins: [] }, ...options }));
|
||||
return out;
|
||||
}
|
||||
|
||||
const POSIX_BIN = "/home/me/.local/bin";
|
||||
|
||||
test("next steps: on PATH without the app, plan2code opens the agent and no PATH line is printed", async () => {
|
||||
const out = await gettingStarted({ pathMissing: false, appInstalled: false, platform: "linux" });
|
||||
assert.match(out, /plan2code\s+opens your AI agent on the Plan2Code dashboard/);
|
||||
assert.match(out, /page that opens in your browser/);
|
||||
assert.doesNotMatch(out, /not on your PATH|export PATH|open a new terminal/);
|
||||
});
|
||||
|
||||
test("next steps: on PATH with the app, steps 2 and 3 name the Plan2Code app", async () => {
|
||||
const out = await gettingStarted({ pathMissing: false, appInstalled: true, platform: "linux" });
|
||||
assert.match(out, /plan2code\s+opens the Plan2Code app/);
|
||||
assert.match(out, /3\. Pick a card on the dashboard: plan2code opens the Plan2Code app/);
|
||||
assert.doesNotMatch(out, /page that opens in your browser|export PATH/);
|
||||
});
|
||||
|
||||
test("next steps: off PATH without the app, the shell's PATH line, a new terminal and the full path", async () => {
|
||||
const out = await gettingStarted({ pathMissing: true, binDir: POSIX_BIN, appInstalled: false, platform: "linux", shell: "/bin/zsh" });
|
||||
assert.match(out, /export PATH="[^"]*\.local\/bin:\$PATH"' >> ~\/\.zshrc/);
|
||||
assert.match(out, /open a new terminal/);
|
||||
assert.ok(out.includes(`"${POSIX_BIN}/plan2code"`), out);
|
||||
assert.match(out, /opens your AI agent on the Plan2Code dashboard/);
|
||||
});
|
||||
|
||||
test("next steps: off PATH with the app on Windows, the PowerShell line, a new terminal, the .cmd path and the app", async () => {
|
||||
const bin = "C:\\Users\\me\\AppData\\Roaming\\npm";
|
||||
const out = await gettingStarted({ pathMissing: true, binDir: bin, appInstalled: true, platform: "win32" });
|
||||
assert.ok(out.includes(`[Environment]::SetEnvironmentVariable('Path', [Environment]::GetEnvironmentVariable('Path', 'User') + ';${bin}', 'User')`), out);
|
||||
assert.match(out, /open a new terminal/);
|
||||
assert.ok(out.includes(`& "${bin}\\plan2code.cmd"`), out);
|
||||
assert.match(out, /opens the Plan2Code app/);
|
||||
});
|
||||
|
||||
test("pathFixLine: bash and other shells get ~/.bashrc, a folder under home is written with $HOME", () => {
|
||||
const fix = installer.pathFixLine("/home/me/.local/bin", { platform: "linux", shell: "/bin/bash", home: "/home/me" });
|
||||
assert.equal(fix.file, "~/.bashrc");
|
||||
assert.equal(fix.line, `echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.bashrc`);
|
||||
assert.equal(installer.pathFixLine("/home/me/.local/bin", { platform: "darwin", shell: "/bin/zsh", home: "/home/me" }).file, "~/.zshrc");
|
||||
assert.equal(installer.pathFixLine("/opt/bin", { platform: "linux", shell: "/bin/bash", home: "/home/me" }).line, `echo 'export PATH="/opt/bin:$PATH"' >> ~/.bashrc`);
|
||||
});
|
||||
|
||||
test("next steps: with no agent found, plan2code's setup page is the lead and custom agents go to User Preferences", async () => {
|
||||
const builtins = [{ name: "Claude Code", installUrl: "https://example.test/claude", install: { linux: [{ run: "curl -fsSL https://example.test/install.sh | bash" }] } }];
|
||||
const out = await gettingStarted({ agents: { found: [], builtins }, platform: "linux" });
|
||||
assert.match(out, /No agent yet\? Just run plan2code: its setup page installs one with you\./);
|
||||
assert.ok(out.includes("curl -fsSL https://example.test/install.sh | bash (https://example.test/claude)"), out);
|
||||
assert.match(out, /User Preferences, Agents & models/);
|
||||
assert.doesNotMatch(out, /NO AI AGENT FOUND|agents\.json/);
|
||||
});
|
||||
|
||||
test("detectAgents: reads the shipped list and lookup, and finds a custom agent by its command", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
|
||||
try {
|
||||
const userFile = path.join(dir, "user-agents.json");
|
||||
fs.writeFileSync(userFile, JSON.stringify({ schema: 1, agents: [{ id: "mine", name: "Mine", command: process.execPath }] }));
|
||||
const nowhere = { path: "", savedPath: "", npmBin: "", home: dir, vars: {} };
|
||||
const result = await installer.detectAgents({ binDir: dir, userAgentsFile: userFile, env: nowhere });
|
||||
assert.ok(result.builtins.some((entry) => entry.id === "claude"), "falls back to src/ when nothing is installed");
|
||||
assert.deepEqual(result.found, ["Mine"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("desktopAppState: installed, failed, or skipped when declined, not offered or not built yet", () => {
|
||||
assert.equal(installer.desktopAppState({ app: true }), "installed");
|
||||
assert.equal(installer.desktopAppState({ app: false }), "failed");
|
||||
assert.equal(installer.desktopAppState({ app: false, appMissing: "no file yet" }), "skipped");
|
||||
assert.equal(installer.desktopAppState({}), "skipped");
|
||||
});
|
||||
|
||||
test("launcher shim: a plan2code without the launcher marker is saved as .bak, ours is replaced in place", () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-shim-"));
|
||||
const foreign = "#!/bin/sh\necho another tool\n";
|
||||
try {
|
||||
const file = path.join(dir, "plan2code");
|
||||
const shim = { file, content: `#!/bin/sh\n# ${installer.LAUNCHER_MARKER}\nexit 0\n` };
|
||||
fs.writeFileSync(file, foreign);
|
||||
assert.equal(installer.isOurLauncherShim(file), false);
|
||||
assert.deepEqual(installer.writeLauncherShim(shim), { backup: `${file}.bak` });
|
||||
assert.equal(fs.readFileSync(`${file}.bak`, "utf8"), foreign);
|
||||
assert.equal(installer.isOurLauncherShim(file), true);
|
||||
assert.deepEqual(installer.writeLauncherShim(shim), { backup: null }, "our own shim is never backed up");
|
||||
assert.equal(fs.readFileSync(`${file}.bak`, "utf8"), foreign);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("install.js: with no terminal the menu is not shown; it says how to install and exits 1", () => {
|
||||
const r = spawnSync(process.execPath, [INSTALL], { encoding: "utf8", input: "", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(r.status, 1, r.stdout + r.stderr);
|
||||
assert.equal(r.stdout.trim(), installer.NO_TERMINAL_MESSAGE);
|
||||
assert.equal(installer.NO_TERMINAL_MESSAGE, "Run this in a terminal, or use `--update` for an unattended install.");
|
||||
});
|
||||
|
||||
test("install.js: piped output carries no escape codes and no boxes", () => {
|
||||
const code = `require(${JSON.stringify(INSTALL)}).printGettingStarted({ commandInstalled: true, agents: { found: [], builtins: [] } })`;
|
||||
const piped = spawnSync(process.execPath, ["-e", code], { encoding: "utf8", env: { ...process.env, HOME, USERPROFILE: HOME } });
|
||||
assert.equal(piped.status, 0, piped.stderr);
|
||||
assert.match(piped.stdout, /How to use Plan2Code/);
|
||||
assert.doesNotMatch(piped.stdout, /\x1b\[|╭|╰/);
|
||||
});
|
||||
|
||||
test("createSpinner: piped, it prints its label once as a plain line and draws nothing", () => {
|
||||
const writes = [];
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
const spinner = installer.createSpinner("Running skills add...", { stream: { isTTY: false, write: (s) => writes.push(s) } }).start();
|
||||
spinner.stop();
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
assert.deepEqual(lines, [" Running skills add..."]);
|
||||
assert.deepEqual(writes, []);
|
||||
});
|
||||
|
||||
test("createSpinner: on a terminal it redraws one line with the seconds and clears it on stop", () => {
|
||||
const writes = [];
|
||||
const spinner = installer.createSpinner("Running skills add...", { stream: { isTTY: true, write: (s) => writes.push(s) } }).start();
|
||||
spinner.stop();
|
||||
assert.match(writes[0], /^\r {2}\S+ Running skills add\.\.\. 0s/);
|
||||
assert.equal(writes.at(-1), "\r\x1b[K");
|
||||
});
|
||||
|
||||
test("detectAgents: an agent only in npm's folder or an install folder off PATH is not present, as the launcher sees it", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-off-"));
|
||||
try {
|
||||
for (const name of ["claude", "claude.cmd"]) fs.writeFileSync(path.join(dir, name), "");
|
||||
if (process.platform !== "win32") fs.chmodSync(path.join(dir, "claude"), 0o755);
|
||||
const none = path.join(dir, "none.json");
|
||||
const off = { path: "", savedPath: "", npmBin: dir, home: dir, pathext: ".CMD", vars: {} };
|
||||
assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: none, env: off })).found, []);
|
||||
const on = { ...off, npmBin: "", path: dir };
|
||||
assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: none, env: on })).found, ["Claude Code"]);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("detectAgents: a custom agents file with the wrong schema is ignored, as the launcher ignores it", async () => {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-schema-"));
|
||||
try {
|
||||
const userFile = path.join(dir, "user-agents.json");
|
||||
fs.writeFileSync(userFile, JSON.stringify({ schema: 99, agents: [{ id: "mine", name: "Mine", command: process.execPath }] }));
|
||||
const nowhere = { path: "", savedPath: "", npmBin: "", home: dir, vars: {} };
|
||||
assert.deepEqual((await installer.detectAgents({ binDir: dir, userAgentsFile: userFile, env: nowhere })).found, []);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("next steps: without the plan2code command, no line tells the person to run it", async () => {
|
||||
const { out } = await captured(() => installer.printGettingStarted({ commandInstalled: false, agents: { found: [], builtins: [] }, platform: "linux" }));
|
||||
assert.doesNotMatch(out, /run plan2code|Just run plan2code/);
|
||||
assert.match(out, /type \/plan2code/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Uninstall: works without the skills CLI, prints only what was installed, removes the console,
|
||||
// lists what stays, and always ends with the Removed / Could not remove / To finish block.
|
||||
// Everything runs against the temp HOME above; the steps that would reach the real machine (the
|
||||
// npm global bin, the desktop folder) are replaced.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const CLAUDE_DIR = path.join(HOME, ".claude");
|
||||
const SKILL_STORE = path.join(HOME, ".agents", "skills");
|
||||
|
||||
/** The legacy sweep reads %APPDATA% and %LOCALAPPDATA% on Windows: point them into the temp HOME while `fn` runs. */
|
||||
function withAppData(fn) {
|
||||
const saved = { APPDATA: process.env.APPDATA, LOCALAPPDATA: process.env.LOCALAPPDATA };
|
||||
process.env.APPDATA = path.join(HOME, "AppData", "Roaming");
|
||||
process.env.LOCALAPPDATA = path.join(HOME, "AppData", "Local");
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(saved)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function makeSkill(name) {
|
||||
fs.mkdirSync(path.join(SKILL_STORE, name), { recursive: true });
|
||||
fs.writeFileSync(path.join(SKILL_STORE, name, "SKILL.md"), "---\nname: x\n---\n");
|
||||
}
|
||||
|
||||
test("uninstall without the skills CLI: the plan2code skill folders go directly, others stay, and the block says links may remain", () => {
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
for (const name of ["plan2code", "plan2code-plan", "plan2code-3-implement", "someone-elses-skill"]) makeSkill(name);
|
||||
const report = installer.newUninstallReport();
|
||||
const result = withAppData(() => installer.uninstallSkillsPiece(report, { cli: { ensure: () => false, remove: () => assert.fail("the CLI is unreachable") } }));
|
||||
assert.equal(result.removed, 3);
|
||||
assert.deepEqual(result.failed, []);
|
||||
assert.deepEqual(fs.readdirSync(SKILL_STORE), ["someone-elses-skill"]);
|
||||
assert.equal(report.finish.length, 1);
|
||||
assert.match(report.finish[0], /could not be reached/);
|
||||
assert.match(report.finish[0], /may remain/);
|
||||
assert.deepEqual(installer.removeSkillsDirectly(SKILL_STORE), { removed: [], failed: [] }, "nothing left to remove, no error");
|
||||
});
|
||||
|
||||
test("uninstall with the skills CLI: it does the removing and no folder is touched by hand", () => {
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
makeSkill("plan2code");
|
||||
const calls = [];
|
||||
const report = installer.newUninstallReport();
|
||||
const result = withAppData(() =>
|
||||
installer.uninstallSkillsPiece(report, {
|
||||
cli: { ensure: () => true, remove: (scope, options) => (calls.push([scope, options.quiet]), 1) },
|
||||
})
|
||||
);
|
||||
assert.deepEqual(calls, [["global", true]]);
|
||||
assert.equal(result.removed, 1);
|
||||
assert.deepEqual(report.finish, [], "nothing is left to do");
|
||||
assert.ok(fs.existsSync(path.join(SKILL_STORE, "plan2code")), "the stand-in CLI removed nothing, and nothing else did");
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
/** uninstallAll() with every step replaced by one that records itself; `results` says what each reports. */
|
||||
function uninstallWith({ pieces, results = {}, probes = {} }) {
|
||||
if (pieces) writeRecord(pieces);
|
||||
else clearRecord();
|
||||
const ran = [];
|
||||
const steps = {};
|
||||
for (const piece of installer.INSTALL_PIECES) {
|
||||
steps[piece] = () => (ran.push(piece), results[piece] || { removed: 1, failed: [] });
|
||||
}
|
||||
const report = installer.newUninstallReport();
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
let code;
|
||||
try {
|
||||
code = installer.uninstallAll({ report, steps, probes, removeConsole: () => {} });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
return { code, ran, report, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
}
|
||||
|
||||
const NO_STRAYS = { skills: () => false, launcher: () => false, app: () => false, statusline: () => false };
|
||||
|
||||
test("uninstall: only the recorded pieces are removed and named, never ones that were not installed", () => {
|
||||
const r = uninstallWith({ pieces: ["skills", "launcher"], probes: NO_STRAYS, results: { skills: { removed: 23, failed: [], detail: "23" } } });
|
||||
assert.equal(r.code, 0, r.out);
|
||||
assert.deepEqual(r.ran, ["skills", "launcher"]);
|
||||
assert.match(r.out, /Removed Skills \(23\)/);
|
||||
assert.match(r.out, /Removed plan2code command/);
|
||||
assert.doesNotMatch(r.out, /Status line|Metrics|Bot|Desktop app|UNINSTALL|plan2code-metrics|plan2code-bot/);
|
||||
assert.deepEqual(r.report.removed, ["Skills (23)", "plan2code command"]);
|
||||
});
|
||||
|
||||
test("uninstall: a piece missing from the record but found on disk is removed, and a piece found nowhere is not run", () => {
|
||||
const r = uninstallWith({ pieces: null, probes: { ...NO_STRAYS, statusline: () => true } });
|
||||
assert.deepEqual(r.ran, ["statusline"]);
|
||||
assert.match(r.out, /Removed Status line/);
|
||||
});
|
||||
|
||||
test("uninstall: the real probes look at the temp HOME and find nothing there", () => {
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), { force: true });
|
||||
fs.rmSync(SKILL_STORE, { recursive: true, force: true });
|
||||
fs.rmSync(installer.APP_DEST, { force: true });
|
||||
assert.equal(installer.UNINSTALL_PROBES.skills(), false);
|
||||
assert.equal(installer.UNINSTALL_PROBES.app(), false);
|
||||
assert.equal(installer.UNINSTALL_PROBES.statusline(), false);
|
||||
fs.mkdirSync(CLAUDE_DIR, { recursive: true });
|
||||
fs.writeFileSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), "// ours");
|
||||
assert.equal(installer.UNINSTALL_PROBES.statusline(), true);
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "plan2code-statusline.js"), { force: true });
|
||||
});
|
||||
|
||||
test("uninstall: the status line says it kept statusline-config.json only when that file exists", async () => {
|
||||
fs.mkdirSync(CLAUDE_DIR, { recursive: true });
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "statusline-config.json"), { force: true });
|
||||
const quiet = (await captured(() => installer.uninstallStatusLine())).out;
|
||||
assert.doesNotMatch(quiet, /Preserved: statusline-config\.json/);
|
||||
fs.writeFileSync(path.join(CLAUDE_DIR, "statusline-config.json"), "{}");
|
||||
const kept = (await captured(() => installer.uninstallStatusLine())).out;
|
||||
assert.match(kept, /Preserved: statusline-config\.json/);
|
||||
fs.rmSync(path.join(CLAUDE_DIR, "statusline-config.json"), { force: true });
|
||||
});
|
||||
|
||||
test("uninstall: a piece that fails is named, makes the exit code 1, and the others still run", () => {
|
||||
const r = uninstallWith({ pieces: ["skills", "launcher", "app"], probes: NO_STRAYS, results: { launcher: { removed: 0, failed: ["EBUSY: file in use"] } } });
|
||||
assert.equal(r.code, 1, r.out);
|
||||
assert.deepEqual(r.ran, ["skills", "launcher", "app"]);
|
||||
assert.deepEqual(r.report.failed, ["plan2code command: EBUSY: file in use"]);
|
||||
assert.match(r.out, /plan2code command: EBUSY: file in use/);
|
||||
});
|
||||
|
||||
test("uninstall: the console's version folders and pointer are removed, a running console is stopped first, and sessions stay", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-home-"));
|
||||
process.env.PLAN2CODE_CONSOLE_HOME = home;
|
||||
try {
|
||||
for (const version of ["3.0.2", "3.1.0"]) {
|
||||
fs.mkdirSync(path.join(home, version, "public"), { recursive: true });
|
||||
fs.writeFileSync(path.join(home, version, "console.mjs"), "// console");
|
||||
}
|
||||
fs.writeFileSync(path.join(home, "console-dir"), path.join(home, "3.1.0"));
|
||||
fs.mkdirSync(path.join(home, "sessions", "s1"), { recursive: true });
|
||||
fs.writeFileSync(path.join(home, "looks.json"), "{}");
|
||||
const stopped = [];
|
||||
const report = installer.newUninstallReport();
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
installer.removeConsoleFolders(report, { stop: (dir) => (stopped.push(dir), 1) });
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
const out = lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "");
|
||||
assert.deepEqual(stopped, [home]);
|
||||
assert.match(out, /Stopped 1 running Plan2Code console first/);
|
||||
assert.deepEqual(fs.readdirSync(home).sort(), ["looks.json", "sessions"]);
|
||||
assert.deepEqual(report.removed, ["Console files"]);
|
||||
assert.deepEqual(report.failed, []);
|
||||
} finally {
|
||||
delete process.env.PLAN2CODE_CONSOLE_HOME;
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("uninstall: a console folder that cannot be removed is reported with what to do, and a missing console home is fine", () => {
|
||||
const home = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-busy-"));
|
||||
process.env.PLAN2CODE_CONSOLE_HOME = home;
|
||||
const realRm = fs.rmSync;
|
||||
try {
|
||||
fs.mkdirSync(path.join(home, "3.0.2"), { recursive: true });
|
||||
fs.mkdirSync(path.join(home, "3.1.0"), { recursive: true });
|
||||
fs.rmSync = (target, options) => {
|
||||
if (String(target).endsWith("3.0.2")) throw new Error("EBUSY: resource busy");
|
||||
return realRm(target, options);
|
||||
};
|
||||
const report = installer.newUninstallReport();
|
||||
const log = console.log;
|
||||
console.log = () => {};
|
||||
try {
|
||||
installer.removeConsoleFolders(report, { stop: () => 0 });
|
||||
} finally {
|
||||
console.log = log;
|
||||
fs.rmSync = realRm;
|
||||
}
|
||||
assert.deepEqual(report.failed, ["Console files 3.0.2: EBUSY: resource busy"]);
|
||||
assert.deepEqual(report.finish, ["Close any open Plan2Code console or app, then run plan2code uninstall again."]);
|
||||
assert.deepEqual(report.removed, ["Console files"]);
|
||||
assert.ok(fs.existsSync(path.join(home, "3.0.2")) && !fs.existsSync(path.join(home, "3.1.0")));
|
||||
process.env.PLAN2CODE_CONSOLE_HOME = path.join(home, "nowhere");
|
||||
assert.doesNotThrow(() => installer.removeConsoleFolders(installer.newUninstallReport(), { stop: () => 0 }));
|
||||
} finally {
|
||||
fs.rmSync = realRm;
|
||||
delete process.env.PLAN2CODE_CONSOLE_HOME;
|
||||
realRm(home, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("uninstall: what stays in the data folder is listed by name with its size, and the closing block always prints", async () => {
|
||||
const data = path.join(HOME, ".plan2code");
|
||||
fs.rmSync(path.join(data, "notepads"), { recursive: true, force: true });
|
||||
fs.mkdirSync(path.join(data, "notepads"), { recursive: true });
|
||||
fs.writeFileSync(path.join(data, "notepads", "a.json"), "x".repeat(2048));
|
||||
fs.mkdirSync(path.join(data, "handoffs"), { recursive: true });
|
||||
const listed = installer.listKeptData(data);
|
||||
const notebooks = listed.find((item) => item.name === "notepads");
|
||||
assert.equal(notebooks.label, "Notebooks");
|
||||
assert.equal(notebooks.bytes, 2048);
|
||||
assert.ok(listed.some((item) => item.name === "handoffs" && item.label === "Handoffs"));
|
||||
|
||||
const kept = await runUninstall({ yes: true });
|
||||
assert.equal(kept.code, 0);
|
||||
assert.match(kept.out, /Your data in .* was kept/);
|
||||
assert.match(kept.out, /Notebooks: 2 KB/);
|
||||
assert.match(kept.out, /Removed: nothing/);
|
||||
assert.match(kept.out, /Could not remove: nothing/);
|
||||
assert.match(kept.out, /To finish: nothing, you are done/);
|
||||
assert.match(kept.out, /Plan2Code is uninstalled/);
|
||||
|
||||
// A failed run still ends on the block, says that something failed, and leaves no cheerful closing line.
|
||||
const failed = await runUninstall({ yes: true, remove: () => 1 });
|
||||
assert.equal(failed.code, 1);
|
||||
assert.match(failed.out, /Removed: nothing/);
|
||||
assert.match(failed.out, /Could not remove:\n\s+✗ One or more pieces/);
|
||||
assert.match(failed.out, /To finish:/);
|
||||
assert.doesNotMatch(failed.out, /Plan2Code is uninstalled/);
|
||||
|
||||
// With the data deleted there is nothing to list, and the block names the data as removed.
|
||||
const purged = await runUninstall({ yes: true, purge: true });
|
||||
assert.doesNotMatch(purged.out, /Notebooks:/);
|
||||
assert.match(purged.out, /Removed: Your Plan2Code data/);
|
||||
fs.rmSync(path.join(data, "notepads"), { recursive: true, force: true });
|
||||
fs.rmSync(path.join(data, "handoffs"), { recursive: true, force: true });
|
||||
});
|
||||
+367
-15
@@ -10,7 +10,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
import { spawn, spawnSync } from "node:child_process";
|
||||
import { createRequire } from "node:module";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
@@ -19,6 +19,9 @@ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const LAUNCHER = path.join(ROOT, "src", "launcher", "plan2code.js");
|
||||
const IS_WINDOWS = process.platform === "win32";
|
||||
const NOTICE = "will use the model you last used in it";
|
||||
// The no-agent pointer to custom agents, word for word as install.js prints it (Task 2.10/2.11).
|
||||
const NO_AGENT_POINTER =
|
||||
"Already use another agent CLI? Add it in User Preferences, Agents & models (the gear on the Plan2Code page), then run `plan2code` again.";
|
||||
|
||||
/**
|
||||
* A temp home and a bin dir holding stand-ins for `clis`; each writes its args to <bin>/<cli>.json.
|
||||
@@ -86,9 +89,12 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
fs.writeFileSync(crashFile, "#!/bin/sh\nexit 3\n");
|
||||
fs.chmodSync(crashFile, 0o755);
|
||||
}
|
||||
const envFor = (env = {}) => ({ ...process.env, PATH: bin, PLAN2CODE_NO_SAVED_PATH: "1", HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env });
|
||||
return {
|
||||
dir,
|
||||
home,
|
||||
launcher,
|
||||
envFor,
|
||||
appFile,
|
||||
crashFile,
|
||||
stateFile: path.join(home, ".plan2code", "launcher.json"),
|
||||
@@ -98,7 +104,7 @@ function sandbox(clis, { installed, project = true, lookup = true, agents } = {}
|
||||
cwd: dir,
|
||||
input: "",
|
||||
encoding: "utf8",
|
||||
env: { ...process.env, PATH: bin, PLAN2CODE_NO_SAVED_PATH: "1", HOME: home, USERPROFILE: home, PLAN2CODE_CONSOLE_HOME: consoleHome, ...env },
|
||||
env: envFor(env),
|
||||
}),
|
||||
argsOf: (cli) => {
|
||||
const file = path.join(bin, `${cli}.json`);
|
||||
@@ -255,7 +261,12 @@ test("launcher: the shipped models.json lists every CLI, and every entry has an
|
||||
const shipped = JSON.parse(fs.readFileSync(path.join(path.dirname(LAUNCHER), "models.json"), "utf8"));
|
||||
for (const cli of ["claude", "devin", "codex"]) {
|
||||
assert.ok(Array.isArray(shipped[cli]), cli);
|
||||
for (const { id, label } of shipped[cli]) assert.ok(id && label, cli);
|
||||
for (const { id, label } of shipped[cli]) {
|
||||
assert.ok(id && label, cli);
|
||||
// A label is the description only: the launcher prints the id beside it, so no label
|
||||
// repeats a name ahead of a gloss ("Sonnet, latest Sonnet" or the same with a dash).
|
||||
assert.doesNotMatch(label, /\u2014|^[^\s,]+, /, `${cli} ${id}: ${label}`);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
@@ -446,8 +457,9 @@ test("launcher: with no CLI installed it exits 127 and explains how to get one a
|
||||
]) {
|
||||
assert.ok(result.stderr.includes(part), part);
|
||||
}
|
||||
assert.ok(result.stderr.includes("Add it by editing `~/.plan2code/agents.json`, then run `plan2code` again."));
|
||||
assert.doesNotMatch(result.stderr, /User Preferences/);
|
||||
// The same pointer install.js prints for custom agents; no hand-editing of agents.json.
|
||||
assert.ok(result.stderr.includes(NO_AGENT_POINTER));
|
||||
assert.doesNotMatch(result.stderr, /editing/);
|
||||
assert.ok(result.stderr.includes("type /plan2code ($plan2code in Codex)"));
|
||||
assert.match(result.stderr, /cd into the project/);
|
||||
});
|
||||
@@ -468,42 +480,136 @@ test("launcher: the CLI's non-zero exit code is passed through", (t) => {
|
||||
assert.equal(result.status, 7, result.stderr);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
});
|
||||
test("launcher: update runs the npx install and starts no agent", (t) => {
|
||||
/** A `git ls-remote --tags` answer for `tags`, written to a file the launcher reads in git's place. */
|
||||
function lsRemoteStub(box, tags) {
|
||||
const file = path.join(box.dir, "ls-remote.txt");
|
||||
const lines = tags.map((tag, i) => `${String(i + 1).repeat(40).slice(0, 40)}\trefs/tags/${tag}`);
|
||||
fs.writeFileSync(file, lines.join("\n") + "\n");
|
||||
return { PLAN2CODE_LS_REMOTE_FILE: file };
|
||||
}
|
||||
|
||||
const REPO = "git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
test("launcher: update installs the newest release tag, by version and not by name or order", (t) => {
|
||||
const box = sandbox(["npx", "claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"]);
|
||||
// v3.10.0 beats v3.9.0 numerically; a pre-release, a peeled line and a non-release tag never count.
|
||||
const env = lsRemoteStub(box, ["v3.9.0", "v3.10.0", "v3.10.1-rc1", "v3.10.0^{}", "nightly", "v3.2.0"]);
|
||||
const result = box.run(["update"], env);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code\.\.\./);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.10\.0\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args, "npx was not run");
|
||||
assert.ok(args.includes("--update"), args.join(" "));
|
||||
assert.ok(args.includes("git+https://github.com/jparkerweb/plan2code.git"), args.join(" "));
|
||||
assert.ok(args.includes(`${REPO}#v3.10.0`), args.join(" "));
|
||||
assert.ok(!args.includes("--force"), args.join(" "));
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: update --main installs the tip of main, as it always did", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update", "--main"], lsRemoteStub(box, ["v9.9.9"]));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to the newest work on main\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args.includes(REPO), args.join(" "));
|
||||
assert.ok(!args.some((arg) => arg.includes("#")), args.join(" "));
|
||||
// Unreleased work on main carries the last release's version, so the installer's "Already on"
|
||||
// check would stop it: --main always reinstalls.
|
||||
assert.ok(args.includes("--force"), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --tag reinstalls for a branch, and not for a release tag", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update", "--tag", "release"]).status, 0);
|
||||
let args = box.argsOf("npx");
|
||||
assert.ok(args.includes(`${REPO}#release`) && args.includes("--force"), args.join(" "));
|
||||
assert.equal(box.run(["update", "--tag", "v3.0.2"]).status, 0);
|
||||
args = box.argsOf("npx");
|
||||
assert.ok(args.includes(`${REPO}#v3.0.2`) && !args.includes("--force"), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --tag installs that ref without asking for the release list", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
// No tag list is available at all: --tag must not need one.
|
||||
const result = box.run(["update", "--tag", "v3.0.2"], { PLAN2CODE_LS_REMOTE_FILE: path.join(box.dir, "missing.txt") });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Updating Plan2Code to v3\.0\.2\.\.\./);
|
||||
assert.ok(box.argsOf("npx").includes(`${REPO}#v3.0.2`), box.argsOf("npx").join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update --force reaches the installer", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update", "--force"], lsRemoteStub(box, ["v3.1.0"])).status, 0);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args.includes("--update") && args.includes("--force"), args.join(" "));
|
||||
assert.ok(args.includes(`${REPO}#v3.1.0`), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: update with no release list says so and installs nothing", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["update"], lsRemoteStub(box, ["nightly", "v1.0"]));
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /could not find the newest Plan2Code release/);
|
||||
assert.match(result.stderr, /--main/);
|
||||
assert.match(result.stderr, /--tag v3\.0\.2/);
|
||||
assert.equal(box.argsOf("npx"), null);
|
||||
});
|
||||
|
||||
test("launcher: update refuses a --tag with no value, both --main and --tag, and an unknown option", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
for (const [args, message] of [
|
||||
[["update", "--tag"], /--tag needs a release or branch/],
|
||||
[["update", "--main", "--tag", "v3.0.2"], /use --main or --tag, not both/],
|
||||
[["update", "--nope"], /unknown option for update: --nope/],
|
||||
]) {
|
||||
const result = box.run(args);
|
||||
assert.equal(result.status, 2, args.join(" "));
|
||||
assert.match(result.stderr, message);
|
||||
assert.equal(box.argsOf("npx"), null);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher: update passes npx's exit code through", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["update"], { P2C_TEST_EXIT: "3" }).status, 3);
|
||||
assert.equal(box.run(["update", "--main"], { P2C_TEST_EXIT: "3" }).status, 3);
|
||||
});
|
||||
|
||||
test("launcher: uninstall runs the npx install with --uninstall and starts no agent", (t) => {
|
||||
const box = sandbox(["npx", "claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["uninstall", "--yes", "--purge"]);
|
||||
const result = box.run(["uninstall", "--yes", "--purge"], lsRemoteStub(box, ["v3.1.0", "v3.0.2"]));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /Uninstalling Plan2Code\.\.\./);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args, "npx was not run");
|
||||
assert.ok(args.includes("--uninstall") && args.includes("--yes") && args.includes("--purge"), args.join(" "));
|
||||
assert.ok(!args.includes("--update"), args.join(" "));
|
||||
// The newest release's installer, never unreleased work on main.
|
||||
assert.ok(args.includes(`${REPO}#v3.1.0`), args.join(" "));
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher: uninstall falls back to main when the newest release cannot be found", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["uninstall", "--yes"], lsRemoteStub(box, ["nightly"]));
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const args = box.argsOf("npx");
|
||||
assert.ok(args.includes(REPO) && !args.some((arg) => arg.includes("#")), args.join(" "));
|
||||
});
|
||||
|
||||
test("launcher: uninstall passes npx's exit code through", (t) => {
|
||||
const box = sandbox(["npx"]);
|
||||
t.after(box.cleanup);
|
||||
assert.equal(box.run(["uninstall"], { P2C_TEST_EXIT: "4" }).status, 4);
|
||||
assert.equal(box.run(["uninstall"], { P2C_TEST_EXIT: "4", ...lsRemoteStub(box, ["v3.1.0"]) }).status, 4);
|
||||
});
|
||||
|
||||
test("launcher: uninstall refuses an unknown option without running npx", (t) => {
|
||||
@@ -948,7 +1054,8 @@ test("launcher agents: a custom agent whose command is not found is left out and
|
||||
const result = none.run([]);
|
||||
assert.equal(result.status, 127);
|
||||
assert.match(result.stderr, /Custom agent Ghost: ghost-cmd not found/);
|
||||
assert.ok(result.stderr.includes("agents.json"));
|
||||
// Custom agents are fixed where they are added: User Preferences, Agents & models.
|
||||
assert.ok(result.stderr.includes(NO_AGENT_POINTER));
|
||||
});
|
||||
|
||||
test("launcher agents: a malformed agents.json warns on a terminal, never crashes, and gives no agents", (t) => {
|
||||
@@ -1045,8 +1152,8 @@ test("launcher list: with no agent and no terminal it prints this OS's install s
|
||||
assert.ok(result.stderr.includes(leadRun(id)), `${id}: ${leadRun(id)}`);
|
||||
assert.ok(result.stderr.includes(builtin(id).installUrl), id);
|
||||
}
|
||||
assert.ok(result.stderr.includes("add another agent by editing `~/.plan2code/agents.json`, then run `plan2code` again") || result.stderr.includes("Add it by editing `~/.plan2code/agents.json`, then run `plan2code` again."));
|
||||
assert.doesNotMatch(result.stderr, /User Preferences/);
|
||||
assert.ok(result.stderr.includes(NO_AGENT_POINTER));
|
||||
assert.doesNotMatch(result.stderr, /agents\.json/);
|
||||
});
|
||||
|
||||
test("launcher list: --cli for a missing built-in prints its lead install line and exits 127", (t) => {
|
||||
@@ -1464,3 +1571,248 @@ test("launcher folder menu: a folder that fails the project check is not recorde
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.deepEqual(JSON.parse(fs.readFileSync(box.stateFile, "utf8")), state);
|
||||
});
|
||||
|
||||
// --help, --version and the Node guard: none of them shows a prompt or starts an agent.
|
||||
const PROMPT_TEXT = /Which|\(Y\/n\)|\(y\/N\)|Choose|Pick/;
|
||||
|
||||
for (const flag of ["--help", "-h", "help"]) {
|
||||
test(`launcher help: ${flag} prints the usage and exits 0 with no prompt`, (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([flag]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /^Usage: plan2code/m);
|
||||
for (const word of ["update", "uninstall", "--tag", "--main", "--force", "Go back to a release", "plan2code update --tag v3.0.2", "--cli", "--classic", "--keep-permissions", "--bypass-permissions", "--pick-folder"]) {
|
||||
assert.ok(result.stdout.includes(word), `the usage names ${word}`);
|
||||
}
|
||||
assert.match(result.stdout, /plan2code -- --help shows your agent's own help/);
|
||||
assert.doesNotMatch(result.stdout, PROMPT_TEXT);
|
||||
assert.equal(box.argsOf("claude"), null, "no agent started");
|
||||
});
|
||||
}
|
||||
|
||||
for (const flag of ["--version", "-v"]) {
|
||||
test(`launcher version: ${flag} prints the installed version and exits 0 with no prompt`, (t) => {
|
||||
const box = sandbox(["claude"], { installed: "9.8.7" });
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([flag]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.stdout.trim(), "Plan2Code v9.8.7");
|
||||
assert.equal(box.argsOf("claude"), null, "no agent started");
|
||||
});
|
||||
}
|
||||
|
||||
test("launcher help: --help after -- goes to the agent, without the separator", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["--", "--help"]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stdout, /^Usage: plan2code/m);
|
||||
assert.deepEqual(box.argsOf("claude"), [...CLASSIC_ARGS, "--help"]);
|
||||
});
|
||||
|
||||
test("launcher app: arguments the app does not take are named in one line", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--model", "opus", "--verbose"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.appArgs().slice(2), ["--agent", "claude", "--model", "opus"]);
|
||||
assert.match(result.stdout, /not passed on: --verbose$/m);
|
||||
});
|
||||
|
||||
test("launcher app: no dropped-argument line when nothing is dropped", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--model", "opus"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stdout, /not passed on/);
|
||||
});
|
||||
|
||||
test("launcher: droppedForApp keeps every argument but the model flag's forms", () => {
|
||||
const { droppedForApp } = require(LAUNCHER);
|
||||
assert.deepEqual(droppedForApp(["--model", "x", "--verbose"], "claude"), ["--verbose"]);
|
||||
assert.deepEqual(droppedForApp(["--model=x", "-p"], "claude"), ["-p"]);
|
||||
assert.deepEqual(droppedForApp(["-m", "x", "-mfoo", "--y"], "codex"), ["--y"]);
|
||||
assert.deepEqual(droppedForApp(["-m", "x"], "claude"), ["-m", "x"]);
|
||||
assert.deepEqual(droppedForApp([], "claude"), []);
|
||||
});
|
||||
|
||||
test("launcher: the Node guard names the version on Node older than 18", () => {
|
||||
const { nodeVersionProblem } = require(LAUNCHER);
|
||||
assert.equal(nodeVersionProblem("16.20.2"), "Plan2Code needs Node.js 18 or newer; you have v16.20.2. Get it from nodejs.org");
|
||||
assert.equal(nodeVersionProblem("18.0.0"), null);
|
||||
assert.equal(nodeVersionProblem("26.1.0"), null);
|
||||
});
|
||||
|
||||
test("launcher: an old Node fails fast with the guard's sentence", () => {
|
||||
// The guard runs before anything else, so a stubbed process.versions.node stops the load.
|
||||
const code = `Object.defineProperty(process.versions, "node", { value: "16.20.2" }); require(${JSON.stringify(LAUNCHER)});`;
|
||||
const result = spawnSync(process.execPath, ["-e", code], { encoding: "utf8" });
|
||||
assert.equal(result.status, 1);
|
||||
assert.match(result.stderr, /Plan2Code needs Node\.js 18 or newer; you have v16\.20\.2\. Get it from nodejs\.org/);
|
||||
});
|
||||
|
||||
test("launcher app: arguments after -- keep the run in this terminal even with the app installed", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--", "--help"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(box.appExists(), false, "the app was not started");
|
||||
assert.deepEqual(box.argsOf("claude"), [...CLASSIC_ARGS, "--help"]);
|
||||
assert.doesNotMatch(result.stdout, /not passed on/);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// Prompts at a "terminal". A preload marks stdin as a TTY, so the launcher asks its questions;
|
||||
// stdin stays a pipe. Each prompt opens its own readline, and a readline takes everything
|
||||
// waiting on the pipe, so answers piped in all at once reach the first prompt only: each
|
||||
// answer is written once its prompt shows on stdout, after a short pause.
|
||||
|
||||
/**
|
||||
* Run the launcher with `steps` ([{ when: RegExp, send }]) answered in order, each `when`
|
||||
* matched against the stdout printed since the last answer. Resolves { status, stdout, stderr,
|
||||
* sent } once it exits (killed after 20s, so a prompt nobody answers fails the test, not hangs).
|
||||
*/
|
||||
function runAtTerminal(box, args, steps, { env = {}, cwd = box.dir } = {}) {
|
||||
const shim = path.join(box.dir, "tty-shim.cjs");
|
||||
fs.writeFileSync(shim, 'Object.defineProperty(process.stdin, "isTTY", { value: true, configurable: true });\n');
|
||||
return new Promise((resolve) => {
|
||||
const child = spawn(process.execPath, ["-r", shim, box.launcher, ...args], { cwd, env: box.envFor(env) });
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
let from = 0;
|
||||
let sent = 0;
|
||||
let writing = false;
|
||||
const next = () => {
|
||||
if (writing || sent >= steps.length) return;
|
||||
if (!steps[sent].when.test(stdout.slice(from))) return;
|
||||
writing = true;
|
||||
from = stdout.length;
|
||||
setTimeout(() => {
|
||||
child.stdin.write(steps[sent].send);
|
||||
sent++;
|
||||
writing = false;
|
||||
next();
|
||||
}, 80);
|
||||
};
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
stdout += chunk;
|
||||
next();
|
||||
});
|
||||
child.stderr.on("data", (chunk) => (stderr += chunk));
|
||||
const timer = setTimeout(() => child.kill(), 20000);
|
||||
child.on("close", (status) => {
|
||||
clearTimeout(timer);
|
||||
resolve({ status, stdout, stderr, sent });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const NOT_A_PROJECT = /doesn't look like a project/;
|
||||
const NOTHING_OPENED = "Nothing opened. cd into your project (or run `git init` here) and run `plan2code` again.";
|
||||
|
||||
test("launcher: isEmptyFolder ignores OS litter and calls an unreadable folder not empty", () => {
|
||||
const { isEmptyFolder } = require(LAUNCHER);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-empty-"));
|
||||
try {
|
||||
assert.equal(isEmptyFolder(dir), true);
|
||||
fs.writeFileSync(path.join(dir, ".DS_Store"), "");
|
||||
fs.writeFileSync(path.join(dir, "Thumbs.db"), "");
|
||||
assert.equal(isEmptyFolder(dir), true, "OS litter only");
|
||||
fs.writeFileSync(path.join(dir, "notes.txt"), "");
|
||||
assert.equal(isEmptyFolder(dir), false);
|
||||
assert.equal(isEmptyFolder(path.join(dir, "missing")), false);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher project check: an empty folder defaults to Yes, so Enter opens it", async (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const empty = path.join(box.dir, "new-project");
|
||||
fs.mkdirSync(empty);
|
||||
const result = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /anyway\? \[Y\/n\]: $/, send: "\n" }], { cwd: empty });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.equal(result.sent, 1, result.stdout);
|
||||
assert.match(result.stdout, NOT_A_PROJECT);
|
||||
assert.ok(!result.stdout.includes(NOTHING_OPENED));
|
||||
assert.ok(box.argsOf("claude"), "the agent started");
|
||||
});
|
||||
|
||||
test("launcher project check: an empty folder answered n opens nothing and says what to do", async (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const empty = path.join(box.dir, "new-project");
|
||||
fs.mkdirSync(empty);
|
||||
const result = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /\[Y\/n\]: $/, send: "n\n" }], { cwd: empty });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.ok(result.stdout.includes(NOTHING_OPENED), result.stdout);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher project check: a folder with files that is not a project keeps No as the default", async (t) => {
|
||||
// The sandbox folder holds home/, bin/ and app/, and no git repo, AGENTS.md or specs/.
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const declined = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /anyway\? \[y\/N\]: $/, send: "\n" }]);
|
||||
assert.equal(declined.status, 0, declined.stderr);
|
||||
assert.equal(declined.sent, 1, declined.stdout);
|
||||
assert.ok(declined.stdout.includes(NOTHING_OPENED), declined.stdout);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
|
||||
const confirmed = await runAtTerminal(box, ["--bypass-permissions", "--model", "opus"], [{ when: /\[y\/N\]: $/, send: "y\n" }]);
|
||||
assert.equal(confirmed.status, 0, confirmed.stderr);
|
||||
assert.ok(!confirmed.stdout.includes(NOTHING_OPENED));
|
||||
assert.ok(box.argsOf("claude"), "a typed y opens it");
|
||||
});
|
||||
|
||||
test("launcher menus: the agent tip shows once, and the model menu prints ids in a column beside each description", async (t) => {
|
||||
const box = sandbox(["claude", "devin"]);
|
||||
t.after(box.cleanup);
|
||||
// Agent menu, keyboard question, then model menu: three prompts, each answered in turn.
|
||||
const steps = (modelAnswer) => [
|
||||
{ when: /Choice \[1\]: $/, send: "1\n" },
|
||||
{ when: /\[Y\/n\]: $/, send: "\n" },
|
||||
{ when: /Choice \[(agent default|\d+)\]: $/, send: modelAnswer },
|
||||
];
|
||||
const first = await runAtTerminal(box, ["--classic"], steps("latest opus\n"));
|
||||
assert.equal(first.status, 0, first.stderr);
|
||||
assert.equal(first.sent, 3, first.stdout);
|
||||
assert.match(first.stdout, /skip this launcher and run `\/plan2code`/);
|
||||
assert.doesNotMatch(first.stdout, /That runs outside the desktop app/, "no app installed, so no line about it");
|
||||
// ids padded to the longest (opusplan), then the description; the first run's Enter is the agent's.
|
||||
assert.match(first.stdout, /^ {2}1\) default {3}your account setting$/m);
|
||||
assert.match(first.stdout, /^ {2}2\) sonnet {4}latest Sonnet$/m);
|
||||
assert.match(first.stdout, /^ {2}5\) opusplan {2}Opus in plan mode, Sonnet otherwise$/m);
|
||||
assert.match(first.stdout, /Choice \[agent default\]: /);
|
||||
assert.ok(box.argsOf("claude").includes("opus"), "a typed description picks its model");
|
||||
const state = JSON.parse(fs.readFileSync(box.stateFile, "utf8"));
|
||||
assert.equal(state.agentTipSeen, true);
|
||||
assert.equal(state.lastModels.claude, "opus");
|
||||
|
||||
// Second run: no tip, and Enter runs the model marked (last used).
|
||||
const second = await runAtTerminal(box, ["--classic"], steps("\n"));
|
||||
assert.equal(second.status, 0, second.stderr);
|
||||
assert.equal(second.sent, 3, second.stdout);
|
||||
assert.doesNotMatch(second.stdout, /skip this launcher/);
|
||||
assert.match(second.stdout, /^ {2}3\) opus {6}latest Opus \(last used\)$/m);
|
||||
assert.match(second.stdout, /Choice \[3\]: /);
|
||||
assert.ok(box.argsOf("claude").includes("opus"));
|
||||
});
|
||||
|
||||
test("launcher menus: with the desktop app installed the tip also says it runs outside the app", async (t) => {
|
||||
const box = sandbox(["claude", "devin"]);
|
||||
t.after(box.cleanup);
|
||||
const result = await runAtTerminal(box, ["--classic", "--bypass-permissions", "--model", "opus"], [{ when: /Choice \[1\]: $/, send: "\n" }], {
|
||||
env: { PLAN2CODE_APP: box.appFile },
|
||||
});
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stdout, /skip this launcher[^\n]*\n[^\n]*That runs outside the desktop app/);
|
||||
assert.equal(box.appExists(), false, "--classic kept the run in this terminal");
|
||||
});
|
||||
+213
-40
@@ -15,8 +15,8 @@
|
||||
* `--cli claude` / `--cli devin` / `--cli codex` skips the question. Before starting it asks
|
||||
* which model to run, from the curated list in models.json (shipped with every install) plus
|
||||
* any models the user added in User Preferences; Enter runs the model the launcher last passed
|
||||
* that agent (marked `(last used)`), or keeps the agent's own last-used model when none is
|
||||
* recorded, and `--model` (or Codex's `-m`) skips the question. Right after the agent is chosen, when it has a
|
||||
* that agent (marked `(last used)`), or passes no model when none is recorded (the prompt reads
|
||||
* `[agent default]`: the agent picks), and `--model` (or Codex's `-m`) skips the question. Right after the agent is chosen, when it has a
|
||||
* flag for skipping permission prompts (every built-in does; a custom agent only with bypassArgs),
|
||||
* it asks at a keyboard, on every launch, whether to turn them off, Yes by default and nothing
|
||||
* remembered (Codex's question also names its sandbox, which the flag turns off too).
|
||||
@@ -71,6 +71,21 @@
|
||||
* its own) with NO_COLOR unset; piped runs print plain text and no banner.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The sentence for a Node.js older than 18, or null when `version` (`process.versions.node`) is
|
||||
* new enough. Kept free of anything newer than old Node can parse, since it runs before the rest.
|
||||
*/
|
||||
function nodeVersionProblem(version) {
|
||||
var major = parseInt(String(version).split('.')[0], 10);
|
||||
if (major >= 18) return null;
|
||||
return 'Plan2Code needs Node.js 18 or newer; you have v' + version + '. Get it from nodejs.org';
|
||||
}
|
||||
var NODE_PROBLEM = nodeVersionProblem(process.versions.node);
|
||||
if (NODE_PROBLEM) {
|
||||
console.error(NODE_PROBLEM);
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const { spawn, spawnSync } = require('child_process');
|
||||
const fs = require('fs');
|
||||
const os = require('os');
|
||||
@@ -254,7 +269,8 @@ function printNoAgentGuidance(missing = [], builtins = CLIS) {
|
||||
console.error(ce.bright('Install one:'));
|
||||
for (const cli of builtins) console.error(` ${ce.cyan(cli.label)}: ${installLine(cli)}`);
|
||||
console.error('');
|
||||
console.error('Already use another agent CLI? Add it by editing `~/.plan2code/agents.json`, then run `plan2code` again.');
|
||||
// Worded as install.js's no-agent advice: the same lead commands above, the same pointer here.
|
||||
console.error('Already use another agent CLI? Add it in User Preferences, Agents & models (the gear on the Plan2Code page), then run `plan2code` again.');
|
||||
for (const cli of missing) console.error(ce.yellow(`Custom agent ${cli.label}: ${cli.entry.command} not found`));
|
||||
console.error('');
|
||||
console.error('After installing, open a new terminal, cd into the project you want to work on and run `plan2code`.');
|
||||
@@ -724,7 +740,7 @@ function isDirectory(dir) {
|
||||
}
|
||||
}
|
||||
|
||||
/** `~/.plan2code/launcher.json`: `{ lastFolder, recentFolders, lastCli, lastModels }`, any key possibly missing. */
|
||||
/** `~/.plan2code/launcher.json`: `{ lastFolder, recentFolders, lastCli, lastModels, agentTipSeen }`, any key possibly missing. */
|
||||
function readState() {
|
||||
try {
|
||||
const state = JSON.parse(fs.readFileSync(STATE_FILE, 'utf8'));
|
||||
@@ -1174,8 +1190,13 @@ async function chooseCli(requested, { fromShortcut } = {}) {
|
||||
installed.forEach((cli, i) =>
|
||||
console.log(` ${c.cyan(`${i + 1})`)} ${cli.label}${cli.id === lastCli ? ` ${c.dim('(last used)')}` : ''}`)
|
||||
);
|
||||
console.log(c.dim('You can also skip this launcher and run `/plan2code` (`$plan2code` in Codex) straight from your agent.'));
|
||||
console.log(c.dim('That runs outside the desktop app, without its session management or Implementation Loops.'));
|
||||
// The tip shows on the first menu only (agentTipSeen in launcher.json); its second line
|
||||
// only when there is a desktop app to run outside of.
|
||||
if (!readState().agentTipSeen) {
|
||||
console.log(c.dim('You can also skip this launcher and run `/plan2code` (`$plan2code` in Codex) straight from your agent.'));
|
||||
if (findApp()) console.log(c.dim('That runs outside the desktop app, without its session management or Implementation Loops.'));
|
||||
saveState({ agentTipSeen: true });
|
||||
}
|
||||
for (;;) {
|
||||
const answer = (await ask(`Choice ${c.green(`[${defaultIndex + 1}]`)}: `)).trim().toLowerCase();
|
||||
if (!answer) return { cli: installed[defaultIndex] };
|
||||
@@ -1287,8 +1308,6 @@ function listModels(cli) {
|
||||
*/
|
||||
async function chooseModel(cli, extraArgs) {
|
||||
if (cli.custom && !listModels(cli).length) return;
|
||||
// A custom agent has no last-used model to keep: left alone it starts on its own default.
|
||||
const keep = cli.custom ? 'its own default model' : 'the last-used model';
|
||||
if (!process.stdin.isTTY) {
|
||||
if (cli.custom) {
|
||||
console.log(`${cli.label} will start with its own default model. To pick one, run \`plan2code --model <id>\`.`);
|
||||
@@ -1323,14 +1342,18 @@ async function chooseModel(cli, extraArgs) {
|
||||
console.log(left.replace(`${i + 1})`, c.cyan(`${i + 1})`)).replace(' (last used)', c.dim(' (last used)')) + right);
|
||||
}
|
||||
} else {
|
||||
models.forEach((model, i) =>
|
||||
console.log(
|
||||
(!model.label ? ` ${c.cyan(`${i + 1})`)} ${model.id}` : ` ${c.cyan(`${i + 1})`)} ${model.id} — ${model.label}`) +
|
||||
c.dim(tag(model))
|
||||
)
|
||||
);
|
||||
// The ids in a padded column, each description beside its id (models.json labels are the
|
||||
// description only). Padded before coloring, as above.
|
||||
const numberWidth = String(models.length).length + 1;
|
||||
const idWidth = Math.max(...models.map((model) => model.id.length));
|
||||
models.forEach((model, i) => {
|
||||
const number = c.cyan(`${i + 1})`.padEnd(numberWidth));
|
||||
const row = model.label ? `${model.id.padEnd(idWidth)} ${model.label}` : model.id;
|
||||
console.log(` ${number} ${row}${c.dim(tag(model))}`);
|
||||
});
|
||||
}
|
||||
const prompt = cli.custom ? '[default]' : lastIndex >= 0 ? `[${lastIndex + 1}]` : '[keep last used]';
|
||||
// With no model recorded (a first run, or a custom agent) Enter passes none: the agent picks.
|
||||
const prompt = !cli.custom && lastIndex >= 0 ? `[${lastIndex + 1}]` : '[agent default]';
|
||||
for (;;) {
|
||||
const answer = (await ask(`Choice ${c.green(prompt)}: `)).trim().toLowerCase();
|
||||
if (!answer) {
|
||||
@@ -1348,7 +1371,7 @@ async function chooseModel(cli, extraArgs) {
|
||||
}
|
||||
console.log(
|
||||
c.yellow(
|
||||
`Type a number from 1 to ${models.length}, a model name, or press Enter ${lastIndex >= 0 ? `for ${models[lastIndex].id}` : `to keep ${keep}`}.`
|
||||
`Type a number from 1 to ${models.length}, a model id or description, or press Enter ${lastIndex >= 0 ? `for ${models[lastIndex].id}` : "for the agent's default"}.`
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -1390,10 +1413,12 @@ function modelFrom(args, cliId) {
|
||||
* its own. Resolves true once it has started, false (after one line saying why) when it could
|
||||
* not, so the caller can carry on with today's terminal flow.
|
||||
*/
|
||||
function startApp(app, { cwd, cliId, model }) {
|
||||
function startApp(app, { cwd, cliId, model, dropped = [] }) {
|
||||
// No cliId (a run with no agent at all) opens the app on its launch card, where its own
|
||||
// Set up an agent button takes over from there.
|
||||
const args = ['--project', cwd, ...(cliId ? ['--agent', cliId] : []), ...(model ? ['--model', model] : [])];
|
||||
// Said before the start: a fallback to the terminal flow below still forwards them.
|
||||
if (dropped.length > 0) console.log(c.dim(`The app opens with the folder, agent and model only, so these are not passed on: ${dropped.join(' ')}`));
|
||||
return new Promise((resolve) => {
|
||||
let child;
|
||||
try {
|
||||
@@ -1496,7 +1521,7 @@ function looksLikeProject(dir) {
|
||||
|
||||
/**
|
||||
* True to proceed with `cwd`: it already looks like a project, or the person confirmed it when
|
||||
* asked. Without a terminal to ask there is nobody to confirm, so it refuses rather than risk
|
||||
* asked (Enter means yes for an empty folder, no otherwise; a no says what to do instead). Without a terminal to ask there is nobody to confirm, so it refuses rather than risk
|
||||
* opening the app (or the terminal flow) on the wrong folder.
|
||||
*/
|
||||
async function confirmProject(cwd) {
|
||||
@@ -1507,12 +1532,31 @@ async function confirmProject(cwd) {
|
||||
);
|
||||
return false;
|
||||
}
|
||||
// An empty folder is most likely a new project being started, so Enter opens it there; a
|
||||
// folder with files in it that still fails the check is more likely the wrong one.
|
||||
const empty = isEmptyFolder(cwd);
|
||||
const answer = (
|
||||
await ask(`${c.yellow(cwd)} doesn't look like a project (no git repo, AGENTS.md or specs folder). Open Plan2Code there anyway? [y/N]: `)
|
||||
await ask(
|
||||
`${c.yellow(cwd)} doesn't look like a project (no git repo, AGENTS.md or specs folder). Open Plan2Code there anyway? ${empty ? '[Y/n]' : '[y/N]'}: `
|
||||
)
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return answer === 'y' || answer === 'yes';
|
||||
const yes = answer === 'y' || answer === 'yes' || (empty && answer === '');
|
||||
if (!yes) console.log('Nothing opened. cd into your project (or run `git init` here) and run `plan2code` again.');
|
||||
return yes;
|
||||
}
|
||||
|
||||
// Files an OS drops into a folder on its own, which leave it as empty as it was.
|
||||
const OS_LITTER = new Set(['.ds_store', 'thumbs.db', 'desktop.ini']);
|
||||
|
||||
/** True when `dir` holds nothing (OS litter such as .DS_Store aside); false when it cannot be read. */
|
||||
function isEmptyFolder(dir) {
|
||||
try {
|
||||
return fs.readdirSync(dir).every((name) => OS_LITTER.has(name.toLowerCase()));
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1630,27 +1674,67 @@ function spawnCommand(file, args, options) {
|
||||
}
|
||||
|
||||
/**
|
||||
* `plan2code update`: the npx install with --update, passing npx's exit code through. No agent
|
||||
* starts. That one install updates the skills, this launcher and the desktop app (when it is
|
||||
* installed) together, so the three never drift apart.
|
||||
* `plan2code update [--main] [--tag <ref>] [--force]`: the npx install with --update, passing
|
||||
* npx's exit code through. No agent starts. That one install updates the skills, this launcher
|
||||
* and the desktop app (when it is installed) together, so the three never drift apart.
|
||||
*
|
||||
* It installs the newest `vX.Y.Z` release tag, found with the same `git ls-remote --tags` rule
|
||||
* the console's release check uses (update-check.mjs, copied beside this file), so a person is
|
||||
* never moved onto work a published release does not have yet. `--main` is the old behavior (the
|
||||
* tip of `main`); `--tag <ref>` installs that tag or branch (the desktop app's Update skills
|
||||
* button pins the app's own tag this way, and it is how to go back to an earlier release);
|
||||
* `--force` reinstalls even when the version is already current. `--main`, and a `--tag` naming a
|
||||
* branch rather than a vX.Y.Z release, always reinstall: unreleased work keeps the last release's
|
||||
* version, so the installer's "Already on" check would otherwise install nothing.
|
||||
*/
|
||||
/** `tag` pins the install to that release (the desktop app's own Update skills button, so it
|
||||
* never pulls in work a published release does not have yet); omitted, `plan2code update` keeps
|
||||
* pulling the latest off `main` as it always has. */
|
||||
function runUpdate(tag) {
|
||||
console.log('Updating Plan2Code...');
|
||||
async function runUpdate({ tag, main, force } = {}) {
|
||||
let ref = tag;
|
||||
if (ref === undefined && !main) {
|
||||
const latest = await newestReleaseTag();
|
||||
if (!latest) {
|
||||
console.error(`${ce.red('plan2code:')} could not find the newest Plan2Code release (git ls-remote did not answer).`);
|
||||
console.error('Check your network, then run plan2code update again, or use --main (the newest work, not a release) or --tag <release> (for example --tag v3.0.2).');
|
||||
return process.exit(1);
|
||||
}
|
||||
ref = `v${latest}`;
|
||||
}
|
||||
console.log(ref === undefined ? 'Updating Plan2Code to the newest work on main...' : `Updating Plan2Code to ${ref}...`);
|
||||
console.log(c.dim('One update covers the skills, the plan2code command and the desktop app (when installed).'));
|
||||
return runInstaller(['--update'], tag);
|
||||
const unreleased = main || (tag !== undefined && !/^v\d+\.\d+\.\d+$/.test(tag));
|
||||
return runInstaller(['--update', ...(force || unreleased ? ['--force'] : [])], ref);
|
||||
}
|
||||
|
||||
/**
|
||||
* The newest release's version (X.Y.Z), or null when it cannot be found. The tag list comes from
|
||||
* update-check.mjs's own `git ls-remote --tags` run and its own pick, beside this file once
|
||||
* installed (or in the repository's web-console folder when run from a checkout).
|
||||
* PLAN2CODE_LS_REMOTE_FILE names a file holding `git ls-remote --tags` output to use instead of
|
||||
* asking git: the tests' stand-in for the network.
|
||||
*/
|
||||
async function newestReleaseTag() {
|
||||
try {
|
||||
const checker = [path.join(__dirname, 'update-check.mjs'), path.join(__dirname, '..', 'web-console', 'update-check.mjs')].find((file) => fs.existsSync(file));
|
||||
if (!checker) return null;
|
||||
const mod = await import(require('url').pathToFileURL(checker).href);
|
||||
const stub = process.env.PLAN2CODE_LS_REMOTE_FILE;
|
||||
const text = stub ? fs.readFileSync(stub, 'utf8') : await mod.runLsRemote();
|
||||
return mod.latestTag(text);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `plan2code uninstall [--yes] [--purge]`: the npx install with --uninstall, which asks before
|
||||
* it removes anything (--yes skips that) and then whether your data in ~/.plan2code goes too
|
||||
* (--purge says yes). The prompts run on this terminal, so stdio is inherited.
|
||||
* (--purge says yes). The prompts run on this terminal, so stdio is inherited. It runs the newest
|
||||
* release's installer, as update does, and falls back to main only when that release cannot be
|
||||
* found, so removing Plan2Code never waits on the network more than installing it did.
|
||||
*/
|
||||
function runUninstall(flags) {
|
||||
async function runUninstall(flags) {
|
||||
console.log('Uninstalling Plan2Code...');
|
||||
return runInstaller(['--uninstall', ...flags]);
|
||||
const latest = await newestReleaseTag();
|
||||
return runInstaller(['--uninstall', ...flags], latest ? `v${latest}` : undefined);
|
||||
}
|
||||
|
||||
/** Run install.js through npx with the given flags, passing npx's exit code through. */
|
||||
@@ -1714,11 +1798,97 @@ async function releaseNotice() {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
/** `{ tag, main, force }` from the words after `update`, or `{ error }` naming what is wrong. */
|
||||
function parseUpdateArgs(args) {
|
||||
const out = { main: false, force: false };
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (arg === '--main') out.main = true;
|
||||
else if (arg === '--force') out.force = true;
|
||||
else if (arg === '--tag') {
|
||||
const ref = args[i + 1];
|
||||
if (!ref || ref.startsWith('--')) return { error: '--tag needs a release or branch, for example --tag v3.0.2' };
|
||||
out.tag = ref;
|
||||
i++;
|
||||
} else return { error: `unknown option for update: ${arg}` };
|
||||
}
|
||||
if (out.main && out.tag !== undefined) return { error: 'use --main or --tag, not both' };
|
||||
return out;
|
||||
}
|
||||
|
||||
/** The usage block `plan2code --help` prints. */
|
||||
function usageText() {
|
||||
return [
|
||||
'Usage: plan2code [options] [-- agent arguments]',
|
||||
'',
|
||||
'Opens the Plan2Code dashboard in your AI agent, in the current folder.',
|
||||
'',
|
||||
'Commands:',
|
||||
' plan2code update [--main] [--force] Update to the newest release (--main: the newest work, --force: reinstall)',
|
||||
' plan2code update --tag <ref> Go back to a release: plan2code update --tag v3.0.2',
|
||||
' plan2code uninstall [--yes] [--purge] Remove Plan2Code (--purge also removes your data)',
|
||||
'',
|
||||
'Options:',
|
||||
' --cli <id> Start this agent without asking (claude, devin, codex or your own)',
|
||||
' --model <id> Start the agent on this model without asking',
|
||||
" --keep-permissions Keep the agent's permission prompts on without asking",
|
||||
" --bypass-permissions Turn the agent's permission prompts off without asking",
|
||||
' --classic Stay in this terminal even when the desktop app is installed',
|
||||
' --pick-folder Ask for the project folder first (the desktop shortcut uses it)',
|
||||
' -h, --help, help Show this help',
|
||||
' -v, --version Show the installed Plan2Code version',
|
||||
'',
|
||||
"Anything after -- goes to the agent as it is, in this terminal: plan2code -- --help shows your agent's own help.",
|
||||
].join('\n');
|
||||
}
|
||||
|
||||
/** The installed version, from the version.json install.js puts beside this file, or null. */
|
||||
function installedVersion() {
|
||||
const data = readJsonFile(path.join(__dirname, 'version.json'));
|
||||
return data && typeof data.version === 'string' ? data.version : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The arguments the desktop app is not given: it takes only the folder, the agent and the model,
|
||||
* so every other forwarded argument (the model flag's own forms aside) is dropped when it opens.
|
||||
*/
|
||||
function droppedForApp(args, cliId) {
|
||||
const dropped = [];
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (arg === '--model' || (cliId === 'codex' && arg === '-m')) {
|
||||
i++;
|
||||
continue;
|
||||
}
|
||||
if (arg.startsWith('--model=') || (cliId === 'codex' && arg.startsWith('-m'))) continue;
|
||||
dropped.push(arg);
|
||||
}
|
||||
return dropped;
|
||||
}
|
||||
|
||||
async function launch() {
|
||||
const argv = process.argv.slice(2);
|
||||
const all = process.argv.slice(2);
|
||||
// Everything after a bare `--` belongs to the agent: the launcher reads only what comes before.
|
||||
const split = all.indexOf('--');
|
||||
const argv = split >= 0 ? all.slice(0, split) : all;
|
||||
const passThrough = split >= 0 ? all.slice(split + 1) : [];
|
||||
if (argv[0] === 'help' || argv.includes('--help') || argv.includes('-h')) {
|
||||
console.log(usageText());
|
||||
return process.exit(0);
|
||||
}
|
||||
if (argv.includes('--version') || argv.includes('-v')) {
|
||||
const version = installedVersion();
|
||||
console.log(version ? `Plan2Code v${version}` : 'Plan2Code (version unknown: no version.json beside this file)');
|
||||
return process.exit(0);
|
||||
}
|
||||
if (argv[0] === UPDATE_COMMAND) {
|
||||
const tagAt = argv.indexOf('--tag');
|
||||
return runUpdate(tagAt >= 0 ? argv[tagAt + 1] : undefined);
|
||||
const parsed = parseUpdateArgs(argv.slice(1));
|
||||
if (parsed.error) {
|
||||
console.error(`${ce.red('plan2code:')} ${parsed.error}`);
|
||||
console.error('Usage: plan2code update [--main] [--force] [--tag <ref>]');
|
||||
return process.exit(2);
|
||||
}
|
||||
return runUpdate(parsed);
|
||||
}
|
||||
if (argv[0] === UNINSTALL_COMMAND) {
|
||||
const flags = argv.slice(1);
|
||||
@@ -1737,7 +1907,8 @@ async function launch() {
|
||||
bypass: argv.includes(BYPASS_PERMISSIONS_FLAG),
|
||||
};
|
||||
const ownFlags = new Set([PICK_FOLDER_FLAG, CLASSIC_FLAG, KEEP_PERMISSIONS_FLAG, BYPASS_PERMISSIONS_FLAG]);
|
||||
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => !ownFlags.has(arg)));
|
||||
const { cli: requestedCli, rest } = takeCliFlag(argv.filter((arg) => !ownFlags.has(arg)));
|
||||
const extraArgs = [...rest, ...passThrough];
|
||||
|
||||
printIntro();
|
||||
await releaseNotice();
|
||||
@@ -1764,7 +1935,7 @@ async function launch() {
|
||||
if (picked.exit !== undefined) return exitWith(picked.exit, fromShortcut);
|
||||
cwd = picked.cwd;
|
||||
cwdSettled = true;
|
||||
if (app && (await startApp(app, { cwd }))) {
|
||||
if (app && (await startApp(app, { cwd, dropped: extraArgs }))) {
|
||||
console.log(`Opened the Plan2Code app in ${c.cyan(cwd)} ${c.dim('(run `plan2code --classic` to stay in this terminal)')}`);
|
||||
return process.exit(0);
|
||||
}
|
||||
@@ -1786,7 +1957,9 @@ async function launch() {
|
||||
// The app has its own permission tick on its launch card, so the question is only for the
|
||||
// terminal flow (asked late if the app fails to start). An agent the setup page started runs
|
||||
// in this terminal even with the app installed: the waiting setup tab is owed the hand-over.
|
||||
const app = !setup && !classic && hasDisplay() ? findApp() : null;
|
||||
// Arguments after a bare `--` are for the agent itself, which the app cannot pass on, so
|
||||
// such a run stays in this terminal too.
|
||||
const app = !setup && !classic && passThrough.length === 0 && hasDisplay() ? findApp() : null;
|
||||
let bypass = app ? null : await chooseBypass(cli, permissions);
|
||||
|
||||
if (!cwdSettled) {
|
||||
@@ -1806,7 +1979,7 @@ async function launch() {
|
||||
}
|
||||
|
||||
// The app takes over from here when it is installed, a window can open and --classic is absent.
|
||||
if (app && (await startApp(app, { cwd, cliId: cli.id, model: modelFrom(extraArgs, cli.id) }))) {
|
||||
if (app && (await startApp(app, { cwd, cliId: cli.id, model: modelFrom(extraArgs, cli.id), dropped: droppedForApp(extraArgs, cli.id) }))) {
|
||||
console.log(`Opened the Plan2Code app in ${c.cyan(cwd)} ${c.dim('(run `plan2code --classic` to stay in this terminal)')}`);
|
||||
return process.exit(0);
|
||||
}
|
||||
@@ -1847,4 +2020,4 @@ async function launch() {
|
||||
// Run only when invoked directly; requiring the file (the tests do) is load-only.
|
||||
if (require.main === module) launch();
|
||||
|
||||
module.exports = { bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick };
|
||||
module.exports = { nodeVersionProblem, usageText, droppedForApp, bypassQuestion, normalizeAgents, buildArgs, parseRegQueryValue, expandPercentVars, addSavedWindowsPath, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject, lastUsedNotice, leadInstall, installLine, findConsoleMjs, runSetupFlow, projectCwd, sameFolder, readRecent, pushRecent, listRecent, recordFolder, folderMenuRows, folderMenuPick, isEmptyFolder };
|
||||
Reference in new issue
Block a user