Show on the desktop app's taskbar when Plan2Code needs you

AI Assisted
This commit is contained in:
jparkerweb committed 2026-10-26 06:36:45 -07:00
1 parent 765d2b3536
commit c602dfed57
25 files changed
+1038 -112

No files matched your search

+17 -9
View File
@@ -16,7 +16,7 @@ plan2code/
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
│ │ └── trail.md # Every-response map visual + pathed resume command
│ ├── shared-references/ # Reference files shared across skills
│ │ ├── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review)
│ │ ├── building-habits.md # Find the cause, test first, pin behavior (quick-task, implement, implement-review)
│ │ └── helper-strength.md # How strong a model and how much effort each helper gets (pathfinder, plan, revise-plan, quick-task, implement, implement-review, review)
│ ├── plan2code-review-references/ # Reference files for review skill
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
@@ -95,11 +95,19 @@ plan2code/
| `src/statusline-claude/` | Claude CLI status bar (see Status Line below) |
| `src/launcher/plan2code.js` | Global `plan2code` command that opens the dashboard skill in Claude Code, Devin or Codex (installed by `I` and Advanced → `E`; also via Advanced → `D`). When the desktop app is installed (`~/.plan2code/app/plan2code-app[.exe]`, or the file `PLAN2CODE_APP` names) and a display exists (Windows and macOS always; Linux needs `DISPLAY` or `WAYLAND_DISPLAY`), it opens the app after the agent and model questions with `--project <folder> --agent <id> [--model <id>]` and exits; `--classic` (never forwarded to the CLI) and a failed spawn keep the terminal flow. The app reads all three (`project::launch_choice`): the picker starts on `--agent`, and `--model` applies to that agent on every start and Restart (`AgentManager::set_model`); a model never applies to another agent |
| `plan2code-app/` | Tauri desktop app (Rust host, xterm panel, the console's dashboard in a frame; its own README). `RELEASE-CHECKLIST.md` lists the by-hand checks before each release. `src-tauri/src/versions.rs` compares the app's version (`tauri.conf.json`) with the installed skills' (`~/.plan2code/bin/version.json`) for the bar's **Update skills** line, which runs `node ~/.plan2code/bin/plan2code.js update` only when pressed |
| `plan2code-app/src-tauri/src/attention.rs` | The taskbar signal's rules, pure and knowing nothing about Tauri: `Signal` (`busy`, `ready`, `attention`, `plain`), `badge_for(signal, os, enabled)` (Windows: green dot on `ready`, red on `attention`; macOS: red `!` on `attention` only; Linux: count 1 on `attention`), `should_flash(prev, next, focused, enabled)` (once, only on a change into `ready` or `attention` while unfocused) and `dot_rgba()` (the dot's pixels, in the favicon's colors, which a test checks against `public/favicon.js`). `main.rs` applies the result through `set_attention`, `set_taskbar_signal` and `clear_attention_cmd`; the page asks with the `attention` and `taskbar` messages (`public/app-bridge.js`) and the switch is `taskbarSignal` in the app's own `~/.plan2code/app.json`. |
| `plan2code-app/src-tauri/src/agents.rs` | Custom agents in the app: `CustomAgent`, the `Agent` handle over built-ins and custom entries, `load_custom_agents`, reading the Agents file below; the console side is `src/web-console/agents.mjs` |
| Desktop app install (`install.js`) | `installDesktopApp()` downloads `plan2code-app-<version>-<windows\|macos\|linux>-<x64\|arm64>[.exe]` and `plan2code-app-<version>-SHA256SUMS.txt` from the GitHub release (`PLAN2CODE_RELEASE_BASE` replaces the URL; the tests serve a stand-in), checks the SHA-256 and places the file in `~/.plan2code/app/` (the old file is renamed aside first, since Windows cannot overwrite a running exe). `app` is an install piece (`INSTALL_PIECES`, after `launcher`), so `plan2code update` updates it with the rest. `install()` asks for it after the command (default yes; a no is kept as `skipped` in `install.json`); unattended it installs it unless it is already recorded or was declined. A failed app never fails the install. `.github/workflows/release-app.yml` builds one file per system (`tauri build --no-bundle`) and the checksum list on a published release, after `scripts/check-versions.mjs --tag` |
### Agents file
`~/.plan2code/agents.json` holds the person's custom agent CLIs (`{ "schema": 1, "agents": [...] }`). The web console is its only writer (User Preferences → Agents, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. A bad file or entry is skipped with a warning, never a crash. Until the feature is finalized, the rules are written out in `specs/agent-setup-and-taskbar-attention/PLAN-DRAFT-20261025.md` section 4.4.
`~/.plan2code/agents.json` holds the person's custom agent CLIs. The web console is its only writer (User Preferences → Agents, through `POST /agents`); the `plan2code` launcher and the desktop app only read it. Each reader carries its own copy of the rules (`src/web-console/agents.mjs` for the console, a copy in `src/launcher/plan2code.js`, `agents.rs` in the app), and `scripts/fixtures/agents-cases.json` is the contract all three readers' tests load: file normalization with its warnings, `buildArgs` command lines and `makeId` ids. Change a rule in the fixture first.
- **File:** `{ "schema": 1, "agents": [...] }`. Any other schema, text that is not JSON, or `agents` that is not a list gives no custom agents and one warning. A missing file is an empty list with no warning. More than 50 entries: the first 50 are used. Unknown keys, in the file and in an entry, are kept when the console saves.
- **Entry:** `id`, `name` and `command` are required; `args` (default `[]`), `prompt` (default `"/plan2code"`, blank allowed), `bypassArgs` (`[]`), `modelArgs` (`["--model", "{model}"]`) and `models` (`[]`, each `{ id, label? }`) are optional. The three argument fields are lists of text, one list item per argument.
- **Rules:** `id` matches `^[a-z0-9][a-z0-9-]{0,31}$`, is not `claude`, `devin` or `codex`, and is unique; `name` is at most 60 characters and unique ignoring case; `command` is not blank. `makeId(name, taken)` makes the id from the name in kebab case (`agent` when nothing is left), with `-2`, `-3` on a clash, at most 32 characters.
- **Bad entries:** a bad entry is skipped with a warning naming it (`agents[i]`, 0-based) and the rest still load, in all three readers. `POST /agents` instead refuses the save with `{ error, index, field }`, and answers `409` while the file holds something `GET /agents` could not read, unless the body says `replace: true`.
- **Command line:** `buildArgs` returns `args` with `{prompt}` filled (the prompt is appended when no argument holds it, and a blank prompt drops an argument that is exactly `{prompt}`), then `modelArgs` with `{model}` filled when a model is chosen, then `bypassArgs` when checks are off. Arguments travel as a list, never through a shell; the Windows `cmd` wrapper for a `.cmd` or `.bat` belongs to the launcher and the app.
## Workflow Prompts (in `src/`)
@@ -115,7 +123,7 @@ plan2code/
| `plan2code-2-document.md` | 2 | Create implementation specs |
| `plan2code-3-implement.md` | 3 | Execute implementation (phase by phase) |
| `plan2code-3-implement-review.md` | 3 | Execute one phase, run focused review and fixes, then request approval |
| `plan2code-review.md` | review | Post-implementation comprehensive review, analysed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
| `plan2code-review.md` | review | Post-implementation comprehensive review, analyzed by one fresh helper when the tool has one (verified in session; the report says who reviewed) |
| `plan2code-4-finalize.md` | 4 | Validate, summarize, feedback, archive (steps 1–7, +optional 6.5) |
| `plan2code-handoff.md` | handoff | Compact the conversation into a self-contained handoff document for a fresh session |
| `plan2code-xray.md` | xray | Explain how and why an area works (files, commits, PRs via `gh` when present), or rank the rough spots worth fixing into `ARCHITECTURE-BRIEF-<date>.md` for Pathfinder or Plan; never edits code |
@@ -250,7 +258,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
| `public/styles/poses.css` | The start-screen poses, one per skill. After the dashboard on purpose: its narrow-window rules override the dashboard's |
| `public/styles/responsive.css` | Print, then the narrow-window rules: last, so its overrides come after everything they override |
| `public/styles/shell.css` | The page shell: banner, top bar and meter, layout, sidebar, aside, footer, waiting and arrival |
| `public/styles/tokens.css` | Colours, type, sizes and the light and dark themes: the variables every other file reads |
| `public/styles/tokens.css` | Colors, type, sizes and the light and dark themes: the variables every other file reads |
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (18 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color; The git board sits right after Watching a build), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a git session → The git board, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
| `git-repo.mjs` | the one read-only reader of a git repository: the worktree status (`countPending()`, behind `pendingFiles()`), the branch table, the default branch, a merge or rebase in progress, the remotes and their web addresses, the last fetch and the pull-request link; `snapshot()` is what `open` and every `reread` store as `state.git`. Every git call carries `GIT_OPTIONAL_LOCKS=0`, so a background look never takes the index lock. Imported by `cmd-open.mjs`, `cmd-post-wait.mjs` and `sessions.mjs`; the git skill's `git.mjs` reaches it through `common.mjs` |
| `public/git-board.js` | PURE, one import (`pr-url.js`): the git board's rules from a `state.git` snapshot: branch order and the Remote only fold at `REMOTE_FOLD` 50, whether a new branch name is free, which buttons show and are enabled, whether the board still waits on the agent (`boardAwaiting()`: from a click until the agent's next post, not just until `wait` collects it), the plain sentence each click sends as `reply`, the "Last refreshed" line, which files start ticked in the commit dialog, and the pull-request link; the next step (ten rules, `nextStep()`), the tab that owns it, per-tab badges (`tabBadges()`), the busy mode and per-control gate (`busyMode()`, `controlAllowed()`), the tab to show (`pickTab()`), and the create-panel sources and clean-up groups. `app.js` only renders what it says |
@@ -289,17 +297,17 @@ Key design points:
- **Top-bar icons.** `#btn-looks` (gear) opens `#looks-modal`, titled User Preferences: Role, Theme, Card width, Highlight color, Sounds and Models. `#btn-feedback` (megaphone) is a plain link to `https://github.com/jparkerweb/plan2code/issues/new/choose`, backed by `.github/ISSUE_TEMPLATE/bug.yml` and `idea.yml` (`config.yml` sets `blank_issues_enabled: false`). `DEFAULT_ACCENT` in `palette.js` is `ocean`.
- **Version in Help.** `GET /version` reads `version.json` beside `server.mjs`, falling back to `../../version.json` for a run from `src/` (the `/version` route in `routes.mjs`). `renderHelpVersion()` in `screens/help-dialog.js` fills `#help-version`. `computeExpectedSkills()` in `install.js` injects the root `version.json` into every `references/web-console/`, so a version bump changes every skill.
- **Models in User Preferences.** `GET` / `POST /models` in `routes.mjs` read the shipped `~/.plan2code/bin/models.json` and read/write the user's `~/.plan2code/models.json` (`SHIPPED_MODELS_FILE` / `USER_MODELS_FILE` in `files.mjs`). `PLAN2CODE_MODELS_DIR` relocates both for tests. The launcher reads the same two files for its model menu.
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (cancelled). The agent loops. Nothing blocks for the whole time a person takes.
- **The wait is bounded.** `wait --seconds 240` exits `0` (answers), `10` (still waiting, `message: "Waiting on your answer in the web console"` to relay), `20` (server gone, resume it) or `30` (canceled). The agent loops. Nothing blocks for the whole time a person takes.
- **A turn is one command, and the CLI does the bookkeeping.** Agent speed is model round trips and typed tokens, not the console (`bench-web-console.mjs --roundtrip`: Send→agent ~70 ms, post→page ~180 ms), so the CLI absorbs every step with one right answer: `consume()` marks the agent `working` when it hands over a submit (`markWorking()`), and `wait` hands the turn back (`markWaiting()`) when it starts with an open question, a finish, or on the dashboard or git board; `post --wait <N>` posts and waits in one process; `settle: true | [ids]` (`settleItems()` in `patches.mjs`) records the latest send's cards as answered from their `submitted`; a new or reopened question with no stated status sets `waiting` and waiting drops `quietMinutes` (`settleAgent()`); a doc whose content changed with no `version` moves up one (`mergeDocs()`); a chat reply with no `id` is `r<re>`; doc blocks with `file` (and `select: "tasks"`, doc-level `refresh: true`) are read from the worktree by `resolveDocFiles()` before the merge, refusing paths outside it; and a hop (`__launch`, `__dashboard`, `__commit`, `__pickup`) comes with `resume` (the exact `open --resume` command) and `skillFile` (`hopFor()`), a pick-up also with `handoffFile`. The wait loop's health check runs beside the 50 ms polling instead of blocking it, and is aborted on exit. `help <topic>` prints any contract file; `help topics` lists them. `token` defaults to the option key in the page's `tokenFor()`, and nothing reads `fallbackText`, so the contract no longer asks for either.
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `screens/starting.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `styles/poses.css`; each `SKILLS` entry's `pose` in `skills.js` is the list (`START_POSES`/`startPose()` in `answers.js` read it), and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never greyed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the seven opted-in skills (`defaultSetting()`); a saved Off stays off.
- **The dashboard scan knows whether the folder is a git repository.** `scanProject()` returns `{ hasAgents, isGit, pending, specs }`; `isGit` comes from `insideGitRepo()`, the same filesystem walk `findRoots()` does (no `git` process, linked worktrees and submodules count, a set `GIT_DIR` / `GIT_WORK_TREE` / `GIT_COMMON_DIR` counts as a repo). The Git card is never grayed, since a clean tree still has branches to switch, pull and push. When `isGit` is `false` the card shows `GIT_INIT_NOTE` ("Not a git repository yet: it offers to start one") as its detail line; a scan with no `isGit` counts as a repo. In a repo, `pending` is `pendingFiles()` in `sessions.mjs`, which calls `countPending()` in `git-repo.mjs`: one bounded `git status --porcelain -z` under `GIT_OPTIONAL_LOCKS=0` (`null` when git cannot say) counting modified, staged, deleted and untracked paths. Above `0` the detail line is `pendingNote(n)` ("3 files to commit"); `0` and `null` show no note. A finish with `commit: true` puts a **Commit it now** button on the finished screen (`commitOffer()`, `renderCommitOffer()`); its `__commit` press makes the agent resume as `git` in the same session and run the commit flow above the board. `open --resume` treats any switch into `git` (this press, or Changelog's "Commit this now?") as a hop, like a dashboard launch: `switchWorkflow()` blanks the page, finish and the last run's `state.git` included, and `draft.json` goes. Without that, the old finish outlived the switch, and the page sat on the old ending above the new questions and the board. A confirm item may carry `files: [{ path, state }]`, drawn as a collapsed table by `filesTable()`. Subagents is **on** by default for the seven opted-in skills (`defaultSetting()`); a saved Off stays off.
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
- **No git process.** `repoRoots()` in `sessions.mjs` finds the common dir and worktree top by walking to `.git` (following `gitdir:` and `commondir` files) — each `git rev-parse` cost 150ms+ on Windows. It asks git only when `GIT_DIR`/`GIT_WORK_TREE`/`GIT_COMMON_DIR` relocate the repo, and uses the native realpath so an 8.3 short name keys the same project git would.
- **The socket handover.** `open` spawns the server first, then binds the loopback port itself (the first `listen()` blocks ~50ms on Windows, overlapped with the server's boot), launches the browser on that URL immediately (Chrome via `start` takes ~900ms to its first request, the longest step of all), and hands the listening socket to the server over IPC (`bindLoopback()`/`handOff()` in `sessions.mjs`, `--handoff` in `server.mjs`). Requests queue in the socket until the server takes it; one `open` already accepted is passed across as a socket and acknowledged (`conn-held`) before the channel is closed. No channel, or no socket within 3s, and the server binds its own port; `open` then opens the real URL.
@@ -333,7 +341,7 @@ Key design points:
- **Continue here, Update CHANGELOG first and Ask prompt blocks.** Three small additions on the same pattern. **Continue here** is page-only: `continueOffer(fin)` (`public/answers.js`) reads `finish.command`, and when it starts with a Plan2Code skill (and the finish is not a pause) `screens/ending.js` draws a button beside the Next step block, hidden when the session meter is red; the press is the dashboard's own `{ "i": "__launch", ... }` through `sendAfterBuild("launch", offer)`, so the agent writes nothing new (`startsClean()` cleans the page for the hop, except out of Git and into Review; a same-skill next step keeps the workflow, so the agent posts `"finish": null`). **Update CHANGELOG first** is `finish.changelog: true`, accepted by `validate()` only on `quick-task` and `finalize` (a paused finish is exempt from that check and the page ignores the flag), and it belongs with `commit: true`; the press is `__changelog`, a `HOP_ACTIONS` entry in `cmd-post-wait.mjs` that resumes as `changelog`, whose "Commit this now?" yes carries on to Git. **Ask prompt blocks** are contract only (`console-chat.md` → Prompts to carry away): the page already draws a Copy button on every fenced block.
- **`__dashboard` also arrives mid-workflow.** A left-pointing triangle (`#btn-home`, filled with `--accent`) sits left of Stop session on every non-dashboard page. Its state comes from the pure `homeButtonState()` in `answers.js`: hidden on the dashboard, on a finish and during a stop, and otherwise gated by the same `turnGate()` Stop now uses (the person's turn, unless the agent has gone adrift). The confirm (`#home-modal`) reuses `stopWarning()`, and the submit carries the staged answers plus `__dashboard`, with `HOME_REPLY`. With no finish on the page, the agent treats it as a stop that lands on the menu: it saves its place as for `__stop`, then resumes as the dashboard with `"finish": null` + `menu`, with no finish and no stop in between (console-stop.md → "Back to the dashboard, mid-workflow"; building.md for builds). `local.homeward` drives Planny's "Saving your place and opening the dashboard…" line until the through-the-dashboard reset clears it.
- **Handoffs live outside every repo, in `~/.plan2code/handoffs/`, and the console owns them** (`handoffs.mjs`; the console ships in every skill, so the Stop flow, the Handoff skill and the dashboard all reach it through `console.mjs`). `handoff new --workflow <w> --skill <s> [--spec specs/<x>] [--title <t>] [--from-stop]` claims one for this checkout and prints `{ ok, id, path, meta }` (exit 2 bad usage, 3 a bad value). Off the dashboard the Stop modal offers **Stop with a handoff** (`#stop-handoff`, suggested) above **Just stop and save** (`#stop-go`); the first sends `__stop` with `handoff: true` and `STOP_HANDOFF_REPLY`, and `wait` adds `handoffSkill` (the built Handoff skill's `SKILL.md`, `handoffFor()`); console-stop.md gives the order (answers, save, `handoff new --from-stop`, write, paused finish naming the file, `stop`). On a dashboard, `cmdOpen()` adds `scan.handoffs` (`listHandoffs(worktree)`) and `scan.handoffsDir` after `scanProject()`, which stays handoff-free because `specs.mjs list` shares it. The picker draws them as dashed `.spec-chip.is-handoff` chips after the specs (`specSel = "handoff:<id>"`); a picked one replaces the skill cards with `renderHandoffPreview()`: **Pick it up here**, **Read it all** (`GET /handoff?id=`, served only for an id in the dashboard's own `state.scan.handoffs`), **Copy for a new conversation** (`handoffCopyText()`) and **Delete** (`openHandoffDelete()`, one step). Pick it up sends `{ "i": "__pickup", "type": "pickup", "handoff": <id> }`; `HOP_ACTIONS.pickup` (`pickupHop()`) reads the stored `.json` only, never the page, and falls back to Quick Task with `fallback: true` when the record, its skill or its spec is gone, or the Handoff skill wrote it (resuming that skill would only write another handoff); `markPickedUp()` stamps `usedAt` as the hop is printed, so the next scan drops the chip. Delete sends `__delete` with `handoff` in place of `spec`, and the agent runs `delete-handoff --handoff <id>` (`removeHandoff()`, exit 3 on a refusal, nothing touched). `open` sweeps handoffs untouched for 30 days (`staleHandoffs()`, the `.json`'s mtime, else the `.md`'s), picked up or not, and reports them in `swept.handoffs`; Cleanup never lists the folder (`KEPT_PLAN2CODE_ENTRIES`).
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labelled "Notebook for <folder>"Line truncated
- **Notebook: the person's, one per folder, in `~/.plan2code/notepads/`, in named tabs, and never the agent's.** `notepads.mjs` is the store's one owner (`PLAN2CODE_NOTEPADS_DIR` moves it for tests). The folder is the session's worktree, else its project (`notepadRoot()` in `routes.mjs`), keyed `<folder-name>-<12 hex>` by `notepadKey()` (the hash over `foldKey()`, so case-only path differences match on Windows and macOS, and two worktrees get two notepads). **Layout:** `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order: [id], last, tabs: { id: { name, created } } }`, the index and the only place order and the last tab live) and, per tab, `tabs/<id>/note.md` with `tabs/<id>/images/<uuid>.jpg` and `<uuid>.thumb.jpg`; a tab id is 12 hex. Every write takes the folder's `notepad.lock`; a read never creates a file, so only the person's edits age a notepad. A delete removes the tab from the index first, then its folder, and the next write sweeps away a tab folder the index no longer names (a delete that crashed half way). **Migration:** the first shape (`v: 1`, one `note.md` and `images/` at the top) reads as one virtual tab, Notes, with the fixed id `LEGACY_TAB_ID`, and a read writes nothing; the first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, so a crash in the middle is finished by the next write and never loses a file. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders. **Routes:** eleven, placed after `/upload` in `ROUTES` (the shape test pins the order): `GET /notepad[?tab=<id>]` (`{ tabs, last, tab: { id, text, savedAt, images } }`, with the tab's `text`, `savedAt` and `images` repeated at the top), `POST /notepad/text?tab=` (`{ text }`, 1 MB, 413 `too-long`), `POST /notepad/image?tab=` and `POST /notepad/thumb?id=<uuid>&tab=` (raw `image/jpeg` the page re-encoded with `reencode()`, 4 MB, 200 pictures per tab: 415 `not-jpeg`, 413 `too-large`, 409 `too-many`), `POST /notepad/image/delete?tab=` (`{ id }`), `POST /notepad/tab` (`{ name }`), `/notepad/tab/rename` (`{ id, name }`), `/notepad/tab/delete` (`{ id }`), `/notepad/tab/order` (`{ order }`, every id once) and `/notepad/tab/last` (`{ id }`), and `GET /notepad/images/<tab>/<uuid>[.thumb].jpg` (matched on the raw request line like `/uploads/`, served through `imagePath()`'s realpath containment, `no-store`). A text or picture request with no `?tab` means the last tab used (and makes Notes when there is none), so an unchanged client keeps working. The ten POSTs are origin-checked, and every refusal is a `NotepadError` turned into `{ error }` (`bad-name`, `duplicate-name`, `too-many-tabs`, `no-such-tab` beside the picture and text codes). None of them writes to the session folder or `events.ndjson`, and `console.mjs` never imports `notepads.mjs`, so nothing in a notepad reaches `state.json` or anything `wait` prints. **The editor, and the CSP.** CodeMirror 6 replaced OverType 2.6.1 after a spike (typing at 200 KB measured about 24 ms a key against about 99 ms, and real heading sizes): `public/vendor/codemirror.esm.js` is one minified file (about 500 KB) made by the dev-only `scripts/vendor-codemirror.mjs` from `scripts/vendor-codemirror-lock.json`, never installed in the repo, and loaded by a dynamic import only when the Notebook first opens. CodeMirror writes its rules as a `<style>` element, which `style-src 'self'` refuses, so the editor lives in the open shadow root of `.notepad-cm-host` where it adopts them as a constructed stylesheet, and its own look is `public/notepad-editor.css`, a `<link>` inside the root. Custom properties inherit across the boundary, so both themes work; page tests reach the editor with Playwright's CSS locators (they pierce open shadow roots) and read its text from `EditorView.findFromDOM()`, since lines the cursor is not on draw without their Markdown marks. CodeMirror's own rules win a tie in specificity (they are adopted after the linked sheet), so `notepad-editor.css` writes `div.cm-editor .cm-scroller` for the few it overrides. `scripts/test-web-console-page-notepad.mjs` fails on any `securitypolicyviolation` with the notepad open. **Upgrading CodeMirror:** change a version in `scripts/vendor-codemirror.mjs`, run `node scripts/vendor-codemirror.mjs --update-lock` (npm and network; it installs in a temp folder), update the sha256 in the files-table row, then run the two notepad test files. **Tabs on the page:** `screens/notepad.js` binds every save and picture to the tab it was made in (a switch waits for the save, and stays put when it cannot), `public/notepad-tabs.js` draws the bar, and `public/notepad.js` holds the name, order and delete rules as pure code. **Cleanup.** No sweep at `open` touches a notepad, and `notepads` is in `KEPT_PLAN2CODE_ENTRIES`, so the folder is never a stray. `cleanupFindings()` lists a notepad as one `notepad:<key>` item (with `folder` from `meta.json`, labeled "Notebook for <folder>" Line truncated
- **A Bug fixed spec deletes in one step.** Its chip shows a visible **Delete** (`.spec-chip-del-label`) instead of the hover ✕, `openDeleteConfirm()` gives it a fixed-bug warning and a **Delete it** button, and `deleteStep()` sends `__delete` on the first press, with no name to type. `chipDetail()` drops the scan's repeated "bug fixed" detail under the label.
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `inbox.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
- **`validate()` in `patches.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
@@ -388,7 +396,7 @@ On a terminal it first prints a Planny banner (`renderBanner()`). With more than
- **Marker-based ownership** — every shim contains `plan2code-launcher`; `uninstallLauncher()` removes only files carrying it, leaving any other `plan2code` bin alone.
- **Resolving the CLI** — the launcher walks `PATH` (+ `PATHEXT` on Windows) itself. An `.exe` is spawned directly; a `.cmd`/`.bat` wrapper goes through `cmd.exe /d /s /c` with quoted args, since Node refuses to spawn batch files without a shell. The installer warns only when neither `claude` nor `devin` is on `PATH`.
- **No bin-name overlap** — the installer's own bin in `package.json` is `plan2code-install` (→ `install.js`), so `plan2code` belongs to the launcher alone. npx runs a package's only bin whatever it's named, so the README's `npx … plan2code.git` command is unaffected; keep it the only bin, or npx will need `-c plan2code-install`.
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person cancelled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
- **`--pick-folder` is shortcut-only** — the launcher strips it before building the CLI's args. The shortcut runs the CLI menu, then the folder picker, then the model menu. With it, a native folder picker chooses the cwd instead: on Windows, the Explorer-style `IFileOpenDialog` (`FOS_PICKFOLDERS`) via `powershell -STA -EncodedCommand`, its C# interop (`WINDOWS_PICKER_SOURCE`) passed in an env var and compiled with `Add-Type` (~0.5s), with a TopMost owner form so it doesn't open behind the console — Windows PowerShell's `FolderBrowserDialog` is the old tree-only dialog, and is kept only as the fallback when `Add-Type` is blocked (Constrained Language Mode, AppLocker); `osascript choose folder` on macOS, and `zenity` then `kdialog` on Linux (only when `DISPLAY`/`WAYLAND_DISPLAY` is set). If there's no picker, or the picker fails, it falls back to a typed `Project folder [last]:` prompt. A picker that exits 0/1 with nothing printed means the person canceled, so the launcher exits 0. The picker starts on the last pick, stored in `~/.plan2code/launcher.json`. From the shortcut, a non-zero exit other than Ctrl+C (130 / `0xC000013A`) waits for Enter so the error doesn't vanish with the window. Typed in a terminal, `plan2code` behaves exactly as before.
**Desktop shortcut** — after the shims are written, `installLauncher()` (now async) calls `offerDesktopShortcut()`. It asks `Also add a Plan2Code shortcut to your desktop? (y/N)`, skips the question when stdin isn't a TTY, and refreshes an existing marked shortcut without asking. `installDesktopShortcut()` writes it to the real desktop (`[Environment]::GetFolderPath('Desktop')` on Windows, which covers OneDrive redirection; `xdg-user-dir DESKTOP` on Linux; `~/Desktop` otherwise):
+17 -3
View File
@@ -211,7 +211,7 @@ explains how and why an area works, or ranks its rough spots into
available: it finds a bug's cause and writes it up as
`specs/<bug-name>/DIAGNOSIS-<date>.md` without fixing it. Pick such a spec in
the picker and it reads *Bug diagnosed*: Quick Task (suggested) and Plan light
up, while Document, Implement, Implement + Review and Finalize stay greyed. Once
up, while Document, Implement, Implement + Review and Finalize stay grayed. Once
Quick Task has fixed it, the folder reads *Bug fixed*: Quick Task offers to
archive it to `specs--completed/`, and until then the picker never opens on it
and hides it while *Hide unavailable workflows* is on. Its chip has a visible
@@ -701,6 +701,19 @@ keyboard-only navigation work.
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude, Devin and Codex tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve.
## Agents and the desktop app in User Preferences
**User Preferences → Agents** adds agent CLIs Plan2Code did not find on its own. Each one has a name, the command to run (a bare name looked up on `PATH`, or a full path), and optional fields:
- **Arguments**: one per row. `{prompt}` is replaced by the start prompt (for example `--message={prompt}`); with no `{prompt}` anywhere, the prompt is added last.
- **Start prompt**: `/plan2code` by default. Leave it blank to start the agent with nothing typed.
- **Bypass arguments**: added when permission checks are off.
- **Model arguments**: added when a model is chosen, with `{model}` replaced (`--model` and `{model}` by default), and a list of **models** to offer, each an id and an optional label.
**Test** on a card shows where the command is found, or "Not found on PATH", and never runs it. Saving a duplicate name, a blank command or a built-in id marks the card and field and writes nothing. The list is plain text in `~/.plan2code/agents.json`, shared by the `plan2code` command and the desktop app; this page is the only thing that writes it, and a broken file or entry is skipped with a warning shown under the list, never a crash. If the file holds something the page could not read, saving asks first (**Save anyway**). `/plan2code` works only in agents that load the installed Plan2Code skills.
**Desktop app** appears only when the page is open inside the desktop app. Its switch, **Show on the taskbar when Plan2Code needs me** (on by default), controls the app's taskbar signal: on Windows a green dot on your move and a red one when it needs attention, plus one short burst of flashes when the window is not focused (the button stays lit until you look); on macOS a red `!` dock badge when it needs attention and one bounce; on Linux a badge where your desktop supports it. Turning it off clears the dot and stops flashes. The choice is kept by the app in its own `~/.plan2code/app.json`.
---
## Troubleshooting
@@ -773,6 +786,7 @@ exception being the note attachments the agent keeps for a spec, above):
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
| `~/.plan2code/agents.json` | your custom agent CLIs (User Preferences → Agents), read by the `plan2code` command and the desktop app | always |
| your system temp directory | the port, process id and session token | until reboot |
Each of the workspace and meter files has exactly one writer: the server owns
@@ -948,14 +962,14 @@ session without searching the skill install dirs.
The vendored file is `src/web-console/public/vendor/marked.esm.js`,
sha256 `7a7d9a521ac9384e0c3a075120a7c486cbd0c3c32cc5601bbb79a23e97403690`.
Only `marked.lexer()` is used; the rendering is ours, in `public/render.js`, and
builds DOM nodes rather than HTML so nothing needs sanitising.
builds DOM nodes rather than HTML so nothing needs sanitizing.
### Refreshing the screenshots
The docs and the landing page show the console through the images in
`docs/screenshots/`, one light and one dark WebP per screen. Rerun the capture
after any change a person would see on the page: a new layout, a renamed
button, a different colour.
button, a different color.
```bash
node scripts/capture-screenshots.mjs # every screen
+18 -1
View File
@@ -88,6 +88,23 @@ Claude Code, Devin or Codex CLI on your `PATH`. It starts the agent with permiss
which opens a folder picker first. Uninstalling (`U`) removes both.
</details>
<details>
<summary>Using another agent CLI, or none yet</summary>
Plan2Code runs inside an AI coding agent CLI. If `plan2code` finds none of Claude Code, Devin or Codex on
your `PATH`, it says so and prints each one's install command and official page, then exits; the desktop app
shows the same help in a panel with an **Install page** link per agent and a **Check again** button, so you
can install one and carry on without restarting.
To use a different agent CLI, open the web console's **User Preferences → Agents** and add it: a name, the
command, and (optionally) its arguments, the start prompt, arguments for skipping permission prompts, and
how it takes a model. Custom agents are saved in `~/.plan2code/agents.json` and used by both the
`plan2code` command (listed after the built-ins; `--cli <id>` picks one) and the desktop app's picker. The
`/plan2code` start prompt only does something in an agent that loads the installed Plan2Code skills; for
any other, leave the start prompt blank and start a skill yourself. Details in
[.readme/web-console.md](.readme/web-console.md#agents-and-the-desktop-app-in-user-preferences).
</details>
<details>
<summary>About the desktop app</summary>
@@ -395,7 +412,7 @@ console or the terminal; add `--web` to skip the question and go straight to the
## Troubleshooting
**The skills aren't recognised.** Re-run the installer and restart your AI tool. Confirm the global
**The skills aren't recognized.** Re-run the installer and restart your AI tool. Confirm the global
install with `npx skills list -g`. For a project install, check the generated directories aren't
gitignored.
+21 -4
View File
@@ -65,15 +65,32 @@ Three things keep today's terminal flow:
The first time the app opens on a folder, a checklist confirms Node, the agent CLI, the project
folder and the skills version before anything else shows; a later launch skips straight past it.
A **launch card** then asks which agent (Claude, Devin or Codex), model and effort (Claude and Codex
only) to start on. Permission checks off is its own tick, on by default (see below; New Session
keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of
just being greyed out. The card is skipped when the launcher already passed an agent to start.
A **launch card** then asks which agent, model and effort (Claude and Codex only) to start on. The
picker lists Claude Code, Devin and Codex, then any custom agents you added in the web console's
**User Preferences → Agents** (saved in `~/.plan2code/agents.json`, shared with the `plan2code`
command), and starts on one that is actually installed, so a machine with only Devin or Codex is ready
to go. Permission checks off is its own tick, on by default (see below; New Session keeps whatever
you picked, and reuses the same agent); a CLI the app cannot find is named, with how to install it,
instead of just being grayed out. The card is skipped when the launcher already passed an agent to
start.
With no agent installed at all, the checklist and the launch card explain what an agent CLI is and
show each built-in's install command with an **Install page** link. Install one (or add a custom
agent) and press **Check again**: the app finds it without a restart.
The window's own title (and so its taskbar entry) reads **Plan2Code - &lt;folder name&gt;** once a
project is open, so two or more windows on different projects read apart without opening each one
to check.
The taskbar entry also shows when Plan2Code needs you, the same states as the console's tab icon in
a browser. On Windows a green dot means it is your move and a red dot means it needs attention, with
one short burst of flashes when the window is not focused; on macOS the dock shows a red `!` badge on
needs attention and bounces once; on Linux a count badge appears where the desktop supports it. There
is no dot while the agent is busy or the step is finished, and it clears when the agent ends or the
page reloads. Turn it off with **Show on the taskbar when Plan2Code needs me** under **User
Preferences → Desktop app** (shown only inside the app). The per-system details are in
[plan2code-app/README.md](../plan2code-app/README.md#agents-and-the-taskbar).
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
**Change project**; **New Session**, whenever an agent exists; the agent's own menu, with a dot for its
state, an amber **checks off** badge while permission checks are off, and **Change agent** once it has
+16
View File
@@ -4,6 +4,22 @@ The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal pane
The app is optional. The Node web console and the skills never depend on it, so running `/plan2code` inside an agent with no app works exactly as before.
## Agents and the taskbar
**Agent picker.** The launch card lists Claude Code, Devin and Codex, then any custom agents from `~/.plan2code/agents.json` (added in the console's User Preferences → Agents, the same list the `plan2code` command uses). The app starts on an agent that is installed (your last pick when it still is), never assumes Claude Code, and a custom agent has no effort row; New Session reuses whichever agent you started. Custom agents offer their own models, and `/plan2code` only does something in an agent that loads the installed Plan2Code skills.
**No agent installed.** The first-run checklist and the launch card show what an agent CLI is, each built-in's install command and an **Install page** link, and a note that other agents are added under Agents. Install one, press **Check again** (the app looks at `PATH` and `agents.json` again), and Start works without restarting the app.
**Taskbar signal.** The console page tells the app when it is busy, your move, or needs attention (the same states as its tab icon), and the app shows it:
| System | Your move | Needs attention |
|---|---|---|
| Windows | green dot on the taskbar button, and one short burst of flashes when the window is not focused (the button then stays lit until focused) | red dot, and the same burst when not focused |
| macOS | no badge (the system badge cannot be green), one bounce when not focused | red `!` dock badge, and one bounce when not focused |
| Linux | the urgency hint when not focused | a count badge of 1 where the desktop supports it, and the urgency hint |
There is no dot while busy or finished. The dot clears when the agent ends, the page reloads or the page stops answering, and a lit taskbar button goes back to normal when the window gets focus. **User Preferences → Desktop app** (shown only inside the app) has the switch **Show on the taskbar when Plan2Code needs me**, on by default; off clears the dot and stops flashes. It is saved as `taskbarSignal` in the app's own `~/.plan2code/app.json`.
## Layout
| Path | What it is |
+15 -1
View File
@@ -73,7 +73,7 @@ file directly after checking it against the release's checksum list.
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
console frame and the terminal included) or Escape, and are not cut off by the bar
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
picker opens; cancelling the picker leaves the running agent and its project untouched
picker opens; canceling the picker leaves the running agent and its project untouched
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
on the launch card (or the checklist, if its own first run has not passed yet)
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
@@ -109,6 +109,20 @@ Do each of Claude Code, Devin and Codex for a few minutes:
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
## Agents and the taskbar (each system)
- [ ] A custom agent added in the console's User Preferences → Agents (the fake agent in `fake-agent/` works) shows in the launch card's picker after the built-ins, starts, and **New Session** starts the same agent again; the bypass box adds its bypass arguments
- [ ] With no agent CLI on `PATH` and no custom agent, the first-run checklist and the launch card show the explainer with each install command and an **Install page** link, and Start is off
- [ ] Each **Install page** link opens the right page in the default browser (Claude Code, Devin, Codex)
- [ ] Install an agent (or add a custom one), press **Check again**: it appears and Start turns on without restarting the app
- [ ] With only one agent installed and nothing remembered, the launch card starts on that agent, not Claude Code
- [ ] Windows: the taskbar button shows a green dot when it is your move and a red dot when Plan2Code needs attention, and no dot while the agent is busy or after it ends
- [ ] Windows: with the window unfocused, the button gives one short burst of flashes when it becomes your move or needs attention (not again on a repeat) and stays lit until the window gets focus
- [ ] macOS: the dock shows a red `!` badge when Plan2Code needs attention (no badge on your move), and bounces once when it becomes your move or needs attention while the app is in the background
- [ ] Linux: where the desktop shows badges, a count of 1 appears on needs attention, and the window is marked as wanting attention while unfocused
- [ ] Reloading the window, or ending the agent, clears the dot
- [ ] User Preferences → Desktop app (shown only inside the app, not in a browser tab) has **Show on the taskbar when Plan2Code needs me**, on by default; switching it off clears the dot at once and stops flashes, and the choice is still off after quitting and reopening the app
## Standalone path
- [ ] `/plan2code` typed inside an agent with the app closed opens the dashboard exactly as before
+73 -19
View File
@@ -139,7 +139,7 @@ pub fn find_on_path(program: &str, path_var: &str) -> Option<PathBuf> {
pub fn installed_at(kind: AgentKind) -> Option<PathBuf> {
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
let program = bin.unwrap_or_else(|| kind.program_name().to_string());
find_on_path(&program, crate::node_check::resolved_path())
find_on_path(&program, &crate::node_check::resolved_path())
}
/// Whether `kind`'s CLI can be run at all.
@@ -244,7 +244,7 @@ fn launch_spec_with(
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
// directories (Task 9.9): the agent CLI itself, and anything it shells
// out to, needs a PATH that finds them anyway.
let env = vec![("PATH".to_string(), crate::node_check::resolved_path().to_string())];
let env = vec![("PATH".to_string(), crate::node_check::resolved_path())];
LaunchSpec { program: program.to_string(), args, env, cwd }
}
@@ -546,7 +546,7 @@ impl Agent {
Agent::Custom(agent) => {
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty());
let command = bin.as_deref().unwrap_or(&agent.command);
resolve_command(command, crate::node_check::resolved_path())
resolve_command(command, &crate::node_check::resolved_path())
}
}
}
@@ -566,9 +566,10 @@ pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option<Agent> {
agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom)
}
/// Every custom agent in `~/.plan2code/agents.json`, read afresh.
pub fn custom_agents() -> Vec<CustomAgent> {
agents_file().map(|file| load_custom_agents(&file).0).unwrap_or_default()
/// Every custom agent in `~/.plan2code/agents.json`, read afresh, with the
/// warnings about anything in the file that was skipped.
pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
agents_file().map(|file| load_custom_agents(&file)).unwrap_or_default()
}
fn clean_command(command: &str) -> &str {
@@ -644,7 +645,7 @@ pub fn agent_launch_spec(
model,
mode,
prompt,
crate::node_check::resolved_path(),
&crate::node_check::resolved_path(),
cfg!(windows),
)
}
@@ -668,6 +669,7 @@ fn custom_launch_spec(
let mut path = base_path.to_string();
let mut program =
resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned());
let mut extra_env = Vec::new();
if windows {
let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) {
@@ -680,13 +682,36 @@ fn custom_launch_spec(
path = format!("{};{}", dir.to_string_lossy(), base_path);
}
}
let mut wrapped = vec!["/c".to_string(), file_name];
wrapped.append(&mut args);
args = wrapped;
// The pseudo-terminal quotes only arguments with a space or a quote,
// so `cmd` would read `&`, `|` or `%` in the rest itself. The line is
// quoted as the launcher's `quoteForCmd` does and handed over in a
// variable: `cmd` expands it once and then parses it, so its quotes
// hold and a `%` inside it is not expanded again.
let line: Vec<String> = std::iter::once(file_name).chain(args).map(|arg| quote_for_cmd(&arg)).collect();
extra_env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
// `cmd` looks in the current folder (the project) before PATH: a
// same-named file there must not run in the agent's place.
extra_env.push(("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
args = vec!["/d".to_string(), "/c".to_string(), format!("%{CMD_LINE_ENV}%")];
program = "cmd".to_string();
}
}
LaunchSpec { program, args, env: vec![("PATH".to_string(), path)], cwd: folder.to_path_buf() }
let mut env = vec![("PATH".to_string(), path)];
env.append(&mut extra_env);
LaunchSpec { program, args, env, cwd: folder.to_path_buf() }
}
/// The variable a custom `.cmd` or `.bat` agent's command line reaches `cmd` in.
const CMD_LINE_ENV: &str = "PLAN2CODE_AGENT_LINE";
/// One argument of a `cmd` line, quoted when `cmd` would otherwise read it: the
/// launcher's `quoteForCmd`.
fn quote_for_cmd(arg: &str) -> String {
let special = |c: char| c.is_whitespace() || "\"&|<>^%!()".contains(c);
if !arg.is_empty() && !arg.chars().any(special) {
return arg.to_string();
}
format!("\"{}\"", arg.replace('"', "\"\""))
}
/// The page a built-in agent installs from; any other id is an error.
@@ -1013,26 +1038,55 @@ mod tests {
let found = Path::new("C:\\with space").join("goose.cmd");
let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!(spec.program, "cmd");
assert_eq!(spec.args, ["/c", "goose.cmd", "/p"]);
assert_eq!(spec.args, ["/d", "/c", "%PLAN2CODE_AGENT_LINE%"]);
assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy()));
assert_eq!(spec.env[1], ("PLAN2CODE_AGENT_LINE".to_string(), "goose.cmd /p".to_string()));
assert_eq!(spec.env[2], ("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
// A bare name keeps the plain PATH.
let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE"));
}
#[test]
fn a_cmd_line_quotes_what_cmd_would_read_as_the_launcher_does() {
assert_eq!(quote_for_cmd("--yes"), "--yes");
assert_eq!(quote_for_cmd(""), "\"\"");
assert_eq!(quote_for_cmd("a|b"), "\"a|b\"");
assert_eq!(quote_for_cmd("%X%"), "\"%X%\"");
assert_eq!(quote_for_cmd("say \"hi\""), "\"say \"\"hi\"\"\"");
let mut agent = goose();
agent.args = vec!["--filter=a|b".to_string(), "{prompt}".to_string()];
let found = Path::new("C:\\tools").join("goose.cmd");
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p & x", "BASE", true);
assert_eq!(spec.env[1].1, "goose.cmd \"--filter=a|b\" \"/p & x\"");
}
#[cfg(windows)]
#[test]
fn a_full_path_cmd_in_a_spaced_folder_resolves_and_wraps() {
let dir = temp_dir("spaced").join("with space");
fn a_full_path_cmd_in_a_spaced_folder_runs_with_its_arguments_intact_and_not_a_project_copy() {
let root = temp_dir("spaced");
let dir = root.join("with space");
let project = root.join("project");
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("goose.cmd"), "@echo off").unwrap();
std::fs::create_dir_all(&project).unwrap();
std::fs::write(dir.join("goose.cmd"), "@echo off\r\necho REAL [%1] [%2]\r\n").unwrap();
// A same-named file in the project folder must not run instead.
std::fs::write(project.join("goose.cmd"), "@echo off\r\necho DECOY\r\n").unwrap();
let mut agent = goose();
agent.command = dir.join("goose.cmd").to_string_lossy().into_owned();
agent.args = vec!["a|b".to_string(), "%PATH%".to_string()];
let found = Agent::Custom(agent.clone()).installed_at().expect("resolves");
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
assert_eq!((spec.program.as_str(), spec.args[1].as_str()), ("cmd", "goose.cmd"));
assert!(spec.env[0].1.starts_with(&dir.to_string_lossy().to_string()));
let _ = std::fs::remove_dir_all(dir.parent().unwrap());
let spec = custom_launch_spec(&agent, Some(&found), &project, None, PermissionMode::Checked, "", &std::env::var("PATH").unwrap_or_default(), true);
let mut command = std::process::Command::new(&spec.program);
// Some shells already set the switch the spec sets; start without it.
command.args(&spec.args).current_dir(&spec.cwd).env_remove("NoDefaultCurrentDirectoryInExePath");
for (key, value) in &spec.env {
command.env(key, value);
}
let out = command.output().expect("cmd runs");
let text = String::from_utf8_lossy(&out.stdout);
assert_eq!(text.trim(), "REAL [\"a|b\"] [\"%PATH%\"]", "{text}");
let _ = std::fs::remove_dir_all(&root);
}
#[test]
+234
View File
@@ -0,0 +1,234 @@
//! The taskbar entry's attention signal. It decides which of four states the
//! desktop app is in (busy, ready, attention, plain), which badge the platform
//! shows for that state, whether a change into a state that wants the person
//! should flash the window, and the pixels of the colored dot. The states and
//! the dot colors mirror the web console's favicon. Knows nothing about Tauri.
//! The caller turns these decisions into calls on the window.
/// What Plan2Code is doing, as the web console's favicon shows it.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Signal {
Busy,
Ready,
Attention,
Plain,
}
/// The two dot colors the taskbar badge can show.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum DotColor {
Green,
Red,
}
/// The badge a platform shows on the taskbar entry.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Badge {
None,
Dot(DotColor),
Label(&'static str),
Count(i64),
}
/// The default size, in pixels, of the square dot image.
pub const DOT_SIZE: u32 = 16;
const GREEN_HEX: &str = "#22c55e";
const RED_HEX: &str = "#e5484d";
const RING_HEX: &str = "#3b332c";
impl Signal {
/// The signal named by a favicon state id ("busy", "ready", "attention"
/// or "plain"). Any other text is `None`.
pub fn from_id(id: &str) -> Option<Signal> {
match id {
"busy" => Some(Signal::Busy),
"ready" => Some(Signal::Ready),
"attention" => Some(Signal::Attention),
"plain" => Some(Signal::Plain),
_ => None,
}
}
}
/// The badge for `signal` on the platform named by `os` (the value of
/// `std::env::consts::OS`). When the badge is turned off, there is none.
/// Windows shows a dot, macOS a "!" label and Linux a count of 1, and only
/// for the states that want the person.
pub fn badge_for(signal: Signal, os: &str, enabled: bool) -> Badge {
if !enabled {
return Badge::None;
}
match (os, signal) {
("windows", Signal::Ready) => Badge::Dot(DotColor::Green),
("windows", Signal::Attention) => Badge::Dot(DotColor::Red),
("macos", Signal::Attention) => Badge::Label("!"),
("linux", Signal::Attention) => Badge::Count(1),
_ => Badge::None,
}
}
/// Whether the window should flash. It does so only when flashing is on, the
/// window is not focused, and the signal just changed into Ready or Attention.
/// A repeat of the same signal does not flash again.
pub fn should_flash(prev: Option<Signal>, next: Signal, focused: bool, enabled: bool) -> bool {
enabled && !focused && matches!(next, Signal::Ready | Signal::Attention) && prev != Some(next)
}
/// The dot as RGBA bytes, row by row: a filled, anti-aliased circle with a
/// 1 px dark ring at its edge, on a transparent square of `size` pixels. The
/// result is `size * size * 4` bytes long, with straight (not premultiplied)
/// alpha.
pub fn dot_rgba(color: DotColor, size: u32) -> Vec<u8> {
let fill = parse_hex(match color {
DotColor::Green => GREEN_HEX,
DotColor::Red => RED_HEX,
});
let ring = parse_hex(RING_HEX);
let n = size as usize;
let mut out = vec![0u8; n * n * 4];
let center = size as f32 / 2.0;
let radius = center - 0.5;
for y in 0..n {
for x in 0..n {
// Distance from the pixel's center to the circle's center.
let dx = x as f32 + 0.5 - center;
let dy = y as f32 + 0.5 - center;
let distance = (dx * dx + dy * dy).sqrt();
let coverage = (radius + 0.5 - distance).clamp(0.0, 1.0);
let rgb = if distance > radius - 1.0 { ring } else { fill };
let alpha = (coverage * 255.0).round() as u8;
let i = (y * n + x) * 4;
out[i..i + 4].copy_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
}
}
out
}
/// The three bytes of a `#rrggbb` color. A malformed pair reads as 0.
fn parse_hex(hex: &str) -> [u8; 3] {
let digits = hex.strip_prefix('#').unwrap_or(hex);
let byte = |i: usize| {
digits
.get(i..i + 2)
.and_then(|pair| u8::from_str_radix(pair, 16).ok())
.unwrap_or(0)
};
[byte(0), byte(2), byte(4)]
}
#[cfg(test)]
mod tests {
use super::*;
const SIGNALS: [Signal; 4] = [Signal::Busy, Signal::Ready, Signal::Attention, Signal::Plain];
fn pixel(buf: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] {
let i = ((y * size + x) * 4) as usize;
[buf[i], buf[i + 1], buf[i + 2], buf[i + 3]]
}
#[test]
fn the_badge_follows_the_platform_table() {
let table: [(Signal, &str, Badge); 16] = [
(Signal::Busy, "windows", Badge::None),
(Signal::Ready, "windows", Badge::Dot(DotColor::Green)),
(Signal::Attention, "windows", Badge::Dot(DotColor::Red)),
(Signal::Plain, "windows", Badge::None),
(Signal::Busy, "macos", Badge::None),
(Signal::Ready, "macos", Badge::None),
(Signal::Attention, "macos", Badge::Label("!")),
(Signal::Plain, "macos", Badge::None),
(Signal::Busy, "linux", Badge::None),
(Signal::Ready, "linux", Badge::None),
(Signal::Attention, "linux", Badge::Count(1)),
(Signal::Plain, "linux", Badge::None),
(Signal::Busy, "freebsd", Badge::None),
(Signal::Ready, "freebsd", Badge::None),
(Signal::Attention, "freebsd", Badge::None),
(Signal::Plain, "freebsd", Badge::None),
];
for (signal, os, want) in table {
assert_eq!(badge_for(signal, os, true), want, "{signal:?} on {os}, enabled");
assert_eq!(badge_for(signal, os, false), Badge::None, "{signal:?} on {os}, disabled");
}
}
#[test]
fn from_id_reads_the_four_words_and_refuses_the_rest() {
assert_eq!(Signal::from_id("busy"), Some(Signal::Busy));
assert_eq!(Signal::from_id("ready"), Some(Signal::Ready));
assert_eq!(Signal::from_id("attention"), Some(Signal::Attention));
assert_eq!(Signal::from_id("plain"), Some(Signal::Plain));
assert_eq!(Signal::from_id("sleeping"), None);
assert_eq!(Signal::from_id("Ready"), None, "the ids are lowercase");
}
#[test]
fn a_change_into_ready_or_attention_flashes_when_unfocused() {
assert!(should_flash(Some(Signal::Busy), Signal::Ready, false, true));
assert!(should_flash(None, Signal::Attention, false, true));
}
#[test]
fn no_flash_while_the_window_is_focused() {
assert!(!should_flash(Some(Signal::Busy), Signal::Ready, true, true));
}
#[test]
fn no_flash_for_a_repeat_of_the_same_signal() {
assert!(!should_flash(Some(Signal::Ready), Signal::Ready, false, true));
assert!(!should_flash(Some(Signal::Attention), Signal::Attention, false, true));
}
#[test]
fn no_flash_for_busy_or_plain() {
for prev in [None, Some(Signal::Ready), Some(Signal::Attention)] {
assert!(!should_flash(prev, Signal::Busy, false, true), "busy from {prev:?}");
assert!(!should_flash(prev, Signal::Plain, false, true), "plain from {prev:?}");
}
}
#[test]
fn no_flash_when_flashing_is_turned_off() {
for signal in SIGNALS.iter().copied() {
assert!(!should_flash(Some(Signal::Busy), signal, false, false), "{signal:?} while disabled");
}
}
#[test]
fn parse_hex_reads_the_byte_pairs() {
assert_eq!(parse_hex("#22c55e"), [0x22, 0xc5, 0x5e]);
assert_eq!(parse_hex("e5484d"), [0xe5, 0x48, 0x4d]);
}
#[test]
fn the_green_dot_is_a_transparent_square_with_a_filled_middle() {
let size = DOT_SIZE;
let buf = dot_rgba(DotColor::Green, size);
assert_eq!(buf.len(), (size * size * 4) as usize);
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
let center = pixel(&buf, size, 8, 8);
assert_eq!(center[3], 255, "the middle is opaque");
assert_eq!(&center[..3], &parse_hex(GREEN_HEX)[..], "the middle is the green fill");
}
#[test]
fn the_red_dot_is_a_transparent_square_with_a_filled_middle() {
let size = DOT_SIZE;
let buf = dot_rgba(DotColor::Red, size);
assert_eq!(buf.len(), (size * size * 4) as usize);
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
let center = pixel(&buf, size, 8, 8);
assert_eq!(center[3], 255, "the middle is opaque");
assert_eq!(&center[..3], &parse_hex(RED_HEX)[..], "the middle is the red fill");
}
#[test]
fn the_fill_colors_match_the_web_console_favicon() {
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../src/web-console/public/favicon.js");
let text = std::fs::read_to_string(path).unwrap();
assert!(text.contains(&format!("ready: \"{GREEN_HEX}\"")), "ready color in favicon.js");
assert!(text.contains(&format!("attention: \"{RED_HEX}\"")), "attention color in favicon.js");
}
}
+1
View File
@@ -3,6 +3,7 @@
pub mod agent_manager;
pub mod agents;
pub mod announce;
pub mod attention;
pub mod brief;
pub mod console_supervisor;
pub mod handoff;
+152 -11
View File
@@ -1,11 +1,12 @@
// Hide the extra console window on Windows release builds.
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use std::sync::{Arc, Mutex};
use std::sync::{Arc, Mutex, OnceLock};
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
use plan2code_app_lib::attention::{self, Badge, Signal};
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, session_on_disk, ConsoleSupervisor};
use plan2code_app_lib::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
@@ -37,6 +38,24 @@ struct AppState {
// (Task 9.9): the first-run checklist's Node row names both.
node_version: Option<String>,
node_binary: Option<String>,
// What the taskbar entry last said, and whether it may say anything.
attention: Mutex<AttentionState>,
// The app itself, once it is set up: the agent's sink clears the taskbar
// through it when the agent ends.
app: Arc<OnceLock<tauri::AppHandle>>,
}
// The console page's last state as the taskbar shows it (attention.rs), and
// the Desktop app switch, `taskbarSignal` in app.json.
struct AttentionState {
last: Option<Signal>,
enabled: bool,
}
impl Default for AttentionState {
fn default() -> Self {
AttentionState { last: None, enabled: true }
}
}
// The operating system and, on Windows, the build number xterm needs for ConPTY.
@@ -47,9 +66,15 @@ fn platform_info() -> serde_json::Value {
}
// What the launch card offers per agent: whether its CLI is on PATH (else how
// to install it), and whether it takes its own reasoning effort.
// to install it), and whether it takes its own reasoning effort; plus the
// warnings about agents.json.
#[tauri::command]
fn agent_availability() -> serde_json::Value {
fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
// "Check again" also works the PATH out again, so a CLI whose installer
// added a new folder to it is found without restarting the app.
if refresh == Some(true) {
node_check::refresh_path();
}
// Built-ins first, then the custom agents, read afresh on every call so
// "Check again" sees a change to agents.json.
let mut entries: Vec<_> = AgentKind::ALL
@@ -70,7 +95,8 @@ fn agent_availability() -> serde_json::Value {
})
})
.collect();
for custom in agents::custom_agents() {
let (customs, warnings) = agents::custom_agents();
for custom in customs {
let at = Agent::Custom(custom.clone()).installed_at();
entries.push(serde_json::json!({
"id": custom.id,
@@ -84,7 +110,9 @@ fn agent_availability() -> serde_json::Value {
"models": custom.models,
}));
}
serde_json::json!(entries)
// What was skipped in agents.json, so a custom agent that vanished from
// the picker is explained, as the launcher and the console do.
serde_json::json!({ "agents": entries, "warnings": warnings })
}
// Opens a built-in agent install page in the default browser. Any other id
@@ -130,9 +158,15 @@ fn windows_build() -> Option<u32> {
}
// Sends the agent's output as raw bytes and its state changes as JSON, on the
// page's latest channel. Nothing is sent while no page has registered one.
fn page_sink(page: PageChannel) -> Sink {
// page's latest channel. Nothing is sent while no page has registered one. An
// agent that ends takes the taskbar's dot with it, page or no page.
fn page_sink(page: PageChannel, app: Arc<OnceLock<tauri::AppHandle>>) -> Sink {
Arc::new(move |event| {
if let AgentEvent::State(snapshot) = &event {
if let (AgentState::Ended { .. }, Some(app)) = (&snapshot.state, app.get()) {
clear_attention(app);
}
}
let Ok(guard) = page.lock() else { return };
let Some(channel) = guard.as_ref() else { return };
let body = match event {
@@ -162,7 +196,7 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
return Ok(Arc::clone(agent));
}
}
let sink = page_sink(Arc::clone(&state.page));
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.app));
let agent = Arc::new(AgentManager::new(dir, sink));
agent.set_before_fresh(before_fresh_hook(state));
*guard = Some(Arc::clone(&agent));
@@ -361,6 +395,99 @@ fn quit_app(app: &tauri::AppHandle) {
app.exit(0);
}
// The console page's state, told on every change (`attention` from the page):
// the taskbar's dot for this system, and one flash on a change into the
// person's move or needs attention while the window is not focused. An
// unknown word does nothing.
#[tauri::command]
fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) {
let Some(next) = Signal::from_id(&signal) else { return };
let Some(window) = app.get_webview_window("main") else { return };
let (prev, enabled) = {
let Ok(mut guard) = state.attention.lock() else { return };
(guard.last.replace(next), guard.enabled)
};
apply_badge(&window, attention::badge_for(next, std::env::consts::OS, enabled));
if attention::should_flash(prev, next, window.is_focused().unwrap_or(true), enabled) {
let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational));
}
}
// The one place a badge reaches the window, in each system's own form. A call
// that fails changes nothing else: the taskbar is a hint, never a blocker.
#[cfg_attr(not(any(target_os = "windows", target_os = "macos", target_os = "linux")), allow(unused_variables))]
fn apply_badge(window: &tauri::WebviewWindow, badge: Badge) {
#[cfg(target_os = "windows")]
{
let icon = match badge {
Badge::Dot(color) => Some(tauri::image::Image::new_owned(
attention::dot_rgba(color, attention::DOT_SIZE),
attention::DOT_SIZE,
attention::DOT_SIZE,
)),
_ => None,
};
let _ = window.set_overlay_icon(icon);
}
#[cfg(target_os = "macos")]
{
let label = match badge {
Badge::Label(text) => Some(text.to_string()),
_ => None,
};
let _ = window.set_badge_label(label);
}
#[cfg(target_os = "linux")]
{
let count = match badge {
Badge::Count(count) => Some(count),
_ => None,
};
let _ = window.set_badge_count(count);
}
}
// No dot and no flash: the agent ended, the page went away, or the switch was
// turned off. The next state the page tells starts from plain.
fn clear_attention(app: &tauri::AppHandle) {
if let Ok(mut guard) = app.state::<AppState>().attention.lock() {
guard.last = Some(Signal::Plain);
}
let Some(window) = app.get_webview_window("main") else { return };
apply_badge(&window, Badge::None);
let _ = window.request_user_attention(None);
}
// The app page clears it when a new page loads in the frame or none answers.
#[tauri::command]
fn clear_attention_cmd(app: tauri::AppHandle) {
clear_attention(&app);
}
// The Desktop app switch in the console's User Preferences (`taskbar` from the
// page). Off clears the dot and stops flashes; on shows the dot for the state
// the page last told at once, since the page only tells it again on a change.
// Either way the last state is kept. Saved in the app's own app.json, never
// in the console's files.
#[tauri::command]
fn set_taskbar_signal(app: tauri::AppHandle, state: State<'_, AppState>, on: bool) -> Result<(), String> {
let saved = settings::settings_file()
.ok_or_else(|| "no home folder found".to_string())
.and_then(|file| settings::save_taskbar_signal(&file, on));
let last = {
let Ok(mut guard) = state.attention.lock() else { return saved };
guard.enabled = on;
guard.last.unwrap_or(Signal::Plain)
};
if let Some(window) = app.get_webview_window("main") {
apply_badge(&window, attention::badge_for(last, std::env::consts::OS, on));
if !on {
let _ = window.request_user_attention(None);
}
}
saved
}
/// What the page draws its bar from: the folder (or that none is chosen yet)
/// and the agent the picker starts on.
#[tauri::command]
@@ -402,6 +529,8 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
// or launch card shown.
"autoStart": state.launch.agent,
"termPanel": term_panel,
// The Desktop app switch, for the page's User Preferences.
"taskbarSignal": state.attention.lock().map_or(true, |guard| guard.enabled),
})
}
@@ -499,7 +628,7 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
/// the old one (its agent stopped, its console stopped) before the new
/// folder is remembered, so `agent_for_project` and `console_start` start
/// fresh for it rather than reusing anything from the one just left. Picking
/// nothing (cancelled) leaves the current project untouched. One project per
/// nothing (canceled) leaves the current project untouched. One project per
/// window stays; this replaces it, it does not add a second.
#[tauri::command]
fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
@@ -580,6 +709,10 @@ fn main() {
launch: project::launch_choice(&args),
node_version,
node_binary,
attention: Mutex::new(AttentionState {
last: None,
enabled: settings::settings_file().map_or(true, |file| settings::load_taskbar_signal(&file)),
}),
..AppState::default()
})
.invoke_handler(tauri::generate_handler![
@@ -600,9 +733,16 @@ fn main() {
change_project,
console_start,
console_status,
console_stop
console_stop,
set_attention,
clear_attention_cmd,
set_taskbar_signal
])
.on_window_event(|window, event| {
// Looking at the window is the answer to its flash.
if let tauri::WindowEvent::Focused(true) = event {
let _ = window.request_user_attention(None);
}
// Closing with an agent running asks first; "no" keeps the window open.
if let tauri::WindowEvent::CloseRequested { api, .. } = event {
let app = window.app_handle().clone();
@@ -613,6 +753,7 @@ fn main() {
}
})
.setup(move |app| {
let _ = app.state::<AppState>().app.set(app.handle().clone());
// Pages the agent's `open` announces: the supervisor and the agent's
// environment follow the console, and the page frame shows it.
let handle = app.handle().clone();
+125 -20
View File
@@ -9,7 +9,7 @@
//! `console_supervisor`, `versions` and `agents` all use it.
use std::process::Command;
use std::sync::OnceLock;
use std::sync::Mutex;
pub const MIN_NODE_MAJOR: u32 = 18;
@@ -73,30 +73,110 @@ fn login_shell_path() -> Option<String> {
(out.status.success() && !path.is_empty()).then_some(path)
}
static RESOLVED_PATH: Mutex<Option<String>> = Mutex::new(None);
/// The PATH every process this app spawns should run with: an explicit
/// `--node`'s directory first, then (macOS and Linux) the login shell's own
/// PATH, then this process's own PATH, each included only once. Resolved
/// once per launch: none of these change while the app runs.
pub fn resolved_path() -> &'static str {
static PATH: OnceLock<String> = OnceLock::new();
PATH.get_or_init(|| {
let args: Vec<String> = std::env::args().collect();
let inherited = std::env::var("PATH").unwrap_or_default();
let mut parts = Vec::new();
if let Some(dir) = node_override_dir(&args) {
parts.push(dir);
}
#[cfg(unix)]
if let Some(login) = login_shell_path() {
parts.push(login);
}
if !inherited.is_empty() {
parts.push(inherited);
}
parts.join(if cfg!(windows) { ";" } else { ":" })
/// PATH, then this process's own PATH, each included only once. Worked out
/// once per launch, and again only on `refresh_path`.
pub fn resolved_path() -> String {
let mut cached = RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner());
cached.get_or_insert_with(|| build_path(false)).clone()
}
/// Work the PATH out again, for "Check again" after an agent CLI was
/// installed: an installer may have added a folder (the login shell's
/// profile on macOS and Linux, the saved user or system PATH on Windows)
/// that this process's own PATH has never had.
pub fn refresh_path() {
let fresh = build_path(true);
*RESOLVED_PATH.lock().unwrap_or_else(|e| e.into_inner()) = Some(fresh);
}
fn build_path(fresh: bool) -> String {
let args: Vec<String> = std::env::args().collect();
let inherited = std::env::var("PATH").unwrap_or_default();
let mut parts = Vec::new();
if let Some(dir) = node_override_dir(&args) {
parts.push(dir);
}
#[cfg(unix)]
if let Some(login) = login_shell_path() {
parts.push(login);
}
// At start this process's PATH already is the saved one; only a refresh
// needs to read it again.
#[cfg(windows)]
if fresh {
parts.extend(saved_windows_path());
}
#[cfg(not(windows))]
let _ = fresh;
if !inherited.is_empty() {
parts.push(inherited);
}
parts.join(if cfg!(windows) { ";" } else { ":" })
}
/// The system then the user PATH as saved in the registry, with `%NAME%`
/// expanded: what a newly opened terminal would get.
#[cfg(windows)]
fn saved_windows_path() -> Vec<String> {
use std::os::windows::process::CommandExt;
let keys = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
keys.iter()
.filter_map(|key| {
let out = Command::new("reg")
.args(["query", key, "/v", "Path"])
.creation_flags(0x0800_0000) // CREATE_NO_WINDOW
.output()
.ok()?;
let value = parse_reg_query_value(&String::from_utf8_lossy(&out.stdout))?;
Some(expand_percent_vars(&value, |name| std::env::var(name).ok()))
})
.collect()
}
/// The value from `reg query <key> /v <name>` output: the text after the
/// `REG_SZ` or `REG_EXPAND_SZ` column on its line.
#[cfg_attr(not(windows), allow(dead_code))]
fn parse_reg_query_value(output: &str) -> Option<String> {
output.lines().find_map(|line| {
let (_, rest) = line.split_once("REG_EXPAND_SZ").or_else(|| line.split_once("REG_SZ"))?;
let value = rest.trim();
(!value.is_empty()).then(|| value.to_string())
})
}
/// `%NAME%` replaced with `lookup(NAME)`; an unknown name stays as written.
#[cfg_attr(not(windows), allow(dead_code))]
fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option<String>) -> String {
let mut out = String::new();
let mut rest = text;
while let Some(start) = rest.find('%') {
out.push_str(&rest[..start]);
let after = &rest[start + 1..];
match after.find('%') {
Some(end) if end > 0 => match lookup(&after[..end]) {
Some(value) => {
out.push_str(&value);
rest = &after[end + 1..];
}
None => {
out.push('%');
rest = after;
}
},
_ => {
out.push('%');
rest = after;
}
}
}
out.push_str(rest);
out
}
/// Where `node` actually resolves, with `resolved_path`: for the first-run
/// checklist to name (Task 9.9), not for `check_node` itself to decide with.
pub fn node_binary_path() -> Option<String> {
@@ -172,4 +252,29 @@ mod tests {
assert_eq!(node_override_dir(&args(&["--node="])), None);
assert_eq!(node_override_dir(&args(&["--agent", "claude"])), None);
}
#[test]
fn reads_the_saved_path_out_of_reg_query_output() {
let out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.local\\bin;C:\\Tools\r\n\r\n";
assert_eq!(parse_reg_query_value(out).as_deref(), Some("%USERPROFILE%\\.local\\bin;C:\\Tools"));
let plain = "HKEY_LOCAL_MACHINE\\x\r\n Path REG_SZ C:\\Windows\r\n";
assert_eq!(parse_reg_query_value(plain).as_deref(), Some("C:\\Windows"));
assert_eq!(parse_reg_query_value("ERROR: The system was unable to find the specified registry key or value.\r\n"), None);
}
#[test]
fn expands_known_percent_names_and_keeps_the_rest() {
let lookup = |name: &str| (name == "USERPROFILE").then(|| "C:\\Users\\sam".to_string());
assert_eq!(expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup), "C:\\Users\\sam\\.local\\bin;C:\\x");
assert_eq!(expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup), "%NOPE%\\bin;C:\\Users\\sam");
assert_eq!(expand_percent_vars("50%", lookup), "50%");
assert_eq!(expand_percent_vars("a%%b", lookup), "a%%b");
}
#[test]
fn refresh_path_keeps_this_process_path() {
refresh_path();
let inherited = std::env::var("PATH").unwrap_or_default();
assert!(resolved_path().ends_with(&inherited));
}
}
+30
View File
@@ -9,6 +9,7 @@ const TERM_DOCK_KEY: &str = "termDock";
const TERM_FRACTION_KEY: &str = "termFraction";
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
const TASKBAR_SIGNAL_KEY: &str = "taskbarSignal";
/// The terminal pane's remembered shape: which edge it docks to, how much of
/// the window it takes (a fraction, not collapsed or maximized), and whether
@@ -100,6 +101,20 @@ pub fn save_first_run_done(file: &Path) -> Result<(), String> {
write(file, settings)
}
/// Whether the taskbar entry shows when Plan2Code needs the person (the
/// Desktop app switch in the console's User Preferences). On unless the file
/// says `false`; anything but a boolean reads as on.
pub fn load_taskbar_signal(file: &Path) -> bool {
read(file).get(TASKBAR_SIGNAL_KEY).and_then(|v| v.as_bool()).unwrap_or(true)
}
/// Save the switch, keeping any other key the file holds.
pub fn save_taskbar_signal(file: &Path, on: bool) -> Result<(), String> {
let mut settings = read(file);
settings.insert(TASKBAR_SIGNAL_KEY.to_string(), serde_json::Value::Bool(on));
write(file, settings)
}
fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> Result<(), String> {
if let Some(parent) = file.parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
@@ -187,6 +202,21 @@ mod tests {
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn the_taskbar_signal_is_on_until_it_is_switched_off() {
assert!(load_taskbar_signal(&temp_file("taskbar-missing")));
let file = temp_file("taskbar");
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
std::fs::write(&file, r#"{"other": 1, "taskbarSignal": "no"}"#).unwrap();
assert!(load_taskbar_signal(&file), "not a boolean reads as on");
save_taskbar_signal(&file, false).unwrap();
assert!(!load_taskbar_signal(&file));
save_taskbar_signal(&file, true).unwrap();
assert!(load_taskbar_signal(&file));
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
let _ = std::fs::remove_dir_all(file.parent().unwrap());
}
#[test]
fn a_bad_dock_or_out_of_range_fraction_on_disk_reads_as_the_default() {
let file = temp_file("term-bad-load");
+20 -1
View File
@@ -8,7 +8,7 @@ use std::sync::{Arc, Mutex, Once};
use std::time::{Duration, Instant};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
use plan2code_app_lib::agents::{Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
use plan2code_app_lib::agents::{agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
mod common;
use common::process_alive;
@@ -299,3 +299,22 @@ fn an_agent_with_no_signal_set_gets_none() {
assert!(!h.seen.contains("ENV PLAN2CODE_IN_APP=1"));
h.manager.stop();
}
#[test]
fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
let mut h = Harness::new();
// Its command is nowhere on PATH: the override replaces it, as for a built-in.
let (mut agents, warnings) = parse_agents_file(r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#);
assert!(warnings.is_empty(), "{warnings:?}");
let goose = Agent::Custom(agents.remove(0));
let spec = agent_launch_spec(&goose, &std::env::temp_dir(), Some("m"), None, PermissionMode::Bypass, "/plan2code");
assert_eq!(PathBuf::from(&spec.program), common::fake_agent());
assert!(spec.args.is_empty());
h.manager.start(goose, None, None, PermissionMode::Checked, None).expect("start the custom agent");
h.wait_for_output(READY, 1);
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()));
h.manager.restart().unwrap();
h.wait_for_output(READY, 2);
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()), "restart must keep the custom agent");
h.manager.stop();
}
+37 -7
View File
@@ -2,7 +2,7 @@
// agent's terminal panel docked at the bottom with a drag handle.
import { mountTerminal } from './terminal.js';
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor } from './meter.js';
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor } from './meter.js';
const { invoke, Channel } = window.__TAURI__.core;
@@ -26,6 +26,7 @@ const barRowEl = document.getElementById('bar-row');
const launchCard = document.getElementById('launch-card');
const launchAgentEl = document.getElementById('launch-agent');
const launchMissingEl = document.getElementById('launch-missing');
const launchWarningEl = document.getElementById('launch-agents-warning');
const launchModelEl = document.getElementById('launch-model');
const launchModelListEl = document.getElementById('launch-model-list');
const launchEffortRow = document.getElementById('launch-effort-row');
@@ -267,14 +268,21 @@ function confirmRestart(onYes) {
// keeps the order Rust sent (built-ins, then custom agents); the map is by id.
let agentList = [];
let agentAvailability = {};
// What was skipped in agents.json, shown under the picker.
let agentWarnings = [];
async function loadAgentAvailability() {
// `refresh` (Check again) also has the app work its PATH out again, so a CLI
// whose installer added a new folder is found without a restart.
async function loadAgentAvailability(refresh = false) {
try {
agentList = await invoke('agent_availability');
const result = await invoke('agent_availability', { refresh });
agentList = result.agents || [];
agentWarnings = result.warnings || [];
agentAvailability = Object.fromEntries(agentList.map((entry) => [entry.id, entry]));
} catch {
// Nothing to show is not a reason to block the card: Start just tries it.
agentList = [];
agentWarnings = [];
agentAvailability = {};
}
}
@@ -346,7 +354,7 @@ function noAgentExplainer() {
// Re-read the agents from disk (a CLI installed or a custom agent added since),
// then redraw whatever shows them and pick the default again.
async function checkAgentsAgain() {
await loadAgentAvailability();
await loadAgentAvailability(true);
applyDefaultAgent((appState && appState.lastAgent) || launchAgentEl.value);
if (!firstRunEl.hidden && appState) renderFirstRun(appState);
}
@@ -371,6 +379,8 @@ function refreshLaunchCard() {
}
}
}
launchWarningEl.hidden = agentWarnings.length === 0;
launchWarningEl.textContent = agentWarnings.map((warning) => `agents.json: ${warning}`).join('\n');
// A custom agent has no separate effort, and offers its models as
// suggestions in the (still free-text) model field.
launchModelListEl.replaceChildren();
@@ -626,13 +636,20 @@ let consoleKnown = false;
function loadFrame(url) {
currentUrl = url;
frameReady = false;
// The page going away takes its taskbar dot with it; the new one tells its own.
clearAttention();
clearTimeout(helloTimer);
helloTimer = setTimeout(onNoHello, HELLO_WAIT_MS);
frame.src = url;
}
function clearAttention() {
invoke('clear_attention_cmd').catch(() => {});
}
// What the console page may ask of this window. Each is a named request with
// no free text, so the page can never type anything but "continue".
// no free text, so the page can never type anything but "continue", and the
// taskbar's two take only their fixed words and a boolean (meter.js).
window.addEventListener('message', (event) => {
if (event.source !== frame.contentWindow) return;
const kind = event.data && event.data.plan2code;
@@ -640,6 +657,17 @@ window.addEventListener('message', (event) => {
frameReady = true;
clearTimeout(helloTimer);
hideState();
// The Desktop app switch in its User Preferences shows what app.json holds.
const on = !appState || appState.taskbarSignal !== false;
event.source.postMessage({ plan2code: 'taskbar-state', on }, '*');
} else if (kind === 'attention') {
const signal = attentionSignal(event.data);
if (signal) invoke('set_attention', { signal }).catch(() => {});
} else if (kind === 'taskbar') {
const on = taskbarSwitch(event.data);
if (on === null) return;
if (appState) appState.taskbarSignal = on;
invoke('set_taskbar_signal', { on }).catch(() => {});
} else if (kind === 'agent-continue') {
typeContinue();
} else if (kind === 'new-session') {
@@ -697,6 +725,8 @@ try {
// No hello in time: ask the console why, and say so with a way forward.
async function onNoHello() {
if (frameReady || !consoleKnown || restarting) return;
// A page that does not answer cannot say it is done needing the person.
clearAttention();
let status = null;
try {
status = await invoke('console_status');
@@ -901,7 +931,7 @@ function setProjectDir(dir) {
// checklist both need it once a folder lands, after the fact.
let appState = null;
// Opens the OS folder picker. A cancelled pick (or a failed one) lands on the
// Opens the OS folder picker. A canceled pick (or a failed one) lands on the
// "No project folder chosen" state with a button that tries again.
async function pickFolder() {
try {
@@ -930,7 +960,7 @@ function afterProjectKnown() {
// Switches to a folder picked fresh: the Rust side tears the old project's
// agent and console down before the new one is remembered, so nothing from
// it carries over. Picking nothing (cancelled) leaves the current project as
// it carries over. Picking nothing (canceled) leaves the current project as
// it was.
async function doChangeProject() {
showState('Choose the new project folder...');
+4 -1
View File
@@ -89,7 +89,7 @@
#dashboard-state[hidden] { display: none; }
#dashboard-state-text { margin: 0; max-width: 60ch; overflow-wrap: anywhere; color: #bbb; }
#dashboard-state-planny[hidden] { display: none; }
/* Drawn and coloured like the console's own Planny (styles/planny.css):
/* Drawn and colored like the console's own Planny (styles/planny.css):
an outlined shell, the star eye, a lip of a smile, round hands. */
#dashboard-state-planny { width: 104px; height: auto; overflow: visible; }
#dashboard-state-planny :is(.ps-shell, .ps-smile, .ps-arm path, .ps-mug, .ps-handle) {
@@ -146,6 +146,8 @@
}
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
#launch-missing code { color: #ddd; }
#launch-agents-warning { margin: 0; font-size: 12px; color: #d7ba7d; white-space: pre-line; }
#launch-agents-warning[hidden] { display: none; }
.agent-explainer { margin: 0; font-size: 12px; line-height: 1.5; }
.agent-explainer ul { margin: 4px 0; padding-left: 18px; }
.agent-explainer code { color: #ddd; }
@@ -296,6 +298,7 @@
<option value="codex">Codex</option>
</select>
<p id="launch-missing" hidden></p>
<p id="launch-agents-warning" hidden></p>
<label for="launch-model">Model</label>
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off" list="launch-model-list">
<datalist id="launch-model-list"></datalist>
+22 -2
View File
@@ -31,7 +31,9 @@ export function continueKeys(kind) {
* (built-ins first, then custom agents): the remembered id when it is
* installed, else the first installed built-in, else the first installed
* custom agent, else the remembered id or the first entry, so the card's
* missing-agent line explains what is wrong instead of picking silently.
* missing-agent line explains what is wrong instead of picking silently. A
* remembered id the list no longer has (a custom agent deleted since) is not
* kept, since the picker could not show it; with no list at all it is.
*/
export function pickDefaultAgent(availability, remembered) {
const list = Array.isArray(availability) ? availability : [];
@@ -41,7 +43,7 @@ export function pickDefaultAgent(availability, remembered) {
if (builtIn) return builtIn.id;
const custom = list.find((a) => a.installed && a.custom);
if (custom) return custom.id;
if (remembered) return remembered;
if (remembered && (rememberedEntry || list.length === 0)) return remembered;
return list.length > 0 ? list[0].id : null;
}
@@ -143,3 +145,21 @@ function lastSegment(dir) {
.filter(Boolean)
.pop();
}
/**
* The console page's taskbar messages, checked here before anything reaches
* the app (attention.rs decides what they mean). `attention` carries one of
* the four states the page's favicon has; `taskbar` carries the Desktop app
* switch as a boolean. Anything else is null, and nothing is forwarded.
*/
export const ATTENTION_STATES = Object.freeze(['busy', 'ready', 'attention', 'plain']);
export function attentionSignal(data) {
const state = data && data.state;
return ATTENTION_STATES.includes(state) ? state : null;
}
export function taskbarSwitch(data) {
const on = data && data.on;
return typeof on === 'boolean' ? on : null;
}
+41 -1
View File
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
import fs from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import { barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
import { findBrowser, launchBrowser } from "./browser.mjs";
const HERE = path.dirname(fileURLToPath(import.meta.url));
@@ -258,3 +258,43 @@ test("pickDefaultAgent with nothing installed returns the remembered id, else th
assert.equal(pickDefaultAgent(none, null), "claude");
assert.equal(pickDefaultAgent([], null), null);
});
test("pickDefaultAgent drops a remembered id the list no longer has, unless there is no list at all", () => {
const none = AVAIL([["claude", false], ["devin", false], ["codex", false]]);
// A custom agent deleted since: the picker could not show it, so the first entry it can.
assert.equal(pickDefaultAgent(none, "gone"), "claude");
// The availability check failed: the fixed options are on the card, the remembered id stands.
assert.equal(pickDefaultAgent([], "devin"), "devin");
});
test("the launch card shows agents.json warnings, and Check again asks for a fresh PATH", () => {
assert.match(INDEX_HTML, /<p id="launch-agents-warning" hidden><\/p>/);
assert.match(APP_JS, /invoke\('agent_availability', \{ refresh \}\)/);
assert.match(APP_JS, /async function checkAgentsAgain\(\) \{\n await loadAgentAvailability\(true\);/);
});
// The console page's taskbar messages reach the app only as one of four fixed
// words or a boolean (attention.rs decides what they mean); app.js forwards
// them through these checks and nothing else.
test("attentionSignal passes only the four favicon states, and taskbarSwitch only a boolean", () => {
for (const state of ["busy", "ready", "attention", "plain"]) {
assert.equal(attentionSignal({ plan2code: "attention", state }), state);
}
for (const data of [{ state: "Ready" }, { state: "urgent" }, { state: "" }, { state: 1 }, {}, null, undefined]) {
assert.equal(attentionSignal(data), null, `${JSON.stringify(data)} is not forwarded`);
}
assert.equal(taskbarSwitch({ on: true }), true);
assert.equal(taskbarSwitch({ on: false }), false);
for (const data of [{ on: "false" }, { on: 0 }, { on: null }, {}, null]) {
assert.equal(taskbarSwitch(data), null, `${JSON.stringify(data)} is not forwarded`);
}
});
test("app.js forwards attention and taskbar through those checks, and clears the dot on a new frame and a lost hello", () => {
assert.match(APP_JS, /const signal = attentionSignal\(event\.data\);\s+if \(signal\) invoke\('set_attention', \{ signal \}\)/);
assert.match(APP_JS, /const on = taskbarSwitch\(event\.data\);\s+if \(on === null\) return;/);
assert.match(APP_JS, /invoke\('set_taskbar_signal', \{ on \}\)/);
assert.match(APP_JS, /function loadFrame\(url\) \{[^}]*clearAttention\(\);[^}]*frame\.src = url;/);
assert.match(APP_JS, /async function onNoHello\(\) \{\s+if \(frameReady \|\| !consoleKnown \|\| restarting\) return;[\s\S]{0,120}clearAttention\(\);/);
assert.match(APP_JS, /plan2code: 'taskbar-state', on/, "the page hears the saved switch on its hello");
});
+30 -1
View File
@@ -704,6 +704,31 @@ test("launcher agents: the model menu is the agent's own models, with no shipped
assert.deepEqual(cli.args(["--model=m2", "-x"]), ["--yes", "/plan2code", "--model", "m2", "--bypass", "-x"]);
});
test("launcher agents: the menu lists the built-ins found first, then the custom agents that resolve", (t) => {
const box = sandbox(["goose", "codex", "claude"]);
t.after(box.cleanup);
const file = writeAgents(box, { schema: 1, agents: [GOOSE, { id: "ghost", name: "Ghost", command: "ghost-cmd" }] });
const { customClis, runnableClis } = require(LAUNCHER);
const realPath = process.env.PATH;
process.env.PATH = path.join(box.dir, "bin");
t.after(() => {
process.env.PATH = realPath;
});
const { installed, missing } = runnableClis(customClis(file, false));
assert.deepEqual(installed.map((cli) => cli.id), ["claude", "codex", "goose"]);
assert.deepEqual(missing.map((cli) => cli.id), ["ghost"]);
});
test("launcher agents: with no terminal to ask, a custom agent's model line names its own default", (t) => {
const box = sandbox(["goose"]);
t.after(box.cleanup);
writeAgents(box, goose());
const result = box.run(["--cli", "goose"]);
assert.equal(result.status, 0, result.stderr);
assert.match(result.stdout, /Goose will start with its own default model\. To pick one, run `plan2code --model <id>`\./);
assert.doesNotMatch(result.stdout, /last used/);
});
test("launcher agents: a custom agent whose command is not found is left out and named when nothing can run", (t) => {
const box = sandbox(["claude"]);
t.after(box.cleanup);
@@ -769,13 +794,17 @@ test("launcher agents: a full-path command starts, and on Windows a .cmd in a fo
if (IS_WINDOWS) {
file = path.join(spaced, "spaced.cmd");
fs.writeFileSync(file, `@"${process.execPath}" "${recorder}" spaced %*\r\n`);
// A same-named file in the project folder (the launcher's cwd) must not run instead.
fs.writeFileSync(path.join(box.dir, "spaced.cmd"), `@"${process.execPath}" "${recorder}" decoy %*\r\n`);
} else {
file = path.join(spaced, "spaced");
fs.writeFileSync(file, `#!/bin/sh\nexec "${process.execPath}" "${recorder}" spaced "$@"\n`);
fs.chmodSync(file, 0o755);
}
writeAgents(box, { schema: 1, agents: [{ id: "spaced", name: "Spaced", command: file, args: ["{prompt}"] }] });
const result = box.run(["--cli", "spaced", "--note", "a b"]);
// Some shells already set the switch the launcher sets; the run starts without it.
const result = box.run(["--cli", "spaced", "--note", "a b"], { NoDefaultCurrentDirectoryInExePath: undefined });
assert.equal(result.status, 0, result.stderr);
assert.deepEqual(box.argsOf("spaced"), ["/plan2code", "--note", "a b"]);
assert.equal(box.argsOf("decoy"), null);
});
+64 -1
View File
@@ -10,7 +10,8 @@ import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { spawn } from "node:child_process";
import { CONSOLE_CLI, ENV, HOME, cli } from "./web-console-test-helpers.mjs";
import { CONSOLE_CLI, ENV, HOME, cli, until } from "./web-console-test-helpers.mjs";
import { openSession, pageSuite } from "./page-test-helpers.mjs";
import { announcePage, inAppSignal } from "../src/web-console/in-app.mjs";
// A stand-in for the app's announce endpoint: records every POST it accepts.
@@ -268,3 +269,65 @@ test("with nothing shown in the window yet, open makes the first session and ann
app.close();
}
});
// The page inside the app's frame: the taskbar's two messages. Driven in a
// real browser (page-test-helpers.mjs), with a parent that keeps every
// message posted to it.
const pages = pageSuite(test);
const FAKE_APP_FRAME = () => {
window.__toApp = [];
Object.defineProperty(window, "parent", { configurable: true, get: () => ({ postMessage: (m) => window.__toApp.push(m) }) });
};
const toApp = (s, kind) => s.page.evaluate((k) => window.__toApp.filter((m) => m.plan2code === k), kind);
const ASKING = { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } };
test("framed, the page tells the app its state once per change, never on a redraw, and plain when it goes away", async (t) => {
const s = await openSession(await pages.browser(), { t, workflow: "implement", clock: true, payload: ASKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
await until(async () => (await toApp(s, "attention")).length >= 1, 5000);
assert.deepEqual((await toApp(s, "attention")).at(-1), { plan2code: "attention", state: "ready" }, "a question waiting is the person's move, as a named request");
const before = (await toApp(s, "attention")).length;
await s.page.clock.fastForward(5_000);
assert.equal((await toApp(s, "attention")).length, before, "the status line's tick redraws without telling the app again");
s.post({ settle: true, items: [{ id: "q1", status: "answered", answer: { text: "x" } }], agent: { status: "working", activity: "Task 1 of 2" } });
await until(async () => (await toApp(s, "attention")).at(-1).state !== "ready", 5000);
const states = (await toApp(s, "attention")).map((m) => m.state);
assert.ok(states.every((state) => ["busy", "ready", "attention", "plain"].includes(state)), states.join(", "));
assert.ok(states.every((state, i) => i === 0 || state !== states[i - 1]), `no state is told twice in a row: ${states.join(", ")}`);
await s.page.evaluate(() => dispatchEvent(new Event("pagehide")));
assert.deepEqual((await toApp(s, "attention")).at(-1), { plan2code: "attention", state: "plain" });
});
test("the Desktop app group shows only in the app's frame, reflects the app's saved switch and tells the app when it changes", async (t) => {
const browser = await pages.browser();
const plain = await openSession(browser, { t, workflow: "implement", payload: ASKING });
await plain.page.locator("#btn-looks").click();
assert.equal(await plain.page.locator("#looks-desktop").isVisible(), false, "not in a browser tab");
const s = await openSession(browser, { t, workflow: "implement", payload: ASKING, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
await s.page.locator("#btn-looks").click();
const box = s.page.locator("#looks-taskbar");
assert.ok(await s.page.locator("#looks-desktop").isVisible(), "shown inside the app");
assert.ok(await box.isChecked(), "on until the app says otherwise");
// The app's answer to the page's hello, from a real window standing in as
// the parent. The same answer from anywhere else is ignored.
await s.page.evaluate(() => {
const frame = document.createElement("iframe");
document.body.append(frame);
const app = frame.contentWindow;
app.postMessage = (m) => window.__toApp.push(m);
Object.defineProperty(window, "parent", { configurable: true, get: () => app });
window.__app = app;
dispatchEvent(new MessageEvent("message", { data: { plan2code: "taskbar-state", on: false }, source: window }));
});
assert.equal(await box.isChecked(), true, "a taskbar-state from anywhere but the parent changes nothing");
await s.page.evaluate(() => {
dispatchEvent(new MessageEvent("message", { data: { plan2code: "taskbar-state", on: false }, source: window.__app }));
});
assert.equal(await box.isChecked(), false, "the parent's saved value");
await box.check();
assert.deepEqual(await toApp(s, "taskbar"), [{ plan2code: "taskbar", on: true }], "a named request with one boolean");
});
+31 -12
View File
@@ -632,13 +632,10 @@ function announceCli(cli) {
}
/**
* Choose the CLI from those installed: the `--cli` pick, the only one installed, or a numbered
* menu defaulting to the last pick. Returns `{ cli }` with its resolved `path`, or `{ code }` (the
* exit code) after printing why none can be used.
* The CLIs that can run, in menu order (the built-ins found on PATH, then the custom agents whose
* command resolves), and the custom agents left out because theirs does not.
*/
async function chooseCli(requested) {
const customs = customClis();
const all = [...CLIS, ...customs];
function runnableClis(customs) {
const installed = CLIS.map((cli) => ({ ...cli, path: findOnPath(cli.id) })).filter((cli) => cli.path);
// A custom agent whose command does not resolve is left out of the menu and named when nothing can run.
const missing = [];
@@ -647,6 +644,18 @@ async function chooseCli(requested) {
if (found) installed.push({ ...cli, ...found });
else missing.push(cli);
}
return { installed, missing };
}
/**
* Choose the CLI from those installed: the `--cli` pick, the only one installed, or a numbered
* menu defaulting to the last pick. Returns `{ cli }` with its resolved `path`, or `{ code }` (the
* exit code) after printing why none can be used.
*/
async function chooseCli(requested) {
const customs = customClis();
const all = [...CLIS, ...customs];
const { installed, missing } = runnableClis(customs);
if (requested !== undefined) {
const known = all.find((cli) => cli.id === requested);
@@ -743,13 +752,20 @@ function listModels(cli) {
}
/**
* Ask which model to run: a numbered list with Enter keeping the model the CLI last used.
* Ask which model to run: a numbered list with Enter keeping the model the CLI last used (a
* custom agent: its own default).
* A pick appends `--model <id>` to `extraArgs`. Without an interactive terminal there is
* nobody to ask, so it just says which model will be used, as it always has.
*/
async function chooseModel(cli, extraArgs) {
if (cli.custom && !listModels(cli).length) return;
// A custom agent has no last-used model to keep: left alone it starts on its own default.
const keep = cli.custom ? 'its own default model' : 'the last-used model';
if (!process.stdin.isTTY) {
if (cli.custom) {
console.log(`${cli.label} will start with its own default model. To pick one, run \`plan2code --model <id>\`.`);
return;
}
console.log(`${cli.label} will use the model you last used in it. To use a different model, open`);
console.log(`\`${cli.id}\` on its own and switch model there, or run \`plan2code --model <name>\`.`);
return;
@@ -773,7 +789,7 @@ async function chooseModel(cli, extraArgs) {
models.forEach((model, i) => console.log(!model.label ? ` ${c.cyan(`${i + 1})`)} ${model.id}` : ` ${c.cyan(`${i + 1})`)} ${model.id} — ${model.label}`));
}
for (;;) {
const answer = (await ask(`Choice ${c.green('[keep last used]')}: `)).trim().toLowerCase();
const answer = (await ask(`Choice ${c.green(cli.custom ? '[default]' : '[keep last used]')}: `)).trim().toLowerCase();
if (!answer) return;
const byNumber = models[Number(answer) - 1];
const byName = models.find((model) => model.id === answer || model.label.toLowerCase() === answer);
@@ -782,7 +798,7 @@ async function chooseModel(cli, extraArgs) {
extraArgs.push('--model', model.id);
return;
}
console.log(c.yellow(`Type a number from 1 to ${models.length}, a model name, or press Enter to keep the last-used model.`));
console.log(c.yellow(`Type a number from 1 to ${models.length}, a model name, or press Enter to keep ${keep}.`));
}
}
@@ -946,7 +962,7 @@ async function confirmProject(cwd) {
/**
* Ask for the project folder: the native picker when there is one, a typed path otherwise.
* Returns the folder, or null when the person cancelled.
* Returns the folder, or null when the person canceled.
*/
async function pickFolder() {
const start = readLastFolder();
@@ -962,7 +978,7 @@ async function pickFolder() {
windowsHide: true,
});
const folder = (result.stdout || '').trim();
// Pickers exit 0 or 1 with nothing printed when cancelled; anything else means the picker
// Pickers exit 0 or 1 with nothing printed when canceled; anything else means the picker
// itself failed, so fall through to the typed prompt rather than giving up.
if (!result.error && folder && result.status === 0) return path.resolve(folder);
if (!result.error && !folder && (result.status === 0 || result.status === 1)) return null;
@@ -1013,6 +1029,9 @@ function spawnCommand(file, args, options) {
// Windows env names are case-insensitive and the copy keeps the original spelling (Path).
const pathKey = Object.keys(env).find((key) => key.toUpperCase() === 'PATH') || 'PATH';
env[pathKey] = path.dirname(file) + path.delimiter + (env[pathKey] || '');
// cmd looks in the current folder (the project) before PATH: a same-named
// file there must not run in the agent's place.
env.NoDefaultCurrentDirectoryInExePath = '1';
return spawn(shell, ['/d', '/s', '/c', `"${[path.basename(file), ...args].map(quoteForCmd).join(' ')}"`], {
...spawnOptions,
env,
@@ -1161,4 +1180,4 @@ async function launch() {
// Run only when invoked directly; requiring the file (the tests do) is load-only.
if (require.main === module) launch();
module.exports = { normalizeAgents, buildArgs, customClis, resolveCustomCommand, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
module.exports = { normalizeAgents, buildArgs, customClis, resolveCustomCommand, runnableClis, listModels, mergeModels, modelEntries, renderBanner, paint, hasModelFlag, compareVersions, modelFrom, hasDisplay, looksLikeProject };
+13
View File
@@ -23,6 +23,19 @@ export function linkLeavesPage(href, origin) {
return (url.protocol === "http:" || url.protocol === "https:") && url.origin !== origin;
}
/**
* Call `handler(data)` for each `{ plan2code: kind, ... }` message the frame's
* parent sends, and for nothing from anywhere else (another frame, the page
* itself). The app's only answer today is `taskbar-state`.
*/
export function onAppMessage(kind, handler) {
window.addEventListener("message", (event) => {
if (!framed() || event.source !== window.parent) return;
const data = event.data;
if (data && typeof data === "object" && data.plan2code === kind) handler(data);
});
}
/** Post `message` to the frame's parent, as `{ plan2code: kind, ...extra }`; nothing outside a frame. */
export function tellApp(kind, extra = {}) {
if (!framed()) return;
+20 -10
View File
@@ -64,7 +64,7 @@
<div id="banner" class="banner" role="status" hidden></div>
<!-- Planny's wake-up on a freshly opened dashboard: a large copy of the
rail drawing that powers on centre stage, then glides into the rail.
rail drawing that powers on center stage, then glides into the rail.
Hidden unless boot.js is playing it; placed entirely by app.css,
because the CSP refuses style attributes. -->
<div class="wake" id="wake" hidden>
@@ -97,7 +97,7 @@
<span class="badge" id="badge">Pathfinder</span>
<h1 id="title">Plan2Code Console</h1>
<!-- The session meter: how much this console session has done. The
ring fills with the points (full at 15); the colour is the
ring fills with the points (full at 15); the color is the
level. Hidden until a frame carries `meter`. -->
<span class="meter-slot">
<button
@@ -812,7 +812,7 @@
Four boxes in a row, each talking both ways with the next: you in
your browser, this page, a small program on 127.0.0.1, and
Plan2Code in your terminal. A dashed outline around all four is
labelled "Your machine only".
labeled "Your machine only".
</desc>
<defs>
<marker id="hd-about-arrow" viewBox="0 0 8 8" refX="7" refY="4" markerWidth="5" markerHeight="5" orient="auto-start-reverse">
@@ -930,7 +930,7 @@
</li>
<li class="help-row">
<dl>
<dt>You see</dt><dd><strong>Not running</strong> (Planny grey and still).</dd>
<dt>You see</dt><dd><strong>Not running</strong> (Planny gray and still).</dd>
<dt>Likely cause</dt><dd>Plan2Code has not checked in for a few minutes.</dd>
<dt>Do this</dt><dd class="for-browser">Look at the terminal. If it is idle, type <code>continue</code> there.</dd><dd class="for-app">Look at the terminal panel. If it is idle, press <strong>continue</strong> in the line beside Planny, which types it there for you.</dd>
</dl>
@@ -998,7 +998,7 @@
<h4>Not running, or not connected?</h4>
<ul>
<li>
<strong>Not running</strong> (Planny grey and still): this page is
<strong>Not running</strong> (Planny gray and still): this page is
fine, but Plan2Code in the terminal has not checked in for
<span data-fact="adriftMinutes">3</span> minutes. It may have finished
its turn, hit an error, or be waiting on you there.
@@ -1386,7 +1386,7 @@
<p id="help-planny-done-text">A green star and both arms up. The session is finished. You can close the tab.</p>
<h4>Not running</h4>
<p>
Grey, still, arms down out of sight. This page is fine, but Plan2Code has not checked in
Gray, still, arms down out of sight. This page is fine, but Plan2Code has not checked in
for <span data-fact="adriftMinutes">3</span> minutes. Anything you answer
is still saved.
</p>
@@ -1762,7 +1762,7 @@
<strong>Start from scratch</strong> for a new idea. The one you pick is
what a step works on, and it decides which cards make sense: a spec
that is half built has no use for Pathfinder, and a new idea cannot be
implemented yet. Cards that do not fit are greyed out with the reason
implemented yet. Cards that do not fit are grayed out with the reason
why.
</p>
<p>
@@ -2026,7 +2026,7 @@
<h4>While something is running</h4>
<ul>
<li>
Everything greys out except switching tabs, searching and opening
Everything grays out except switching tabs, searching and opening
folds, so nothing queues up behind the running command.
</li>
<li>What is running shows where the next step usually sits.</li>
@@ -2049,7 +2049,7 @@
<strong>Done with git</strong> ends the board. If anything happened, the
last screen lists the commits, pushes and branches created or deleted,
with <strong>Back to the dashboard</strong>; if nothing did, the page
goes straight back to the dashboard. It greys while a command runs and
goes straight back to the dashboard. It grays while a command runs and
comes back when it is done; if Plan2Code stops checking in,
<strong>Stop session</strong> in the top bar ends the session instead.
While a question of Plan2Code's waits, it cancels that question and
@@ -2423,7 +2423,7 @@
</li>
<li>
<strong>Highlight color</strong>: one of
<span data-fact="accentCount">32</span>, ocean blue to begin with. It marks
<span data-fact="accentCount">38</span>, ocean blue to begin with. It marks
what is yours to do, and Planny's star uses it while he works.
</li>
<li>
@@ -2664,6 +2664,16 @@
<span class="help" id="agents-status" role="status"></span>
</div>
</fieldset>
<!-- Only inside the desktop app (framed()): the app saves the switch in its own app.json. -->
<fieldset class="modal-ranges looks-desktop" id="looks-desktop" hidden>
<legend>Desktop app</legend>
<label><input type="checkbox" id="looks-taskbar" checked /> <span>Show on the taskbar when Plan2Code needs me</span></label>
<p class="help">
Windows: a colored dot on the taskbar button (green on your move, red when it
needs you) and a short burst of flashes. macOS: a red badge on the dock icon when it needs
you, and a bounce. Linux: depends on your desktop.
</p>
</fieldset>
</div>
<div class="modal-actions">
<button type="button" class="btn ghost" id="looks-reset">Back to default</button>
+20 -5
View File
@@ -1044,6 +1044,16 @@ function continueButton() {
return btn;
}
// The favicon state last told to the app (attention.rs turns it into the
// taskbar's dot). Told only when it changes, never on every status redraw.
let lastAttention = null;
function tellAttention(state) {
if (state === lastAttention) return;
lastAttention = state;
tellApp("attention", { state });
}
export function renderStatus() {
if (!page.S) return;
const bot = $("planny");
@@ -1089,8 +1099,11 @@ export function renderStatus() {
tick.textContent = count || "";
$("agent-spin").hidden = !spin;
$("dock").classList.toggle("is-flying", Boolean(spin));
// The tab icon's bar says the same thing from another tab (favicon.js).
setFavicon(faviconState({ mood, spin, finished: Boolean(finish()) }));
// The tab icon's bar says the same thing from another tab (favicon.js),
// and the app's taskbar entry from another window.
const icon = faviconState({ mood, spin, finished: Boolean(finish()) });
setFavicon(icon);
tellAttention(icon);
};
// Before `gone`, deliberately. Once a session has finished, no server is the
@@ -1311,7 +1324,7 @@ export function renderSidebar() {
box.appendChild(head);
for (const e of SKILL_CATALOG.filter((x) => x.group === g.id)) {
const av = cardPresentation(e, scan(), selSpec(), menu);
// Unavailable for the selected spec fades hard; the brief greying
// Unavailable for the selected spec fades hard; the brief graying
// while a launch is in flight or the server is away does not.
const b = el(
"button",
@@ -1439,7 +1452,7 @@ function paintMain(main) {
if (isDashboard() && !finish()) {
if (page.local.launching) renderLaunching(main);
else if (page.dashPick) {
// A spec-switch under an open confirm can grey the pick out. Rather
// A spec-switch under an open confirm can gray the pick out. Rather
// than offer START on a card that cannot launch, drop back to the
// menu — the picker's new selection speaks for itself there.
if (cardAvailability(page.dashPick, scan(), selSpec()).on) renderConfirm(main, page.dashPick);
@@ -1620,7 +1633,7 @@ export function renderFooter() {
const hint = $("send-hint");
hint.replaceChildren();
hint.title = state.why;
// Something is turning while the turn is not theirs. A line of grey text
// Something is turning while the turn is not theirs. A line of gray text
// saying "one moment" reads the same whether the agent is working on it or
// has quietly died; a spinner is the difference between the two at a glance.
// A spinner says "something is happening". Nothing is, once the other end
@@ -1932,6 +1945,8 @@ export function wireChrome() {
try {
navigator.sendBeacon("/bye");
} catch {}
// A page that goes away leaves no dot on the app's taskbar behind it.
tellAttention("plain");
});
// Under the app, a link off the page goes to the default browser through
+11
View File
@@ -7,6 +7,7 @@ import { ROLES, ROLE_NOT_SET, ROLE_NOT_SET_LABEL, needsRoleNudge, normalizeRole
import { isDashboard } from "../selectors.js";
import { el, lightDismiss } from "../render.js";
import { page, redraw } from "../state.js";
import { framed, onAppMessage, tellApp } from "../app-bridge.js";
const $ = (id) => document.getElementById(id);
@@ -552,4 +553,14 @@ export function wireLooks() {
saveModels();
renderModels();
});
// Desktop app: the taskbar switch, kept by the app in its own app.json. The
// app says what it holds once the page is up; checked until it does.
if (framed()) {
$("looks-desktop").hidden = false;
onAppMessage("taskbar-state", (data) => {
if (typeof data.on === "boolean") $("looks-taskbar").checked = data.on;
});
$("looks-taskbar").addEventListener("change", (e) => tellApp("taskbar", { on: e.target.checked }));
}
}
+6 -3
View File
@@ -57,7 +57,7 @@
}
/* Folded-in sections. A page holds one card; what used to be cards of their
own (the "all caught up" lull, the session notes) is a labelled section
own (the "all caught up" lull, the session notes) is a labeled section
inside it instead. */
.card-lead { margin: 0 0 16px; }
.card-extra { margin: 18px 0 0; }
@@ -162,7 +162,7 @@
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
}
.sa-strength { margin: 8px 0 0; display: flex; flex-wrap: wrap; gap: 6px; }
/* A helper's strength and effort, coloured by rank: calm teal, amber, violet. */
/* A helper's strength and effort, colored by rank: calm teal, amber, violet. */
.sa-badge {
--b: var(--ink-2);
--b-soft: var(--panel);
@@ -755,7 +755,10 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
.modal.looks .modal-ranges + .modal-ranges { margin-top: 18px; }
.looks-row { grid-template-columns: repeat(3, minmax(0, 1fr)); }
.looks-row .help { grid-column: 1 / -1; }
/* The per-cue boxes sit under the master switch, greyed and locked while it
/* The Desktop app group exists only inside the app; elsewhere it stays hidden
in spite of the grid above. */
.looks-desktop[hidden] { display: none; }
/* The per-cue boxes sit under the master switch, grayed and locked while it
is off rather than hidden, so the picks stay visible. */
.looks-sound-events { display: grid; gap: 8px; }
.looks-sound-events.is-off { opacity: 0.45; }