mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-16 04:45:33 -08:00
v3-orchestrator
This commit is contained in:
1 parent
7a4b7c6db8
commit
681c4a4b85
27 files changed
+1138
-36
No files matched your search
@@ -92,7 +92,9 @@ plan2code/
|
||||
| `version.json` | Version metadata (name, version, description) |
|
||||
| `QUICK-REFERENCE.md` | User quick-reference card |
|
||||
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`) |
|
||||
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent |
|
||||
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
|
||||
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
|
||||
|
||||
## Workflow Prompts (in `src/`)
|
||||
|
||||
@@ -189,6 +191,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `cmd-chat.mjs` | the `chat` command: hand over Quick questions now, never waiting |
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
|
||||
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
|
||||
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
|
||||
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
|
||||
@@ -285,7 +288,7 @@ Key design points:
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the five opted-in skills (`defaultSetting()`); a saved Off stays off.
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
## Gotchas / Pitfalls
|
||||
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number.
|
||||
- **Version sync:** When adding a new version to `CHANGELOG.md`, also update `version.json` and `package.json` (root) to match. `README.md` (the `Version X.Y.Z` line near the top) also carries the version, and `version.json`'s `releaseDate` moves with it. `version.json` is copied into every skill's `references/web-console/` (the console's Help shows it), so after a bump run `npm run build:skills` or `npm test` (`--verify-skills`) fails. The installer displays the version from `version.json` in its header. All three files (`CHANGELOG.md`, `version.json`, `package.json`) must always show the same version number. The desktop app carries it too (`plan2code-app/src-tauri/tauri.conf.json`, `plan2code-app/package.json`, `plan2code-app/src-tauri/Cargo.toml`, and `Cargo.lock`'s `plan2code-app` entry follows the build): `node scripts/check-versions.mjs [--tag vX.Y.Z]` compares all six, and the release workflow runs it before building. It reports a mismatch today because the app is at 3.0.0 while the rest is still 2.x; it is deliberately not part of `npm test`, so bump the app's files with the release that ships v3.0.0.
|
||||
- **CHANGELOG ordering:** Entries in `CHANGELOG.md` must be in reverse-chronological order — newest version at the top, oldest at the bottom. New entries are always inserted immediately after the file header.
|
||||
- **CHANGELOG house format is not Keep a Changelog:** version headings are `## vX.Y.Z` — with a `v` prefix and **no date**. The release date is recorded only in `version.json`'s `releaseDate`. Category headings carry emoji: `### ✨ Added`, `### 🔧 Changed`, `### 🐛 Fixed`, `### 💥 Breaking`, `### 🗑️ Removed`, `### 📚 Documentation`. Older entries contain one-off variants (`🎁 Added`, `📦 Updated`, `📝 Documentation`, `🏎️ Improved`, `🧪 Testing`) — do not introduce new ones. The `.claude/skills/plan2code-changelog/` skill automates version selection and formatting; use it rather than hand-rolling an entry.
|
||||
- **PowerShell mangles the CHANGELOG emoji:** `Get-Content` / `Select-String` render the `###` heading emoji as `?` under the default Windows console encoding, so a heading audit done that way reports garbage. Read `CHANGELOG.md` with a file-read or grep tool instead.
|
||||
|
||||
@@ -24,3 +24,8 @@ SYNC.md
|
||||
# Throwaway design prototypes (ai-assist-prototype). The decision they
|
||||
# recorded lives in the code and the CHANGELOG; the files stay local.
|
||||
prototypes/
|
||||
|
||||
# The Tauri app (plan2code-app/)
|
||||
plan2code-app/target/
|
||||
plan2code-app/src-tauri/gen/
|
||||
plan2code-app/ui/vendor/
|
||||
@@ -106,3 +106,4 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- When `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone).
|
||||
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
|
||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
||||
@@ -2,6 +2,25 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v3.0.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **Restart** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
|
||||
- **desktop app**: a context meter in the bar reads how full the running agent's context window is: a real-ish number from Claude's own transcript or Codex's session log (labeled best-effort, since both formats are undocumented), a clearly labeled estimate for Devin or any agent with no documented signal, and a gentle nudge near 70% suggesting Restart, shown only for a real or best-effort reading.
|
||||
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Restart the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
|
||||
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
|
||||
|
||||
## v2.11.1
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: a card whose thread ends with the person's own words now blocks the patch that settles or reopens it, until the agent replies in the same thread. Exempt once the item is deleted, or the whole session is ending.
|
||||
|
||||
## v2.11.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
@@ -88,6 +88,28 @@ Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permiss
|
||||
which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>About the desktop app</summary>
|
||||
|
||||
The installer also offers the **Plan2Code desktop app**: one window with the dashboard and your agent's
|
||||
terminal side by side, docked bottom or right and collapsible. Every console page, not only the
|
||||
dashboard, opens inside it. A launch card asks which agent, model and effort to start on, with
|
||||
permission checks off as its own opt-in tick (off by default); a **Restart** button then replaces the
|
||||
agent with a fresh one on a brief built from the session, and a status strip below the top bar shows
|
||||
the agent, the page open and a context meter that nudges you toward Restart once Claude's or Codex's
|
||||
context is getting full. Once it is installed, `plan2code` opens the app instead of running the agent
|
||||
in your terminal. `plan2code --classic` keeps the terminal flow, and so does a Linux machine with no
|
||||
display (over SSH, say) or any machine over an SSH session. `plan2code update` updates the skills, the
|
||||
command and the app together, and the bar offers the same **Update skills** when the app and the
|
||||
installed skills disagree.
|
||||
|
||||
The first release is unsigned, so macOS (**Open Anyway** in System Settings, Privacy & Security) or
|
||||
Windows (**More info**, then **Run anyway**) may ask you to allow it once. The app starts the agent
|
||||
with its normal approval prompts unless you tick the launch card's permission-checks-off option (the
|
||||
plain `plan2code` command above, without the app, still starts with checks off by default). Details:
|
||||
[docs/desktop-app.md](docs/desktop-app.md).
|
||||
</details>
|
||||
|
||||
**Supported tools:** every agent supported by the skills CLI, including Claude Code · Cursor ·
|
||||
GitHub Copilot · Windsurf · Codex · Continue · Codeium · Zed · Amp · OpenCode · Devin · Crush · Pi ·
|
||||
Gemini CLI · Cline · Roo · Kilo · Goose · Trae · Qwen Code.
|
||||
@@ -186,7 +208,7 @@ The dashboard's cards, and when each one lights up for the spec you pick:
|
||||
| Refresh AGENTS.md | Brings AGENTS.md and its notes up to date with what the project has learned lately. | The project has an AGENTS.md |
|
||||
| Pathfinder | A foggy idea becomes a clear list of decisions, settled one question at a time. | You start fresh, or the spec is still being explored |
|
||||
| Plan | Requirements, technical design and your approval: the shape of what gets built. | You start fresh, or the spec has a finished Pathfinder map, a drafted plan or a bug diagnosis |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases and not fully built |
|
||||
| Revise the plan | Requirements changed mid-build? Adjust the plan without starting over. | The spec is written up into phases, built or not |
|
||||
| Document | The plan becomes a checklist of small tasks, grouped into phases, that a developer can just do. | The spec has a drafted plan |
|
||||
| Implement | Builds the next phase, task by task, with a report and your sign-off at the end. | The spec has phases with tasks still to build |
|
||||
| Implement + review | One phase built, then a careful review of the changes, then your sign-off. All in one run. | The spec has phases with tasks still to build |
|
||||
|
||||
+235
-7
@@ -20,6 +20,7 @@ const fs = require('fs');
|
||||
const path = require('path');
|
||||
const os = require('os');
|
||||
const readline = require('readline');
|
||||
const crypto = require('crypto');
|
||||
|
||||
// Load project version metadata
|
||||
let projectVersion = { name: 'Plan2Code', version: 'unknown' };
|
||||
@@ -983,6 +984,9 @@ async function install({ unattended = false, outcome = {} } = {}) {
|
||||
const launcherFailed = failed ? false : (await installLauncher({ quiet: true, unattended })) !== 0;
|
||||
outcome.launcher = !failed && !launcherFailed;
|
||||
|
||||
// The desktop app comes last and is an extra: its failure leaves the install a success.
|
||||
if (!failed && !launcherFailed) await offerDesktopApp({ unattended, outcome });
|
||||
|
||||
// Summary
|
||||
console.log(`${COLORS.CYAN}╔═══════════════════════════════════════════════════════════════════════════╗${COLORS.RESET}`);
|
||||
console.log(`${COLORS.CYAN}║${COLORS.RESET}${' '.repeat(75)}${COLORS.CYAN}║${COLORS.RESET}`);
|
||||
@@ -1212,6 +1216,7 @@ function runInteractive() {
|
||||
const botResult = uninstallPlan2CodeBot();
|
||||
const statusLineResult = uninstallStatusLine();
|
||||
const launcherResult = uninstallLauncher();
|
||||
uninstallDesktopApp();
|
||||
const exitCode = uninstallResult !== 0 ? uninstallResult : loopResult !== 0 ? loopResult : metricsResult !== 0 ? metricsResult : botResult !== 0 ? botResult : statusLineResult !== 0 ? statusLineResult : launcherResult;
|
||||
process.exit(exitCode);
|
||||
} else {
|
||||
@@ -2317,10 +2322,14 @@ const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.m
|
||||
const LAUNCHER_VERSION_DEST = path.join(path.dirname(LAUNCHER_DEST), 'version.json');
|
||||
// What a global install put on this machine, so `plan2code update` reinstalls exactly that.
|
||||
const INSTALL_RECORD = path.join(os.homedir(), '.plan2code', 'install.json');
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'statusline', 'loop', 'metrics', 'bot'];
|
||||
const INSTALL_PIECES = ['skills', 'launcher', 'app', 'statusline', 'loop', 'metrics', 'bot'];
|
||||
const LAUNCHER_PICK_FOLDER_FLAG = '--pick-folder';
|
||||
|
||||
/** `~/.plan2code/install.json` as `{ version, scope, pieces }`, or null when missing or unparsable. */
|
||||
/**
|
||||
* `~/.plan2code/install.json` as `{ version, scope, pieces }`, or null when missing or unparsable.
|
||||
* `skipped` lists optional pieces (the desktop app) the person said no to, so an unattended
|
||||
* `plan2code update` does not install them; it is left out of the file while empty.
|
||||
*/
|
||||
function readInstallRecord() {
|
||||
try {
|
||||
const record = JSON.parse(fs.readFileSync(INSTALL_RECORD, 'utf8'));
|
||||
@@ -2330,12 +2339,14 @@ function readInstallRecord() {
|
||||
}
|
||||
|
||||
/** Temp file, then rename, so a crash never leaves a half-written record. A failure only skips the record. */
|
||||
function writeInstallRecord(pieces) {
|
||||
function writeInstallRecord(pieces, skipped = (readInstallRecord() || {}).skipped || []) {
|
||||
const record = {
|
||||
version: projectVersion.version,
|
||||
scope: 'global',
|
||||
pieces: [...new Set(pieces)].filter((piece) => INSTALL_PIECES.includes(piece)).sort(),
|
||||
};
|
||||
const declined = [...new Set(skipped)].filter((piece) => INSTALL_PIECES.includes(piece) && !record.pieces.includes(piece)).sort();
|
||||
if (declined.length > 0) record.skipped = declined;
|
||||
const tmp = `${INSTALL_RECORD}.${process.pid}.tmp`;
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(INSTALL_RECORD), { recursive: true });
|
||||
@@ -2354,6 +2365,12 @@ function recordInstalled(piece) {
|
||||
writeInstallRecord([...(record ? record.pieces : []), piece]);
|
||||
}
|
||||
|
||||
/** Remember that an optional piece was declined. Needs a record: one holding no pieces would make update do nothing. */
|
||||
function recordSkipped(piece) {
|
||||
const record = readInstallRecord();
|
||||
if (record) writeInstallRecord(record.pieces, [...(record.skipped || []), piece]);
|
||||
}
|
||||
|
||||
/** Drop a piece after its uninstall; no record means nothing to forget. */
|
||||
function forgetInstalled(piece) {
|
||||
const record = readInstallRecord();
|
||||
@@ -2539,6 +2556,8 @@ function isOurShortcut(file) {
|
||||
/**
|
||||
* Put a shortcut on the desktop that runs `plan2code --pick-folder` through the shim in
|
||||
* `binDir`, so the person picks the project folder in a native dialog before the CLI opens.
|
||||
* It is the same `plan2code` command as a typed one, so it opens the desktop app instead
|
||||
* when the app is installed (the launcher decides; the shortcut never names the app).
|
||||
* On Windows it opens in PowerShell — PowerShell 7 (`pwsh`) when installed, Windows
|
||||
* PowerShell otherwise — running the `.ps1` shim, rather than cmd.exe running the `.cmd` one.
|
||||
*/
|
||||
@@ -2575,7 +2594,7 @@ function installDesktopShortcut(binDir, file) {
|
||||
P2C_FILE: file,
|
||||
P2C_SCRIPT: `${shim}.ps1`,
|
||||
P2C_ARGS: LAUNCHER_PICK_FOLDER_FLAG,
|
||||
P2C_DESCRIPTION: 'Open the Plan2Code dashboard in Claude Code, Devin or Codex',
|
||||
P2C_DESCRIPTION: 'Open Plan2Code: the desktop app when it is installed, otherwise your agent in a terminal',
|
||||
P2C_ICON: icon,
|
||||
}
|
||||
);
|
||||
@@ -2595,7 +2614,7 @@ function installDesktopShortcut(binDir, file) {
|
||||
`# ${LAUNCHER_MARKER}`,
|
||||
'Type=Application',
|
||||
`Name=${SHORTCUT_NAME}`,
|
||||
'Comment=Open the Plan2Code dashboard in Claude Code, Devin or Codex',
|
||||
'Comment=Open Plan2Code: the desktop app when it is installed, otherwise your agent in a terminal',
|
||||
`Exec="${shim}" ${LAUNCHER_PICK_FOLDER_FLAG}`,
|
||||
...(icon ? [`Icon=${icon}`] : []),
|
||||
'Terminal=true',
|
||||
@@ -2745,6 +2764,210 @@ function uninstallLauncher() {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// DESKTOP APP
|
||||
// ============================================================================
|
||||
|
||||
/**
|
||||
* The desktop app is one plain executable per system, attached to each GitHub release by
|
||||
* .github/workflows/release-app.yml as `plan2code-app-<version>-<os>-<arch>[.exe]` beside
|
||||
* `plan2code-app-<version>-SHA256SUMS.txt`. Installing it downloads the file for this machine,
|
||||
* checks it against that list and puts it in ~/.plan2code/app/, where the launcher looks.
|
||||
* PLAN2CODE_RELEASE_BASE replaces the release download URL (the tests serve a stand-in).
|
||||
* The app is an extra on top of the skills and the command: when it cannot be installed they
|
||||
* stay installed, and `plan2code --classic` is today's flow.
|
||||
*/
|
||||
const APP_DIR = path.join(os.homedir(), '.plan2code', 'app');
|
||||
const APP_DEST = path.join(APP_DIR, process.platform === 'win32' ? 'plan2code-app.exe' : 'plan2code-app');
|
||||
const APP_DOWNLOAD_TIMEOUT_MS = 120000;
|
||||
|
||||
function releaseBase(version) {
|
||||
const base = process.env.PLAN2CODE_RELEASE_BASE || `https://github.com/jparkerweb/plan2code/releases/download/v${version}`;
|
||||
return base.replace(/\/+$/, '');
|
||||
}
|
||||
|
||||
/** The release file for a system, or null when the app is not built for it. */
|
||||
function appAssetName(version, platform = process.platform, arch = process.arch) {
|
||||
const system = { win32: 'windows', darwin: 'macos', linux: 'linux' }[platform];
|
||||
const cpu = { x64: 'x64', arm64: 'arm64' }[arch];
|
||||
if (!system || !cpu) return null;
|
||||
return `plan2code-app-${version}-${system}-${cpu}${platform === 'win32' ? '.exe' : ''}`;
|
||||
}
|
||||
|
||||
/** The SHA-256 a checksum list (`<hex> <name>` or `<hex> *<name>` lines) gives for `name`, or null. */
|
||||
function checksumFor(list, name) {
|
||||
for (const line of list.split(/\r?\n/)) {
|
||||
const match = line.trim().match(/^([0-9a-fA-F]{64})\s+\*?(.+)$/);
|
||||
if (match && match[2] === name) return match[1].toLowerCase();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** The bytes at `url`; an HTTP error is thrown with its `status`. */
|
||||
async function download(url) {
|
||||
const response = await fetch(url, { signal: AbortSignal.timeout(APP_DOWNLOAD_TIMEOUT_MS) });
|
||||
if (!response.ok) {
|
||||
const error = new Error(`HTTP ${response.status} from ${url}`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
return Buffer.from(await response.arrayBuffer());
|
||||
}
|
||||
|
||||
/**
|
||||
* Put the app at `dest`, replacing an older one. The new file is written beside it first, and
|
||||
* the old one is renamed aside rather than overwritten: Windows will not overwrite a running
|
||||
* program but will rename it, and the old file goes when the app next ends.
|
||||
*/
|
||||
function placeApp(bytes, dest) {
|
||||
fs.mkdirSync(path.dirname(dest), { recursive: true });
|
||||
const tmp = `${dest}.${process.pid}.tmp`;
|
||||
const aside = `${dest}.old`;
|
||||
fs.writeFileSync(tmp, bytes, { mode: 0o755 });
|
||||
try {
|
||||
fs.rmSync(aside, { force: true });
|
||||
} catch {}
|
||||
let movedAside = false;
|
||||
try {
|
||||
fs.renameSync(dest, aside);
|
||||
movedAside = true;
|
||||
} catch (error) {
|
||||
if (error.code !== 'ENOENT') {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
try {
|
||||
fs.renameSync(tmp, dest);
|
||||
} catch (error) {
|
||||
if (movedAside) {
|
||||
try {
|
||||
fs.renameSync(aside, dest);
|
||||
} catch {}
|
||||
}
|
||||
fs.rmSync(tmp, { force: true });
|
||||
throw error;
|
||||
}
|
||||
try {
|
||||
fs.rmSync(aside, { force: true });
|
||||
} catch {}
|
||||
if (process.platform !== 'win32') fs.chmodSync(dest, 0o755);
|
||||
}
|
||||
|
||||
/**
|
||||
* Download, verify and place the desktop app for this release. Returns 0, or 1 after saying
|
||||
* plainly why not (and that the skills and the command are fine); `outcome.app` is true or false.
|
||||
*/
|
||||
async function installDesktopApp({ quiet = false, unattended = false, outcome = {} } = {}) {
|
||||
if (quiet) {
|
||||
console.log(`${COLORS.YELLOW}${SYMBOLS.ACTIVE} INSTALLING THE DESKTOP APP${COLORS.RESET}`);
|
||||
} else {
|
||||
displaySectionHeader('DESKTOP APP', '[ INSTALL ]');
|
||||
}
|
||||
const version = projectVersion.version;
|
||||
const name = appAssetName(version);
|
||||
const base = releaseBase(version);
|
||||
const fail = (reason) => {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} The desktop app was not installed: ${reason}`);
|
||||
console.log(` ${COLORS.DIM}The skills and the plan2code command are installed and work as before; run ${COLORS.CYAN}plan2code --classic${COLORS.DIM} to stay in your terminal, or install again later.${COLORS.RESET}`);
|
||||
console.log('');
|
||||
outcome.app = false;
|
||||
return 1;
|
||||
};
|
||||
// No build for this system or this release yet (the version is bumped on main before the
|
||||
// release's files are attached): not a failure when unattended, since an update must not fail
|
||||
// for it and an app that is installed stays as it is.
|
||||
const noBuild = (reason) => {
|
||||
if (!unattended) return fail(reason);
|
||||
outcome.app = false;
|
||||
outcome.appMissing = reason;
|
||||
console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No desktop app update: ${reason}${COLORS.RESET}`);
|
||||
console.log('');
|
||||
return 0;
|
||||
};
|
||||
|
||||
if (!name) return noBuild(`there is no desktop app build for ${process.platform}-${process.arch}.`);
|
||||
let bytes;
|
||||
try {
|
||||
const list = (await download(`${base}/plan2code-app-${version}-SHA256SUMS.txt`)).toString('utf8');
|
||||
const expected = checksumFor(list, name);
|
||||
if (!expected) return fail(`the release's checksum list has no entry for ${name}.`);
|
||||
bytes = await download(`${base}/${name}`);
|
||||
const actual = crypto.createHash('sha256').update(bytes).digest('hex');
|
||||
if (actual !== expected) {
|
||||
return fail(`${name} does not match its checksum (expected ${expected.slice(0, 12)}..., got ${actual.slice(0, 12)}...), so it was thrown away.`);
|
||||
}
|
||||
} catch (error) {
|
||||
return error.status === 404
|
||||
? noBuild(`release v${version} has no desktop app file for ${process.platform}-${process.arch} yet.`)
|
||||
: fail(`could not download it (${error.message}).`);
|
||||
}
|
||||
try {
|
||||
placeApp(bytes, APP_DEST);
|
||||
} catch (error) {
|
||||
return fail(`the file was verified but could not be put in ${APP_DIR} (${error.message}); close the app and try again.`);
|
||||
}
|
||||
recordInstalled('app');
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${APP_DEST}`);
|
||||
console.log(` ${COLORS.YELLOW}${SYMBOLS.WARNING}${COLORS.RESET} The app is unsigned, and it starts the agent with permission checks off. See docs/desktop-app.md for how to allow it on macOS and Windows.`);
|
||||
console.log('');
|
||||
outcome.app = true;
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The app step of a skills install. Interactive: ask (default yes), and remember a no.
|
||||
* Unattended (`plan2code update`): yes, without asking, unless the app is already recorded (the
|
||||
* update loop updates it as its own piece) or was declined before.
|
||||
*/
|
||||
async function offerDesktopApp({ unattended = false, outcome = {} } = {}) {
|
||||
const record = readInstallRecord();
|
||||
// A system the app is not built for is never asked about, or retried on every update.
|
||||
if (!appAssetName(projectVersion.version)) {
|
||||
if (!unattended) console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No desktop app is built for ${process.platform}-${process.arch}; skipping it.${COLORS.RESET}`);
|
||||
return;
|
||||
}
|
||||
if (unattended) {
|
||||
if (record && (record.pieces.includes('app') || (record.skipped || []).includes('app'))) return;
|
||||
await installDesktopApp({ quiet: true, unattended, outcome });
|
||||
return;
|
||||
}
|
||||
if (!process.stdin.isTTY) return;
|
||||
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
||||
const answer = await new Promise((resolve) => {
|
||||
rl.question(` ${COLORS.CYAN}Also install the Plan2Code desktop app?${COLORS.RESET} (Y/n): `, resolve);
|
||||
});
|
||||
rl.close();
|
||||
if (answer.trim().toLowerCase().startsWith('n')) {
|
||||
recordSkipped('app');
|
||||
return;
|
||||
}
|
||||
await installDesktopApp({ quiet: true, outcome });
|
||||
}
|
||||
|
||||
/** Remove the desktop app and what the installer left beside it. */
|
||||
function uninstallDesktopApp() {
|
||||
displaySectionHeader('DESKTOP APP', '[ UNINSTALL ]');
|
||||
let removed = false;
|
||||
for (const file of [APP_DEST, `${APP_DEST}.old`]) {
|
||||
if (!fs.existsSync(file)) continue;
|
||||
try {
|
||||
fs.rmSync(file, { force: true });
|
||||
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Removed: ${file}`);
|
||||
removed = true;
|
||||
} catch (error) {
|
||||
console.log(` ${COLORS.RED}${SYMBOLS.ERROR}${COLORS.RESET} Failed to remove ${file}: ${error.message}`);
|
||||
}
|
||||
}
|
||||
forgetInstalled('app');
|
||||
try {
|
||||
fs.rmdirSync(APP_DIR);
|
||||
} catch {}
|
||||
if (!removed) console.log(` ${COLORS.DIM}${SYMBOLS.INFO} No desktop app found${COLORS.RESET}`);
|
||||
console.log('');
|
||||
return 0;
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// UPDATE (`plan2code update` runs the npx install with --update)
|
||||
// ============================================================================
|
||||
@@ -2757,6 +2980,7 @@ function uninstallLauncher() {
|
||||
const UPDATE_STEPS = {
|
||||
skills: install,
|
||||
launcher: installLauncher,
|
||||
app: installDesktopApp,
|
||||
statusline: installStatusLine,
|
||||
loop: installPlan2CodeLoop,
|
||||
metrics: installPlan2CodeMetrics,
|
||||
@@ -2786,6 +3010,8 @@ async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
try {
|
||||
const code = await steps[piece]({ quiet: true, unattended: true, outcome });
|
||||
results[piece] = code === 0 ? 'updated' : 'failed: see the messages above';
|
||||
// The release has no app file yet: the installed one stays, and the update does not fail.
|
||||
if (piece === 'app' && code === 0 && outcome.appMissing) results[piece] = 'kept (no new desktop app file yet)';
|
||||
} catch (error) {
|
||||
results[piece] = `failed: ${error.message}`;
|
||||
}
|
||||
@@ -2796,13 +3022,15 @@ async function update({ steps = UPDATE_STEPS } = {}) {
|
||||
results.skills = outcome.skills ? 'updated' : 'failed: see the messages above';
|
||||
}
|
||||
if (piece === 'skills' && outcome.launcher === true) results.launcher = 'updated';
|
||||
// The same for the app, when install() brought it in for the first time.
|
||||
if (piece === 'skills' && outcome.app === true) results.app = 'updated';
|
||||
console.log('');
|
||||
}
|
||||
|
||||
console.log(`${COLORS.BRIGHT}UPDATE SUMMARY${COLORS.RESET}`);
|
||||
const failed = [];
|
||||
for (const piece of INSTALL_PIECES.filter((p) => p in results)) {
|
||||
const ok = results[piece] === 'updated';
|
||||
const ok = results[piece] === 'updated' || results[piece].startsWith('kept');
|
||||
if (!ok) failed.push(piece);
|
||||
console.log(` ${ok ? COLORS.GREEN + SYMBOLS.SUCCESS : COLORS.RED + SYMBOLS.ERROR}${COLORS.RESET} ${piece}: ${results[piece]}`);
|
||||
}
|
||||
@@ -2840,4 +3068,4 @@ if (require.main === module) {
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = { update, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
|
||||
module.exports = { update, installDesktopApp, offerDesktopApp, recordSkipped, appAssetName, checksumFor, APP_DEST, UPDATE_STEPS, INSTALL_RECORD, INSTALL_PIECES, readInstallRecord, recordInstalled, forgetInstalled, SOURCE_PROMPTS, generateSkillName };
|
||||
+2
-2
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.11.0",
|
||||
"version": "3.0.0",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
@@ -8,7 +8,7 @@
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"build:skills": "node install.js --build-skills",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs"
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0",
|
||||
|
||||
@@ -7,7 +7,9 @@
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import crypto from "node:crypto";
|
||||
import fs from "node:fs";
|
||||
import http from "node:http";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { spawnSync } from "node:child_process";
|
||||
@@ -186,3 +188,315 @@ test("install.js: --update is in the usage line, and an unknown option still exi
|
||||
assert.equal(result.status, 1);
|
||||
assert.ok(result.stderr.includes("Usage: node install.js [--build-skills | --verify-skills | --update]"), result.stderr);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
// The desktop app: downloaded from a release, checked against its checksum list, placed in
|
||||
// ~/.plan2code/app/. A stand-in release server stands in for GitHub; PLAN2CODE_RELEASE_BASE
|
||||
// points the installer at it, and nothing here reaches the network.
|
||||
// ---------------------------------------------------------------------------------------------
|
||||
|
||||
const ASSET = installer.appAssetName(VERSION);
|
||||
const SUMS = `plan2code-app-${VERSION}-SHA256SUMS.txt`;
|
||||
const APP_DIR = path.dirname(installer.APP_DEST);
|
||||
const sha = (bytes) => crypto.createHash("sha256").update(bytes).digest("hex");
|
||||
|
||||
/** A release server for `files` (`{ path: Buffer | string }`); `hits` lists every path asked for. */
|
||||
async function releaseServer(files) {
|
||||
const hits = [];
|
||||
const server = http.createServer((req, res) => {
|
||||
const name = decodeURIComponent(req.url.slice(1));
|
||||
hits.push(name);
|
||||
if (name in files) {
|
||||
res.writeHead(200);
|
||||
res.end(files[name]);
|
||||
} else {
|
||||
res.writeHead(404);
|
||||
res.end("not found");
|
||||
}
|
||||
});
|
||||
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
process.env.PLAN2CODE_RELEASE_BASE = `http://127.0.0.1:${server.address().port}/release`;
|
||||
return {
|
||||
hits,
|
||||
close: () => {
|
||||
delete process.env.PLAN2CODE_RELEASE_BASE;
|
||||
server.close();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A release serving `bytes` as this system's app, listed under `listedHash` (default: its real hash). */
|
||||
function goodRelease(bytes, listedHash = sha(bytes)) {
|
||||
return {
|
||||
[`release/${ASSET}`]: bytes,
|
||||
[`release/${SUMS}`]: `${listedHash} ${ASSET}\n${"0".repeat(64)} plan2code-app-other\n`,
|
||||
};
|
||||
}
|
||||
|
||||
/** Run `fn` with console output captured; resolves `{ result, out }`. */
|
||||
async function captured(fn) {
|
||||
const lines = [];
|
||||
const log = console.log;
|
||||
console.log = (...args) => lines.push(args.join(" "));
|
||||
try {
|
||||
const result = await fn();
|
||||
return { result, out: lines.join("\n").replace(/\x1b\[[0-9;]*m/g, "") };
|
||||
} finally {
|
||||
console.log = log;
|
||||
}
|
||||
}
|
||||
|
||||
function freshApp() {
|
||||
fs.rmSync(APP_DIR, { recursive: true, force: true });
|
||||
clearRecord();
|
||||
}
|
||||
|
||||
test("app: the release file is named by system and cpu, and an unbuilt system has none", () => {
|
||||
assert.equal(installer.appAssetName("3.0.0", "win32", "x64"), "plan2code-app-3.0.0-windows-x64.exe");
|
||||
assert.equal(installer.appAssetName("3.0.0", "darwin", "arm64"), "plan2code-app-3.0.0-macos-arm64");
|
||||
assert.equal(installer.appAssetName("3.0.0", "darwin", "x64"), "plan2code-app-3.0.0-macos-x64");
|
||||
assert.equal(installer.appAssetName("3.0.0", "linux", "x64"), "plan2code-app-3.0.0-linux-x64");
|
||||
assert.equal(installer.appAssetName("3.0.0", "freebsd", "x64"), null);
|
||||
assert.equal(installer.appAssetName("3.0.0", "linux", "ia32"), null);
|
||||
});
|
||||
|
||||
test("app: checksumFor reads text and binary mode lines and wants the exact name", () => {
|
||||
const hex = "ab".repeat(32);
|
||||
const list = `${hex} plan2code-app-1-linux-x64\n${"cd".repeat(32)} *plan2code-app-1-macos-arm64\r\nnot a checksum line\n`;
|
||||
assert.equal(installer.checksumFor(list, "plan2code-app-1-linux-x64"), hex);
|
||||
assert.equal(installer.checksumFor(list, "plan2code-app-1-macos-arm64"), "cd".repeat(32));
|
||||
assert.equal(installer.checksumFor(list, "plan2code-app-1-linux"), null);
|
||||
assert.equal(installer.checksumFor("", "x"), null);
|
||||
});
|
||||
|
||||
test("app installed: the file is downloaded, verified, placed and recorded", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const bytes = Buffer.from("pretend this is an executable");
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
const outcome = {};
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.equal(outcome.app, true);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["app", "launcher", "skills"]);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)], "no temp or .old file is left");
|
||||
assert.match(out, /unsigned/);
|
||||
assert.deepEqual(server.hits, [`release/${SUMS}`, `release/${ASSET}`]);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app checksum mismatch: the file is rejected, nothing is placed and the old app stays", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
fs.mkdirSync(APP_DIR, { recursive: true });
|
||||
fs.writeFileSync(installer.APP_DEST, "the app that was already here");
|
||||
writeRecord(["skills", "launcher", "app"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64)));
|
||||
try {
|
||||
const outcome = {};
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome }));
|
||||
assert.equal(result, 1);
|
||||
assert.equal(outcome.app, false);
|
||||
assert.match(out, /does not match its checksum/);
|
||||
// Said plainly: the rest is installed and --classic is today's flow.
|
||||
assert.match(out, /skills and the plan2code command are installed/);
|
||||
assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the app that was already here");
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app: a release without the file, or without a checksum entry, fails plainly and places nothing", { skip: !ASSET }, async () => {
|
||||
for (const files of [{}, { [`release/${SUMS}`]: `${"2".repeat(64)} some-other-file\n` }]) {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const server = await releaseServer(files);
|
||||
try {
|
||||
const outcome = {};
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true, outcome }));
|
||||
assert.equal(result, 1, out);
|
||||
assert.equal(outcome.app, false);
|
||||
assert.match(out, /The desktop app was not installed: /);
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false);
|
||||
assert.deepEqual(installer.readInstallRecord().pieces, ["skills", "launcher"], "a failed install leaves the record as it was");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test("app: a server that is not there fails plainly", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
process.env.PLAN2CODE_RELEASE_BASE = "http://127.0.0.1:1/release";
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /could not download it/);
|
||||
} finally {
|
||||
delete process.env.PLAN2CODE_RELEASE_BASE;
|
||||
}
|
||||
});
|
||||
|
||||
test("app update: plan2code update replaces an older app and reports it", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
fs.mkdirSync(APP_DIR, { recursive: true });
|
||||
fs.writeFileSync(installer.APP_DEST, "an older app");
|
||||
writeRecord(["app"]);
|
||||
const bytes = Buffer.from("the newer app");
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
// The real app step, in the real update loop; the record lists only the app.
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: updated/);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
assert.deepEqual(fs.readdirSync(APP_DIR), [path.basename(installer.APP_DEST)]);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app update: a checksum mismatch fails the update naming the app, nothing else", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["app"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("tampered bytes"), "1".repeat(64)));
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /Update failed for: app/);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app update: a release with no app file yet keeps the installed app and does not fail the update", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
fs.mkdirSync(APP_DIR, { recursive: true });
|
||||
fs.writeFileSync(installer.APP_DEST, "the installed app");
|
||||
writeRecord(["app"]);
|
||||
// main moves to a new version before the release's files are attached: every file is a 404.
|
||||
const server = await releaseServer({});
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.update({ steps: installer.UPDATE_STEPS }));
|
||||
assert.equal(result, 0, out);
|
||||
assert.match(out, /app: kept/);
|
||||
assert.doesNotMatch(out, /Update failed/);
|
||||
assert.equal(fs.readFileSync(installer.APP_DEST, "utf8"), "the installed app");
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app: interactively, a release with no app file is a plain failure, and a placement error is not called a download error", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
let server = await releaseServer({});
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /has no desktop app file for/);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
|
||||
// The download is fine but the folder cannot be made: a file sits where the app folder goes.
|
||||
fs.mkdirSync(path.dirname(APP_DIR), { recursive: true });
|
||||
fs.writeFileSync(APP_DIR, "in the way");
|
||||
server = await releaseServer(goodRelease(Buffer.from("a good file")));
|
||||
try {
|
||||
const { result, out } = await captured(() => installer.installDesktopApp({ quiet: true }));
|
||||
assert.equal(result, 1);
|
||||
assert.match(out, /the file was verified but could not be put in/);
|
||||
assert.doesNotMatch(out, /could not download/);
|
||||
} finally {
|
||||
server.close();
|
||||
fs.rmSync(APP_DIR, { force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("app offered: a system with no build is never asked about, never downloaded for and says nothing red", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const server = await releaseServer(goodRelease(Buffer.from("never fetched")));
|
||||
const arch = Object.getOwnPropertyDescriptor(process, "arch");
|
||||
Object.defineProperty(process, "arch", { value: "ia32", configurable: true });
|
||||
try {
|
||||
for (const unattended of [true, false]) {
|
||||
const { out } = await captured(() => installer.offerDesktopApp({ unattended, outcome: {} }));
|
||||
assert.doesNotMatch(out, /was not installed/);
|
||||
}
|
||||
assert.deepEqual(server.hits, []);
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false);
|
||||
} finally {
|
||||
Object.defineProperty(process, "arch", arch);
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app offered: unattended with no app file in the release yet is a dim note, not a failure", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const server = await releaseServer({});
|
||||
try {
|
||||
const outcome = {};
|
||||
const { out } = await captured(() => installer.offerDesktopApp({ unattended: true, outcome }));
|
||||
assert.match(out, /No desktop app update/);
|
||||
assert.doesNotMatch(out, /was not installed/);
|
||||
assert.equal(outcome.app, false);
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app skipped: an unattended offer downloads nothing when the app is recorded or was declined", { skip: !ASSET }, async () => {
|
||||
const server = await releaseServer(goodRelease(Buffer.from("never fetched")));
|
||||
try {
|
||||
// Recorded: the update loop owns it. Declined: the person said no once.
|
||||
for (const record of [{ pieces: ["skills", "app"] }, { pieces: ["skills"], skipped: ["app"] }]) {
|
||||
freshApp();
|
||||
fs.mkdirSync(path.dirname(RECORD), { recursive: true });
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", ...record }));
|
||||
await captured(() => installer.offerDesktopApp({ unattended: true, outcome: {} }));
|
||||
assert.equal(fs.existsSync(installer.APP_DEST), false, JSON.stringify(record));
|
||||
}
|
||||
assert.deepEqual(server.hits, []);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("app offered: unattended with nothing recorded about it means yes, and installing clears an old no", { skip: !ASSET }, async () => {
|
||||
freshApp();
|
||||
writeRecord(["skills", "launcher"]);
|
||||
const bytes = Buffer.from("first time app");
|
||||
const server = await releaseServer(goodRelease(bytes));
|
||||
try {
|
||||
const outcome = {};
|
||||
await captured(() => installer.offerDesktopApp({ unattended: true, outcome }));
|
||||
assert.equal(outcome.app, true);
|
||||
assert.deepEqual(fs.readFileSync(installer.APP_DEST), bytes);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
// A recorded decline is dropped once the piece is installed, and the key leaves the file when empty.
|
||||
fs.writeFileSync(RECORD, JSON.stringify({ version: "1.0.0", scope: "global", pieces: ["skills"], skipped: ["app"] }));
|
||||
installer.recordInstalled("app");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["app", "skills"] });
|
||||
});
|
||||
|
||||
test("app declined: the no is remembered next to the pieces, and needs a record to be kept", () => {
|
||||
clearRecord();
|
||||
installer.recordSkipped("app");
|
||||
assert.equal(installer.readInstallRecord(), null, "no record is invented for a decline");
|
||||
writeRecord(["skills"]);
|
||||
installer.recordSkipped("app");
|
||||
assert.deepEqual(installer.readInstallRecord(), { version: VERSION, scope: "global", pieces: ["skills"], skipped: ["app"] });
|
||||
installer.recordInstalled("launcher");
|
||||
assert.deepEqual(installer.readInstallRecord().skipped, ["app"], "other writes keep the decline");
|
||||
});
|
||||
+230
-2
@@ -25,8 +25,11 @@ const NOTICE = "will use the model you last used in it";
|
||||
* `installed: "X.Y.Z"` runs an installed copy instead, as install.js lays it out: the launcher,
|
||||
* models.json and update-check.mjs in <home>/.plan2code/bin/ beside a version.json saying X.Y.Z.
|
||||
*/
|
||||
function sandbox(clis, { installed } = {}) {
|
||||
function sandbox(clis, { installed, project = true } = {}) {
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-launcher-"));
|
||||
// `dir` is the launcher's cwd below; mark it as a project so the project-confirmation gate
|
||||
// does not fire in every other test here. The gate's own tests pass `project: false`.
|
||||
if (project) fs.writeFileSync(path.join(dir, "AGENTS.md"), "");
|
||||
const home = path.join(dir, "home");
|
||||
const bin = path.join(dir, "bin");
|
||||
fs.mkdirSync(home);
|
||||
@@ -57,8 +60,31 @@ function sandbox(clis, { installed } = {}) {
|
||||
fs.chmodSync(file, 0o755);
|
||||
}
|
||||
}
|
||||
// A stand-in for the desktop app that records its arguments like the CLIs do. It is not
|
||||
// on PATH: the launcher finds it through PLAN2CODE_APP, set only for the run that wants it.
|
||||
const appDir = path.join(dir, "app");
|
||||
fs.mkdirSync(appDir);
|
||||
const appFile = path.join(appDir, IS_WINDOWS ? "stand-in-app.cmd" : "stand-in-app");
|
||||
if (IS_WINDOWS) {
|
||||
// The first line leaves the sandbox folder (the app's working directory) so nothing holds it open.
|
||||
fs.writeFileSync(appFile, `@cd /d "${os.tmpdir()}"\r\n@"${process.execPath}" "${recorder}" app %*\r\n`);
|
||||
} else {
|
||||
fs.writeFileSync(appFile, `#!/bin/sh\ncd "${os.tmpdir()}" && exec "${process.execPath}" "${recorder}" app "$@"\n`);
|
||||
fs.chmodSync(appFile, 0o755);
|
||||
}
|
||||
// One that starts and dies at once, as a program with a missing system library does.
|
||||
const crashFile = path.join(appDir, IS_WINDOWS ? "crashing-app.cmd" : "crashing-app");
|
||||
if (IS_WINDOWS) {
|
||||
fs.writeFileSync(crashFile, "@exit /b 3\r\n");
|
||||
} else {
|
||||
fs.writeFileSync(crashFile, "#!/bin/sh\nexit 3\n");
|
||||
fs.chmodSync(crashFile, 0o755);
|
||||
}
|
||||
return {
|
||||
dir,
|
||||
home,
|
||||
appFile,
|
||||
crashFile,
|
||||
stateFile: path.join(home, ".plan2code", "launcher.json"),
|
||||
cacheFile: path.join(consoleHome, "update-check.json"),
|
||||
run: (args, env = {}) =>
|
||||
@@ -72,8 +98,28 @@ function sandbox(clis, { installed } = {}) {
|
||||
const file = path.join(bin, `${cli}.json`);
|
||||
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
|
||||
},
|
||||
// The app starts detached and the launcher exits at once, so its record can land a moment later.
|
||||
appArgs: () => {
|
||||
const file = path.join(bin, "app.json");
|
||||
for (let waited = 0; waited < 10000 && !fs.existsSync(file); waited += 50) {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 50);
|
||||
}
|
||||
return fs.existsSync(file) ? JSON.parse(fs.readFileSync(file, "utf8")) : null;
|
||||
},
|
||||
appExists: () => fs.existsSync(path.join(bin, "app.json")),
|
||||
// A detached release-check refresh may still be writing its cache; retry rather than fail.
|
||||
cleanup: () => fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 }),
|
||||
// The stand-in app runs detached with the sandbox as its folder, so on Windows it can hold
|
||||
// the directory for a moment after its record lands, and rmSync's own retries give up on
|
||||
// that EPERM at once. Try again for a few seconds; a temp folder left behind is harmless.
|
||||
cleanup: () => {
|
||||
for (let attempt = 0; attempt < 25; attempt++) {
|
||||
try {
|
||||
return fs.rmSync(dir, { recursive: true, force: true, maxRetries: 10, retryDelay: 100 });
|
||||
} catch {
|
||||
Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 200);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -379,3 +425,185 @@ test("launcher: a piped run prints no escape codes, with or without NO_COLOR", (
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// The desktop app hand-off. The stand-in app is found through PLAN2CODE_APP; "no display" is
|
||||
// only something a Linux run can ask for, since Windows and macOS always count as having one.
|
||||
const NO_DISPLAY = { DISPLAY: "", WAYLAND_DISPLAY: "" };
|
||||
const CLASSIC_ARGS = ["/plan2code", "--permission-mode", "bypassPermissions"];
|
||||
|
||||
test("launcher app: with no app installed the agent starts exactly as before", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.argsOf("claude"), CLASSIC_ARGS);
|
||||
assert.equal(box.appExists(), false);
|
||||
});
|
||||
|
||||
test("launcher app: --classic runs today's flow even with the app installed, and is never forwarded", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run(["--classic", "--verbose"], { PLAN2CODE_APP: box.appFile });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.argsOf("claude"), [...CLASSIC_ARGS, "--verbose"]);
|
||||
assert.equal(box.appExists(), false);
|
||||
});
|
||||
|
||||
test("launcher app: no display on Linux runs today's flow even with the app installed", { skip: process.platform !== "linux" }, (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([], { PLAN2CODE_APP: box.appFile, ...NO_DISPLAY });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.argsOf("claude"), CLASSIC_ARGS);
|
||||
assert.equal(box.appExists(), false);
|
||||
});
|
||||
|
||||
test("launcher app: with the app and a display it starts the app on the folder, agent and model, and no agent", (t) => {
|
||||
const box = sandbox(["claude", "codex"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run(["--cli", "codex", "--model", "gpt-5"], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
const appArgs = box.appArgs();
|
||||
assert.ok(appArgs, "the stand-in app was never started");
|
||||
// The launcher runs in the sandbox folder, so that folder is the project.
|
||||
assert.equal(appArgs[0], "--project");
|
||||
assert.equal(fs.realpathSync(appArgs[1]), fs.realpathSync(box.dir));
|
||||
assert.deepEqual(appArgs.slice(2), ["--agent", "codex", "--model", "gpt-5"]);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
assert.equal(box.argsOf("codex"), null);
|
||||
assert.match(result.stdout, /Opened the Plan2Code app/);
|
||||
});
|
||||
|
||||
test("launcher app: a model is left out of the app's arguments when none was chosen", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run([], { PLAN2CODE_APP: box.appFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.deepEqual(box.appArgs().slice(2), ["--agent", "claude"]);
|
||||
});
|
||||
|
||||
test("launcher app: an app that cannot start falls back to the terminal flow", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
// Present but not runnable (no execute bit on POSIX, not a program on Windows).
|
||||
const broken = path.join(path.dirname(box.appFile), IS_WINDOWS ? "broken.exe" : "broken");
|
||||
fs.writeFileSync(broken, "not a program");
|
||||
const result = box.run([], { PLAN2CODE_APP: broken, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stderr, /could not start the app/);
|
||||
assert.deepEqual(box.argsOf("claude"), CLASSIC_ARGS);
|
||||
});
|
||||
|
||||
test("launcher app: modelFrom reads --model, --model= and Codex's -m", () => {
|
||||
const { modelFrom } = require(LAUNCHER);
|
||||
assert.equal(modelFrom(["--model", "x"], "claude"), "x");
|
||||
assert.equal(modelFrom(["--model=x"], "claude"), "x");
|
||||
assert.equal(modelFrom(["-m", "x"], "codex"), "x");
|
||||
assert.equal(modelFrom(["-m=x"], "codex"), "x");
|
||||
assert.equal(modelFrom(["-m", "x"], "claude"), null);
|
||||
assert.equal(modelFrom(["--verbose"], "claude"), null);
|
||||
});
|
||||
|
||||
test("launcher app: an app that starts and then exits with a failure falls back to the terminal flow", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const display = process.platform === "linux" ? { DISPLAY: ":0" } : {};
|
||||
const result = box.run([], { PLAN2CODE_APP: box.crashFile, ...display });
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stderr, /the app exited at once \(code 3\)/);
|
||||
assert.deepEqual(box.argsOf("claude"), CLASSIC_ARGS);
|
||||
assert.doesNotMatch(result.stdout, /Opened the Plan2Code app/);
|
||||
});
|
||||
|
||||
test("launcher app: hasDisplay refuses an SSH session on Windows and macOS, but Linux only cares about DISPLAY", () => {
|
||||
const launcherPath = require.resolve(LAUNCHER);
|
||||
const realPlatform = process.platform;
|
||||
const saved = {
|
||||
DISPLAY: process.env.DISPLAY,
|
||||
WAYLAND_DISPLAY: process.env.WAYLAND_DISPLAY,
|
||||
SSH_CONNECTION: process.env.SSH_CONNECTION,
|
||||
SSH_TTY: process.env.SSH_TTY,
|
||||
};
|
||||
for (const key of Object.keys(saved)) delete process.env[key];
|
||||
|
||||
// IS_WINDOWS/IS_MAC are consts captured from process.platform at require time, so testing a
|
||||
// platform other than this machine's needs a fresh module instance loaded under a faked one.
|
||||
function hasDisplayOn(platform) {
|
||||
Object.defineProperty(process, "platform", { value: platform, configurable: true });
|
||||
delete require.cache[launcherPath];
|
||||
try {
|
||||
return require(LAUNCHER).hasDisplay();
|
||||
} finally {
|
||||
Object.defineProperty(process, "platform", { value: realPlatform, configurable: true });
|
||||
delete require.cache[launcherPath];
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
for (const platform of ["win32", "darwin"]) {
|
||||
assert.equal(hasDisplayOn(platform), true, platform);
|
||||
process.env.SSH_CONNECTION = "10.0.0.1 51000 10.0.0.2 22";
|
||||
assert.equal(hasDisplayOn(platform), false, `${platform} SSH_CONNECTION`);
|
||||
delete process.env.SSH_CONNECTION;
|
||||
process.env.SSH_TTY = "/dev/ttys000";
|
||||
assert.equal(hasDisplayOn(platform), false, `${platform} SSH_TTY`);
|
||||
delete process.env.SSH_TTY;
|
||||
}
|
||||
// Linux never looks at the SSH env vars; DISPLAY/WAYLAND_DISPLAY alone still decides.
|
||||
process.env.SSH_CONNECTION = "10.0.0.1 51000 10.0.0.2 22";
|
||||
assert.equal(hasDisplayOn("linux"), false);
|
||||
process.env.DISPLAY = ":0";
|
||||
assert.equal(hasDisplayOn("linux"), true);
|
||||
delete process.env.DISPLAY;
|
||||
delete process.env.SSH_CONNECTION;
|
||||
} finally {
|
||||
for (const [key, value] of Object.entries(saved)) {
|
||||
if (value === undefined) delete process.env[key];
|
||||
else process.env[key] = value;
|
||||
}
|
||||
// Re-require with the real platform so later tests in this file see the host's own module.
|
||||
delete require.cache[launcherPath];
|
||||
require(LAUNCHER);
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher app: looksLikeProject checks for a .git entry, AGENTS.md or a specs folder", () => {
|
||||
const { looksLikeProject } = require(LAUNCHER);
|
||||
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-project-"));
|
||||
try {
|
||||
assert.equal(looksLikeProject(dir), false);
|
||||
fs.writeFileSync(path.join(dir, "AGENTS.md"), "");
|
||||
assert.equal(looksLikeProject(dir), true);
|
||||
fs.rmSync(path.join(dir, "AGENTS.md"));
|
||||
// A worktree's .git is a file, not a directory, and still counts.
|
||||
fs.writeFileSync(path.join(dir, ".git"), "gitdir: ../elsewhere/.git/worktrees/x\n");
|
||||
assert.equal(looksLikeProject(dir), true);
|
||||
fs.rmSync(path.join(dir, ".git"));
|
||||
assert.equal(looksLikeProject(dir), false);
|
||||
fs.mkdirSync(path.join(dir, "specs"));
|
||||
assert.equal(looksLikeProject(dir), true);
|
||||
} finally {
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("launcher app: a folder that doesn't look like a project is refused without a terminal to confirm it", (t) => {
|
||||
const box = sandbox(["claude"], { project: false });
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.match(result.stderr, /doesn't look like a project/);
|
||||
assert.equal(box.argsOf("claude"), null);
|
||||
});
|
||||
|
||||
test("launcher app: an AGENTS.md marks the folder as a project, so the agent starts as usual", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const result = box.run([]);
|
||||
assert.equal(result.status, 0, result.stderr);
|
||||
assert.doesNotMatch(result.stderr, /doesn't look like a project/);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
});
|
||||
@@ -1144,7 +1144,8 @@ test("the dashboard matrix lights only the cards a spec state allows", () => {
|
||||
assert.equal(on(skill, scan, s), true, `${skill} on for ${s.state}`);
|
||||
}
|
||||
}
|
||||
assert.equal(on("plan2code-1b-revise-plan", scan, sel("built")), false);
|
||||
// Revise stays lit on a built spec: a change found in the last manual checks is still a plan change.
|
||||
assert.equal(on("plan2code-1b-revise-plan", scan, sel("built")), true);
|
||||
assert.equal(on("plan2code-4-finalize", scan, sel("built")), true);
|
||||
|
||||
// A diagnosed bug: Quick Task (its next step) and Plan, never the build steps.
|
||||
|
||||
@@ -106,6 +106,56 @@ test("the dashboard refuses question cards: nothing there would draw them", () =
|
||||
assert.ok(validate(state).some((p) => p.includes("dashboard draws no question cards")));
|
||||
});
|
||||
|
||||
test("an unanswered note blocks a settle that ignores it", () => {
|
||||
const withNote = {
|
||||
...choice("q1"),
|
||||
thread: [{ who: "user", text: "Why this option?" }],
|
||||
submitted: { k: "A", at: "2026-01-01T00:00:00.000Z" },
|
||||
};
|
||||
const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), items: [withNote] };
|
||||
const next = applyPatch(state, { settle: ["q1"] });
|
||||
assert.ok(validate(next).some((p) => p.includes('item "q1" has an unanswered note')));
|
||||
});
|
||||
|
||||
test("adding a thread reply in the same patch clears the note and allows the settle", () => {
|
||||
const withNote = {
|
||||
...choice("q1"),
|
||||
thread: [{ who: "user", text: "Why this option?" }],
|
||||
submitted: { k: "A", at: "2026-01-01T00:00:00.000Z" },
|
||||
};
|
||||
const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), items: [withNote] };
|
||||
const next = applyPatch(state, {
|
||||
items: [{ id: "q1", thread: [{ who: "agent", text: "Because it matches the brief." }] }],
|
||||
settle: ["q1"],
|
||||
});
|
||||
assert.deepEqual(validate(next), []);
|
||||
});
|
||||
|
||||
test("an item with no user note left unanswered is unaffected", () => {
|
||||
const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), items: [choice("q1"), choice("q2")] };
|
||||
assert.deepEqual(validate(state), []);
|
||||
const answered = {
|
||||
...choice("q3"),
|
||||
thread: [{ who: "user", text: "Note" }, { who: "agent", text: "Reply." }],
|
||||
};
|
||||
assert.deepEqual(validate({ ...state, items: [answered] }), []);
|
||||
});
|
||||
|
||||
test("deleting the item in the same patch is exempt from the unanswered-note check", () => {
|
||||
const withNote = { ...choice("q1"), thread: [{ who: "user", text: "Why this option?" }] };
|
||||
const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), items: [withNote] };
|
||||
const next = applyPatch(state, { items: [{ id: "q1", _delete: true }] });
|
||||
assert.deepEqual(next.items, []);
|
||||
assert.deepEqual(validate(next), []);
|
||||
});
|
||||
|
||||
test("a finish patch is exempt from the unanswered-note check", () => {
|
||||
const withNote = { ...choice("q1"), thread: [{ who: "user", text: "Why this option?" }] };
|
||||
const state = { ...blankState({ sid: "x", project: "p", workflow: "plan" }), items: [withNote] };
|
||||
const next = applyPatch(state, { finish: { headline: "Done" } });
|
||||
assert.deepEqual(validate(next), []);
|
||||
});
|
||||
|
||||
/* ------------------------------------------------------------- the CLI */
|
||||
|
||||
test("post --file reads a patch PowerShell wrote: a UTF-8 BOM, or UTF-16", () => {
|
||||
|
||||
@@ -439,6 +439,10 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
|
||||
// Handoffs are Plan2Code's own, however old: swept by age on open, never offered here.
|
||||
backdate(put(path.join(plan2code, "handoffs", "2025-01-01-0900-handoff.md")));
|
||||
backdate(path.join(plan2code, "handoffs"));
|
||||
// The desktop app and its settings are Plan2Code's own too, however old.
|
||||
backdate(put(path.join(plan2code, "app", "plan2code-app"), "x"));
|
||||
backdate(path.join(plan2code, "app"));
|
||||
backdate(put(path.join(plan2code, "app.json")));
|
||||
// In use right now: a held lock and a temp between its write and rename.
|
||||
const live = [put(path.join(consoleDir, "workspaces.json.lock"), ""), put(path.join(plan2code, "models.json.123.tmp"))];
|
||||
kept.push(...live);
|
||||
@@ -454,6 +458,7 @@ test("cleanup finds old sessions and strays in both folders, and keeps every pro
|
||||
"session:20250801-101010-aaaaaa",
|
||||
]);
|
||||
assert.equal(items.some((i) => i.id === "root:handoffs"), false, "the handoffs folder is never a stray");
|
||||
for (const id of ["root:app", "root:app.json"]) assert.equal(items.some((i) => i.id === id), false, `${id} is never a stray`);
|
||||
assert.equal(STRAY_GRACE_MS, 60 * 60 * 1000);
|
||||
assert.equal(items.find((i) => i.id === "console:p1.json").bytes, 5);
|
||||
assert.equal(items.find((i) => i.id === "root:console-dev").kind, "folder");
|
||||
|
||||
@@ -176,7 +176,7 @@ const CARDS = {
|
||||
planned: { on: false, reason: "Needs a spec that is already written up" },
|
||||
documented: { on: true },
|
||||
building: { on: true },
|
||||
built: { on: false, reason: "The spec is fully built" },
|
||||
built: { on: true },
|
||||
unrecognized: { on: false, reason: "Needs a spec that is already written up" },
|
||||
},
|
||||
"plan2code-2-document": {
|
||||
|
||||
+144
-8
@@ -22,8 +22,12 @@
|
||||
* `--pick-folder` (passed by the desktop shortcut, never forwarded to the CLI) asks for the
|
||||
* project folder with a native folder picker first, starting on the folder picked last time.
|
||||
*
|
||||
* When the desktop app is installed (~/.plan2code/app/) and a display exists, `plan2code` opens
|
||||
* the app on the chosen folder, agent and model instead of running the agent in this terminal.
|
||||
* `--classic` (never forwarded to the CLI), no app, and no display on Linux keep the flow above.
|
||||
*
|
||||
* `plan2code update` starts no agent: it re-runs the npx install with `--update`, which
|
||||
* reinstalls whatever ~/.plan2code/install.json lists. Before an agent starts, one line says
|
||||
* reinstalls whatever ~/.plan2code/install.json lists (the desktop app included). Before an agent starts, one line says
|
||||
* when a newer release is out (releaseNotice), read from the web console's cached release check
|
||||
* and never waiting on the network.
|
||||
*
|
||||
@@ -42,6 +46,13 @@ const IS_WINDOWS = process.platform === 'win32';
|
||||
const IS_MAC = process.platform === 'darwin';
|
||||
const PICK_FOLDER_FLAG = '--pick-folder';
|
||||
const CLI_FLAG = '--cli';
|
||||
const CLASSIC_FLAG = '--classic';
|
||||
// Where install.js puts the desktop app, and the one file in it the launcher starts.
|
||||
// PLAN2CODE_APP names a different executable (the tests start a stand-in this way).
|
||||
const APP_DIR = path.join(os.homedir(), '.plan2code', 'app');
|
||||
const APP_FILE = IS_WINDOWS ? 'plan2code-app.exe' : 'plan2code-app';
|
||||
// How long a freshly started app may take to fall over before the launcher calls it started.
|
||||
const APP_START_GRACE_MS = 1200;
|
||||
const STATE_FILE = path.join(os.homedir(), '.plan2code', 'launcher.json');
|
||||
// Menus longer than this print compactly (id-only, two columns).
|
||||
const MODELS_MENU_COMPACT_AT = 30;
|
||||
@@ -541,6 +552,74 @@ async function chooseModel(cli, extraArgs) {
|
||||
}
|
||||
}
|
||||
|
||||
/** A window can open: assumed on Windows and macOS, and on Linux only with an X11 or Wayland display. */
|
||||
function hasDisplay() {
|
||||
// sshd sets one of these for an SSH login on both platforms, and there is no window to open
|
||||
// there. A plain background/service context (no SSH, no desktop) cannot be told apart from an
|
||||
// ordinary desktop login on Windows or macOS without a new dependency, so SSH is as far as this goes.
|
||||
if ((IS_WINDOWS || IS_MAC) && (process.env.SSH_CONNECTION || process.env.SSH_TTY)) return false;
|
||||
return IS_WINDOWS || IS_MAC || Boolean(process.env.DISPLAY || process.env.WAYLAND_DISPLAY);
|
||||
}
|
||||
|
||||
/** The installed desktop app's executable, or null when it is not installed. */
|
||||
function findApp() {
|
||||
const file = process.env.PLAN2CODE_APP || path.join(APP_DIR, APP_FILE);
|
||||
try {
|
||||
return fs.statSync(file).isFile() ? file : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** The model the forwarded arguments pick (`--model x`, `--model=x`, Codex's `-m x`), or null. */
|
||||
function modelFrom(args, cliId) {
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
if (arg === '--model' || (cliId === 'codex' && arg === '-m')) return args[i + 1] || null;
|
||||
if (arg.startsWith('--model=')) return arg.slice('--model='.length) || null;
|
||||
if (cliId === 'codex' && arg.startsWith('-m=')) return arg.slice(3) || null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the desktop app on the folder, agent and model and let it run on 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 }) {
|
||||
const args = ['--project', cwd, '--agent', cliId, ...(model ? ['--model', model] : [])];
|
||||
return new Promise((resolve) => {
|
||||
let child;
|
||||
try {
|
||||
child = spawnCommand(app, args, { cwd, detached: true, stdio: 'ignore' });
|
||||
} catch (error) {
|
||||
console.error(`${ce.yellow('plan2code:')} could not start the app (${error.message}); opening in this terminal instead.`);
|
||||
return resolve(false);
|
||||
}
|
||||
child.once('error', (error) => {
|
||||
console.error(`${ce.yellow('plan2code:')} could not start the app (${error.message}); opening in this terminal instead.`);
|
||||
resolve(false);
|
||||
});
|
||||
child.once('spawn', () => {
|
||||
// A program that starts and then dies (a missing system library is reported after the
|
||||
// exec, not as a spawn error) must not strand the person with a closed terminal: an exit
|
||||
// with a failure inside the grace period falls back to the terminal flow.
|
||||
const timer = setTimeout(() => {
|
||||
child.removeAllListeners('exit');
|
||||
child.unref();
|
||||
resolve(true);
|
||||
}, APP_START_GRACE_MS);
|
||||
child.once('exit', (code, signal) => {
|
||||
clearTimeout(timer);
|
||||
if (code === 0) return resolve(true);
|
||||
console.error(`${ce.yellow('plan2code:')} the app exited at once (${signal ? `signal ${signal}` : `code ${code}`}); opening in this terminal instead.`);
|
||||
resolve(false);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The native folder picker for this OS, as a command to run: it prints the chosen folder, or
|
||||
* nothing when the person cancels. Null when this OS has no picker we can drive.
|
||||
@@ -588,7 +667,7 @@ function getPickerCommand(start) {
|
||||
};
|
||||
}
|
||||
|
||||
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
|
||||
if (!hasDisplay()) return null;
|
||||
if (findOnPath('zenity')) {
|
||||
return { command: 'zenity', args: ['--file-selection', '--directory', `--title=${PICKER_PROMPT}`, `--filename=${start}${path.sep}`] };
|
||||
}
|
||||
@@ -598,6 +677,39 @@ function getPickerCommand(start) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* A git repo (a `.git` entry, file or directory since worktrees use a file), or has `AGENTS.md`
|
||||
* or a `specs/` folder: enough to call `dir` a project without asking first.
|
||||
*/
|
||||
function looksLikeProject(dir) {
|
||||
return (
|
||||
fs.existsSync(path.join(dir, '.git')) ||
|
||||
fs.existsSync(path.join(dir, 'AGENTS.md')) ||
|
||||
isDirectory(path.join(dir, 'specs'))
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* opening the app (or the terminal flow) on the wrong folder.
|
||||
*/
|
||||
async function confirmProject(cwd) {
|
||||
if (looksLikeProject(cwd)) return true;
|
||||
if (!process.stdin.isTTY) {
|
||||
console.error(
|
||||
`${ce.yellow('plan2code:')} ${cwd} doesn't look like a project (no git repo, AGENTS.md or specs folder); run \`plan2code\` there from a terminal to confirm, or cd into a project first.`
|
||||
);
|
||||
return false;
|
||||
}
|
||||
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]: `)
|
||||
)
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
return answer === 'y' || answer === 'yes';
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
|
||||
* Returns the folder, or null when the person cancelled.
|
||||
@@ -660,15 +772,24 @@ function spawnCommand(file, args, options) {
|
||||
: spawn(file, args, options);
|
||||
}
|
||||
|
||||
/** `plan2code update`: the npx install with --update, passing npx's exit code through. No agent starts. */
|
||||
function runUpdate() {
|
||||
/**
|
||||
* `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.
|
||||
*/
|
||||
/** `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...');
|
||||
console.log(c.dim('One update covers the skills, the plan2code command and the desktop app (when installed).'));
|
||||
const npx = findOnPath('npx');
|
||||
if (!npx) {
|
||||
console.error(`${ce.red('plan2code:')} npx was not found on your PATH. It comes with Node.js 18+ (https://nodejs.org).`);
|
||||
return process.exit(127);
|
||||
}
|
||||
const child = spawnCommand(npx, ['--yes', '--allow-git=all', `git+${REPO_URL}`, '--update'], { stdio: 'inherit' });
|
||||
const spec = tag ? `git+${REPO_URL}#${tag}` : `git+${REPO_URL}`;
|
||||
const child = spawnCommand(npx, ['--yes', '--allow-git=all', spec, '--update'], { stdio: 'inherit' });
|
||||
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
|
||||
process.on(signal, () => {});
|
||||
}
|
||||
@@ -723,9 +844,15 @@ async function releaseNotice() {
|
||||
|
||||
async function launch() {
|
||||
const argv = process.argv.slice(2);
|
||||
if (argv[0] === UPDATE_COMMAND) return runUpdate();
|
||||
if (argv[0] === UPDATE_COMMAND) {
|
||||
const tagAt = argv.indexOf('--tag');
|
||||
return runUpdate(tagAt >= 0 ? argv[tagAt + 1] : undefined);
|
||||
}
|
||||
const fromShortcut = argv.includes(PICK_FOLDER_FLAG);
|
||||
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(argv.filter((arg) => arg !== PICK_FOLDER_FLAG));
|
||||
const classic = argv.includes(CLASSIC_FLAG);
|
||||
const { cli: requestedCli, rest: extraArgs } = takeCliFlag(
|
||||
argv.filter((arg) => arg !== PICK_FOLDER_FLAG && arg !== CLASSIC_FLAG)
|
||||
);
|
||||
|
||||
printIntro();
|
||||
await releaseNotice();
|
||||
@@ -746,8 +873,17 @@ async function launch() {
|
||||
console.log(`Opening Plan2Code in ${c.cyan(folder)}`);
|
||||
}
|
||||
|
||||
if (!(await confirmProject(cwd))) return process.exit(0);
|
||||
|
||||
if (!hasModelFlag(extraArgs, cli.id)) await chooseModel(cli, extraArgs);
|
||||
|
||||
// The app takes over from here when it is installed, a window can open and --classic is absent.
|
||||
const app = !classic && hasDisplay() ? findApp() : null;
|
||||
if (app && (await startApp(app, { cwd, cliId: cli.id, model: modelFrom(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);
|
||||
}
|
||||
|
||||
const args = cli.args(extraArgs);
|
||||
const options = { cwd, stdio: 'inherit' };
|
||||
|
||||
@@ -777,4 +913,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 = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions };
|
||||
module.exports = { mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
|
||||
+1
-1
@@ -39,7 +39,7 @@ The page draws the cards itself — you never send the list. It also knows the r
|
||||
- `documented` ("Ready to build"): Implement is next.
|
||||
- `building` ("Building"): Implement is next.
|
||||
- `built` ("Ready to finalize"): Finalize is next.
|
||||
- A `documented` or `building` spec whose `[/]` phase file holds a waiting `**Plan change:**` line in its Notes (Implement paused for a revision; `(applied <date>):` or `(dropped <date>):` means done): recommend Revise the plan instead, `details` "Plan change waiting from Phase N". On a `built` spec the Revise card is greyed, so name the waiting brief in `note`.
|
||||
- A `documented` or `building` spec whose `[/]` phase file holds a waiting `**Plan change:**` line in its Notes (Implement paused for a revision; `(applied <date>):` or `(dropped <date>):` means done): recommend Revise the plan instead, `details` "Plan change waiting from Phase N". The Revise card is lit on a `built` spec too (a change found in the last manual checks): recommend it there only for a waiting brief, and say so in `note`; otherwise Finalize stays the next step.
|
||||
- A spec that scans `unrecognized` ("files on disk") is input, not progress: its folder rides along on a Pathfinder or Plan launch as reference, and those are the only pipeline cards it lights. Read the files and recommend the fit — a settled design doc the person wrote is Plan's brief, loose notes are Pathfinder's. No skill generates such a doc; see the table below for what each one does write. Never flag Document or anything downstream of it for such a spec.
|
||||
- A `diagnosed` spec ("Bug diagnosed") is a bug Diagnose wrote up: recommend Quick Task, or Plan when its `DIAGNOSIS-<date>.md` sizes the fix as big; its folder rides along on either launch.
|
||||
- A `fixed` spec ("Bug fixed") is a diagnosed bug Quick Task fixed but did not archive: finished, so never recommend for it or name it in the note; the picker never pre-selects one and hides it while unavailable workflows are hidden. The person archives it (Quick Task offers that once the bug is fixed) or deletes it with the picker's ✕.
|
||||
|
||||
@@ -51,6 +51,7 @@ import { readPrHosts, resetSubagentCursor } from "./settings.mjs";
|
||||
import { WORKFLOWS, isWorkflow } from "./public/skills.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
import { snapshot } from "./git-repo.mjs";
|
||||
import { announcePage, currentSession, inAppSignal } from "./in-app.mjs";
|
||||
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
|
||||
import {
|
||||
readPatch,
|
||||
@@ -95,6 +96,10 @@ function leavePointer() {
|
||||
}
|
||||
}
|
||||
|
||||
// Printed on every `open`: this console can be framed by the desktop app (the
|
||||
// embed mode, and the in-app signal). The app refuses a console without it.
|
||||
const EMBED_API = 1;
|
||||
|
||||
export async function cmdOpen() {
|
||||
trace("open: start");
|
||||
// A workflow the console does not know is refused first, before the pointer,
|
||||
@@ -105,6 +110,20 @@ export async function cmdOpen() {
|
||||
die(`unknown workflow "${args.workflow}"; one of: ${WORKFLOWS.join(", ")}`, 2);
|
||||
}
|
||||
leavePointer();
|
||||
// Under the desktop app the page belongs in the app's window: never the
|
||||
// browser, and (unless a session was named) the app's own session, so one
|
||||
// console serves the whole window. A session that is gone is simply not
|
||||
// reused: the open below makes a new one and announces its address.
|
||||
const inApp = inAppSignal();
|
||||
if (inApp) {
|
||||
args["no-open"] = true;
|
||||
const named = args.resume || args.session;
|
||||
if (!named) {
|
||||
// The window knows its current session; the environment's is only a fallback.
|
||||
const sid = path.basename((await currentSession(inApp)) || inApp.sid || "");
|
||||
if (sid && fs.existsSync(sessionDir(sid))) args.resume = sid;
|
||||
}
|
||||
}
|
||||
const { project, worktree, branch } = repoRoots();
|
||||
reapHandles(project);
|
||||
trace("open: project found");
|
||||
@@ -369,13 +388,16 @@ export async function cmdOpen() {
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const inAppReport = await tellApp(inApp, { url: existing.url, sid, workflow: state.workflow });
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
session: dir,
|
||||
url: existing.url,
|
||||
embed: EMBED_API,
|
||||
reused: true,
|
||||
...inAppReport,
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
@@ -416,12 +438,18 @@ export async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const inAppReport = await tellApp(inApp, { url: handle.url, sid, workflow: state.workflow });
|
||||
if (inAppReport.inApp && !inAppReport.announced) {
|
||||
notes.push(`The app did not take the page. Open ${handle.url} in a browser, or press Reload in the app.`);
|
||||
}
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
session: dir,
|
||||
url: handle.url,
|
||||
embed: EMBED_API,
|
||||
...inAppReport,
|
||||
port: handle.port,
|
||||
pid: handle.pid,
|
||||
pendingResult: carried,
|
||||
@@ -437,6 +465,16 @@ export async function cmdOpen() {
|
||||
sweep();
|
||||
}
|
||||
|
||||
/**
|
||||
* Under the app, say which page to show; outside it, nothing and no keys.
|
||||
* The report rides on `open`'s output so the agent can tell what happened.
|
||||
*/
|
||||
async function tellApp(signal, page) {
|
||||
if (!signal) return {};
|
||||
const announced = signal.announce ? await announcePage(signal, page) : false;
|
||||
return { inApp: true, announced };
|
||||
}
|
||||
|
||||
/**
|
||||
* The workspace as `open` hands it to the agent, and the cursor seeded to
|
||||
* match: the agent now has the whole list, so no change up to here is owed.
|
||||
|
||||
@@ -382,6 +382,10 @@ A patch that breaks one is refused, exit `3`, with the reason:
|
||||
7. **`run`, `folderIssue` and `helpers` are well formed** (their topic files).
|
||||
8. **A doc's `version` never goes back.**
|
||||
9. **A finish `command` has no placeholders** (`<` or `>`).
|
||||
10. **Every note gets a reply.** A card whose thread ends with the person's own
|
||||
words stays that way until a patch adds an agent reply to it; settling or
|
||||
reopening it does not count. Exempt once the item is deleted, or the whole
|
||||
session is ending.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -665,6 +665,21 @@ export function validate(state) {
|
||||
if (recs.length > 1) problems.push(`item "${item.id}" marks ${recs.length} options recommended; at most one`);
|
||||
}
|
||||
|
||||
// A note on a card is unanswered the moment no agent words follow it in its
|
||||
// thread. Once that is true, no patch may move past it except one that
|
||||
// finally replies: deleting the item drops it from state.items before this
|
||||
// check ever sees it, and the session's own ending is exempt because
|
||||
// nothing further is coming to answer into.
|
||||
if (state.finish == null) {
|
||||
for (const item of state.items) {
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const last = thread[thread.length - 1];
|
||||
if (isPlainObject(last) && last.who === "user") {
|
||||
problems.push(`item "${item.id}" has an unanswered note from the person; reply in its thread before this patch`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The dashboard's page is the menu: a card posted there is drawn nowhere,
|
||||
// yet counts as open (and keeps Stop live for a question nobody can see).
|
||||
if (state.workflow === "dashboard" && state.items.some((i) => isOpen(i))) {
|
||||
|
||||
@@ -66,3 +66,14 @@ connect();
|
||||
setTimeout(() => {
|
||||
if (!wakeHoldsChime) sound("sessionStart");
|
||||
}, 0);
|
||||
|
||||
// Inside the desktop app's frame, tell the app this page drew. A frame the
|
||||
// browser refused (or a server that died) never sends it, which is how the app
|
||||
// tells a blocked page from a slow one. The message carries no data.
|
||||
if (window.parent && window.parent !== window) {
|
||||
try {
|
||||
window.parent.postMessage({ plan2code: "console-ready" }, "*");
|
||||
} catch {
|
||||
/* no parent to tell */
|
||||
}
|
||||
}
|
||||
@@ -2610,7 +2610,7 @@
|
||||
the editor on open. -->
|
||||
<dialog class="modal notepad" id="notepad-modal" aria-labelledby="notepad-title">
|
||||
<h2 id="notepad-title">Notebook</h2>
|
||||
<p class="modal-blurb">A private space to keep track of notes, uploaded images related to your in-progress work on this project. Saved on this machine and <strong class="private-note">never shared to the AI Agent</strong>.</p>
|
||||
<p class="modal-blurb">A private space to keep track of notes and uploaded images related to your in-progress work on this project. Saved on this machine and <strong class="private-note">never shared to the AI Agent</strong>.</p>
|
||||
<div class="notepad-tabbar">
|
||||
<div class="notepad-tabs" id="notepad-tabs" role="tablist" aria-label="Notebook tabs"></div>
|
||||
<button type="button" class="btn small ghost notepad-tab-new" id="notepad-tab-new">+ New tab</button>
|
||||
|
||||
@@ -11,7 +11,7 @@ import {
|
||||
finish,
|
||||
} from "../selectors.js";
|
||||
import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton } from "../render.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, renderSwatches, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER } from "../meter.js";
|
||||
@@ -990,6 +990,7 @@ export function wireDashboard() {
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("delete-cancel").addEventListener("click", () => $("delete-modal").close());
|
||||
$("handoff-close").addEventListener("click", () => $("handoff-modal").close());
|
||||
lightDismiss($("handoff-modal"));
|
||||
$("delete-go").addEventListener("click", deleteStep);
|
||||
$("delete-name").addEventListener("input", () => {
|
||||
$("delete-go").disabled = !deleteTarget || $("delete-name").value.trim() !== deleteTarget.name;
|
||||
|
||||
@@ -161,8 +161,8 @@ export const SKILLS = Object.freeze([
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 1, started: "Revise plan started", ran: "Plan revised", resume: "overview",
|
||||
subagents: null,
|
||||
states: ["documented", "building"],
|
||||
greyed: { default: "Needs a spec that is already written up", built: "The spec is fully built" },
|
||||
states: ["documented", "building", "built"],
|
||||
greyed: { default: "Needs a spec that is already written up" },
|
||||
card: {
|
||||
group: "pipeline",
|
||||
chip: "Step 1b",
|
||||
|
||||
@@ -303,9 +303,10 @@
|
||||
.handoff-preview-next { margin: 0 0 16px; font-size: 14px; color: var(--ink); }
|
||||
.handoff-preview-actions { display: flex; flex-wrap: wrap; gap: 10px; }
|
||||
.handoff-preview-actions .btn.danger { margin-left: auto; }
|
||||
.modal.handoff-read { max-width: 720px; }
|
||||
.modal.handoff-read { width: min(960px, calc(100vw - 32px)); max-width: none; }
|
||||
.modal.handoff-read[open] { display: flex; flex-direction: column; max-height: calc(100vh - 48px); }
|
||||
.handoff-body { flex: 1; min-height: 0; overflow-y: auto; margin-top: 8px; }
|
||||
.handoff-body.md { max-width: none; }
|
||||
.modal.handoff-read .modal-actions { flex: none; }
|
||||
|
||||
/* A spec's Delete button sits beside its chip, not inside it: a button cannot
|
||||
|
||||
@@ -151,11 +151,14 @@ function signIn(req, res, ctx, url) {
|
||||
const given = url.pathname.slice(3).replace(/\/$/, "");
|
||||
if (!ctx.token || !timingSafeEq(given, ctx.token)) return send(res, 403, "Not found", "text/plain");
|
||||
ctx.touch();
|
||||
// Inside the app's frame the page is cross-site, and SameSite=Strict would
|
||||
// never be sent back, so embed mode loosens the cookie to None; Secure, which
|
||||
// loopback counts as a trustworthy origin for. Anywhere else it stays Strict.
|
||||
res.writeHead(
|
||||
302,
|
||||
baseHeaders({
|
||||
location: "/",
|
||||
"set-cookie": `${cookieName(ctx)}=${ctx.token}; HttpOnly; SameSite=Strict; Path=/`,
|
||||
"set-cookie": `${cookieName(ctx)}=${ctx.token}; HttpOnly; ${embedAncestor() === "'none'" ? "SameSite=Strict" : "SameSite=None; Secure"}; Path=/`,
|
||||
})
|
||||
);
|
||||
return res.end();
|
||||
@@ -163,6 +166,22 @@ function signIn(req, res, ctx, url) {
|
||||
|
||||
/* -------------------------------------------------------- the page itself */
|
||||
|
||||
// PLAN2CODE_EMBED_ORIGIN is an opt-in widening of frame-ancestors for a shell
|
||||
// that embeds the page. The whole value must be exactly one allowed origin:
|
||||
// a loopback http origin with a real port, or one of the three tauri origins,
|
||||
// which name the embedding app page itself (that page is not on 127.0.0.1).
|
||||
// Anything else (a list, a wildcard, a bare host, another scheme) is ignored
|
||||
// and the directive keeps 'none'.
|
||||
function embedAncestor() {
|
||||
const value = process.env.PLAN2CODE_EMBED_ORIGIN;
|
||||
if (!value) return "'none'";
|
||||
if (value === "http://tauri.localhost" || value === "https://tauri.localhost" || value === "tauri://localhost") return value;
|
||||
const m = /^http:\/\/(127\.0\.0\.1|localhost):(\d{1,5})$/.exec(value);
|
||||
if (!m) return "'none'";
|
||||
const port = Number(m[2]);
|
||||
return port >= 1 && port <= 65535 ? value : "'none'";
|
||||
}
|
||||
|
||||
function page(req, res, ctx) {
|
||||
let html;
|
||||
try {
|
||||
@@ -176,7 +195,7 @@ function page(req, res, ctx) {
|
||||
const csp =
|
||||
"default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; " +
|
||||
"font-src 'self'; connect-src 'self'; media-src 'self'; " +
|
||||
"base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
||||
"base-uri 'none'; form-action 'none'; frame-ancestors " + embedAncestor();
|
||||
return send(res, 200, html, TYPES[".html"], { "content-security-policy": csp });
|
||||
}
|
||||
|
||||
|
||||
@@ -344,9 +344,10 @@ export async function removeScratch(consoleDir, names) {
|
||||
// console, the launcher (bin/, launcher.json), the install record that
|
||||
// `plan2code update` reads (install.json), the models the person added and
|
||||
// the handoffs (old ones go one by one, by age, on open: handoffs.mjs) and
|
||||
// the notepads, removed only one at a time through Cleanup (notepads.mjs).
|
||||
// the notepads, removed only one at a time through Cleanup (notepads.mjs), and
|
||||
// the desktop app (app/, which install.js fills, and app.json, its settings).
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "install.json", "models.json", "handoffs", "notepads", "app", "app.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.11.0",
|
||||
"version": "3.0.0",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
|
||||
Reference in new issue
Block a user