Add the agent-less setup page, a shared agent list and the split Agents & models tab

AI Assisted
This commit is contained in:
jparkerweb committed 2026-11-03 04:08:27 -08:00
1 parent c122332657
commit 33f1783979
55 files changed
+5453 -1345

No files matched your search

@@ -0,0 +1,156 @@
---
name: plan2code-launcher-update
description: "Refresh the plan2code launcher's shipped data: the curated model menu in src/launcher/models.json from `devin models list` and Claude Code's documented model aliases, and the agent list's install data in src/launcher/agents.json re-checked against each vendor's docs, with the maintainer approving every change before anything is written. Use this skill when the user says 'update the models', 'refresh models.json', 'new Claude model', 'devin models changed', 'update the agents', 'refresh agents.json', 'agent install commands changed', 're-check the agent list', or otherwise asks to bring the launcher's model menu or agent install data up to date."
---
# Plan2Code Launcher Update
Bring the launcher's shipped data up to date: the curated model menu (`src/launcher/models.json`) with the models each CLI offers today, and the agent list (`src/launcher/agents.json`) with what each vendor's docs say today. Discover the current facts, show the maintainer a diff against the shipped files, apply only the changes they approve, validate both files, and run `npm test`. This skill never commits.
**Repo-local by design.** This skill lives in the repo's `.claude/skills/` and is intentionally NOT wired into `install.js` — it is a maintainer dev tool, not part of the shipped product, so it is never installed to `~/.claude/skills/`. Do **not** copy it there: the uninstaller (`uninstallSkills()` in `install.js`) and every re-install (`install()`) both run `cleanLegacyPaths()`, which deletes every entry matching `/^plan2code-/` under `~/.claude/skills/` (the `LEGACY_PATHS` row for Claude Code skills), so a copy placed there would be silently removed.
**Terminal only.** This skill runs in the terminal, with no web console session. Ask every question here.
## Workflow
### Step 1 — Preflight
Run from the repo root (the folder holding `install.js` and `src/launcher/`). Run `git status --porcelain -- src/launcher/models.json src/launcher/agents.json`. If it prints anything, warn — do not stop:
> The shipped launcher files already have uncommitted changes. The diff below compares against the files as they stand on disk, including those changes.
### Step 2 — Read the current files
Read `src/launcher/models.json`. It has four keys: `_note` (a string), `claude`, `devin` and `codex` (each an array of `{ "id", "label" }`; `codex` is empty today, because Codex's docs name no models to verify and the launcher skips the model question for it). Keep the `_note` text exactly as read — Step 9 writes it back verbatim and the Validation rules check it.
Read `src/launcher/agents.json`. It has `schema` (currently `1`) and `agents`, a list of entries. Each entry carries `id`, `name`, `kind` (`builtin` or `template`), `command`, `prompt`, `args`, `bypassArgs`, `modelArgs`, and optional `note`. A `builtin` entry also carries `installUrl`, `install` (lists under `win`, `mac` and `linux`, each `{ label, run, note? }`) and `installDirs` (the same OS keys). Keep the file's shape and order exactly as read.
### Step 3 — Discover Devin's models
If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerShell), run:
```bash
devin models list
```
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 7 as the proposed list.
### Step 4 — Discover Claude Code's models
Look up Claude Code's current model documentation — the model configuration page in the Claude Code docs. Locate it on each run (search the Claude Code docs for model configuration) rather than using a remembered URL; docs move. List the documented model aliases (for example `default`, `sonnet`, `opus`, `haiku`, `opusplan`) and what each one means, and name the page you used. Keep `default` as the file's first entry even though the docs call it a special value rather than an alias. Bracketed aliases such as `opus[1m]` are valid ids; propose them only when the maintainer wants them in the menu.
If the lookup fails or the page does not list aliases, say so, and switch to **guided manual edits** for Claude, exactly as in Step 3.
### Step 4b: Check Codex's models
Look up Codex's current model documentation (locate it on each run). Propose `codex` entries only for model ids the docs name explicitly. If they name none, say so and leave `codex` empty. If entries are added, the `_note` sentence about Codex goes stale; keep `_note` verbatim as everywhere else, but tell the maintainer so they can reword it by hand. If the lookup fails, use guided manual edits as in Step 3.
### Step 5: Re-check the agent list against vendor docs
For each entry in `agents.json`, locate the vendor's current install documentation on each run (search for it; do not use a remembered URL, since docs move and `installUrl` itself may be stale). Compare the file against what the docs say today:
- **Built-ins** (`claude`, `devin`, `codex`): `installUrl`, every `install` line per OS (`label`, `run`, `note`), and `installDirs` per OS. Keep the lead-installer order: the vendor's native installer first, then npm where it exists, with requirement notes (like Claude Code's Node 22+ npm note) carried on their lines. Also re-check `command`, `prompt`, `args`, `bypassArgs` and `modelArgs` against the vendor's CLI reference.
- **Templates** (`copilot`, `opencode`, `gemini`, `pi`): `command`, the first-prompt form (`prompt` plus where `{prompt}` sits in `args`), `bypassArgs`, `modelArgs`, and any `note`. Confirm the template rule still holds: the docs must confirm both that the agent loads the installed Plan2Code skills (the skills folders the vendor documents) and that it starts an interactive session with a first prompt. A template that no longer passes the rule is proposed for removal, and the maintainer is told why.
Name the docs page used for each entry. If an entry's docs cannot be found or read, say so, and carry nothing for that entry into Step 7. Never propose a change from memory.
### Step 6: Re-check Cursor CLI and Aider
Cursor CLI and Aider were left out of the templates for want of one confirmation each: Cursor CLI's skills loading in the CLI (its editor docs list skills folders, the CLI's did not), and Aider's skills support and an interactive first prompt. Re-check both against the same template rule as Step 5: the docs must confirm both that the agent loads the installed Plan2Code skills and that it starts an interactive session with a first prompt.
Propose a new `template` entry only when both are confirmed, in the shape of the existing entries (`id`, `name`, `command`, `prompt` worded for that agent's skill invocation, `args` with the prompt in the vendor's documented first-prompt form, `bypassArgs`, `modelArgs`). When one side is still unconfirmed, say which and propose nothing.
### Step 7 — Show the diff
For `models.json`, compare the discovered list with the current one by `id` and show one table:
| Change | id | Current label | Proposed label | Source |
| --- | --- | --- | --- | --- |
| added | `new-id` | — | New label | `devin models list` |
| gone | `old-id` | Old label | — | not in `devin models list` |
| relabeled | `same-id` | Old label | New label | Claude Code docs: <page> |
- **added:** offered by the CLI, not in the file.
- **gone:** in the file, no longer offered.
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style.
For `agents.json`, show one table with one row per changed field:
| Change | Entry | Field | Current | Proposed | Source |
| --- | --- | --- | --- | --- | --- |
| changed | `claude` | `install.win[0].run` | old command | new command | <vendor docs page> |
| added | `cursor` | new template | | template entry | <vendor docs page> |
| gone | `gemini` | whole entry | template | | skills no longer confirmed |
Summarize unchanged entries as a count under each table ("19 Devin entries unchanged", "3 built-ins unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If all tables are empty, say the files are current and stop.
### Step 8 — Approve each change
Ask about each row, one at a time: **yes**, **no**, or **edit** (they type the value to use). Write nothing until every row has an answer. A "no" leaves that entry exactly as it is today.
### Step 9 — Edit the files
Apply only the approved rows:
- Keep `_note` in `models.json` and `schema` in `agents.json` verbatim.
- Keep the existing order. Remove a **gone** entry where it stands, change a **changed** or **relabeled** value in place, and append each **added** entry at the end of its list.
- Write two-space-indented JSON with a trailing newline, matching each file's current formatting.
### Step 10 — Validate
Check the edited files against every rule under Validation rules. On a failure, show the rule and the entry that broke it, and go back to Step 8 for the affected rows. Do not run tests on a file that fails validation.
### Step 11 — Test
Run `npm test` from the repo root and report the result honestly: pass, or the failing suite and its output. Never describe a failing run as passing.
### Step 12 — Remind about the release
A launcher data change reaches people only with the next release. Remind the maintainer to add a `CHANGELOG.md` line and keep `CHANGELOG.md`, `version.json` and `package.json` on the same version — `/plan2code-changelog` does both.
### Step 13 — Suggest a commit
Suggest a one-line commit message that says what changed, and do not run it:
```bash
git add src/launcher/models.json src/launcher/agents.json
git commit -m "Refresh the launcher's model menu and agent install data"
```
Give `add` and `commit` as two separate commands (Windows PowerShell 5.1 has no `&&`).
## Validation rules
Check every rule before `npm test` (Step 10). They mirror the shipped-file tests in `scripts/test-launcher.mjs` ("the shipped models.json is curated Devin at low/medium/high only") and `scripts/test-agent-lookup.mjs` (the shipped `agents.json` loads clean) plus the menus' own needs:
**`models.json`:**
- The file is valid JSON.
- `_note` is present and unchanged from what Step 2 read.
- `claude` and `devin` are both non-empty arrays; `codex` is an array (empty is allowed).
- `devin` has at most 30 entries.
- Every entry in `claude`, `devin` and `codex` has a non-empty string `id` and a non-empty string `label`.
- Ids are unique within each list, and labels are unique within each list.
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
**`agents.json`:**
- The file is valid JSON, `schema` is `1`, and `agents` is a non-empty array.
- Ids are unique, and `kind` is `builtin` or `template` on every entry.
- The `builtin` entries are exactly `claude`, `devin` and `codex`, and each carries a non-empty `installUrl`, an `install` list under each of `win`, `mac` and `linux` (every line a non-empty `label` and `run`), and `installDirs` under the same keys.
- Every entry has a non-empty `id`, `name` and `command`; `name` is at most 60 characters.
- Every `template` entry would pass `normalizeAgents()` in `src/web-console/agents.mjs` with no warnings (the check `scripts/test-agent-lookup.mjs` runs): a kebab-case `id` that is not a built-in id, `args`, `bypassArgs` and `modelArgs` lists of strings when present.
- Every `template` entry's docs still confirm both skill loading and an interactive first prompt (Steps 5 and 6); the maintainer approved any removal this breaks.
**Warn on renames.** When an entry is **gone** and a near-identical id is **added** in the same list (a changed version number or suffix, say `glm-5-3-high` → `glm-5-4-high`), call the pair out before approval as a likely rename. People's own lists in `~/.plan2code/models.json` merge with the shipped one by id (`mergeModels()` in `src/launcher/plan2code.js`), so a renamed id can bring back a user's old copy of the entry beside the new one. Approve the pair knowingly, or keep the old id.
## Rules
- **Never commit and never push** — Step 13 suggests the commit; the maintainer runs it.
- **Touch only `src/launcher/models.json` and `src/launcher/agents.json`**, plus `CHANGELOG.md` only if the maintainer asks for the release line.
- **Nothing is written before every row is answered** (Step 8).
- **Never install this skill** — never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
@@ -1,116 +0,0 @@
---
name: plan2code-model-update
description: "Refresh the plan2code launcher's curated model menu in src/launcher/models.json from `devin models list` and Claude Code's documented model aliases, with the maintainer approving every change before anything is written. Use this skill when the user says 'update the models', 'refresh models.json', 'new Claude model', 'devin models changed', or otherwise asks to bring the launcher's model list up to date."
---
# Plan2Code Model Update
Bring the launcher's curated model menu (`src/launcher/models.json`) up to date with the models each CLI offers today. Discover what Devin and Claude Code currently offer, show the maintainer a diff against the shipped file, apply only the changes they approve, validate the file, and run `npm test`. This skill never commits.
**Repo-local by design.** This skill lives in the repo's `.claude/skills/` and is intentionally NOT wired into `install.js` — it is a maintainer dev tool, not part of the shipped product, so it is never installed to `~/.claude/skills/`. Do **not** copy it there: the uninstaller (`uninstallSkills()` in `install.js`) and every re-install (`install()`) both run `cleanLegacyPaths()`, which deletes every entry matching `/^plan2code-/` under `~/.claude/skills/` (the `LEGACY_PATHS` row for Claude Code skills), so a copy placed there would be silently removed.
**Terminal only.** This skill runs in the terminal, with no web console session. Ask every question here.
## Workflow
### Step 1 — Preflight
Run from the repo root (the folder holding `install.js` and `src/launcher/`). Run `git status --porcelain -- src/launcher/models.json`. If it prints anything, warn — do not stop:
> `src/launcher/models.json` already has uncommitted changes. The diff below compares against the file as it stands on disk, including those changes.
### Step 2 — Read the current file
Read `src/launcher/models.json`. It has three keys: `_note` (a string), `claude` and `devin` (each an array of `{ "id", "label" }`). Keep the `_note` text exactly as read — Step 7 writes it back verbatim and the Validation rules check it.
### Step 3 — Discover Devin's models
If `devin` is on PATH (`command -v devin` in bash, `Get-Command devin` in PowerShell), run:
```bash
devin models list
```
Show its raw output to the maintainer before any interpretation — the format is not a stable contract. The output is long (hundreds of ids across about twenty families), so save it to a scratch file outside the repo, say where, and show the family headings in full. From it, take the explicit ids at Low, Medium and High effort only, plus `adaptive`. Skip every id the Validation rules forbid (`xhigh`, `max`, `fast`, `priority` endings), and also skip `none`-effort ids, ids with no effort suffix (such as `swe-1-7`, which is a Max model), and `fusion-*` combinations.
The 30-entry cap means the file can never hold every family at three efforts. Propose additions by family — newest and most-used first — and say how many entries that leaves.
If `devin` is not on PATH or the command fails, say so with the error, and switch to **guided manual edits** for Devin: ask the maintainer which ids to add, remove or relabel, one at a time, and carry those into Step 5 as the proposed list.
### Step 4 — Discover Claude Code's models
Look up Claude Code's current model documentation — the model configuration page in the Claude Code docs. Locate it on each run (search the Claude Code docs for model configuration) rather than using a remembered URL; docs move. List the documented model aliases (for example `default`, `sonnet`, `opus`, `haiku`, `opusplan`) and what each one means, and name the page you used. Keep `default` as the file's first entry even though the docs call it a special value rather than an alias. Bracketed aliases such as `opus[1m]` are valid ids; propose them only when the maintainer wants them in the menu.
If the lookup fails or the page does not list aliases, say so, and switch to **guided manual edits** for Claude, exactly as in Step 3.
### Step 5 — Show the diff
For each CLI, compare the discovered list with the current one by `id` and show one table:
| Change | id | Current label | Proposed label | Source |
| --- | --- | --- | --- | --- |
| added | `new-id` | — | New label | `devin models list` |
| gone | `old-id` | Old label | — | not in `devin models list` |
| relabeled | `same-id` | Old label | New label | Claude Code docs: <page> |
- **added:** offered by the CLI, not in the file.
- **gone:** in the file, no longer offered.
- **relabeled:** same `id`, a better or changed label. Propose a label in the file's existing style.
Summarize unchanged entries as a count under the table ("19 Devin entries unchanged") instead of listing them. If approving every **added** Devin row would take the list past 30 entries, say so above the table and by how many. Call out any likely rename before approval (see the rename warning under Validation rules). If both tables are empty, say the file is current and stop.
### Step 6 — Approve each change
Ask about each row, one at a time: **yes**, **no**, or **edit the label** (they type the label to use). Write nothing until every row has an answer. A "no" leaves that entry exactly as it is today.
### Step 7 — Edit `models.json`
Apply only the approved rows:
- Keep `_note` verbatim.
- Keep the existing order. Remove a **gone** entry where it stands, change a **relabeled** label in place, and append each **added** entry at the end of its list.
- Write two-space-indented JSON with a trailing newline, matching the file's current formatting.
### Step 8 — Validate
Check the edited file against every rule under Validation rules. On a failure, show the rule and the entry that broke it, and go back to Step 6 for the affected rows. Do not run tests on a file that fails validation.
### Step 9 — Test
Run `npm test` from the repo root and report the result honestly: pass, or the failing suite and its output. Never describe a failing run as passing.
### Step 10 — Remind about the release
A launcher model change reaches people only with the next release. Remind the maintainer to add a `CHANGELOG.md` line and keep `CHANGELOG.md`, `version.json` and `package.json` on the same version — `/plan2code-changelog` does both.
### Step 11 — Suggest a commit
Suggest a one-line commit message that says what changed, and do not run it:
```bash
git add src/launcher/models.json
git commit -m "Refresh the launcher's model menu"
```
Give `add` and `commit` as two separate commands (Windows PowerShell 5.1 has no `&&`).
## Validation rules
Check every rule before `npm test` (Step 8). They mirror the shipped-file test in `scripts/test-launcher.mjs` ("the shipped models.json is curated Devin at low/medium/high only") plus the menu's own needs:
- The file is valid JSON.
- `_note` is present and unchanged from what Step 2 read.
- `claude` and `devin` are both non-empty arrays.
- `devin` has at most 30 entries.
- Every entry has a non-empty string `id` and a non-empty string `label`.
- Ids are unique within each list, and labels are unique within each list.
- No Devin id ends in `xhigh`, `max`, `fast` or `priority`.
**Warn on renames.** When an entry is **gone** and a near-identical id is **added** in the same list (a changed version number or suffix, say `glm-5-3-high` → `glm-5-4-high`), call the pair out before approval as a likely rename. People's own lists in `~/.plan2code/models.json` merge with the shipped one by id (`mergeModels()` in `src/launcher/plan2code.js`), so a renamed id can bring back a user's old copy of the entry beside the new one. Approve the pair knowingly, or keep the old id.
## Rules
- **Never commit and never push** — Step 11 suggests the commit; the maintainer runs it.
- **Touch only `src/launcher/models.json`**, plus `CHANGELOG.md` only if the maintainer asks for the release line.
- **Nothing is written before every row is answered** (Step 6).
- **Never install this skill** — never add it to `install.js`, and never copy it to `~/.claude/skills/` (the uninstaller deletes `plan2code-*` entries there).
+8
View File
@@ -2124,6 +2124,12 @@ const LAUNCHER_STATE = path.join(os.homedir(), '.plan2code', 'launcher.json');
// compares it with the version.json written beside it.
const UPDATE_CHECK_SRC = path.join(__dirname, 'src', 'web-console', 'update-check.mjs');
const UPDATE_CHECK_DEST = path.join(path.dirname(LAUNCHER_DEST), 'update-check.mjs');
// The shared agent list and lookup rule live beside the launcher so the command, the console
// and the app all read one copy; both are overwritten on every install.
const AGENTS_SRC = path.join(__dirname, 'src', 'launcher', 'agents.json');
const AGENTS_DEST = path.join(path.dirname(LAUNCHER_DEST), 'agents.json');
const AGENT_LOOKUP_SRC = path.join(__dirname, 'src', 'web-console', 'agent-lookup.mjs');
const AGENT_LOOKUP_DEST = path.join(path.dirname(LAUNCHER_DEST), 'agent-lookup.mjs');
const LAUNCHER_VERSION_DEST = path.join(path.dirname(LAUNCHER_DEST), 'version.json');
// What a global install put on this machine, so `plan2code update` reinstalls exactly that.
const INSTALL_RECORD = path.join(os.homedir(), '.plan2code', 'install.json');
@@ -2483,6 +2489,8 @@ async function installLauncher({ quiet = false, unattended = false } = {}) {
// Models the user added in User Preferences live in ~/.plan2code/models.json and are untouched.
fs.copyFileSync(MODELS_SRC, MODELS_DEST);
fs.copyFileSync(UPDATE_CHECK_SRC, UPDATE_CHECK_DEST);
fs.copyFileSync(AGENTS_SRC, AGENTS_DEST);
fs.copyFileSync(AGENT_LOOKUP_SRC, AGENT_LOOKUP_DEST);
fs.writeFileSync(LAUNCHER_VERSION_DEST, JSON.stringify(projectVersion, null, 2) + '\n');
if (process.platform !== 'win32') fs.chmodSync(LAUNCHER_DEST, 0o755);
console.log(` ${COLORS.GREEN}${SYMBOLS.SUCCESS}${COLORS.RESET} Installed: ${LAUNCHER_DEST}`);
+1 -1
View File
@@ -11,7 +11,7 @@
"fix:eol": "node scripts/fix-line-endings.mjs",
"play": "node scripts/play.mjs",
"pretest": "node scripts/fix-line-endings.mjs",
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node scripts/node-test.mjs scripts/test-line-endings.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-pointers.mjs scripts/test-console-wire-budgets.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-activities.mjs scripts/test-web-console-activities-rapids.mjs scripts/test-web-console-activities-bounce.mjs scripts/test-web-console-activities-bounce-game.mjs scripts/test-web-console-activities-ghoul.mjs scripts/test-web-console-activities-ghoul-graveyard.mjs scripts/test-web-console-activities-ghoul-grounds.mjs scripts/test-web-console-activities-ghoul-chapel.mjs scripts/test-web-console-activities-ghoul-sanatorium.mjs scripts/test-web-console-activities-ghoul-village.mjs scripts/test-web-console-activities-ghoul-mine.mjs scripts/test-web-console-activities-ghoul-carnival.mjs scripts/test-web-console-activities-ghoul-frozen.mjs scripts/test-web-console-activities-ghoul-bog.mjs scripts/test-web-console-activities-ghoul-bogboat.mjs scripts/test-web-console-activities-ghoul-ride.mjs scripts/test-web-console-activities-ghoul-cart.mjs scripts/test-web-console-activities-ghoul-sled.mjs scripts/test-web-console-activities-ghoul-banister.mjs scripts/test-web-console-activities-ghoul-gurney.mjs scripts/test-web-console-activities-ghoul-hearse.mjs scripts/test-web-console-activities-ghoul-wagon.mjs scripts/test-web-console-activities-ghoul-pew.mjs scripts/test-web-console-activities-ghoul-mower.mjs scripts/test-web-console-activities-ghoul-tray.mjs scripts/test-web-console-activities-ghoul-arms.mjs scripts/test-web-console-activities-ghoul-dice.mjs scripts/test-web-console-activities-ghoul-gameover.mjs scripts/test-web-console-activities-ghoul-intro.mjs scripts/test-web-console-activities-ghoul-bossintro.mjs scripts/test-web-console-activities-ghoul-story.mjs scripts/test-web-console-activities-ghoul-bones.mjs scripts/test-web-console-activities-ghoul-retry.mjs scripts/test-web-console-activities-bounce-cars.mjs scripts/test-web-console-tones.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-skill-test-runs.mjs scripts/test-launcher.mjs scripts/test-agents-file.mjs scripts/test-agent-lookup.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-loop.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-web-console-page-send.mjs scripts/test-web-console-page-loop.mjs scripts/test-web-console-page-activities.mjs scripts/test-web-console-page-setup.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
},
"devDependencies": {
"gpt-tokenizer": "2.9.0",
File diff suppressed because it is too large. Load diff
@@ -42,6 +42,7 @@ pub struct ConsoleSupervisor {
console_dir: PathBuf,
project_dir: PathBuf,
embed_origin: String,
workflow: String,
session: ConsoleSession,
stopped: bool,
}
@@ -177,12 +178,25 @@ impl ConsoleSupervisor {
/// the project folder with `PLAN2CODE_EMBED_ORIGIN` set, and keep the
/// session it prints.
pub fn start(project_dir: PathBuf, embed_origin: String) -> Result<ConsoleSupervisor, String> {
Self::start_with_workflow(project_dir, embed_origin, "dashboard")
}
/// `start` for another workflow: today only `setup`, the agent-less page
/// the app itself opens for Set up an agent (the one exception to the
/// app never starting a console of its own).
pub fn start_with_workflow(
project_dir: PathBuf,
embed_origin: String,
workflow: &str,
) -> Result<ConsoleSupervisor, String> {
let console_dir = find_console_dir()?;
let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?;
let session =
Self::open_session(&console_dir, &project_dir, &embed_origin, None, workflow)?;
Ok(ConsoleSupervisor {
console_dir,
project_dir,
embed_origin,
workflow: workflow.to_string(),
session,
stopped: false,
})
@@ -211,6 +225,7 @@ impl ConsoleSupervisor {
console_dir,
project_dir,
embed_origin,
workflow: "dashboard".to_string(),
session,
stopped: false,
})
@@ -221,12 +236,13 @@ impl ConsoleSupervisor {
project_dir: &Path,
embed_origin: &str,
resume: Option<&str>,
workflow: &str,
) -> Result<ConsoleSession, String> {
let mut command = node_command(console_dir);
command.arg("open");
match resume {
Some(sid) => command.args(["--resume", sid, "--no-open"]),
None => command.args(["--workflow", "dashboard", "--no-open"]),
None => command.args(["--workflow", workflow, "--no-open"]),
};
let output = command
.current_dir(project_dir)
@@ -318,10 +334,14 @@ impl ConsoleSupervisor {
}
let sid = self.session.sid.clone();
let on_disk = session_on_disk(&sid);
let (console_dir, project_dir, embed_origin) =
(&self.console_dir, &self.project_dir, &self.embed_origin);
let (console_dir, project_dir, embed_origin, workflow) = (
&self.console_dir,
&self.project_dir,
&self.embed_origin,
&self.workflow,
);
self.session = resume_or_fresh(&sid, on_disk, |resume| {
Self::open_session(console_dir, project_dir, embed_origin, resume)
Self::open_session(console_dir, project_dir, embed_origin, resume, workflow)
})?;
self.stopped = false;
Ok(true)
+1
View File
@@ -12,6 +12,7 @@ pub mod loop_driver;
pub mod loop_notify;
pub mod loop_report;
pub mod loop_tools;
pub mod models;
pub mod node_check;
pub mod project;
pub mod pty_host;
+177 -22
View File
@@ -5,13 +5,14 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, OnceLock};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
use plan2code_app_lib::agents::{self, Agent, PermissionMode};
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
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::loop_driver::{self, Hooks, LastLoop, LoopFacts, LoopSlot};
use plan2code_app_lib::models;
use plan2code_app_lib::node_check;
use plan2code_app_lib::project::{self, ProjectDir};
use plan2code_app_lib::quit_prompt::{loop_quit_prompt, quit_prompt, QuitCase};
@@ -87,28 +88,34 @@ fn platform_info() -> serde_json::Value {
// warnings about agents.json.
#[tauri::command]
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.
// "Check again" also works the PATH out again and re-reads the shipped
// agent list, so a CLI whose installer added a new folder to PATH, or a
// list an update rewrote, is seen without restarting the app.
if refresh == Some(true) {
node_check::refresh_path();
agents::refresh_agent_list();
}
// 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
// Built-ins from the shipped list first, then the custom agents, read
// afresh on every call so "Check again" sees a change to agents.json.
// `state` is the shared lookup's answer: found (on PATH), outside (on
// the saved PATH, in npm's folder or an install folder: needs setup,
// not missing) or missing. `folder` names where an outside hit lives.
let mut entries: Vec<_> = agents::builtin_entries()
.iter()
.map(|&kind| {
let at = agents::installed_at(kind);
.map(|entry| {
let hit = agents::lookup_agent(entry);
serde_json::json!({
"id": kind.id(),
"label": kind.label(),
"installed": at.is_some(),
// Which binary was used (Task 9.9), when one was found.
"path": at.map(|p| p.to_string_lossy().into_owned()),
"installHint": kind.install_hint(),
"installUrl": kind.install_url(),
"hasEffort": kind.has_effort(),
"id": entry.id,
"label": entry.name,
"installed": hit.state == "found",
"state": hit.state,
"path": hit.path.map(|p| p.to_string_lossy().into_owned()),
"folder": hit.folder.map(|p| p.to_string_lossy().into_owned()),
"installHint": agents::install_hint(entry),
"installUrl": entry.install_url,
"hasEffort": agents::has_effort(&entry.id),
"custom": false,
"models": null,
"models": models::models_for_builtin(&entry.id),
})
})
.collect();
@@ -119,6 +126,7 @@ fn agent_availability(refresh: Option<bool>) -> serde_json::Value {
"id": custom.id,
"label": custom.name,
"installed": at.is_some(),
"state": if at.is_some() { "found" } else { "missing" },
"path": at.map(|p| p.to_string_lossy().into_owned()),
"installHint": null,
"installUrl": null,
@@ -145,11 +153,11 @@ fn open_install_page(id: String) -> Result<(), String> {
}
let mut command = if cfg!(windows) {
let mut c = std::process::Command::new("rundll32.exe");
c.args(["url.dll,FileProtocolHandler", url]);
c.args(["url.dll,FileProtocolHandler", &url]);
c
} else if cfg!(target_os = "macos") {
let mut c = std::process::Command::new("open");
c.arg(url);
c.arg(&url);
c
} else {
let browser = std::env::var("BROWSER")
@@ -157,7 +165,7 @@ fn open_install_page(id: String) -> Result<(), String> {
.filter(|b| !b.is_empty())
.unwrap_or_else(|| "xdg-open".to_string());
let mut c = std::process::Command::new(browser);
c.arg(url);
c.arg(&url);
c
};
command
@@ -298,6 +306,13 @@ fn take_announced(
if !on_disk(&notice.sid) {
return false;
}
// An agent-less setup session never takes the window by announcing
// itself (NFR-2): the only setup console allowed here is the one the app
// itself started for Set up an agent, which carries no announce
// variables and drives the frame through console_setup_start instead.
if notice.workflow == "setup" {
return false;
}
if let Ok(mut guard) = state.console.lock() {
match guard.as_mut() {
Some(sup) => sup.follow(&notice.url, &notice.sid),
@@ -857,8 +872,10 @@ fn change_project(
/// The console the agent opened, alive and as it is now, or restarted on the
/// same session when it died. The app never starts a dashboard of its own:
/// the agent does, by running the skill, and announces it. Nothing to show yet
/// is an error the page words for the person.
/// the agent does, by running the skill, and announces it. The one exception
/// is `console_setup_start` below: the agent-less `setup` page, which is no
/// dashboard and has no agent to announce it, so the app opens it itself.
/// Nothing to show yet is an error the page words for the person.
#[tauri::command]
fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String> {
console_start_impl(&state)
@@ -901,6 +918,44 @@ fn console_stop(state: State<'_, AppState>) -> Result<(), String> {
Ok(())
}
/// Set up an agent: the agent-less `setup` page shown in this window. This
/// is the one exception to the app never starting a console of its own (see
/// `console_start` above): the setup page is not a dashboard and has no
/// agent behind it, and nothing else can open it here. The console is
/// started the way the `plan2code` command starts it (`console.mjs open
/// --workflow setup`, no announce variables, so it never claims the window
/// on its own), and the URL comes back for the page to frame. When
/// `console.mjs` cannot be found the error names it, and the page shows its
/// plain "skills are missing" checklist row.
#[tauri::command]
fn console_setup_start(
app: tauri::AppHandle,
state: State<'_, AppState>,
) -> Result<serde_json::Value, String> {
let origin = window_origin(&app);
console_setup_start_impl(&state, &origin)
}
fn console_setup_start_impl(state: &AppState, origin: &str) -> Result<serde_json::Value, String> {
refuse_while_looping(state, "console")?;
let dir = state
.project
.lock()
.ok()
.and_then(|p| p.as_ref().map(|p| p.dir.clone()))
.ok_or("no project folder chosen")?;
// The setup console starts before the old one is stopped: a failed open
// (a missing console.mjs, a dead session store) leaves what was showing.
let sup = ConsoleSupervisor::start_with_workflow(dir, origin.to_string(), "setup")?;
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
if let Some(mut old) = guard.take() {
let _ = old.stop();
}
let session = serde_json::to_value(sup.session()).map_err(|e| e.to_string())?;
*guard = Some(sup);
Ok(session)
}
// What the setup screen shows about the agent a loop would use: the running
// agent's launch choice, else what the launcher chose.
#[tauri::command]
@@ -1255,6 +1310,7 @@ fn main() {
console_start,
console_status,
console_stop,
console_setup_start,
loop_start,
loop_notify_test,
loop_facts,
@@ -1537,6 +1593,105 @@ mod tests {
.unwrap_or(false)
}
#[test]
fn a_setup_session_is_never_taken_from_an_announce() {
// NFR-2: the only setup page in the window is the one the app itself
// opened for Set up an agent. Whatever announces "setup" is refused,
// even a session the console store really holds.
let state = state_for("project-a");
let mut setup = notice("setup-console");
setup.workflow = "setup".into();
assert!(!take_announced(
&state,
&setup,
app_origin().to_string(),
|_| true
));
assert!(state.console.lock().unwrap().is_none(), "nothing adopted");
}
#[test]
fn the_setup_console_needs_a_project_to_open_in() {
let state = AppState::default();
let error = console_setup_start_impl(&state, "http://127.0.0.1:1430")
.expect_err("no project, no setup page");
assert!(error.contains("project"), "{error}");
}
#[test]
fn the_setup_console_starts_on_the_setup_workflow() {
// Same setup as `real_console` below: the repo's own console source,
// a throwaway session home, no browser, no in-app variables.
let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
if !have_node() || !console_dir.join("console.mjs").is_file() {
eprintln!("skipping: node or the console source is not here");
return;
}
let pid = std::process::id();
let project = std::env::temp_dir().join(format!("p2c-setup-test-project-{pid}"));
std::fs::create_dir_all(&project).unwrap();
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir);
std::env::set_var(
"PLAN2CODE_CONSOLE_HOME",
std::env::temp_dir().join(format!("p2c-setup-test-home-{pid}")),
);
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
for name in [
"PLAN2CODE_IN_APP",
"PLAN2CODE_APP_ANNOUNCE",
"PLAN2CODE_APP_TOKEN",
"PLAN2CODE_CONSOLE_SID",
] {
std::env::remove_var(name);
}
let state = state_for("project-a");
state.project.lock().unwrap().as_mut().unwrap().dir = project.clone();
let session = console_setup_start_impl(&state, "http://127.0.0.1:1430")
.expect("the setup page opens");
let url = session["url"].as_str().unwrap();
assert!(url.starts_with("http://127.0.0.1:"), "{url}");
let sid = session["sid"].as_str().unwrap();
// It is an agent-less setup session on disk, not a dashboard.
let home = std::env::var("PLAN2CODE_CONSOLE_HOME").unwrap();
let on_disk: serde_json::Value = serde_json::from_str(
&std::fs::read_to_string(
PathBuf::from(home)
.join("sessions")
.join(sid)
.join("state.json"),
)
.expect("the session's own state"),
)
.unwrap();
assert_eq!(on_disk["workflow"].as_str(), Some("setup"), "{on_disk}");
let _ = state.console.lock().unwrap().take().unwrap().stop();
}
#[test]
fn availability_reports_each_builtins_lookup_state() {
// Every entry carries the shared lookup's state: found (on PATH),
// outside (needing setup, not missing) or missing, with `folder` for
// where an outside hit lives.
let json = agent_availability(None);
let entries = json["agents"].as_array().unwrap();
assert!(!entries.is_empty());
let mut builtins = 0;
for entry in entries {
let state = entry["state"].as_str().unwrap();
assert!(["found", "outside", "missing"].contains(&state), "{entry}");
if entry["custom"] == false {
builtins += 1;
assert!(entry["installUrl"].is_string() || entry["installUrl"].is_null());
}
if state == "found" {
assert_eq!(entry["installed"], true, "{entry}");
assert!(entry["path"].is_string(), "{entry}");
}
}
assert!(builtins >= 3, "claude, devin and codex are listed");
}
/// A real console, the same way `tests/console_supervisor.rs` sets one
/// up: `PLAN2CODE_CONSOLE_DIR` points at the repo's own console source,
/// `PLAN2CODE_CONSOLE_HOME` keeps its session files out of the real one.
+237
View File
@@ -0,0 +1,237 @@
//! The launch card's model menu for a built-in agent: the same list the
//! `plan2code` launcher's model question offers (`listModels` in
//! `src/launcher/plan2code.js`). The shipped `bin/models.json` (refreshed by
//! every install, and baked in here as the fallback) comes first, then the
//! user's own additions in `~/.plan2code/models.json` (written by User
//! Preferences) whose ids the shipped list does not already have. Custom
//! agents never come through here: their menu is their own `models` in
//! agents.json.
use serde_json::Value;
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use crate::agents::CustomModel;
/// The shipped model menu, baked in beside agents.json so the launch card
/// still offers a list when the installed `bin/models.json` cannot be read.
const BAKED_MODELS: &str = include_str!("../../../src/launcher/models.json");
/// The shipped `bin/models.json`: `PLAN2CODE_MODELS_DIR/bin/models.json` when
/// the tests relocate the models home, else the launcher's own
/// `~/.plan2code/bin/models.json` (`PLAN2CODE_LAUNCHER_DIR` still honored).
fn shipped_models_file() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("PLAN2CODE_MODELS_DIR") {
return Some(PathBuf::from(dir).join("bin").join("models.json"));
}
crate::versions::launcher_dir().map(|dir| dir.join("models.json"))
}
/// The user's `models.json`: `PLAN2CODE_MODELS_DIR/models.json` when set, else
/// `~/.plan2code/models.json` (the same file the console's User Preferences
/// writes, `USER_MODELS_FILE` in files.mjs).
fn user_models_file() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("PLAN2CODE_MODELS_DIR") {
return Some(PathBuf::from(dir).join("models.json"));
}
Some(std::env::home_dir()?.join(".plan2code").join("models.json"))
}
/// `[{ id, label }]` from a parsed models file for one agent; anything
/// malformed is skipped (`modelEntries` in plan2code.js: an entry needs a
/// non-empty string `id` and a string `label`; a blank label is no label).
fn model_entries(file: &Value, cli_id: &str) -> Vec<CustomModel> {
let mut models = Vec::new();
let Some(items) = file.get(cli_id).and_then(Value::as_array) else {
return models;
};
for item in items {
let Some(id) = item.get("id").and_then(Value::as_str) else {
continue;
};
let id = id.trim();
if id.is_empty() {
continue;
}
let Some(label) = item.get("label").and_then(Value::as_str) else {
continue;
};
let label = label.trim();
models.push(CustomModel {
id: id.to_string(),
label: (!label.is_empty()).then(|| label.to_string()),
});
}
models
}
/// The shipped list first, then the user's additions the shipped list does not
/// already have (`mergeModels` in plan2code.js).
fn merge_models(shipped: Vec<CustomModel>, user: Vec<CustomModel>) -> Vec<CustomModel> {
let mut seen: HashSet<String> = shipped.iter().map(|m| m.id.clone()).collect();
let mut out = shipped;
out.extend(user.into_iter().filter(|m| seen.insert(m.id.clone())));
out
}
fn read_json(file: &Path) -> Option<Value> {
serde_json::from_str(&std::fs::read_to_string(file).ok()?).ok()
}
/// One built-in's menu from explicit file paths, so tests never touch the real
/// home. A shipped file that is missing or will not parse falls back to the
/// baked list; a user file the same way means no additions.
fn models_for(
cli_id: &str,
shipped_file: Option<&Path>,
user_file: Option<&Path>,
) -> Vec<CustomModel> {
let shipped = shipped_file
.and_then(read_json)
.or_else(|| serde_json::from_str(BAKED_MODELS).ok())
.unwrap_or(Value::Null);
let user = user_file.and_then(read_json).unwrap_or(Value::Null);
merge_models(
model_entries(&shipped, cli_id),
model_entries(&user, cli_id),
)
}
/// The launch card's model menu for the built-in `cli_id` (empty when it has
/// none, like the launcher's skipped question; `models` on a custom agent's
/// agents.json entry covers customs).
pub fn models_for_builtin(cli_id: &str) -> Vec<CustomModel> {
models_for(
cli_id,
shipped_models_file().as_deref(),
user_models_file().as_deref(),
)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn model(id: &str, label: Option<&str>) -> CustomModel {
CustomModel {
id: id.to_string(),
label: label.map(str::to_string),
}
}
fn temp_dir(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("models-test-{}-{tag}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(dir.join("bin")).unwrap();
dir
}
#[test]
fn model_entries_keeps_only_id_and_label_pairs() {
let file = json!({
"_note": "not a list",
"claude": [
{ "id": "sonnet", "label": "Sonnet - latest" },
{ "id": "opus" },
{ "id": " ", "label": "blank id" },
{ "label": "no id" },
"not an object",
{ "id": "haiku", "label": " " },
{ "id": "fable", "label": "Fable" }
]
});
assert_eq!(
model_entries(&file, "claude"),
vec![
model("sonnet", Some("Sonnet - latest")),
model("haiku", None),
model("fable", Some("Fable")),
]
);
assert!(model_entries(&file, "codex").is_empty());
assert!(model_entries(&Value::Null, "claude").is_empty());
}
#[test]
fn merge_models_appends_only_the_user_ids_the_shipped_list_lacks() {
let shipped = vec![model("a", Some("A")), model("b", Some("B"))];
let user = vec![
model("b", Some("user's B")),
model("c", Some("C")),
model("c", Some("dupe")),
];
assert_eq!(
merge_models(shipped, user),
vec![
model("a", Some("A")),
model("b", Some("B")),
model("c", Some("C"))
]
);
}
#[test]
fn models_for_merges_the_shipped_and_user_files() {
let dir = temp_dir("merge");
std::fs::write(
dir.join("bin").join("models.json"),
r#"{ "claude": [{ "id": "sonnet", "label": "Sonnet" }] }"#,
)
.unwrap();
std::fs::write(
dir.join("models.json"),
r#"{ "claude": [
{ "id": "sonnet", "label": "ignored dupe" },
{ "id": "my-new", "label": "Mine" }
] }"#,
)
.unwrap();
assert_eq!(
models_for(
"claude",
Some(&dir.join("bin").join("models.json")),
Some(&dir.join("models.json"))
),
vec![
model("sonnet", Some("Sonnet")),
model("my-new", Some("Mine"))
]
);
}
#[test]
fn models_for_falls_back_to_the_baked_list() {
// No shipped file at all (or one that will not parse): the baked copy
// of src/launcher/models.json still offers its list.
let dir = temp_dir("baked");
let missing = dir.join("bin").join("models.json");
let baked = models_for("claude", Some(&missing), Some(&missing));
assert_eq!(baked.first().map(|m| m.id.as_str()), Some("default"));
assert!(baked.len() > 1);
std::fs::write(&missing, "{ nope").unwrap();
assert!(models_for("claude", Some(&missing), Some(&missing)).len() > 1);
assert!(models_for("codex", Some(&missing), Some(&missing)).is_empty());
}
#[test]
fn models_for_ignores_an_unreadable_user_file() {
let dir = temp_dir("user");
let shipped = dir.join("bin").join("models.json");
let user = dir.join("models.json");
std::fs::write(
&shipped,
r#"{ "claude": [{ "id": "sonnet", "label": "S" }] }"#,
)
.unwrap();
std::fs::write(&user, "{ nope").unwrap();
assert_eq!(
models_for("claude", Some(&shipped), Some(&user)),
vec![model("sonnet", Some("S"))]
);
assert_eq!(
models_for("claude", Some(&shipped), None),
vec![model("sonnet", Some("S"))]
);
}
}
+19 -1
View File
@@ -171,9 +171,27 @@ fn parse_reg_query_value(output: &str) -> Option<String> {
})
}
/// The saved system and user PATH as one PATH string (Windows only): what a
/// newly opened terminal gets, kept apart from the process PATH so the agent
/// lookup can answer `saved-path`. "" elsewhere / when tests ask it off
/// (PLAN2CODE_NO_SAVED_PATH, as the launcher's addSavedWindowsPath() honors).
pub fn saved_path_value() -> String {
#[cfg(windows)]
{
if std::env::var_os("PLAN2CODE_NO_SAVED_PATH").is_some_and(|v| !v.is_empty()) {
return String::new();
}
saved_windows_path().join(";")
}
#[cfg(not(windows))]
{
String::new()
}
}
/// `%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 {
pub(crate) 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('%') {
+3 -4
View File
@@ -165,7 +165,6 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
#[cfg(test)]
mod tests {
use super::*;
use crate::agents::AgentKind;
fn launch_choice(args: &[String]) -> LaunchChoice {
launch_choice_in(args, None)
@@ -181,7 +180,7 @@ mod tests {
#[test]
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
let want = LaunchChoice {
agent: Some(AgentKind::Codex.id().to_string()),
agent: Some("codex".to_string()),
model: Some("gpt-5".into()),
};
assert_eq!(
@@ -210,7 +209,7 @@ mod tests {
assert_eq!(
launch_choice(&args(&["--agent", "claude"])),
LaunchChoice {
agent: Some(AgentKind::Claude.id().to_string()),
agent: Some("claude".to_string()),
model: None
}
);
@@ -239,7 +238,7 @@ mod tests {
assert_eq!(
launch_choice(&args(&["--agent", "devin", "--model"])),
LaunchChoice {
agent: Some(AgentKind::Devin.id().to_string()),
agent: Some("devin".to_string()),
model: None
}
);
+1 -1
View File
@@ -30,7 +30,7 @@ pub struct VersionStatus {
/// `~/.plan2code/bin`, or `PLAN2CODE_LAUNCHER_DIR` when it is set (tests only, the same
/// convention `PLAN2CODE_CONSOLE_HOME` and `PLAN2CODE_APP_AGENT_BIN` already use).
fn launcher_dir() -> Option<PathBuf> {
pub(crate) fn launcher_dir() -> Option<PathBuf> {
if let Ok(dir) = std::env::var("PLAN2CODE_LAUNCHER_DIR") {
return Some(PathBuf::from(dir));
}
@@ -9,7 +9,7 @@ use std::time::{Duration, Instant};
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
use plan2code_app_lib::agents::{
agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV,
agent_launch_spec, builtin_entry, parse_agents_file, Agent, PermissionMode, AGENT_BIN_ENV,
};
mod common;
@@ -113,7 +113,7 @@ impl Harness {
fn start_and_wait_ready(&mut self) {
self.manager
.start(
Agent::Builtin(AgentKind::Claude),
Agent::Builtin(builtin_entry("claude").unwrap()),
None,
None,
PermissionMode::Bypass,
@@ -139,7 +139,7 @@ fn a_second_start_while_running_is_refused() {
let generation = h.manager.snapshot().generation;
let refused = h.manager.start(
Agent::Builtin(AgentKind::Devin),
Agent::Builtin(builtin_entry("devin").unwrap()),
None,
None,
PermissionMode::Bypass,
@@ -160,7 +160,7 @@ fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
let mut h = Harness::new();
h.manager
.start(
Agent::Builtin(AgentKind::Codex),
Agent::Builtin(builtin_entry("codex").unwrap()),
Some("gpt-5".to_string()),
Some("high".to_string()),
PermissionMode::Checked,
+93 -37
View File
@@ -2,7 +2,7 @@
// agent's terminal panel docked at the bottom with a drag handle.
import { mountTerminal } from './terminal.js';
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle } from './meter.js';
import { attentionSignal, barNextSteps, continueKeys, defaultRightFraction, folderName, lastAgentNotice, pickDefaultAgent, taskbarSwitch, windowTitleFor, deadConsoleAction, loopBanner, loopLocks, loopStopLabels, loopWindowTitle } from './meter.js';
const { invoke, Channel } = window.__TAURI__.core;
@@ -49,7 +49,7 @@ 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 launchModelRowEl = document.getElementById('launch-model-row');
const launchEffortRow = document.getElementById('launch-effort-row');
const launchEffortEl = document.getElementById('launch-effort');
const launchBypassEl = document.getElementById('launch-bypass');
@@ -58,6 +58,8 @@ const launchStartBtn = document.getElementById('launch-start');
const firstRunEl = document.getElementById('first-run');
const firstRunListEl = document.getElementById('first-run-list');
const firstRunStartBtn = document.getElementById('first-run-start');
const launchNoticeEl = document.getElementById('launch-notice');
const setupCloseBtn = document.getElementById('setup-close');
const nextStepEl = document.getElementById('next-step');
const nextStepTextEl = document.getElementById('next-step-text');
const nextStepBtn = document.getElementById('next-step-button');
@@ -339,6 +341,11 @@ function populateAgentSelect(selected) {
// Pick the agent to start on and show the card's state for it.
function applyDefaultAgent(remembered) {
// The saved (last used) agent is gone but another works: one line, then
// carry on (FR-13). lastAgentNotice gives the pick it names.
const using = lastAgentNotice(agentList, remembered);
launchNoticeEl.hidden = !using;
if (using) launchNoticeEl.textContent = `${agentLabel(remembered)} (last used) was not found, using ${agentLabel(using)}`;
populateAgentSelect(pickDefaultAgent(agentList, remembered));
refreshLaunchCard();
}
@@ -357,33 +364,63 @@ function installPageButton(id) {
return button;
}
// Shown when no agent CLI is installed, in the first-run checklist and on the
// launch card: what an agent CLI is, each built-in's install command and page,
// and a way to look again once one is installed.
function noAgentExplainer() {
const box = document.createElement('div');
box.className = 'agent-explainer';
const intro = document.createElement('p');
intro.className = 'agent-explainer';
intro.textContent = 'An agent CLI is the AI coding assistant Plan2Code runs for you in its terminal. None was found on PATH. Install one of these:';
const list = document.createElement('ul');
for (const entry of agentList.filter((a) => !a.custom)) {
const item = document.createElement('li');
item.append(`${entry.label}: `);
const code = document.createElement('code');
code.textContent = entry.installHint || '';
item.append(code, installPageButton(entry.id));
list.append(item);
// Where the setup page was opened from, while it is up: the screen to return
// to when it closes or reports agent-found. Null: no setup page up.
let setupReturn = null;
// The Set up an agent button, shown wherever the app says "no agent" (FR-17).
function setupButton(returnTo) {
const btn = document.createElement('button');
btn.type = 'button';
btn.className = 'setup-agent-btn';
btn.textContent = 'Set up an agent';
btn.onclick = () => openAgentSetup(returnTo);
return btn;
}
// Open the console's agent-less setup page in this window (FR-15, FR-17). No
// poll timer: a dead setup page needs no reconnect, and the Back button still
// returns.
async function openAgentSetup(returnTo) {
try {
const session = await invoke('console_setup_start');
setupReturn = returnTo;
hideState();
hideFirstRun();
hideLaunchCard();
markConsoleAlive();
consoleKnown = true;
setupCloseBtn.hidden = false;
loadFrame(session.url);
} catch (error) {
const text = String(error);
// A missing console.mjs means the skills install itself is gone (FR-16).
setAgentStatus(
text.includes('not installed') || text.includes('console.mjs')
? "Plan2Code's skills are missing: run `plan2code update`."
: `Could not open the setup page: ${text}`,
{ error: true }
);
}
const other = document.createElement('p');
other.className = 'agent-explainer';
other.textContent = 'Already use another agent CLI? Add it in User Preferences under Agents.';
const check = document.createElement('button');
check.type = 'button';
check.textContent = 'Check again';
check.onclick = checkAgentsAgain;
box.append(intro, list, other, check);
return box;
}
// The setup page is done: it found an agent (agent-found carries its id) or
// the person pressed Back. Return to where the app was, recheck the agents,
// and pick the found one on the launch card for the person to press Start
// (FR-14, FR-17).
async function finishSetup(foundId) {
if (setupReturn === null) return;
const returnTo = setupReturn;
setupReturn = null;
setupCloseBtn.hidden = true;
currentUrl = null;
frameReady = false;
frame.src = 'about:blank';
invoke('console_stop').catch(() => {});
await loadAgentAvailability(true);
applyDefaultAgent(foundId || (appState && appState.lastAgent) || launchAgentEl.value);
if (returnTo === 'first-run' && appState) showFirstRun(appState);
else showLaunchCard();
}
// Re-read the agents from disk (a CLI installed or a custom agent added since),
@@ -403,7 +440,11 @@ function refreshLaunchCard() {
launchMissingEl.replaceChildren();
if (!installed) {
if (!agentList.some((a) => a.installed)) {
launchMissingEl.append(noAgentExplainer());
launchMissingEl.append('No agent found. ', setupButton('launch-card'));
} else if (info && info.state === 'outside') {
// Found on the saved PATH, in npm's folder or an install folder, but
// not on PATH itself: setup, not a fresh install.
launchMissingEl.append(`${agentLabel(kind)} was found${info.folder ? ` in ${info.folder}` : ''}, but it is not on PATH. `, setupButton('launch-card'));
} else {
launchMissingEl.append(`${agentLabel(kind)} was not found on PATH.`);
if (info && !info.custom) {
@@ -416,15 +457,26 @@ 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();
for (const model of (info && info.custom && info.models) || []) {
// The model dropdown lists what the `plan2code` launcher would ask with:
// built-ins get the shipped + user models.json merge from Rust, customs
// their own agents.json models. An empty list hides the row, like the
// launcher's skipped model question; the first option passes no flag, so
// the agent runs on its own (last-used) model.
const models = (info && info.models) || [];
launchModelEl.replaceChildren();
const noModel = document.createElement('option');
noModel.value = '';
noModel.textContent = "Default (the agent's own model)";
launchModelEl.append(noModel);
for (const model of models) {
const option = document.createElement('option');
option.value = model.id;
if (model.label) option.label = model.label;
launchModelListEl.append(option);
option.textContent = model.label ? `${model.id}: ${model.label}` : model.id;
launchModelEl.append(option);
}
launchModelRowEl.hidden = models.length === 0;
// A model the launcher picked (--model) sticks only while it is listed.
if (appState && models.some((model) => model.id === appState.launchModel)) launchModelEl.value = appState.launchModel;
const levels = info && info.custom ? [] : EFFORT_OPTIONS[kind] || [];
launchEffortRow.hidden = levels.length === 0;
launchEffortEl.replaceChildren();
@@ -495,7 +547,7 @@ function renderFirstRun(state) {
if (agentsKnown.length === 0) {
agentsDetail.textContent = 'Could not check.';
} else if (!anyAgentInstalled) {
agentsDetail.append(noAgentExplainer());
agentsDetail.append('No agent found. ', setupButton('first-run'));
} else {
agentsKnown.forEach((a, i) => {
if (i > 0) agentsDetail.append(', ');
@@ -537,7 +589,7 @@ firstRunStartBtn.onclick = async () => {
async function startAgent(event) {
if (event) event.preventDefault();
const kind = launchAgentEl.value;
const model = launchModelEl.value.trim() || null;
const model = launchModelEl.value || null;
const info = agentAvailability[kind];
const effort = !(info && info.custom) && (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
const mode = launchBypassEl.checked ? 'bypass' : 'checked';
@@ -563,6 +615,7 @@ async function agentAction(command) {
}
launchCard.addEventListener('submit', startAgent);
setupCloseBtn.onclick = () => finishSetup();
restartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
// Only ever enabled once the agent has ended: nothing active to lose, so no confirm.
changeAgentBtn.onclick = () => {
@@ -700,6 +753,9 @@ window.addEventListener('message', (event) => {
} else if (kind === 'attention') {
const signal = attentionSignal(event.data);
if (signal) invoke('set_attention', { signal }).catch(() => {});
} else if (kind === 'agent-found') {
const id = typeof event.data.id === 'string' ? event.data.id : '';
void finishSetup(id || null);
} else if (kind === 'taskbar') {
const on = taskbarSwitch(event.data);
if (on === null) return;
+18 -4
View File
@@ -188,6 +188,17 @@
background: #2a2a2a; color: #ddd; border: 1px solid #555; border-radius: 4px; font: inherit;
}
#launch-missing { margin: 0; font-size: 12px; color: #d7ba7d; }
#launch-notice { margin: 0; font-size: 12px; color: #9ab; }
#launch-notice[hidden] { display: none; }
/* Set up an agent, shown wherever the app says "no agent". */
.setup-agent-btn { font: inherit; font-size: 12px; margin-top: 4px; padding: 3px 10px; cursor: pointer;
background: var(--accent); color: var(--accent-ink); border: 1px solid var(--accent); border-radius: 4px; }
/* The way out of the setup page, over its frame. */
#setup-close { position: absolute; top: 10px; right: 10px; z-index: 2; font: inherit; font-size: 12px;
padding: 4px 10px; border-radius: 6px; cursor: pointer; border: 1px solid var(--rule-2);
background: var(--panel); color: var(--ink); }
#setup-close:hover { background: var(--panel-2); }
#setup-close[hidden] { display: none; }
#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; }
@@ -196,7 +207,7 @@
.agent-explainer code { color: #ddd; }
.agent-explainer button, #launch-missing button { font: inherit; font-size: 12px; margin-left: 6px; padding: 1px 8px; cursor: pointer; }
.agent-explainer .agent-link, #launch-missing .agent-link { background: none; border: 0; padding: 0; color: #75beff; text-decoration: underline; }
#launch-effort-row[hidden] { display: none; }
#launch-effort-row[hidden], #launch-model-row[hidden] { display: none; }
#launch-bypass-row { display: flex; align-items: center; gap: 8px; color: #ccc; font-size: 13px; cursor: pointer; }
#launch-bypass-row input { margin: 0; }
#launch-bypass-warning { margin: 0; font-size: 12px; color: #d7ba7d; }
@@ -321,6 +332,7 @@
<div id="workspace">
<main id="dashboard">
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></iframe>
<button id="setup-close" type="button" hidden>Back</button>
<div id="dashboard-state" hidden>
<!-- Planny on a coffee break: shown only before a New Session press,
the one state here that is a question rather than a status. The
@@ -362,11 +374,13 @@
<option value="devin">Devin</option>
<option value="codex">Codex</option>
</select>
<p id="launch-notice" hidden></p>
<p id="launch-missing" hidden></p>
<p id="launch-agents-warning" hidden></p>
<label for="launch-model">Model</label>
<input id="launch-model" type="text" placeholder="Default (your account setting)" autocomplete="off" list="launch-model-list">
<datalist id="launch-model-list"></datalist>
<div id="launch-model-row">
<label for="launch-model">Model</label>
<select id="launch-model"></select>
</div>
<div id="launch-effort-row">
<label for="launch-effort">Effort</label>
<select id="launch-effort"></select>
+16
View File
@@ -47,6 +47,22 @@ export function pickDefaultAgent(availability, remembered) {
return list.length > 0 ? list[0].id : null;
}
/**
* The one-line notice for the launch card when the remembered agent is gone
* but another works (FR-13): the id the card picks instead, or null when the
* remembered one still runs or nothing else does.
*/
export function lastAgentNotice(list, remembered) {
const entries = Array.isArray(list) ? list : [];
if (!remembered) return null;
const hit = entries.find((a) => a.id === remembered);
if (hit && hit.installed) return null;
const using = pickDefaultAgent(entries, remembered);
if (!using || using === remembered) return null;
const usingEntry = entries.find((a) => a.id === using);
return usingEntry && usingEntry.installed ? using : null;
}
/**
* What the right end of the bar offers, most pressing first: the bar shows
* the first step (short text plus its one button) and counts the rest as
+170
View File
@@ -0,0 +1,170 @@
{
"$comment": "The one agent lookup rule (src/web-console/agent-lookup.mjs findAgent) as cases both the Node suite (scripts/test-agent-lookup.mjs) and cargo test load. Each case makes temp folders named under `dirs` (a list of file names per folder), then calls findAgent(entry, env): `{name}` in env values, installDirs and `folder` expands to that folder's path. env: path, savedPath, npmBin, pathext, platform, home, vars (for %NAME% expansion). state is found | outside | missing; where is path | saved-path | npm | install-dir | null; file names the hit the found path must end with (null when missing).",
"cases": [
{
"name": "found on PATH",
"platform": "linux",
"entry": { "command": "goose", "installDirs": { "linux": ["{install}"] } },
"dirs": { "bin": ["goose"], "install": [] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "", "pathext": "", "home": "{home}" },
"state": "found",
"where": "path",
"folder": "{bin}",
"file": "goose"
},
{
"name": "found on Windows PATH through PATHEXT (.cmd)",
"platform": "win",
"entry": { "command": "goose" },
"dirs": { "bin": ["goose.cmd"] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD;.BAT" },
"state": "found",
"where": "path",
"folder": "{bin}",
"file": "goose.cmd"
},
{
"name": "found on Windows PATH through PATHEXT (.exe)",
"platform": "win",
"entry": { "command": "goose" },
"dirs": { "bin": ["goose.exe"] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD;.BAT" },
"state": "found",
"where": "path",
"folder": "{bin}",
"file": "goose.exe"
},
{
"name": "found only on the saved Windows PATH is outside",
"platform": "win",
"entry": { "command": "goose" },
"dirs": { "saved": ["goose.cmd"] },
"env": { "path": "{bin}", "savedPath": "{saved}", "npmBin": "", "pathext": ".EXE;.CMD;.BAT" },
"state": "outside",
"where": "saved-path",
"folder": "{saved}",
"file": "goose.cmd"
},
{
"name": "found only in npm's global folder is outside",
"platform": "linux",
"entry": { "command": "goose" },
"dirs": { "npm": ["goose"] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "{npm}", "pathext": "" },
"state": "outside",
"where": "npm",
"folder": "{npm}",
"file": "goose"
},
{
"name": "found only in an install folder is outside",
"platform": "linux",
"entry": { "command": "goose", "installDirs": { "linux": ["{install}"] } },
"dirs": { "install": ["goose"] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "{npm}", "pathext": "" },
"state": "outside",
"where": "install-dir",
"folder": "{install}",
"file": "goose"
},
{
"name": "an install folder with ~ expands against home",
"platform": "linux",
"entry": { "command": "goose", "installDirs": { "linux": ["~/toolbin"] } },
"dirs": { "home": ["toolbin/goose"] },
"env": { "path": "", "savedPath": "", "npmBin": "", "pathext": "", "home": "{home}" },
"state": "outside",
"where": "install-dir",
"folder": "{home}/toolbin",
"file": "goose"
},
{
"name": "an install folder with %NAME% expands against vars",
"platform": "win",
"entry": { "command": "goose", "installDirs": { "win": ["%TOOLS%\\bin"] } },
"dirs": { "tools": ["bin/goose.exe"] },
"env": { "path": "", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD", "vars": { "TOOLS": "{tools}" } },
"state": "outside",
"where": "install-dir",
"folder": "{tools}/bin",
"file": "goose.exe"
},
{
"name": "a command carrying its own extension is tried as written",
"platform": "win",
"entry": { "command": "goose.cmd" },
"dirs": { "bin": ["goose.cmd"] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "", "pathext": ".EXE;.CMD;.BAT" },
"state": "found",
"where": "path",
"folder": "{bin}",
"file": "goose.cmd"
},
{
"name": "not found anywhere is missing",
"platform": "linux",
"entry": { "command": "goose", "installDirs": { "linux": ["{install}"] } },
"dirs": { "bin": [], "install": [] },
"env": { "path": "{bin}", "savedPath": "", "npmBin": "", "pathext": "" },
"state": "missing",
"where": null,
"folder": null,
"file": null
},
{
"name": "a command written as a full path is checked as a file",
"platform": "linux",
"entry": { "command": "{bin}/goose" },
"dirs": { "bin": ["goose"] },
"env": { "path": "", "savedPath": "", "npmBin": "", "pathext": "" },
"state": "found",
"where": "path",
"folder": "{bin}",
"file": "goose"
},
{
"name": "a PATH entry with a space still finds the command",
"platform": "linux",
"entry": { "command": "goose" },
"dirs": { "with space": ["goose"] },
"env": { "path": "{with space}", "savedPath": "", "npmBin": "", "pathext": "" },
"state": "found",
"where": "path",
"folder": "{with space}",
"file": "goose"
},
{
"name": "PATH wins over the saved PATH and npm",
"platform": "win",
"entry": { "command": "goose" },
"dirs": { "bin": ["goose.exe"], "saved": ["goose.exe"], "npm": ["goose.exe"] },
"env": { "path": "{bin}", "savedPath": "{saved}", "npmBin": "{npm}", "pathext": ".EXE;.CMD;.BAT" },
"state": "found",
"where": "path",
"folder": "{bin}",
"file": "goose.exe"
},
{
"name": "the saved PATH wins over npm and install folders",
"platform": "win",
"entry": { "command": "goose", "installDirs": { "win": ["{install}"] } },
"dirs": { "saved": ["goose.exe"], "npm": ["goose.exe"], "install": ["goose.exe"] },
"env": { "path": "", "savedPath": "{saved}", "npmBin": "{npm}", "pathext": ".EXE;.CMD;.BAT" },
"state": "outside",
"where": "saved-path",
"folder": "{saved}",
"file": "goose.exe"
},
{
"name": "npm wins over install folders",
"platform": "linux",
"entry": { "command": "goose", "installDirs": { "linux": ["{install}"] } },
"dirs": { "npm": ["goose"], "install": ["goose"] },
"env": { "path": "", "savedPath": "", "npmBin": "{npm}", "pathext": "" },
"state": "outside",
"where": "npm",
"folder": "{npm}",
"file": "goose"
}
]
}
+224 -1
View File
@@ -1,5 +1,5 @@
{
"$comment": "The rules of ~/.plan2code/agents.json (PLAN-DRAFT 4.4) as cases every reader's tests load: the console (src/web-console/agents.mjs), the launcher and the desktop app. files: `raw` is the file's text (null: no file); `warnings` lists substrings, each found in some warning, and an empty list means no warnings at all; entries are named agents[i], 0-based. buildArgs: `options` as passed (a missing prompt means the entry's own). ids: makeId(input, taken).",
"$comment": "The rules of ~/.plan2code/agents.json (PLAN-DRAFT 4.4) as cases every reader's tests load: the console (src/web-console/agents.mjs), the launcher and the desktop app. files: `raw` is the file's text (null: no file); `warnings` lists substrings, each found in some warning, and an empty list means no warnings at all; entries are named agents[i], 0-based. buildArgs: `options` as passed (a missing prompt means the entry's own); an argument exactly `{bypass}` or `{model}` expands to bypassArgs / modelArgs in place and suppresses the end-append for that flag. ids: makeId(input, taken).",
"files": [
{
"name": "no file",
@@ -1637,6 +1637,229 @@
"--yes-always"
]
},
{
"name": "{bypass} expands to bypassArgs in place when on",
"entry": {
"id": "devin",
"name": "Devin",
"command": "devin",
"args": [
"{bypass}",
"--",
"{prompt}"
],
"prompt": "/plan2code",
"bypassArgs": [
"--permission-mode",
"bypass"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"bypass": true
},
"args": [
"--permission-mode",
"bypass",
"--",
"/plan2code"
]
},
{
"name": "{bypass} drops out when off",
"entry": {
"id": "devin",
"name": "Devin",
"command": "devin",
"args": [
"{bypass}",
"--",
"{prompt}"
],
"prompt": "/plan2code",
"bypassArgs": [
"--permission-mode",
"bypass"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"bypass": false
},
"args": [
"--",
"/plan2code"
]
},
{
"name": "{model} expands to modelArgs in place when chosen",
"entry": {
"id": "devin",
"name": "Devin",
"command": "devin",
"args": [
"{model}",
"--",
"{prompt}"
],
"prompt": "/plan2code",
"bypassArgs": [
"--permission-mode",
"bypass"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"model": "opus",
"bypass": false
},
"args": [
"--model",
"opus",
"--",
"/plan2code"
]
},
{
"name": "{model} drops out with no model chosen",
"entry": {
"id": "devin",
"name": "Devin",
"command": "devin",
"args": [
"{model}",
"--",
"{prompt}"
],
"prompt": "/plan2code",
"bypassArgs": [
"--permission-mode",
"bypass"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"bypass": false
},
"args": [
"--",
"/plan2code"
]
},
{
"name": "Devin's shape: bypass and model ahead of the -- and the prompt",
"entry": {
"id": "devin",
"name": "Devin",
"command": "devin",
"args": [
"{bypass}",
"{model}",
"--",
"{prompt}"
],
"prompt": "/plan2code",
"bypassArgs": [
"--permission-mode",
"bypass"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"model": "swe-2-high",
"bypass": true
},
"args": [
"--permission-mode",
"bypass",
"--model",
"swe-2-high",
"--",
"/plan2code"
]
},
{
"name": "Codex's shape: bypass then model then the $-prompt",
"entry": {
"id": "codex",
"name": "Codex",
"command": "codex",
"args": [
"{bypass}",
"{model}",
"{prompt}"
],
"prompt": "$plan2code",
"bypassArgs": [
"--dangerously-bypass-approvals-and-sandbox"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"model": "gpt-5",
"bypass": true
},
"args": [
"--dangerously-bypass-approvals-and-sandbox",
"--model",
"gpt-5",
"$plan2code"
]
},
{
"name": "an entry holding neither placeholder keeps the appended order",
"entry": {
"id": "aider",
"name": "Aider",
"command": "aider",
"args": [
"{prompt}"
],
"prompt": "/plan2code",
"bypassArgs": [
"--yes-always"
],
"modelArgs": [
"--model",
"{model}"
],
"models": []
},
"options": {
"model": "sonnet",
"bypass": true
},
"args": [
"/plan2code",
"--model",
"sonnet",
"--yes-always"
]
},
{
"name": "placeholders are replaced as plain text",
"entry": {
+126
View File
@@ -0,0 +1,126 @@
// The one agent lookup rule (src/web-console/agent-lookup.mjs) against the
// shared cases every reader's tests load (scripts/fixtures/agent-lookup-cases.json),
// plus loadAgentList()'s file handling and the shipped src/launcher/agents.json.
import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import { findAgent, loadAgentList } from "../src/web-console/agent-lookup.mjs";
import { normalizeAgents } from "../src/web-console/agents.mjs";
const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const CASES = JSON.parse(fs.readFileSync(path.join(ROOT, "scripts", "fixtures", "agent-lookup-cases.json"), "utf8"));
// The .cmd cases check a shim's lookup; cmd's own current-folder rule must not
// color a temp-folder stat, so the switch is cleared for the whole suite.
const savedSwitch = process.env.NoDefaultCurrentDirectoryInExePath;
delete process.env.NoDefaultCurrentDirectoryInExePath;
/**
* The folders a case names, as real temp dirs with its files inside.
* `{name}` in a value expands to that folder's path.
*/
function stage(t, c) {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-lookup-"));
t.after(() => fs.rmSync(base, { recursive: true, force: true }));
const dirs = {};
for (const [name, files] of Object.entries(c.dirs || {})) {
const dir = path.join(base, name);
dirs[name] = dir;
for (const file of files) {
const target = path.join(dir, file);
fs.mkdirSync(path.dirname(target), { recursive: true });
fs.writeFileSync(target, "");
}
if (!files.length) fs.mkdirSync(dir, { recursive: true });
}
const fill = (value) =>
typeof value === "string"
? value.replace(/\{([^}]+)\}/g, (whole, name) => {
if (!(name in dirs)) {
const dir = path.join(base, name);
dirs[name] = dir;
return dir;
}
return dirs[name];
})
: value;
const env = {};
for (const [key, value] of Object.entries(c.env || {})) {
env[key] = value && typeof value === "object" ? Object.fromEntries(Object.entries(value).map(([k, v]) => [k, fill(v)])) : fill(value);
}
env.platform = c.platform;
const entry = JSON.parse(JSON.stringify(c.entry || {}), (key, value) => (typeof value === "string" ? fill(value) : value));
return { entry, env, fill };
}
for (const c of CASES.cases) {
test(`findAgent: ${c.name}`, (t) => {
const { entry, env, fill } = stage(t, c);
const got = findAgent(entry, env);
assert.equal(got.state, c.state, `state: ${JSON.stringify(got)}`);
assert.equal(got.where, c.where, `where: ${JSON.stringify(got)}`);
if (c.state === "missing") {
assert.equal(got.path, null);
assert.equal(got.folder, null);
return;
}
assert.ok(got.path && fs.statSync(got.path).isFile(), `path is a real file: ${JSON.stringify(got)}`);
if (c.file) assert.equal(path.basename(got.path), c.file);
if (c.folder) {
const want = path.normalize(fill(c.folder));
assert.equal(path.normalize(got.folder), want, `folder: ${JSON.stringify(got)}`);
}
});
}
test("the fixture covers every case it promises", () => {
const names = CASES.cases.map((c) => c.name);
for (const word of ["PATH", "PATHEXT", "saved", "npm", "install", "missing", "full path", "space"]) {
assert.ok(names.some((n) => n.includes(word)), `a case names ${word}`);
}
});
/* ------------------------------------------------------- loadAgentList */
function listDir(t, contents) {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agentlist-"));
t.after(() => fs.rmSync(dir, { recursive: true, force: true }));
if (contents !== undefined) fs.writeFileSync(path.join(dir, "agents.json"), contents);
return dir;
}
test("loadAgentList: a missing file gives empty lists and a warning, never a throw", (t) => {
const { builtins, templates, warnings } = loadAgentList({ dir: listDir(t) });
assert.deepEqual(builtins, []);
assert.deepEqual(templates, []);
assert.equal(warnings.length, 1);
assert.match(warnings[0], /missing/);
});
test("loadAgentList: bad JSON and a wrong schema warn and give nothing", (t) => {
const bad = loadAgentList({ dir: listDir(t, "{ nope") });
assert.deepEqual([bad.builtins, bad.templates], [[], []]);
assert.match(bad.warnings[0], /not valid JSON/);
const wrong = loadAgentList({ dir: listDir(t, JSON.stringify({ schema: 2, agents: [] })) });
assert.deepEqual([wrong.builtins, wrong.templates], [[], []]);
assert.match(wrong.warnings[0], /schema/);
});
test("loadAgentList: the shipped agents.json loads with 3 built-ins and 4 templates", () => {
const { builtins, templates, warnings } = loadAgentList({ dir: path.join(ROOT, "src", "launcher") });
assert.deepEqual(warnings, []);
assert.deepEqual(builtins.map((a) => a.id), ["claude", "devin", "codex"]);
assert.deepEqual(templates.map((a) => a.id), ["copilot", "opencode", "gemini", "pi"]);
});
test("every shipped template passes normalizeAgents() with no warnings", () => {
const { templates } = loadAgentList({ dir: path.join(ROOT, "src", "launcher") });
const { agents, warnings } = normalizeAgents(JSON.stringify({ schema: 1, agents: templates }));
assert.deepEqual(warnings, []);
assert.equal(agents.length, templates.length);
});
+13
View File
@@ -371,3 +371,16 @@ test("framed, an Activities game in full screen asks the app for the whole scree
await until(async () => (await told()).at(-1) === false, 5000);
assert.deepEqual(await told(), [true, false, true, false, true, false], "and so does a new question");
});
test("framed, the setup page's agent-found names the agent; unframed it says nothing", async (t) => {
const browser = await pages.browser();
const s = await openSession(browser, { t, workflow: "setup", env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
await s.page.evaluate(() => import("/app-bridge.js").then((m) => m.agentFound("claude")));
assert.deepEqual(await toApp(s, "agent-found"), [{ plan2code: "agent-found", id: "claude" }], "a named request with the found id");
const plain = await openSession(browser, { t, workflow: "setup" });
const unframed = await plain.page.evaluate(() =>
import("/app-bridge.js").then((m) => { m.agentFound("devin"); return m.framed(); })
);
assert.equal(unframed, false, "outside the app the message goes nowhere and does not throw");
});
+1 -1
View File
@@ -553,7 +553,7 @@ test("agents: no file is an empty list, a save is written whole and keeps unknow
fs.rmSync(file, { force: true });
const get = async () => (await fetch(baseUrl + "/agents", { headers: { cookie: cookieFor(baseUrl, token) } })).json();
assert.deepEqual(await get(), { agents: [], warnings: [] }, "no file");
assert.deepEqual(await get(), { agents: [], warnings: [], builtins: [], templates: [] }, "no file");
fs.mkdirSync(MODELS_DIR, { recursive: true });
fs.writeFileSync(file, "{ \"schema\": 1, \"agents\": [");
const broken = await get();
+80 -38
View File
@@ -85,19 +85,27 @@ test("the violet highlight and dark theme chosen in preferences stick across a r
assert.deepEqual(await firstPaintAttrs(s), { theme: null, accent: null }, "the first paint still carries the old looks");
});
// The Agents & models tab: the summary table, its rows and the form Edit opens.
// The Agents & models tab: the split's row list, its rows and the pane the
// pick opens the form in (the list stays on screen; there is no back page).
const AGENTS_FILE = path.join(MODELS_DIR, "agents.json");
const agentsTable = (s) => s.page.locator("#agents-table");
const agentRow = (s, key) => s.page.locator(`#agents-table tr[data-key="${key}"]`);
const agentRow = (s, key) => agentsTable(s).locator(`.split-row[data-key="${key}"]`);
const agentForm = (s) => s.page.locator("#agents-form");
const formField = (s, name) => agentForm(s).getByRole("textbox", { name, exact: true });
const formButton = (s, name) => agentForm(s).getByRole("button", { name, exact: true });
const formPane = (s) => agentForm(s).locator(".prefs-agents-fields");
const unsavedPrompt = (s) => s.page.locator("#prefs-unsaved");
async function openAgentsTab(s) {
// The dialog's DOM survives a close, so the row, a stale form and even a
// stale empty pane can match before load() resolves. Wait on the fetch
// itself first; the empty pane only draws once it has.
const loaded = s.page.waitForResponse((r) => r.url().endsWith("/agents"));
await s.page.click("#btn-looks");
await s.page.click("#prefs-tab-agents");
await loaded;
await agentRow(s, "cli:claude").waitFor();
await agentForm(s).locator(".split-empty").waitFor();
}
// agents.json as the test starts it: none, or the entries given. Removed after.
@@ -117,41 +125,41 @@ test("Agents & models: the table lists Claude, Devin and Codex, and a model id t
t.after(() => fs.rmSync(path.join(MODELS_DIR, "models.json"), { force: true }));
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAgentsTab(s);
const keys = await agentsTable(s).locator("tbody tr[data-key]").evaluateAll((rows) => rows.map((r) => r.dataset.key));
const keys = await agentsTable(s).locator(".split-row[data-key]").evaluateAll((rows) => rows.map((r) => r.dataset.key));
assert.deepEqual(keys, ["cli:claude", "cli:devin", "cli:codex"]);
assert.equal(await textOf(agentRow(s, "cli:codex").locator(".prefs-agents-name > span").first()), "Codex");
assert.equal(await textOf(agentRow(s, "cli:codex").locator(".row-name")), "Codex");
await s.page.getByRole("button", { name: "Edit Codex" }).click();
await agentForm(s).waitFor();
assert.equal(await agentsTable(s).isVisible(), false, "the form takes the table's place");
await formPane(s).waitFor();
assert.equal(await agentRow(s, "cli:codex").getAttribute("aria-current"), "true", "the picked row is marked; the list stays beside the form");
await agentForm(s).locator(".prefs-agents-none").filter({ hasText: /^No models ship for Codex yet/ }).waitFor();
assert.equal(await agentForm(s).locator(".models-row.locked").count(), 0, "nothing comes with Plan2Code for Codex");
await formButton(s, "Add a model").click();
const id = formField(s, "Model id");
await id.fill("gpt-test-codex-1");
await id.press("Tab");
await s.page.waitForTimeout(300);
await formField(s, "Model id").fill("gpt-test-codex-1");
await formButton(s, "Add a model").click();
await formField(s, "Model id").nth(1).fill("gpt-test-codex-2");
// Remove drops the row from the draft; it still reaches the file only on Save.
await agentForm(s).locator(".agent-row.model").first().getByRole("button", { name: "Remove" }).click();
assert.equal(await agentForm(s).locator(".agent-row.model").count(), 1, "the removed row is gone");
await agentForm(s).locator(".prefs-unsaved-badge").waitFor();
const before = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user);
assert.deepEqual(before.codex, [], "nothing is saved before Save");
assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), true);
await formButton(s, "Save").click();
await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved\. Restart plan2code/ }).waitFor();
const saved = await s.page.evaluate(async () => (await (await fetch("/models")).json()).user);
assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-1"], "the id was not saved under Codex");
assert.deepEqual(saved.codex.map((m) => m.id), ["gpt-test-codex-2"], "only the kept model was saved under Codex");
assert.deepEqual([saved.claude, saved.devin], [[], []], "the id leaked into another agent's menu");
assert.equal(await agentForm(s).locator(".prefs-unsaved-badge").isVisible(), false, "saved, nothing is unsaved");
// The summary counts it on Codex's row, and so does a fresh page.
await formButton(s, "Back to summary").click();
assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label") || document.activeElement?.id), "Edit Codex", "focus comes back to the row just left");
assert.match(await textOf(agentRow(s, "cli:codex").locator(".prefs-agents-models")), /^1: gpt-test-codex-1$/);
assert.match(await textOf(agentRow(s, "cli:codex").locator(".row-models")), /^1: gpt-test-codex-2$/);
await s.page.reload({ waitUntil: "domcontentloaded" });
await drawn(s.page);
await openAgentsTab(s);
await s.page.getByRole("button", { name: "Edit Codex" }).click();
assert.equal(await formField(s, "Model id").inputValue(), "gpt-test-codex-1");
assert.equal(await formField(s, "Model id").inputValue(), "gpt-test-codex-2");
});
test("Agents & models: a person adds an agent, tests its command, sees it after a reload, and deletes it", async (t) => {
@@ -159,10 +167,10 @@ test("Agents & models: a person adds an agent, tests its command, sees it after
seedAgents(t);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAgentsTab(s);
assert.equal(await agentsTable(s).locator('tr[data-key^="agent:"]').count(), 0, "no agents before one is added");
assert.equal(await agentsTable(s).locator('.split-row[data-key^="agent:"]').count(), 0, "no agents before one is added");
await s.page.click("#agents-add");
await agentForm(s).waitFor();
await formPane(s).waitFor();
assert.equal(await agentForm(s).locator("details.prefs-agents-args").evaluate((d) => d.open), true, "the arguments are open on a new agent");
await formField(s, "Name").fill("Test Agent");
await formField(s, "Command").fill("node");
@@ -189,12 +197,13 @@ test("Agents & models: a person adds an agent, tests its command, sees it after
await formButton(s, "Delete agent").click();
await formButton(s, "Yes, delete").click();
await agentsTable(s).waitFor();
assert.equal(await agentsTable(s).locator('tr[data-key^="agent:"]').count(), 0);
await row.waitFor({ state: "detached" });
assert.equal(await agentsTable(s).locator('.split-row[data-key^="agent:"]').count(), 0);
assert.deepEqual(JSON.parse(fs.readFileSync(AGENTS_FILE, "utf8")).agents, []);
assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label") || document.activeElement?.id), "agents-add", "with its row gone, focus goes to Add agent");
assert.equal(await textOf(s.page.locator("#agents-status")), "Deleted.");
await s.page.click("#agents-add");
await formPane(s).waitFor();
assert.equal(await s.page.locator("#agents-status").innerText(), "", "opening a form clears Deleted.");
});
@@ -240,6 +249,7 @@ test("Agents & models: a file holding entries the page could not read is only re
await s.page.locator("#agents-status").filter({ hasText: /schema 2/ }).waitFor();
await s.page.click("#agents-add");
await formPane(s).waitFor();
assert.equal(await formButton(s, "Save anyway").count(), 0, "no Save anyway before a save is tried");
await formField(s, "Name").fill("Mine");
await formField(s, "Command").fill("node");
@@ -281,16 +291,17 @@ test("Agents & models: a discarded edit never rides along with another agent's S
await openAgentsTab(s);
await s.page.getByRole("button", { name: "Edit Alpha" }).click();
await formField(s, "Command").fill("alpha-cli --dropped");
await formButton(s, "Back to summary").click();
// Picking another row is the way out of a form; a dirty draft asks first.
await s.page.getByRole("button", { name: "Edit Beta" }).click();
await unsavedPrompt(s).waitFor();
assert.equal(await textOf(s.page.locator("#prefs-unsaved-name")), "Alpha");
assert.equal(await s.page.locator("#looks-modal .prefs-body").evaluate((b) => b.inert), true, "the dialog behind the prompt is out of reach");
await unsavedPrompt(s).getByRole("button", { name: "Discard", exact: true }).click();
await agentsTable(s).waitFor();
await unsavedPrompt(s).waitFor({ state: "hidden" });
await formPane(s).waitFor();
assert.equal(await s.page.locator("#looks-modal .prefs-body").evaluate((b) => b.inert), false);
assert.equal(await s.page.evaluate(() => document.activeElement?.getAttribute("aria-label") || document.activeElement?.id), "Edit Alpha", "focus comes back to the row just left");
assert.equal(await textOf(agentForm(s).locator(".prefs-agents-title")), "Beta", "the pick the prompt asked about carries on");
await s.page.getByRole("button", { name: "Edit Beta" }).click();
await formField(s, "Command").fill("beta-cli --kept");
await formButton(s, "Save").click();
await agentForm(s).locator(".prefs-saved").filter({ hasText: /^Saved$/ }).waitFor();
@@ -298,18 +309,20 @@ test("Agents & models: a discarded edit never rides along with another agent's S
assert.deepEqual(agents.map((a) => [a.id, a.command]), [["alpha", "alpha-cli"], ["beta", "beta-cli --kept"]]);
});
test("Agents & models: an unsaved edit asks first on Back, Close, Esc, a backdrop click and a tab switch", async (t) => {
test("Agents & models: an unsaved edit asks first on a row pick, Close, Esc, a backdrop click and a tab switch", async (t) => {
noSavedLooks(t);
seedAgents(t, TWO_AGENTS);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAgentsTab(s);
const modal = s.page.locator("#looks-modal");
const edit = async (command) => {
if (!(await agentForm(s).isVisible())) await s.page.getByRole("button", { name: "Edit Alpha" }).click();
if (!(await agentForm(s).locator(".prefs-agents-title").filter({ hasText: "Alpha" }).count())) {
await s.page.getByRole("button", { name: "Edit Alpha" }).click();
}
await formField(s, "Command").fill(command);
};
const triggers = {
back: () => formButton(s, "Back to summary").click(),
row: () => s.page.getByRole("button", { name: "Edit Beta" }).click(),
close: () => s.page.click("#looks-done"),
esc: () => formField(s, "Command").press("Escape"),
backdrop: () => s.page.mouse.click(4, 4),
@@ -376,24 +389,53 @@ test("Agents & models: a command not on PATH is marked, and the orchestrator row
const badge = agentRow(s, "agent:ghost").locator(".prefs-badge");
await badge.filter({ hasText: "Not found on PATH" }).waitFor();
assert.equal(await badge.evaluate((b) => b.classList.contains("missing")), true);
const soon = agentsTable(s).locator("tr.prefs-agents-soon");
const soon = agentsTable(s).locator(".split-row.soon");
assert.match(await textOf(soon), /v3 orchestrator\s+Nothing to set yet\./);
assert.equal(await soon.getByRole("button").count(), 0);
});
test("Agents & models: below 720 px the Models column is hidden and the form is one column", async (t) => {
test("Agents & models: below 720 px the split stacks and the form is one column", async (t) => {
noSavedLooks(t);
seedAgents(t, TWO_AGENTS);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await s.page.setViewportSize({ width: 600, height: 800 });
await openAgentsTab(s);
const cells = agentsTable(s).locator(".prefs-agents-models");
const shown = [];
for (let i = 0; i < (await cells.count()); i++) shown.push(await styleOf(cells.nth(i), "display"));
assert.ok(shown.length > 0 && shown.every((d) => d === "none"), `the Models cells are hidden: ${shown}`);
const cols = await styleOf(s.page.locator("#agents-split"), "grid-template-columns");
assert.equal(cols.trim().split(/\s+/).length, 1, `the split stacks: ${cols}`);
assert.equal(await styleOf(s.page.locator("#agents-table"), "overflow-y"), "auto", "the row list scrolls");
await s.page.getByRole("button", { name: "Edit Alpha" }).click();
const cols = await styleOf(agentForm(s).locator(".prefs-agents-fields"), "grid-template-columns");
assert.equal(cols.trim().split(/\s+/).length, 1, `one column: ${cols}`);
const fields = await styleOf(agentForm(s).locator(".prefs-agents-fields"), "grid-template-columns");
assert.equal(fields.trim().split(/\s+/).length, 1, `one column: ${fields}`);
});
// The shipped bin/agents.json beside the user file: where starter templates
// come from. Removed after so the next test's list has none.
const SHIPPED_AGENTS_FILE = path.join(MODELS_DIR, "bin", "agents.json");
function seedShipped(t, agents) {
fs.mkdirSync(path.dirname(SHIPPED_AGENTS_FILE), { recursive: true });
fs.writeFileSync(SHIPPED_AGENTS_FILE, JSON.stringify({ schema: 1, agents }));
t.after(() => fs.rmSync(SHIPPED_AGENTS_FILE, { force: true }));
}
test("Agents & models: shipped templates offer a prefilled new-agent form", async (t) => {
noSavedLooks(t);
seedAgents(t);
seedShipped(t, [
{ id: "templar", name: "Templar", kind: "template", command: "templar", prompt: "/plan2code", args: ["{prompt}"], note: "A starter agent." },
]);
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
await openAgentsTab(s);
await agentsTable(s).locator(".split-list-head", { hasText: "Or start from a template" }).waitFor();
const row = agentRow(s, "setup:Templar");
assert.match(await textOf(row), /Templar\s+templar/);
await row.click();
const use = agentForm(s).getByRole("button", { name: "Use this template", exact: true });
await use.waitFor();
assert.match(await textOf(agentForm(s)), /A starter agent\./);
await use.click();
await formPane(s).waitFor();
assert.equal(await formField(s, "Name").inputValue(), "Templar");
assert.equal(await formField(s, "Command").inputValue(), "templar");
});
test("Cleanup scans the console home and lists an old session folder with its size", async (t) => {
@@ -517,10 +559,10 @@ test("Set up preferences on the dashboard opens on Appearance with agents and mo
await s.page.locator("#looks-modal[open]").waitFor();
assert.equal(await selectedTab(s), "prefs-tab-appearance");
await s.page.click("#prefs-tab-agents");
const goose = s.page.locator('#agents-table tr[data-key="agent:goose"]');
const goose = s.page.locator('#agents-table .split-row[data-key="agent:goose"]');
await goose.waitFor();
assert.match(await textOf(goose.locator(".prefs-agents-name")), /^Goose/);
assert.equal(await s.page.locator('#agents-table tr[data-key="cli:claude"]').count(), 1, "the built-ins are listed");
assert.match(await textOf(goose.locator(".row-name")), /^Goose/);
assert.equal(await s.page.locator('#agents-table .split-row[data-key="cli:claude"]').count(), 1, "the built-ins are listed");
assert.doesNotMatch(await s.page.locator("#agents-status").innerText(), /could not be loaded/);
});
+402
View File
@@ -0,0 +1,402 @@
// Page tests for the agent-less setup page (`console.mjs open --workflow
// setup`, with or without --for-cli): the three found states and their way
// forward, the forCli ordering, Check again, Use it from here, a template
// becoming a custom agent, Start and its grace line, the /handover move, and
// the quiet chrome an agent-less session keeps. Run with:
// node --test scripts/test-web-console-page-setup.mjs
//
// Each test drives the real console in a real Chrome or Edge through
// scripts/page-test-helpers.mjs: one browser for the file, a fresh console
// session per test. The found states are deterministic: a shipped agents.json
// written under MODELS_DIR/bin before the server starts, fake .cmd files (one
// file name is found on every OS), PATH pointed at a fixture dir, npm's
// global folder at an empty prefix and the saved Windows PATH switched off.
// That is the same recipe test-web-console-server.mjs's agentFixtures() uses.
//
// The page is the agents view's "setup" mount (agents-view.js on
// .setup-agents), a master-detail split: button.split-row[data-key] rows in
// [data-av="table"] on the left, the picked row's state and way forward
// (Start, Use it from here, the install lines, a template's Use) drawn as
// .setup-detail in [data-av="form"] on the right after the row is clicked.
// Row badges are drawn on first load; everything actionable wants the click.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import test from "node:test";
import assert from "node:assert/strict";
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
import { cli, sessionUrl, readState, until, MODELS_DIR } from "./web-console-test-helpers.mjs";
const suite = pageSuite(test);
// The desktop-app markers a spawned console must never carry into these
// tests: test-web-console-server.mjs's NO_APP, plus the setup hand-over pair,
// which would turn a plain `open` into a hand-over of its own.
const NO_APP = {
PLAN2CODE_IN_APP: undefined,
PLAN2CODE_APP_TOKEN: undefined,
PLAN2CODE_APP_ANNOUNCE: undefined,
PLAN2CODE_EMBED_ORIGIN: undefined,
PLAN2CODE_CONSOLE_SID: undefined,
PLAN2CODE_APP_VERSION: undefined,
PLAN2CODE_SETUP_ANNOUNCE: undefined,
PLAN2CODE_SETUP_TOKEN: undefined,
};
const PATH_KEY = Object.keys(process.env).find((k) => k.toUpperCase() === "PATH") || "PATH";
const OS_KEY = process.platform === "win32" ? "win" : process.platform === "darwin" ? "mac" : "linux";
const SHIPPED_FILE = path.join(MODELS_DIR, "bin", "agents.json");
const USER_AGENTS_FILE = path.join(MODELS_DIR, "agents.json");
// The missing builtin's install lines, one list per OS; the server serves
// only this OS's. Windows carries a note so that part of the row is checked.
const INSTALL = {
win: [{ label: "PowerShell", run: "irm https://example.com/gone | iex", note: "Run it in an elevated shell." }],
mac: [{ label: "Terminal", run: "brew install gone-agent" }],
linux: [{ label: "Terminal", run: "apt install gone-agent" }],
};
// Fake commands and a shipped list that put one builtin in each state: two on
// PATH (for the --for-cli ordering), one only in its installDirs, one
// nowhere. `npmCommands` are bare names dropped into the fake npm global bin,
// where a custom agent's command reads as "outside". Everything is written
// before the session's server starts, and removed after the test.
function agentFixtures(t, { userAgents = [], npmCommands = [] } = {}) {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-setup-"));
const onPath = path.join(base, "onpath");
const outside = path.join(base, "outside");
const npmPrefix = path.join(base, "npm-prefix");
const npmBin = process.platform === "win32" ? npmPrefix : path.join(npmPrefix, "bin");
fs.mkdirSync(onPath, { recursive: true });
fs.mkdirSync(outside, { recursive: true });
fs.mkdirSync(npmBin, { recursive: true });
fs.writeFileSync(path.join(onPath, "found-one.cmd"), "@rem stand-in\r\n");
fs.writeFileSync(path.join(onPath, "found-two.cmd"), "@rem stand-in\r\n");
fs.writeFileSync(path.join(outside, "outer.cmd"), "@rem stand-in\r\n");
for (const name of npmCommands) fs.writeFileSync(path.join(npmBin, name), "@rem stand-in\r\n");
// The template's command is a path, so the agent its Save writes finds a file.
const templar = path.join(base, "templar.cmd");
fs.writeFileSync(templar, "@rem stand-in\r\n");
const shipped = {
schema: 1,
agents: [
{ id: "found-one", name: "Found One", kind: "builtin", command: "found-one.cmd" },
{ id: "found-two", name: "Found Two", kind: "builtin", command: "found-two.cmd" },
{
id: "outer",
name: "Outer Agent",
kind: "builtin",
command: "outer.cmd",
installDirs: { win: [outside], mac: [outside], linux: [outside] },
},
{
id: "gone",
name: "Gone Agent",
kind: "builtin",
command: "p2c-gone-xyz.cmd",
installUrl: "https://example.com/gone",
install: INSTALL,
},
{
id: "templar",
name: "Templar",
kind: "template",
command: templar,
prompt: "/plan2code",
args: ["{prompt}"],
note: "A starter agent.",
},
],
};
fs.mkdirSync(path.dirname(SHIPPED_FILE), { recursive: true });
fs.writeFileSync(SHIPPED_FILE, JSON.stringify(shipped));
if (userAgents.length) {
fs.writeFileSync(USER_AGENTS_FILE, JSON.stringify({ schema: 1, agents: userAgents }));
} else {
fs.rmSync(USER_AGENTS_FILE, { force: true });
}
t.after(() => {
fs.rmSync(SHIPPED_FILE, { force: true });
fs.rmSync(USER_AGENTS_FILE, { force: true });
fs.rmSync(base, { recursive: true, force: true });
});
const env = {
...NO_APP,
PLAN2CODE_NO_SAVED_PATH: "1",
npm_config_prefix: npmPrefix,
[PATH_KEY]: onPath + path.delimiter + (process.env[PATH_KEY] || ""),
};
return { base, onPath, outside, npmBin, templar, env };
}
// The split's left column and the detail pane. Rows are found by data-key
// ("setup:<id>" for builtins and custom agents, "setup:<template name>" for
// templates) rather than by name: a custom agent saved from a template shares
// the template's name, and only the key keeps them apart.
const table = (s) => s.page.locator('.setup-agents [data-av="table"]');
const rowByKey = (s, key) => table(s).locator(`button.split-row[data-key="setup:${key}"]`);
const pane = (s) => s.page.locator('.setup-agents [data-av="form"]');
const detail = (s) => pane(s).locator(".setup-detail");
const button = (s, name) => s.page.getByRole("button", { name, exact: true });
const checkAgain = (s) => s.page.locator(".setup-actions").getByRole("button", { name: "Check again", exact: true });
// Click a row and wait for the pane to draw that entry's .setup-detail: the
// .prefs-agents-title names the picked agent or template.
async function pick(s, key, name) {
await rowByKey(s, key).click();
const d = detail(s);
await d.locator(".prefs-agents-title").getByText(name, { exact: true }).waitFor();
return d;
}
test("the setup page renders found, outside and missing rows with their way forward", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
await s.page.locator(".setup-screen h2", { hasText: "No agent yet" }).waitFor();
assert.equal(await s.page.locator('.setup-stage [data-pose="setup"]').count(), 1, "Planny's setup pose");
await rowByKey(s, "gone").waitFor();
assert.equal(await s.page.locator('.setup-agents [data-av="intro"]').count(), 1, "the intro line");
assert.equal(await s.page.locator(".setup-agents .split").count(), 1, "the split layout");
assert.equal(await s.page.locator('.setup-agents [data-av="status"]').count(), 1, "the status line");
assert.equal(await table(s).locator("button.split-row").count(), 5, "the four builtin rows and the template");
// Nothing picked yet: the pane shows the empty text, and the row badges are
// already drawn with each entry's state.
assert.equal(await pane(s).locator(".split-empty").count(), 1, "the pane's empty text before a pick");
assert.equal(await rowByKey(s, "found-one").locator(".prefs-badge.ok").count(), 1);
assert.equal(await textOf(rowByKey(s, "found-one").locator(".prefs-badge")), "Found");
assert.equal(await textOf(rowByKey(s, "outer").locator(".prefs-badge")), "Found outside PATH");
assert.equal(await textOf(rowByKey(s, "gone").locator(".prefs-badge")), "Not found");
// On PATH: the Found badge, the resolved path, and Start.
const one = await pick(s, "found-one", "Found One");
assert.match(await textOf(one.locator(".setup-agent-line")), /found-one\.cmd/, "the resolved path");
assert.equal(await one.getByRole("button", { name: "Start with this agent", exact: true }).count(), 1);
// In an install dir but not on PATH: where it is, Use it from here, a PATH note.
const outer = await pick(s, "outer", "Outer Agent");
assert.equal(await textOf(outer.locator(".setup-agent-line .prefs-badge")), "Found outside PATH");
assert.match(await textOf(outer.locator(".setup-agent-line")), /Found at .+outer\.cmd, but not on PATH/);
assert.equal(await outer.getByRole("button", { name: "Use it from here", exact: true }).count(), 1);
assert.match(await textOf(outer.locator("p.help")), /add its folder to (your )?PATH/, "the do-it-yourself PATH note");
// Nowhere: the install lines with Copy buttons, and the Install page link.
const gone = await pick(s, "gone", "Gone Agent");
assert.equal(await textOf(gone.locator(".prefs-badge")), "Not found");
const steps = gone.locator(".setup-install");
const want = INSTALL[OS_KEY];
assert.equal(await steps.count(), want.length, "this OS's install lines");
for (const [i, step] of want.entries()) {
const d = steps.nth(i);
assert.equal(await textOf(d.locator("span").first()), step.label);
assert.equal(await textOf(d.locator("code")), step.run);
if (step.note) assert.ok((await textOf(d)).includes(step.note), "the install note");
assert.equal(await d.getByRole("button", { name: "Copy", exact: true }).count(), 1, "each line has Copy");
}
const installPage = gone.locator("a", { hasText: "Install page" });
assert.equal(await installPage.count(), 1);
assert.equal(await installPage.getAttribute("href"), "https://example.com/gone");
assert.equal(await installPage.getAttribute("target"), "_blank");
// The template head and row, its detail, and the two actions.
const head = table(s).locator(".split-list-head");
assert.equal(await head.count(), 1);
assert.match(await textOf(head), /Or start from a template/);
assert.match(await textOf(rowByKey(s, "Templar").locator(".row-name")), /Templar/);
const tpl = await pick(s, "Templar", "Templar");
assert.match(await textOf(tpl.locator("p.help")), /A starter agent\./);
assert.equal(await tpl.getByRole("button", { name: "Use this template", exact: true }).count(), 1);
assert.equal(await button(s, "Add agent").count(), 1);
assert.equal(await checkAgain(s).count(), 1);
});
test("a session opened --for-cli lists that agent first and offers only its Start", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", open: ["--for-cli", "found-two"], env: f.env });
await rowByKey(s, "gone").waitFor();
const rows = table(s).locator("button.split-row");
const keys = [];
for (let i = 0; i < (await rows.count()); i++) keys.push(await rows.nth(i).getAttribute("data-key"));
assert.deepEqual(
keys,
["setup:found-two", "setup:found-one", "setup:outer", "setup:gone", "setup:Templar"],
"the forCli builtin leads, the rest keep shipped order"
);
const two = await pick(s, "found-two", "Found Two");
assert.equal(await two.getByRole("button", { name: "Start with this agent", exact: true }).count(), 1, "the forCli agent can start");
const one = await pick(s, "found-one", "Found One");
assert.equal(await textOf(one.locator(".setup-agent-line .prefs-badge")), "Found");
assert.equal(
await one.getByRole("button", { name: "Start with this agent", exact: true }).count(),
0,
"another found agent is not offered"
);
});
test("Check again re-fetches the states and redraws a row that changed", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
const gone = await pick(s, "gone", "Gone Agent");
await gone.locator(".prefs-badge.missing").waitFor();
assert.equal(await textOf(gone.locator(".prefs-badge")), "Not found");
assert.equal(await gone.getByRole("button", { name: "Start with this agent" }).count(), 0);
// The command turns up on PATH between checks.
fs.writeFileSync(path.join(f.onPath, "p2c-gone-xyz.cmd"), "@rem stand-in\r\n");
await checkAgain(s).click();
const goneRow = rowByKey(s, "gone");
await goneRow.locator(".prefs-badge.ok").waitFor();
assert.equal(await textOf(goneRow.locator(".prefs-badge")), "Found");
// The picked row's pane re-drew with the new state too.
const again = detail(s);
await again.locator(".setup-agent-line .prefs-badge.ok").waitFor();
assert.equal(await again.getByRole("button", { name: "Start with this agent", exact: true }).count(), 1);
});
test("Use it from here writes the found location and the row becomes found", async (t) => {
const f = agentFixtures(t, { userAgents: [{ id: "mine", name: "Mine", command: "mine.cmd" }], npmCommands: ["mine.cmd"] });
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
const mine = rowByKey(s, "mine");
const before = await pick(s, "mine", "Mine");
await before.locator(".prefs-badge.missing").waitFor();
assert.equal(await textOf(before.locator(".prefs-badge")), "Found outside PATH");
await before.getByRole("button", { name: "Use it from here", exact: true }).click();
await mine.locator(".prefs-badge.ok").waitFor();
assert.equal(await textOf(mine.locator(".prefs-badge")), "Found");
const saved = JSON.parse(fs.readFileSync(USER_AGENTS_FILE, "utf8"));
assert.equal(saved.agents.length, 1);
assert.equal(saved.agents[0].command, path.join(f.npmBin, "mine.cmd"), "the command is where it was found");
// The picked pane re-drew: the now-found agent offers Start.
const after = detail(s);
await after.locator(".setup-agent-line .prefs-badge.ok").waitFor();
assert.equal(await after.getByRole("button", { name: "Start with this agent", exact: true }).count(), 1);
});
test("Use it from here on the --for-cli agent still offers Start", async (t) => {
// The materialized custom entry becomes the forCli target (a built-in's own
// id can never name a custom entry), so Start survives the swap.
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", open: ["--for-cli", "outer"], env: f.env });
const outer = await pick(s, "outer", "Outer Agent");
await outer.getByRole("button", { name: "Use it from here", exact: true }).waitFor();
await outer.getByRole("button", { name: "Use it from here", exact: true }).click();
// The saved copy lands in the list under its own id ("outer-agent"), and
// picking it shows the session's one Start moved onto it.
await rowByKey(s, "outer-agent").waitFor();
const savedRow = await pick(s, "outer-agent", "Outer Agent");
const starts = savedRow.getByRole("button", { name: "Start with this agent", exact: true });
await starts.waitFor();
assert.equal(await starts.count(), 1, "the saved agent keeps the session's one Start");
const one = await pick(s, "found-one", "Found One");
assert.equal(await one.getByRole("button", { name: "Start with this agent" }).count(), 0, "no other row's Start");
});
test("Use this template fills the shared form, and Save lands a found custom agent", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
await rowByKey(s, "gone").waitFor();
// The template's row sits under the "Or start from a template" head; its
// data-key keeps it apart from the same-named agent its Save will write.
const tpl = await pick(s, "Templar", "Templar");
await tpl.getByRole("button", { name: "Use this template", exact: true }).click();
const form = pane(s);
const name = form.locator('input[data-field="name"]');
await name.waitFor();
assert.equal(await name.inputValue(), "Templar");
assert.equal(await form.locator('input[data-field="command"]').inputValue(), f.templar);
assert.equal(await form.locator('input[data-field="prompt"]').inputValue(), "/plan2code");
await form.getByRole("button", { name: "Save", exact: true }).click();
await form.locator(".prefs-saved").filter({ hasText: "Saved" }).waitFor();
const saved = JSON.parse(fs.readFileSync(USER_AGENTS_FILE, "utf8"));
assert.equal(saved.schema, 1);
assert.deepEqual(
saved.agents.map((a) => [a.id, a.name, a.command]),
[["templar", "Templar", f.templar]],
"the template lands in agents.json"
);
// Back on the list the row is there as a custom agent: pick it (leaving a
// clean form is always free on this page) and its pane carries an Edit.
// Its state comes with the next fetch, which Check again is for.
const templar = rowByKey(s, "templar");
const again = await pick(s, "templar", "Templar");
assert.equal(await again.getByRole("button", { name: "Edit Templar", exact: true }).count(), 1, "a custom agent pane gets Edit");
await checkAgain(s).click();
await templar.locator(".prefs-badge.ok").waitFor();
assert.equal(await textOf(templar.locator(".prefs-badge")), "Found");
});
test("Start posts the __start action, the starting pane shows, then the grace line", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
const one = await pick(s, "found-one", "Found One");
await one.getByRole("button", { name: "Start with this agent", exact: true }).waitFor();
// Shorten the two-minute grace so its line is observable in a test, but keep
// it long enough that the hidden state is still checkable before it lands.
await s.page.evaluate(() => {
window.__P2C_SETUP_GRACE_MS = 400;
});
await one.getByRole("button", { name: "Start with this agent", exact: true }).click();
const starting = s.page.locator(".setup-starting");
await starting.waitFor();
assert.match(await textOf(starting.locator(".launch-title")), /^Starting Found One/);
// The pick is the session's result: the action the launcher's wait collects.
const resultPath = path.join(s.session, "result.json");
assert.equal(await until(() => fs.existsSync(resultPath), 5000), true, "result.json was written");
const result = JSON.parse(fs.readFileSync(resultPath, "utf8"));
assert.deepEqual(result.actions, [{ i: "__start", type: "start", agent: "found-one" }]);
// The hint starts hidden; a move that never comes earns it after the grace wait.
await s.page.waitForFunction(() => {
const n = document.querySelector(".setup-no-page");
return Boolean(n && n.hidden);
});
const noPage = starting.locator(".setup-no-page");
await noPage.waitFor({ state: "visible" });
assert.match(await textOf(noPage), /did not open a page\./);
});
test("a /handover post with the setup token moves the page to the new session", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
await rowByKey(s, "found-one").waitFor();
const otherDir = tempProject();
const other = cli(["open", "--workflow", "plan", "--no-open"], { cwd: otherDir, env: f.env });
t.after(() => cli(["stop", "--session", other.json.sid, "--force"], { cwd: otherDir }));
const target = sessionUrl(other.json.url);
const res = await fetch(`${sessionUrl(s.url).base}/handover`, {
method: "POST",
headers: {
"content-type": "application/json",
"x-plan2code-token": readState(s.session).setup.token,
connection: "close",
},
body: JSON.stringify({ url: other.json.url }),
});
assert.equal(res.status, 204);
// The sign-in link sets the session cookie and lands on the session's root.
await s.page.waitForURL((u) => u.origin === target.base && u.pathname === "/", { timeout: 15000 });
});
test("the setup page keeps no agent-silence UI: no adrift or offline lines, no Ask, top bar down to Help", async (t) => {
const f = agentFixtures(t);
const s = await openSession(await suite.browser(), { t, workflow: "setup", env: f.env });
await s.page.locator(".setup-screen").waitFor();
const check = async (when) => {
assert.match(await s.page.locator("#planny").getAttribute("class"), /\bis-setup\b/, `${when}: Planny's mood`);
assert.match(await textOf(s.page.locator("#agent-text")), /No agent yet\. Pick one below/, `${when}: the dock line`);
assert.equal(await s.page.locator("#banner").isHidden(), true, `${when}: no banner`);
assert.equal(await s.page.locator("#btn-about").isVisible(), true, `${when}: Help stays`);
const tabs = (await s.page.locator(".view-tab").allInnerTexts()).map((x) => x.trim());
assert.equal(tabs.some((x) => /ask|subagents/i.test(x)), false, `${when}: no Ask or Subagents tab (${tabs})`);
for (const id of ["meter-pill", "btn-activities", "btn-subagents", "btn-home", "btn-stop", "btn-brief", "btn-notepad"]) {
assert.equal(await s.page.locator("#" + id).isHidden(), true, `${when}: #${id} is hidden`);
}
};
await check("on load");
// A quiet stretch changes nothing: the silence states are switched off.
await s.page.waitForTimeout(1500);
await check("after a wait");
});
+404 -1
View File
@@ -43,6 +43,7 @@ import {
HANDOFFS_DIR,
HOME,
ENV,
MODELS_DIR,
cookieFor,
cli,
payload,
@@ -52,6 +53,7 @@ import {
sessionUrl,
readState,
sleep,
until,
} from "./web-console-test-helpers.mjs";
// Every page load used to fetch /state, then /looks, then open the stream,
@@ -551,7 +553,7 @@ test("User Preferences: wider, its body scrolls and the button bar stays put, wi
const actions = dialog[1].indexOf('<div class="modal-actions">');
assert.ok(body >= 0 && actions > body, "the fieldsets sit in .prefs-body, before the actions");
assert.ok(dialog[1].lastIndexOf("</fieldset>") < actions, "every fieldset is inside the scrolling body");
assert.match(css, /\.modal\.prefs \{ max-width: 880px; \}/);
assert.match(css, /\.modal\.prefs \{ width: min\(1080px, var\(--card-width\), calc\(100vw - 32px\)\); max-width: none; \}/);
assert.match(css, /\.prefs-body \{[^}]*overflow-y: auto/);
assert.match(css, /\.modal\.prefs \.modal-actions \{[^}]*flex: none/);
assert.match(html, /<dialog class="modal looks subagents" id="subagents-modal"/, "Subagents keeps its own classes");
@@ -919,3 +921,404 @@ test("/open-link takes an http or https link and refuses every other kind", asyn
cli(["stop", "--session", res.json.sid, "--force"]);
}
});
/* ------------------------- first-run agent setup (the setup workflow) ------------------------- */
// `open --workflow setup` is the agent-less page the launcher opens when no agent
// can run: the session state carries the hand-over the launcher's agent posts
// back to /handover, and `open` prints it for the launcher to read.
test("open --workflow setup records the hand-over data and prints it, and a plain resume keeps its token", () => {
const res = cli(["open", "--workflow", "setup", "--for-cli", "devin", "--no-open"], { env: NO_APP });
try {
const state = readState(res.json.session);
assert.equal(state.workflow, "setup");
assert.equal(state.setup.forCli, "devin");
assert.match(state.setup.token, /^[A-Za-z0-9_-]{10,}$/);
assert.ok(state.setup.created);
assert.deepEqual(res.json.setup, { url: res.json.url, token: state.setup.token });
assert.match(res.json.setup.url, /\/s\/[A-Za-z0-9_-]+\/$/, "the page's own sign-in link");
cli(["open", "--resume", res.json.sid, "--workflow", "setup", "--no-open"], { env: NO_APP });
assert.equal(readState(res.json.session).setup.token, state.setup.token, "a plain resume keeps the token the launcher's agent holds");
// A resume naming --for-cli is a new hand-over: a fresh token and target.
const retarget = cli(["open", "--resume", res.json.sid, "--workflow", "setup", "--for-cli", "codex", "--no-open"], { env: NO_APP });
const now = readState(res.json.session).setup;
assert.equal(now.forCli, "codex");
assert.notEqual(now.token, state.setup.token);
assert.equal(retarget.json.setup.token, now.token);
} finally {
cli(["stop", "--session", res.json.sid, "--force"]);
}
});
// The shipped and custom agent lists the setup page shows. Commands carry .cmd
// so one file name is found on every OS. The env points npm's global folder at
// a fixture dir and kills the saved PATH: a builtin goes "outside" through its
// installDirs, a custom agent through the npm folder (agentsGet looks custom
// commands up by name only, so installDirs never applies to them).
const NO_APP = {
PLAN2CODE_IN_APP: undefined,
PLAN2CODE_APP_TOKEN: undefined,
PLAN2CODE_APP_ANNOUNCE: undefined,
PLAN2CODE_EMBED_ORIGIN: undefined,
PLAN2CODE_CONSOLE_SID: undefined,
PLAN2CODE_APP_VERSION: undefined,
};
function agentFixtures(base) {
const outside = path.join(base, "outside");
fs.mkdirSync(outside);
fs.writeFileSync(path.join(outside, "testagent.cmd"), "@rem stand-in\r\n");
const onPath = path.join(base, "onpath.cmd");
fs.writeFileSync(onPath, "@rem stand-in\r\n");
// npm's global bin: the prefix itself on Windows, <prefix>/bin elsewhere.
const npmBin = process.platform === "win32" ? path.join(base, "npm-prefix") : path.join(base, "npm-prefix", "bin");
fs.mkdirSync(npmBin, { recursive: true });
const inNpm = path.join(npmBin, "agenttwo.cmd");
fs.writeFileSync(inNpm, "@rem stand-in\r\n");
const shipped = {
schema: 1,
agents: [
{
id: "testagent",
name: "Test Agent",
kind: "builtin",
command: "testagent.cmd",
prompt: "/plan2code",
args: ["{prompt}"],
bypassArgs: ["--yes"],
modelArgs: ["--model", "{model}"],
installUrl: "https://example.com/get",
install: {
win: [{ label: "PowerShell", run: "irm x | iex", note: "n" }],
mac: [{ label: "Terminal", run: "curl x" }],
linux: [],
},
installDirs: { win: [outside], mac: [outside], linux: [outside] },
},
{ id: "gone", name: "Gone Agent", kind: "builtin", command: "gone-agent-xyz.cmd" },
{ id: "templ", name: "Templ", kind: "template", command: "templ", prompt: "Use plan2code", args: ["{prompt}"], note: "a starter" },
],
};
const user = {
schema: 1,
agents: [
{ id: "myagent", name: "My Agent", command: onPath },
{ id: "agenttwo", name: "Agent Two", command: "agenttwo.cmd" },
],
};
const shippedFile = path.join(MODELS_DIR, "bin", "agents.json");
const userFile = path.join(MODELS_DIR, "agents.json");
fs.mkdirSync(path.dirname(shippedFile), { recursive: true });
fs.writeFileSync(shippedFile, JSON.stringify(shipped));
fs.writeFileSync(userFile, JSON.stringify(user));
return { outside, onPath, inNpm, shipped, shippedFile, userFile };
}
const AGENT_ENV = (base) => ({ PLAN2CODE_NO_SAVED_PATH: "1", npm_config_prefix: path.join(base, "npm-prefix"), ...NO_APP });
test("GET /agents reports found, outside and missing for the custom and shipped lists", async () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
const res = cli(["open", "--workflow", "setup", "--no-open"], { env: AGENT_ENV(base) });
try {
const f = agentFixtures(base);
const { base: url, cookie } = sessionUrl(res.json.url);
const got = await (await fetch(`${url}/agents`, { headers: { cookie, connection: "close" } })).json();
const mine = got.agents.find((a) => a.id === "myagent");
assert.deepEqual(
{ state: mine.state, path: mine.path, where: mine.where, folder: mine.folder },
{ state: "found", path: f.onPath, where: "path", folder: path.dirname(f.onPath) }
);
const two = got.agents.find((a) => a.id === "agenttwo");
assert.deepEqual({ state: two.state, path: two.path, where: two.where }, { state: "outside", path: f.inNpm, where: "npm" });
const testagent = got.builtins.find((b) => b.id === "testagent");
assert.deepEqual({ state: testagent.state, where: testagent.where }, { state: "outside", where: "install-dir" });
assert.equal(testagent.name, "Test Agent");
assert.equal(testagent.command, "testagent.cmd");
assert.equal(testagent.prompt, "/plan2code");
assert.deepEqual(testagent.args, ["{prompt}"]);
assert.deepEqual(testagent.bypassArgs, ["--yes"]);
assert.deepEqual(testagent.modelArgs, ["--model", "{model}"]);
assert.equal(testagent.installUrl, "https://example.com/get");
const OS_KEY = process.platform === "win32" ? "win" : process.platform === "darwin" ? "mac" : "linux";
assert.deepEqual(testagent.install, f.shipped.agents[0].install[OS_KEY], "only this OS's install steps");
const gone = got.builtins.find((b) => b.id === "gone");
assert.deepEqual(
{ state: gone.state, path: gone.path, where: gone.where, folder: gone.folder },
{ state: "missing", path: null, where: null, folder: null }
);
// Templates come back as the form fields only: no `kind`, no found state.
assert.deepEqual(got.templates, [{ id: "templ", name: "Templ", command: "templ", prompt: "Use plan2code", args: ["{prompt}"], note: "a starter" }]);
assert.deepEqual(got.warnings, []);
} finally {
cli(["stop", "--session", res.json.sid, "--force"]);
fs.rmSync(path.join(MODELS_DIR, "agents.json"), { force: true });
fs.rmSync(path.join(MODELS_DIR, "bin", "agents.json"), { force: true });
fs.rmSync(base, { recursive: true, force: true });
}
});
test("POST /agents/use-path writes findAgent's hit into agents.json, and only that", async () => {
const base = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-agents-"));
const res = cli(["open", "--workflow", "setup", "--no-open"], { env: AGENT_ENV(base) });
try {
const f = agentFixtures(base);
const { base: url, cookie } = sessionUrl(res.json.url);
const usePath = (body) =>
fetch(`${url}/agents/use-path`, {
method: "POST",
headers: { "content-type": "application/json", cookie, origin: url, connection: "close" },
body: JSON.stringify(body),
});
const readUser = () => JSON.parse(fs.readFileSync(f.userFile, "utf8"));
const missing = await usePath({ id: "gone" });
assert.equal(missing.status, 409, "not on PATH and nowhere else either");
assert.deepEqual(await missing.json(), { error: "not-found" });
const unknown = await usePath({ id: "nope" });
assert.equal(unknown.status, 404, "no such agent at all");
assert.deepEqual(await unknown.json(), { error: "not-found" });
// Already on PATH: a 200 and no write.
const before = fs.readFileSync(f.userFile, "utf8");
const found = await usePath({ id: "myagent" });
assert.equal(found.status, 200);
assert.deepEqual(await found.json(), { ok: true, id: "myagent", command: f.onPath });
assert.equal(fs.readFileSync(f.userFile, "utf8"), before);
// Off PATH ("outside"): the command becomes where it was found. A path in
// the body is never taken.
const outside = await usePath({ id: "agenttwo", command: "should-not-be-taken", path: "should-not-be-taken" });
assert.equal(outside.status, 200);
const wanted = f.inNpm;
assert.deepEqual(await outside.json(), { ok: true, id: "agenttwo", command: wanted });
assert.equal(readUser().agents.find((a) => a.id === "agenttwo").command, wanted);
// A built-in is materialized as a new custom entry under a generated id;
// the file's other entries stand.
const builtin = await usePath({ id: "testagent" });
assert.equal(builtin.status, 200);
const saved = await builtin.json();
assert.equal(saved.id, "test-agent", "makeId kebab-cases the name");
const created = readUser().agents.find((a) => a.id === "test-agent");
assert.equal(created.command, path.join(f.outside, "testagent.cmd"));
assert.equal(created.name, "Test Agent");
assert.equal(created.prompt, "/plan2code");
assert.equal(readUser().schema, 1);
assert.deepEqual(readUser().agents.map((a) => a.id), ["myagent", "agenttwo", "test-agent"]);
} finally {
cli(["stop", "--session", res.json.sid, "--force"]);
fs.rmSync(path.join(MODELS_DIR, "agents.json"), { force: true });
fs.rmSync(path.join(MODELS_DIR, "bin", "agents.json"), { force: true });
fs.rmSync(base, { recursive: true, force: true });
}
});
// The setup tab's move: another Plan2Code process POSTs the session's sign-in
// link here, the page's stream gets a `move` event and state.setup.moved is
// set. Only a setup session answers, only for the token `open` printed, and
// only a loopback console /s/ link is a legal destination.
test("POST /handover takes only the setup token and a console sign-in link, and moves the page", async () => {
const res = cli(["open", "--workflow", "setup", "--no-open"], { env: NO_APP });
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:(\d+))\/s\/([^/]+)\//);
const cookie = cookieFor(m[1], m[3]);
const port = Number(m[2]);
const token = res.json.setup.token;
const handover = (body, headers = {}) =>
new Promise((resolve, reject) => {
const req = http.request(
{
host: "127.0.0.1",
port,
path: "/handover",
method: "POST",
headers: { "content-type": "application/json", "x-plan2code-token": token, connection: "close", ...headers },
},
(r) => {
const chunks = [];
r.on("data", (c) => chunks.push(c));
r.on("end", () => resolve({ status: r.statusCode, body: Buffer.concat(chunks).toString("utf8") }));
}
);
req.on("error", reject);
req.end(JSON.stringify(body));
});
const other = cli(["open", "--workflow", "plan", "--no-open"], { env: NO_APP });
try {
// No cookie at all: the hand-over has its own token, which is the point.
for (const headers of [{ "x-plan2code-token": "wrong-token" }, { "x-plan2code-token": "" }]) {
const no = await handover({ url: "http://127.0.0.1:9/s/abc/" }, headers);
assert.equal(no.status, 403, JSON.stringify(headers));
assert.deepEqual(JSON.parse(no.body), { error: "forbidden" });
}
for (const url of [
"https://127.0.0.1:9/s/abc/",
"http://example.com/s/abc/",
"http://127.0.0.1/s/abc/",
"http://127.0.0.1:9/x/abc/",
"http://127.0.0.1:9/s/a b/",
"javascript:alert(1)",
"",
42,
null,
]) {
const no = await handover({ url });
assert.equal(no.status, 400, JSON.stringify(url));
assert.deepEqual(JSON.parse(no.body), { error: "bad-url" });
}
// The stream sees the move the POST causes.
const events = new Promise((resolve, reject) => {
const req = http.request({ host: "127.0.0.1", port, path: "/events", headers: { cookie } }, (r) => {
let buf = "";
r.setEncoding("utf8");
r.on("data", (c) => (buf += c));
setTimeout(() => {
req.destroy();
resolve(buf);
}, 1500);
});
req.on("error", reject);
req.end();
});
await sleep(150); // the GET must land before the POST
const target = "http://localhost:9/s/NewAgent_1-2/";
const ok = await handover({ url: target });
assert.equal(ok.status, 204);
const stream = await events;
assert.ok(stream.includes(`event: move\ndata: ${JSON.stringify({ url: target })}`), stream);
const setup = readState(res.json.session).setup;
assert.equal(setup.moved.url, target);
assert.ok(setup.moved.at);
// A session that is not the setup page never answers, whatever the header.
const otherPort = Number(other.json.url.match(/^http:\/\/127\.0\.0\.1:(\d+)\//)[1]);
const notSetup = await new Promise((resolve, reject) => {
const req = http.request(
{
host: "127.0.0.1",
port: otherPort,
path: "/handover",
method: "POST",
headers: { "content-type": "application/json", "x-plan2code-token": token },
},
(r) => {
const chunks = [];
r.on("data", (c) => chunks.push(c));
r.on("end", () => resolve({ status: r.statusCode, body: Buffer.concat(chunks).toString("utf8") }));
}
);
req.on("error", reject);
req.end(JSON.stringify({ url: "http://127.0.0.1:9/s/abc/" }));
});
assert.equal(notSetup.status, 404);
assert.deepEqual(JSON.parse(notSetup.body), { error: "not-found" });
} finally {
cli(["stop", "--session", res.json.sid, "--force"]);
cli(["stop", "--session", other.json.sid, "--force"]);
}
});
// The other half of the hand-over: an agent opened under PLAN2CODE_SETUP_* posts
// its link to the setup console's /handover instead of opening a browser, and a
// refused post falls back to the browser with a note saying so.
test("an agent opened with the setup hand-over posts its link, and a refused post says so", async () => {
const setup = cli(["open", "--workflow", "setup", "--no-open"], { env: NO_APP });
const token = readState(setup.json.session).setup.token;
let agent;
try {
// setup.url is the setup session's own link; /handover resolves off it, so
// the running server answers. No --no-open: that flag is what skips this.
agent = cli(["open", "--workflow", "plan"], {
env: { ...NO_APP, PLAN2CODE_SETUP_ANNOUNCE: setup.json.setup.url, PLAN2CODE_SETUP_TOKEN: token },
});
assert.equal(agent.json.handover, true);
const moved = readState(setup.json.session).setup.moved;
assert.equal(moved.url, agent.json.url, "the setup session learned where its tab went");
const bad = cli(["open", "--workflow", "plan"], {
env: { ...NO_APP, PLAN2CODE_SETUP_ANNOUNCE: setup.json.setup.url, PLAN2CODE_SETUP_TOKEN: "wrong-token" },
});
try {
assert.equal("handover" in bad.json, false);
assert.match(bad.json.note, /Could not move the setup tab/);
} finally {
cli(["stop", "--session", bad.json.sid, "--force"]);
}
} finally {
if (agent) cli(["stop", "--session", agent.json.sid, "--force"]);
cli(["stop", "--session", setup.json.sid, "--force"]);
}
});
// The idle deadline is the only thing that stops an orphan server (server.mjs's
// comment says why it must not be optimized away); a setup session honors it too.
test("a setup session still stops on --idle-ms", async () => {
const res = cli(["open", "--workflow", "setup", "--idle-ms", "300", "--no-open"], { env: NO_APP });
try {
const events = path.join(res.json.session, "events.ndjson");
// The deadline is checked on a 20s tick, so the exit lands within a tick of the cap.
const gone = await until(() => fs.existsSync(events) && fs.readFileSync(events, "utf8").includes('"reason":"idle"'), 40000);
assert.ok(gone, "the server never recorded its idle exit");
} finally {
cli(["stop", "--session", res.json.sid, "--force"]);
}
});
// NFR-2: the launcher scrubs the app-window variables before spawning the setup
// console (test-launcher.mjs has the spawn half), so nothing can leak the page
// into an app window. Even with an announce URL left in the environment a
// console without the full signal never calls it; with the signal it does.
test("a setup console without the app signal never calls a leftover announce URL", async () => {
const calls = [];
const stub = http.createServer((req, res) => {
req.resume();
req.on("end", () => {
calls.push(`${req.method} ${req.url}`);
res.writeHead(req.url === "/session" ? 404 : 204).end();
});
});
await new Promise((r) => stub.listen(0, "127.0.0.1", r));
const announce = `http://127.0.0.1:${stub.address().port}`;
try {
const res = cli(["open", "--workflow", "setup", "--no-open"], { env: { ...NO_APP, PLAN2CODE_APP_ANNOUNCE: announce } });
try {
assert.equal(res.json.inApp, undefined);
assert.equal(res.json.announced, undefined);
assert.deepEqual(calls, [], "a stray announce URL alone is not the signal");
} finally {
cli(["stop", "--session", res.json.sid, "--force"]);
}
// With the full signal the same open announces, as the in-app tests cover.
// Spawned asynchronously: the announce endpoint lives in this process, so a
// blocking spawn would deadlock (the same reason test-in-app uses openAsync).
const inApp = await new Promise((resolve) => {
const child = spawn(
process.execPath,
[path.join(ROOT, "src", "web-console", "console.mjs"), "open", "--workflow", "setup", "--no-open"],
{
cwd: ROOT,
env: { ...ENV, ...NO_APP, PLAN2CODE_IN_APP: "1", PLAN2CODE_APP_ANNOUNCE: announce, PLAN2CODE_APP_TOKEN: "tok" },
windowsHide: true,
}
);
let out = "";
child.stdout.on("data", (c) => (out += c));
child.on("close", (status) => resolve({ status, json: JSON.parse(out.trim().split("\n").filter(Boolean).pop()) }));
});
try {
assert.equal(inApp.json.announced, true);
assert.ok(calls.some((c) => c.startsWith("POST /page")), JSON.stringify(calls));
} finally {
cli(["stop", "--session", inApp.json.sid, "--force"]);
}
} finally {
stub.close();
}
});
+8 -6
View File
@@ -555,9 +555,11 @@ test("console-launches.md and the dashboard prompt teach the handoff pick-up and
test("every module the page imports is actually served", async () => {
const dir = path.join(ROOT, "src", "web-console", "public");
const wanted = new Set(["app.js"]);
// The modules beside app.js and the screens under screens/, each import
// resolved from the file that makes it (a screen's "../state.js" is state.js).
const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...fs.readdirSync(path.join(dir, "screens")).map((f) => `screens/${f}`)];
// The modules beside app.js and the screens under screens/ (subfolders too:
// screens/agents/ is a directory), each import resolved from the file that
// makes it (a screen's "../state.js" is state.js).
const screens = (abs, rel) => fs.readdirSync(abs, { withFileTypes: true }).flatMap((e) => e.isDirectory() ? screens(path.join(abs, e.name), `${rel}${e.name}/`) : e.name.endsWith(".js") ? [`${rel}${e.name}`] : []);
const files = [...fs.readdirSync(dir).filter((f) => f.endsWith(".js")), ...screens(path.join(dir, "screens"), "screens/")];
for (const f of files) {
const src = fs.readFileSync(path.join(dir, f), "utf8");
for (const m of src.matchAll(/^\s*import\b[^"']*["'](\.\.?\/[^"']+)["']/gm)) wanted.add(path.posix.join(path.posix.dirname(f), m[1]));
@@ -651,9 +653,9 @@ test("the favicon is served as an SVG with a PNG fallback and the page points at
/* ---------------------------------------------------------------- help */
test("help: 20 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 20);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 20);
test("help: 21 tabs with unique ids", () => {
assert.equal(HELP_TABS.length, 21);
assert.equal(new Set(HELP_TABS.map((t) => t.id)).size, 21);
assert.ok(Object.isFrozen(HELP_TABS) && HELP_TABS.every((t) => Object.isFrozen(t)), "the tab list is frozen");
const ids = HELP_TABS.map((t) => t.id);
assert.equal(ids.indexOf("loop"), ids.indexOf("build") + 1, "Implementation Loop comes right after Watching a build");
+7 -4
View File
@@ -121,7 +121,10 @@ test("shape: the define-only check names a page file that touches the page at lo
// A screen reaches the rest of the page through ../state.js and the pure
// modules beside it, never through another screen: only core.js (the render
// loop, which draws every screen) imports screens, and only app.js (the
// entry) imports core.js. Each import that breaks that is named.
// entry) imports core.js. A screen's own components are not screens: files
// under a subdirectory of screens/ (screens/agents/) may be imported by the
// screen they serve and by each other, but never the other way, and never a
// top-level screen file. Each import that breaks that is named.
function pageImportProblems(pub) {
const problems = [];
for (const p of sourceFiles(pub).filter((f) => f.endsWith(".js") && (!f.includes("/") || f.startsWith("screens/")))) {
@@ -131,7 +134,7 @@ function pageImportProblems(pub) {
if (!spec.startsWith(".")) continue;
const target = path.posix.join(path.posix.dirname(p), spec);
if (target === "screens/core.js" && p !== "app.js") problems.push(`${p} imports ${spec}: only app.js imports core.js`);
else if (p.startsWith("screens/") && p !== "screens/core.js" && target.startsWith("screens/"))
else if (p.startsWith("screens/") && p !== "screens/core.js" && /^screens\/[^/]+\.js$/.test(target))
problems.push(`${p} imports ${spec}: a screen imports ../state.js and the modules beside it, never another screen`);
}
}
@@ -184,8 +187,8 @@ test("shape: no page module sets a style attribute from script", () => {
// and WORKSPACE_EDITS for /workspace/add, /edit and /remove. The git board has
// no routes of its own: its buttons are sends (`__git`), through /submit.
const ROUTE_ORDER = [
"/health", "/s/", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/cleanup", "/upload",
"/health", "/s/", "/handover", "/", "SERVABLE", "/overview", "/handoff", "/version", "/state", "/events", "/draft",
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/agents", "/agents", "/agents/test", "/agents/use-path", "/cleanup", "/upload",
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/tab/sent", "/notepad/images/",
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace",
+24 -8
View File
@@ -17,6 +17,7 @@ import {
labelFor,
WORKFLOWS,
isWorkflow,
isAgentless,
} from "../src/web-console/public/skills.js";
import { CONSOLE_WORKFLOWS, SKILL_CATALOG, catalogEntry, launchVariant, START_POSES, WORKFLOW_LABEL, dashNoteKind, onInitialPick, startPose, startingHint } from "../src/web-console/public/answers.js";
import { LAUNCH_COUNTED, PROGRESS_WORKFLOWS } from "../src/web-console/public/meter.js";
@@ -60,7 +61,7 @@ test("every skill the console knows has one entry, the dashboard included", () =
const workflows = SKILLS.map((s) => s.workflow);
assert.deepEqual([...workflows].sort(), Object.keys(WORKFLOW_LABEL).sort());
assert.equal(new Set(workflows).size, workflows.length, "one entry per workflow");
assert.deepEqual(SKILLS.map((s) => s.command).sort(), [...CONSOLE_WORKFLOWS].sort());
assert.deepEqual(SKILLS.map((s) => s.command).filter(Boolean).sort(), [...CONSOLE_WORKFLOWS].sort());
// The cards come first, in the dashboard's order.
const carded = SKILLS.filter((s) => s.card);
assert.deepEqual(carded.map((s) => s.skill), SKILL_CATALOG.map((e) => e.skill));
@@ -76,6 +77,17 @@ test("every skill the console knows has one entry, the dashboard included", () =
test("the derived exports agree with each entry", () => {
for (const s of SKILLS) {
const w = s.workflow;
// The setup page is a workflow the launcher opens, not a skill an agent
// picks: it has no skill name, command or card for the exports to mirror.
if (s.agentless) {
for (const f of ["workflow", "label", "name"]) assert.ok(typeof s[f] === "string" && s[f].trim(), `${w}: ${f} must be filled in`);
assert.equal(s.skill, null, `${w}: agent-less has no skill`);
assert.equal(s.command, null, `${w}: agent-less has no command`);
assert.equal(s.card, null, `${w}: agent-less has no card`);
assert.equal(s.pose, startPose(w), `${w}: pose`);
assert.equal(s.metered, LAUNCH_COUNTED.has(w), `${w}: metered`);
continue;
}
for (const f of ["skill", "workflow", "label", "name"]) assert.ok(typeof s[f] === "string" && s[f].trim(), `${w}: ${f} must be filled in`);
assert.equal(s.command, "/" + s.skill, `${w}: command`);
assert.equal(s.label, WORKFLOW_LABEL[w], `${w}: label`);
@@ -177,9 +189,10 @@ function poseProblems(skills, drawn) {
return problems;
}
// Every workflow the console can open has its notes behind `console.mjs help`.
// Every skill workflow the console can open has its notes behind
// `console.mjs help`; agent-less pages are opened by the launcher, not picked.
function helpProblems(skills, topics) {
return skills.filter((s) => !Object.hasOwn(topics, s.workflow)).map((s) => `${s.skill} (${s.workflow}) has no help topic in console.mjs`);
return skills.filter((s) => !s.agentless && !Object.hasOwn(topics, s.workflow)).map((s) => `${s.skill} (${s.workflow}) has no help topic in console.mjs`);
}
// The skills with a card, plus the dashboard, are exactly what install.js builds.
@@ -302,7 +315,7 @@ test("docs: console.md's open step names every workflow", () => {
const m = text.match(/`<w>` is one of ([\s\S]*?)\. Launched from the dashboard/);
assert.ok(m, "console.md: the open step's `<w>` sentence is not where the test looks");
const said = [...m[1].matchAll(/`([^`]+)`/g)].map((x) => x[1]);
assert.deepEqual(listProblems("src/web-console/console.md", said, WORKFLOWS), []);
assert.deepEqual(listProblems("src/web-console/console.md", said, WORKFLOWS.filter((w) => !isAgentless(w))), []);
});
test("docs: the dashboard skill's launch table maps every skill to its workflow", () => {
@@ -313,7 +326,7 @@ test("docs: the dashboard skill's launch table maps every skill to its workflow"
const cells = line.split("|").map((c) => c.trim()).filter(Boolean);
for (let i = 0; i + 1 < cells.length; i += 2) pairs.push(`${cells[i]} -> ${cells[i + 1]}`);
}
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => `${s.skill} -> ${s.workflow}`);
const want = SKILLS.filter((s) => s.skill && s.workflow !== "dashboard").map((s) => `${s.skill} -> ${s.workflow}`);
assert.deepEqual(listProblems("src/plan2code.md (A pick arrives)", pairs, want), []);
});
@@ -327,7 +340,7 @@ test("docs: the dashboard skill's reads-and-writes table has a row for every ski
if (m[1] === "3-implement(-review)") said.push("3-implement", "3-implement-review");
else said.push(m[1]);
}
const want = SKILLS.filter((s) => s.workflow !== "dashboard").map((s) => s.skill.replace(/^plan2code-/, ""));
const want = SKILLS.filter((s) => s.skill && s.workflow !== "dashboard").map((s) => s.skill.replace(/^plan2code-/, ""));
assert.deepEqual(listProblems("src/plan2code.md (What each skill reads and writes)", said, want), []);
});
@@ -336,8 +349,11 @@ test("docs: `console.mjs help` lists every workflow, in order", () => {
const m = out.match(/workflows: ([\s\S]*?)\n\s*\n/);
assert.ok(m, "console.mjs help prints no workflows: list");
const said = m[1].split(/[·\s]+/).filter(Boolean);
assert.deepEqual(listProblems("console.mjs help", said, WORKFLOWS), []);
assert.deepEqual(said, [...WORKFLOWS], "console.mjs help: the workflows are in skills.js order");
// The CLI's usage lists only the workflows an agent can pick: the agent-less
// setup page is opened by the launcher, never typed here (phase-2 note).
const listed = WORKFLOWS.filter((w) => !isAgentless(w));
assert.deepEqual(listProblems("console.mjs help", said, listed), []);
assert.deepEqual(said, [...listed], "console.mjs help: the workflows are in skills.js order");
});
// A count goes stale the day a skill is added; the docs say "every skill".
+24 -11
View File
@@ -401,19 +401,21 @@ test("help: the stuck tab is second, and openHelpOn only opens a tab that exists
assert.match(opener[1], /HELP_TABS\.some\(/, "openHelpOn only opens a tab that exists");
});
test("models: Codex is a model CLI on the server and the page, with its own row in the agents table", () => {
const server = fs.readFileSync(path.join(ROOT, "src", "web-console", "routes.mjs"), "utf8");
const app = publicSource("screens/agents-view.js");
test("models: the page's built-in rows match the shipped agent list's builtins", () => {
const app = publicSource("screens/agents/agents-data.js");
const list = (src) => JSON.parse(src.match(/const MODEL_CLIS = (\[[^\]]*\]);/)[1]);
assert.deepEqual(list(server), ["claude", "devin", "codex"]);
assert.deepEqual(list(app), list(server), "the page's rows match the server's lists");
// routes.mjs no longer carries a literal MODEL_CLIS: both sides read the
// builtin ids from the shipped agent list (agent-lookup.mjs).
const shipped = JSON.parse(fs.readFileSync(path.join(ROOT, "src", "launcher", "agents.json"), "utf8"));
const builtinIds = shipped.agents.filter((a) => a.kind === "builtin").map((a) => a.id);
assert.deepEqual(list(app), builtinIds, "the page's rows match the shipped builtins");
assert.ok(!/for \(const cli of \["claude", "devin"\]\)/.test(app), "no loop over a hard-coded pair");
assert.match(app, /\.\.\.MODEL_CLIS\.map\(\(cli\) => \(\{\s*key: "cli:" \+ cli,/, "the table draws a built-in row per MODEL_CLIS entry");
const names = app.match(/const BUILT_IN = \{([^}]*)\};/)[1];
for (const cli of list(app)) assert.match(names, new RegExp(`\\b${cli}: "`), `${cli} has a name in the table`);
assert.ok(!publicSource("index.html").includes("models-tab-"), "the separate Models toggles are gone");
const shipped = JSON.parse(fs.readFileSync(path.join(ROOT, "src", "launcher", "models.json"), "utf8"));
for (const cli of list(server)) assert.ok(Array.isArray(shipped[cli]), `the launcher's models.json has ${cli}`);
const models = JSON.parse(fs.readFileSync(path.join(ROOT, "src", "launcher", "models.json"), "utf8"));
for (const cli of list(app)) assert.ok(Array.isArray(models[cli]), `the launcher's models.json has ${cli}`);
});
test("getting started: the new help, status and finished-screen strings carry no em dash", () => {
@@ -486,13 +488,24 @@ test("prefs: the dialog is four tab panels in PREFS_TABS order, each section in
test("prefs: the new modules are served and preloaded, and Preferences' styles leave the shared classes alone", () => {
const html = publicSource("index.html");
for (const m of ["tabs.js", "prefs.js", "screens/prefs-dialog.js", "screens/agents-view.js"]) {
for (const m of [
"tabs.js",
"prefs.js",
"screens/prefs-dialog.js",
"screens/agents-view.js",
"screens/agents/agents-data.js",
"screens/agents/agents-list-editor.js",
"screens/agents/agents-summary.js",
"screens/agents/agents-form.js",
]) {
assert.ok(SERVABLE.has(m), `${m} is servable`);
assert.ok(html.includes(`rel="modulepreload" href="/${m}"`), `the page preloads ${m}`);
}
const css = publicSource("styles/prefs.css");
for (const cls of ["looks", "looks-row", "modal-ranges"]) {
assert.ok(!new RegExp(`\\.${cls}(?![\\w-])`).test(css), `prefs.css does not style .${cls} (the Subagents dialog shares it)`);
for (const sheet of ["styles/prefs.css", "styles/agents.css"]) {
const css = publicSource(sheet);
for (const cls of ["looks", "looks-row", "modal-ranges"]) {
assert.ok(!new RegExp(`\\.${cls}(?![\\w-])`).test(css), `${sheet} does not style .${cls} (the Subagents dialog shares it)`);
}
}
});
+129
View File
@@ -0,0 +1,129 @@
{
"schema": 1,
"agents": [
{
"id": "claude",
"name": "Claude Code",
"kind": "builtin",
"command": "claude",
"prompt": "/plan2code",
"args": ["{prompt}", "{bypass}", "{model}"],
"bypassArgs": ["--permission-mode", "bypassPermissions"],
"modelArgs": ["--model", "{model}"],
"installUrl": "https://code.claude.com/docs/en/setup",
"install": {
"win": [
{ "label": "PowerShell", "run": "irm https://claude.ai/install.ps1 | iex" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code", "note": "Needs Node.js 22 or later" }
],
"mac": [
{ "label": "Terminal", "run": "curl -fsSL https://claude.ai/install.sh | bash" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code", "note": "Needs Node.js 22 or later" }
],
"linux": [
{ "label": "Terminal", "run": "curl -fsSL https://claude.ai/install.sh | bash" },
{ "label": "npm", "run": "npm install -g @anthropic-ai/claude-code", "note": "Needs Node.js 22 or later" }
]
},
"installDirs": {
"win": ["%USERPROFILE%\\.local\\bin"],
"mac": ["~/.local/bin"],
"linux": ["~/.local/bin"]
}
},
{
"id": "devin",
"name": "Devin",
"kind": "builtin",
"command": "devin",
"prompt": "/plan2code",
"args": ["{bypass}", "{model}", "--", "{prompt}"],
"bypassArgs": ["--permission-mode", "bypass"],
"modelArgs": ["--model", "{model}"],
"installUrl": "https://docs.devin.ai/cli",
"install": {
"win": [
{ "label": "PowerShell", "run": "irm https://static.devin.ai/cli/setup.ps1 | iex" }
],
"mac": [
{ "label": "Terminal", "run": "curl -fsSL https://cli.devin.ai/install.sh | bash" }
],
"linux": [
{ "label": "Terminal", "run": "curl -fsSL https://cli.devin.ai/install.sh | bash" }
]
},
"installDirs": {
"win": ["%LOCALAPPDATA%\\devin\\cli\\bin", "%LOCALAPPDATA%\\devin\\bin"],
"mac": ["~/.local/bin"],
"linux": ["~/.local/bin"]
}
},
{
"id": "codex",
"name": "Codex",
"kind": "builtin",
"command": "codex",
"prompt": "$plan2code",
"args": ["{bypass}", "{model}", "{prompt}"],
"bypassArgs": ["--dangerously-bypass-approvals-and-sandbox"],
"modelArgs": ["--model", "{model}"],
"installUrl": "https://github.com/openai/codex",
"install": {
"win": [
{ "label": "PowerShell", "run": "powershell -ExecutionPolicy ByPass -c \"irm https://chatgpt.com/codex/install.ps1 | iex\"" },
{ "label": "npm", "run": "npm install -g @openai/codex" }
],
"mac": [
{ "label": "Terminal", "run": "curl -fsSL https://chatgpt.com/codex/install.sh | sh" },
{ "label": "npm", "run": "npm install -g @openai/codex" }
],
"linux": [
{ "label": "Terminal", "run": "curl -fsSL https://chatgpt.com/codex/install.sh | sh" },
{ "label": "npm", "run": "npm install -g @openai/codex" }
]
},
"installDirs": {
"win": ["%USERPROFILE%\\.local\\bin"],
"mac": ["~/.local/bin"],
"linux": ["~/.local/bin"]
}
},
{
"id": "copilot",
"name": "GitHub Copilot CLI",
"kind": "template",
"command": "copilot",
"prompt": "Use the /plan2code skill",
"args": ["-i", "{prompt}"],
"bypassArgs": ["--allow-all-tools"],
"modelArgs": ["--model", "{model}"]
},
{
"id": "opencode",
"name": "OpenCode",
"kind": "template",
"command": "opencode",
"prompt": "Use the plan2code skill",
"args": ["--prompt", "{prompt}"],
"bypassArgs": ["--auto"]
},
{
"id": "gemini",
"name": "Gemini CLI",
"kind": "template",
"command": "gemini",
"prompt": "Use the plan2code skill",
"args": ["{prompt}"],
"bypassArgs": ["--approval-mode=yolo"],
"note": "For unpaid tier and Google One accounts Gemini CLI was replaced by Antigravity CLI on June 18, 2026; whether gemini still runs depends on the account."
},
{
"id": "pi",
"name": "Pi",
"kind": "template",
"command": "pi",
"prompt": "/skill:plan2code",
"args": ["{prompt}"]
}
]
}
+48 -20
View File
@@ -20,6 +20,14 @@
{
"id": "opusplan",
"label": "Opus Plan — Opus in plan mode, Sonnet otherwise"
},
{
"id": "fable",
"label": "Fable, latest Fable"
},
{
"id": "best",
"label": "Best, Fable where available, otherwise Opus"
}
],
"devin": [
@@ -59,18 +67,6 @@
"id": "claude-sonnet-5-5-high",
"label": "Claude Sonnet 5.5 High"
},
{
"id": "gpt-6-sol-low",
"label": "GPT-6 Sol Low Thinking"
},
{
"id": "gpt-6-sol-medium",
"label": "GPT-6 Sol Medium Thinking"
},
{
"id": "gpt-6-sol-high",
"label": "GPT-6 Sol High Thinking"
},
{
"id": "gpt-6-luna-low",
"label": "GPT-6 Luna Low Thinking"
@@ -95,14 +91,6 @@
"id": "gemini-3-8-flash-high",
"label": "Gemini 3.8 Flash High"
},
{
"id": "kimi-k3-low",
"label": "Kimi K3 Low"
},
{
"id": "kimi-k3-high",
"label": "Kimi K3 High"
},
{
"id": "glm-5-3-low",
"label": "GLM-5.3 Low"
@@ -110,6 +98,46 @@
{
"id": "glm-5-3-high",
"label": "GLM-5.3 High"
},
{
"id": "gpt-6-1-sol-low",
"label": "GPT-6.1 Sol Low Thinking"
},
{
"id": "gpt-6-1-sol-medium",
"label": "GPT-6.1 Sol Medium Thinking"
},
{
"id": "gpt-6-1-sol-high",
"label": "GPT-6.1 Sol High Thinking"
},
{
"id": "claude-haiku-5-5-high",
"label": "Claude Haiku 5.5 High"
},
{
"id": "claude-fable-5-1-low",
"label": "Claude Fable 5.1 Low"
},
{
"id": "claude-fable-5-1-medium",
"label": "Claude Fable 5.1 Medium"
},
{
"id": "claude-fable-5-1-high",
"label": "Claude Fable 5.1 High"
},
{
"id": "gpt-6-astra-low",
"label": "GPT-6 Astra Low Thinking"
},
{
"id": "gpt-6-astra-medium",
"label": "GPT-6 Astra Medium Thinking"
},
{
"id": "gpt-6-astra-high",
"label": "GPT-6 Astra High Thinking"
}
],
"codex": []
+235
View File
@@ -0,0 +1,235 @@
// Plan2Code - the one agent list (agents.json) and the one rule for where an
// agent's command is found: the shipped list the launcher, the console and
// (mirrored in Rust) the desktop app read; defines only.
//
// install.js copies this file to ~/.plan2code/bin/ beside plan2code.js and
// agents.json, so `loadAgentList()` reads its sibling by default. The shared
// cases in scripts/fixtures/agent-lookup-cases.json pin the Node and Rust
// lookups to the same answers.
//
// Node built-ins only. No build step.
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { spawnSync } from "node:child_process";
import { fileURLToPath } from "node:url";
const AGENT_LIST_SCHEMA = 1;
const MODULE_DIR = path.dirname(fileURLToPath(import.meta.url));
const isFile = (file) => {
try {
return fs.statSync(file).isFile();
} catch {
return false;
}
};
/**
* The shipped agent list: `agents.json` in `dir` (default: the folder holding
* this module, so the installed copy in ~/.plan2code/bin/ reads its sibling).
* Returns `{ builtins, templates, warnings }`; a missing or bad file means
* empty lists and one warning, never a throw, so callers fall back. With
* `optional` an absent file warns nothing: the shipped list simply is not
* there, while a malformed one is still named.
*/
export function loadAgentList({ dir = MODULE_DIR, optional = false } = {}) {
const warnings = [];
let file;
try {
file = JSON.parse(fs.readFileSync(path.join(dir, "agents.json"), "utf8"));
} catch (error) {
if (optional && error && error.code === "ENOENT") return { builtins: [], templates: [], warnings };
const why = error && error.code === "ENOENT" ? "is missing" : "is not valid JSON";
return { builtins: [], templates: [], warnings: [`agents.json ${why}`] };
}
if (!file || typeof file !== "object" || Array.isArray(file)) {
return { builtins: [], templates: [], warnings: ["agents.json is not an object"] };
}
if (file.schema !== AGENT_LIST_SCHEMA) {
return { builtins: [], templates: [], warnings: [`agents.json has schema ${JSON.stringify(file.schema)}, not ${AGENT_LIST_SCHEMA}`] };
}
const list = Array.isArray(file.agents) ? file.agents : [];
const builtins = [];
const templates = [];
list.forEach((entry, index) => {
if (!entry || typeof entry !== "object" || Array.isArray(entry)) {
warnings.push(`agents[${index}] skipped: not an object`);
return;
}
if (entry.kind === "builtin") builtins.push(entry);
else if (entry.kind === "template") templates.push(entry);
else warnings.push(`agents[${index}] skipped: unknown kind ${JSON.stringify(entry.kind)}`);
});
return { builtins, templates, warnings };
}
/** `%NAME%` replaced from `env` (case-insensitive, as Windows reads it); an unknown name stays as written. */
function expandPercentVars(text, env) {
const lookup = (name) => {
const key = Object.keys(env).find((k) => k.toUpperCase() === name.toUpperCase());
return key === undefined ? undefined : env[key];
};
return text.replace(/%([^%]+)%/g, (whole, name) => lookup(name) ?? whole);
}
/** `~` at the start (alone or before a separator) replaced with `home`. */
function expandHome(text, home) {
return text.replace(/^~(?=$|[\\/])/, home);
}
/** The folders a PATH-like string names, quotes stripped. */
function pathDirs(pathValue) {
return String(pathValue || "")
.split(path.delimiter)
.filter(Boolean)
.map((dir) => dir.replace(/^"|"$/g, ""));
}
/** `command` in `dirs`, each extension tried on Windows. The first file hit, or null. */
function findInDirs(command, dirs, extensions) {
for (const dir of dirs) {
const hit = findInDir(command, dir, extensions);
if (hit) return hit;
}
return null;
}
/**
* `command` (a bare name) in `dir`, PATHEXT tried on Windows. Extensions come
* in uppercase there while files are usually lowercase: both cases are tried
* so the path returned names the file as written. The first hit, or null.
*/
function findInDir(command, dir, extensions) {
// A name that already carries an extension (goose.cmd) is tried as written first.
const exts = path.extname(command) ? ["", ...extensions] : extensions;
for (const ext of exts) {
for (const name of new Set([command + ext.toLowerCase(), command + ext])) {
const candidate = path.join(dir, name);
if (isFile(candidate)) return candidate;
}
}
return null;
}
/**
* The saved user and system PATH from the Windows registry (what a newly
* opened terminal gets), as one PATH string, or "" elsewhere / on failure.
* PLAN2CODE_NO_SAVED_PATH keeps it out of test runs, as the launcher's
* addSavedWindowsPath() honors it.
*/
function savedWindowsPath(windows) {
if (!windows || process.env.PLAN2CODE_NO_SAVED_PATH) return "";
const reg = path.join(process.env.SystemRoot || "C:\\Windows", "System32", "reg.exe");
const parts = [];
for (const key of ["HKLM\\SYSTEM\\CurrentControlSet\\Control\\Session Manager\\Environment", "HKCU\\Environment"]) {
let out;
try {
out = spawnSync(reg, ["query", key, "/v", "Path"], { encoding: "utf8", windowsHide: true, timeout: 5000 });
} catch {
continue;
}
const value = parseRegQueryValue(out && out.stdout);
if (value) parts.push(expandPercentVars(value, process.env));
}
return parts.join(path.delimiter);
}
/** The value after the REG_SZ / REG_EXPAND_SZ column in `reg query` output, or null. */
function parseRegQueryValue(output) {
for (const line of String(output || "").split(/\r?\n/)) {
const match = /\sREG_(?:EXPAND_)?SZ\s+(.*)$/.exec(line);
if (match && match[1].trim()) return match[1].trim();
}
return null;
}
let cachedNpmBin; // undefined: not worked out yet; null: no npm folder found.
/**
* npm's global bin folder, worked out once per process: derived without
* spawning where possible (npm_config_prefix, %APPDATA%\npm on Windows),
* `npm config get prefix` with a short timeout only as the fallback, and a
* failure means "no npm folder", never an error.
*/
function npmGlobalBin(windows, env) {
if (cachedNpmBin !== undefined) return cachedNpmBin;
cachedNpmBin = null;
const prefix = env.npm_config_prefix;
if (prefix) {
cachedNpmBin = windows ? prefix : path.join(prefix, "bin");
} else if (windows && env.APPDATA) {
cachedNpmBin = path.join(env.APPDATA, "npm");
} else {
try {
const out = spawnSync("npm", ["config", "get", "prefix"], {
encoding: "utf8",
windowsHide: true,
timeout: 3000,
});
const got = (out && out.stdout ? out.stdout.trim() : "") || "";
if (got) cachedNpmBin = windows ? got : path.join(got, "bin");
} catch {}
}
return cachedNpmBin;
}
/** Tests only: drop the cached npm folder so a later findAgent() derives it again. */
export function resetNpmBinCache() {
cachedNpmBin = undefined;
}
/**
* Where `entry.command` can run from: `{ state, path, where, folder }` with
* `state` "found" (on the process PATH), "outside" (on the saved Windows PATH,
* in npm's global folder or in one of the entry's installDirs) or "missing".
* `where` is "path" | "saved-path" | "npm" | "install-dir" | null and `folder`
* the directory it was found in. A command with a path separator is checked
* as a file, PATHEXT tried on Windows when it has none.
*
* `env` overrides `path`, `pathext`, `savedPath`, `npmBin`, `platform` and
* `home` for tests: pass strings ("" for none); `platform` is "win" | "mac" |
* "linux" (default: this OS).
*/
export function findAgent(entry, env = {}) {
const command = String(entry && entry.command ? entry.command : "").trim().replace(/^"(.*)"$/, "$1");
if (!command) return { state: "missing", path: null, where: null, folder: null };
const platform = env.platform || (process.platform === "win32" ? "win" : process.platform === "darwin" ? "mac" : "linux");
const windows = platform === "win";
const pathext = env.pathext !== undefined ? env.pathext : process.env.PATHEXT;
const extensions = windows ? String(pathext || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
// A command written as a path is checked as a file, never looked up.
if (command.includes("/") || (windows && command.includes("\\"))) {
const full = path.resolve(command);
const tries = windows && !path.extname(full) ? extensions.map((ext) => full + ext) : [full];
const hit = tries.find(isFile);
return hit
? { state: "found", path: hit, where: "path", folder: path.dirname(hit) }
: { state: "missing", path: null, where: null, folder: null };
}
const searchPath = env.path !== undefined ? env.path : process.env.PATH;
const onPath = findInDirs(command, pathDirs(searchPath), extensions);
if (onPath) return { state: "found", path: onPath, where: "path", folder: path.dirname(onPath) };
const saved = env.savedPath !== undefined ? env.savedPath : savedWindowsPath(windows);
const onSaved = findInDirs(command, pathDirs(saved), extensions);
if (onSaved) return { state: "outside", path: onSaved, where: "saved-path", folder: path.dirname(onSaved) };
const npmBin = env.npmBin !== undefined ? env.npmBin : npmGlobalBin(windows, process.env);
const onNpm = npmBin ? findInDir(command, npmBin, extensions) : null;
if (onNpm) return { state: "outside", path: onNpm, where: "npm", folder: path.dirname(onNpm) };
const home = env.home !== undefined ? env.home : os.homedir();
const dirs = (entry.installDirs && entry.installDirs[platform]) || [];
for (const dir of dirs) {
const expanded = expandPercentVars(expandHome(String(dir), home), env.vars || process.env);
const hit = findInDir(command, expanded, extensions);
if (hit) return { state: "outside", path: hit, where: "install-dir", folder: path.dirname(hit) };
}
return { state: "missing", path: null, where: null, folder: null };
}
+53 -11
View File
@@ -10,7 +10,23 @@
import fs from "node:fs";
import path from "node:path";
export const BUILTIN_AGENT_IDS = ["claude", "devin", "codex"];
import { loadAgentList } from "./agent-lookup.mjs";
import { SHIPPED_AGENTS_FILE } from "./files.mjs";
// The built-in ids come from the shipped list (bin/agents.json), so adding a
// built-in agent needs no code change here. The hard-coded trio is only the
// fallback for a missing or unreadable file. Worked out once at load, never
// throws: a broken shipped file must not take the whole module down.
function shippedBuiltinIds() {
try {
const { builtins } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE) });
const ids = builtins.map((a) => a && a.id).filter((id) => typeof id === "string" && id);
if (ids.length) return ids;
} catch {}
return ["claude", "devin", "codex"];
}
export const BUILTIN_AGENT_IDS = shippedBuiltinIds();
export const AGENTS_SCHEMA = 1;
export const MAX_AGENTS = 50;
@@ -169,29 +185,55 @@ function trimDashes(text) {
/**
* The arguments that start an entry, in order: `args` with {prompt} filled
* (the prompt appended when no argument holds it), then `modelArgs` when a
* model is chosen, then `bypassArgs` when checks are off. `prompt` defaults
* to the entry's own; a blank one drops an argument that is exactly
* {prompt}. Plain text in, plain text out: no quoting for any shell.
* model is chosen, then `bypassArgs` when checks are off. An argument that is
* exactly `{bypass}` or `{model}` expands to the entry's `bypassArgs` /
* `modelArgs` in place (nothing when off / unset) and that flag is no longer
* appended at the end. `prompt` defaults to the entry's own; a blank one
* drops an argument that is exactly {prompt}. Plain text in, plain text out:
* no quoting for any shell.
*/
export function buildArgs(entry, { prompt, model, bypass } = {}) {
const text = prompt === undefined ? (typeof entry.prompt === "string" ? entry.prompt : DEFAULT_PROMPT) : String(prompt ?? "");
const blank = !text.trim();
const modelArgs = entry.modelArgs || DEFAULT_MODEL_ARGS;
const out = [];
let placed = false;
let hasBypass = false;
let hasModel = false;
for (const arg of entry.args || []) {
if (!arg.includes("{prompt}")) {
if (arg === "{bypass}") {
hasBypass = true;
if (bypass) out.push(...(entry.bypassArgs || []));
continue;
}
if (arg === "{model}") {
hasModel = true;
if (model) for (const m of modelArgs) out.push(m.split("{model}").join(model));
continue;
}
if (arg.includes("{bypass}")) hasBypass = true;
if (arg.includes("{model}")) hasModel = true;
if (!arg.includes("{prompt}") && !arg.includes("{model}")) {
out.push(arg);
continue;
}
placed = true;
if (arg === "{prompt}" && blank) continue;
out.push(arg.split("{prompt}").join(text));
if (arg === "{prompt}" && blank) {
placed = true;
continue;
}
let next = arg;
if (next.includes("{prompt}")) {
placed = true;
next = next.split("{prompt}").join(text);
}
if (next.includes("{model}")) next = next.split("{model}").join(model || "");
out.push(next);
}
if (!placed && !blank) out.push(text);
if (model) {
for (const arg of entry.modelArgs || DEFAULT_MODEL_ARGS) out.push(arg.split("{model}").join(model));
if (model && !hasModel) {
for (const arg of modelArgs) out.push(arg.split("{model}").join(model));
}
if (bypass) out.push(...(entry.bypassArgs || []));
if (bypass && !hasBypass) out.push(...(entry.bypassArgs || []));
return out;
}
+6 -3
View File
@@ -4,7 +4,7 @@ import fs from "node:fs";
import path from "node:path";
import { HERE } from "./files.mjs";
import { WORKFLOWS, isBuild } from "./public/skills.js";
import { WORKFLOWS, isBuild, isAgentless } from "./public/skills.js";
// The CLI's own pieces, handed over by console.mjs through useCli() before
// any command runs: console.mjs runs on import, so it cannot be imported back.
@@ -22,8 +22,11 @@ function workflowLines(width = 78) {
const pad = " ".repeat(lead.length);
const lines = [];
let line = "";
WORKFLOWS.forEach((w, i) => {
const piece = i < WORKFLOWS.length - 1 ? `${w} ·` : w;
// Agent-less modes are opened by the launcher or the app, never by an agent
// typing --workflow, so they stay off the usage list (spec phase-2 note).
const listed = WORKFLOWS.filter((w) => !isAgentless(w));
listed.forEach((w, i) => {
const piece = i < listed.length - 1 ? `${w} ·` : w;
const start = lines.length ? pad : lead;
if (line && (start + line + " " + piece).length > width) {
lines.push(start + line);
+111 -21
View File
@@ -1,6 +1,7 @@
// Plan2Code Web Console - the `open` command: start or resume a session, its server and the browser.
import fs from "node:fs";
import http from "node:http";
import path from "node:path";
import { spawn } from "node:child_process";
@@ -53,6 +54,7 @@ import { WORKFLOWS, isWorkflow } from "./public/skills.js";
import { startsClean } from "./public/hops.js";
import { snapshot } from "./git-repo.mjs";
import { announcePage, currentSession, inAppSignal } from "./in-app.mjs";
import { findAgent } from "./agent-lookup.mjs";
import { handoffsDir, listHandoffs, removeHandoffs, staleHandoffs } from "./handoffs.mjs";
import {
readPatch,
@@ -139,6 +141,14 @@ export async function cmdOpen() {
if (sid && fs.existsSync(sessionDir(sid))) args.resume = sid;
}
}
// The launcher's setup flow hands this open's page back to the console that
// asked for it: instead of a browser, the session's link is POSTed to that
// console's /handover, which moves the launcher's own tab here. Fresh opens
// outside the app only; a resume or an in-app session keeps its own flow.
const setupAnnounce =
!inApp && !args.resume && !args.session && process.env.PLAN2CODE_SETUP_ANNOUNCE && process.env.PLAN2CODE_SETUP_TOKEN
? { announce: process.env.PLAN2CODE_SETUP_ANNOUNCE, token: process.env.PLAN2CODE_SETUP_TOKEN }
: null;
const { project, worktree, branch } = repoRoots();
reapHandles(project);
trace("open: project found");
@@ -235,12 +245,21 @@ export async function cmdOpen() {
}
if (args.title) s.title = args.title;
if (args.spec) s.specDir = args.spec;
// A setup session carries the hand-over data the launcher needs: which
// CLI it is setting up and the per-session token /handover checks. On
// resume it is rewritten only when --for-cli is passed or the session
// has none yet; a plain resume keeps the existing token valid.
if (args.workflow === "setup" && (args["for-cli"] !== undefined || !s.setup)) {
s.setup = { forCli: args["for-cli"] || null, token: newToken(), created: nowIso() };
}
// The loop lock follows the flag: --loop locks the page, and a resume
// without it (Fix it by hand, from a stop screen) is an ordinary,
// unlocked session.
// unlocked session. `loopExpect` goes with the lock: the app restamps it
// on its next look, so a stale setup never judges a new run.
if (loopMode) s.loop = { driving: true };
else {
delete s.loop;
delete s.loopExpect;
// The loop's cards mean nothing without it, and validate() refuses
// handledBy outside a loop session, which would wedge every post.
s.items = (s.items || []).map(({ handledBy, ...item }) => item);
@@ -270,6 +289,11 @@ export async function cmdOpen() {
if (args.workflow === "dashboard") state.wake = true;
// Locked from the first frame, before the state is first written.
if (loopMode) state.loop = { driving: true };
// The setup session's hand-over data (forCli + the token /handover
// checks), created with the state so the first write already has it.
if (args.workflow === "setup") {
state.setup = { forCli: args["for-cli"] || null, token: newToken(), created: nowIso() };
}
}
// A first payload's meter and folder reports, as `post` takes them: checked
@@ -336,7 +360,7 @@ export async function cmdOpen() {
? healthOk(existing).then((ok) => ok || healthOk(existing, 5000))
: Promise.resolve(false);
let boot = null;
if (!existing) boot = await startServer(project, worktree, sid, dir);
if (!existing) boot = await startServer(project, worktree, sid, dir, { noBrowser: Boolean(setupAnnounce) });
// The dashboard's spec picker reads its inventory straight off the session
// state, so the scan belongs to `open` rather than to the agent: filesystem
@@ -437,6 +461,11 @@ export async function cmdOpen() {
// Reuse a live server if one is already serving this session.
if (existing && (await reusable)) {
const remote = remoteWarning();
const reuseNotes = [];
if (remote.note) reuseNotes.push(remote.note);
// Reuse only happens under --resume/--session, where a setup hand-over is
// never armed, so this path just reopens the page.
if (!args["no-open"]) openBrowser(existing.url);
const inAppReport = await tellApp(inApp, { url: existing.url, sid, workflow: state.workflow });
const [owed, subCursor] = subagentsOwed();
@@ -446,12 +475,14 @@ export async function cmdOpen() {
session: dir,
url: existing.url,
embed: EMBED_API,
...(state.setup && state.setup.token ? { setup: { url: existing.url, token: state.setup.token } } : {}),
...inAppReport,
...(carried ? { pendingResult: true } : {}),
terminalLine: terminalLine(existing.url),
...folders,
...owed,
...remoteWarning(),
...(remote.remote ? { remote: remote.remote } : {}),
...(reuseNotes.length ? { note: reuseNotes.join(" ") } : {}),
});
advanceSubagents(dir, subCursor);
sweep();
@@ -467,7 +498,7 @@ export async function cmdOpen() {
// socket, a server that died taking it). Once more the old way, where
// the server binds its own port: slower, and certain.
started.kill();
started = await startServer(project, worktree, sid, dir, { handoff: false });
started = await startServer(project, worktree, sid, dir, { handoff: false, noBrowser: Boolean(setupAnnounce) });
handle = await awaitHandle(started);
}
if (!handle) {
@@ -481,9 +512,24 @@ export async function cmdOpen() {
// The early tab went to the port `open` bound. If the server ended up
// anywhere else, that tab is a dead end, so send the browser to the real one.
if (!args["no-open"] && handle.url !== started.opened) openBrowser(handle.url);
const remote = remoteWarning();
// With a setup hand-over the early tab was never sent at all: only the
// FINAL url is POSTed to the launcher console's /handover, which moves its
// own tab here. A failed hand-over falls back to the browser and a note.
let handoverDone = false;
const notes = [];
if (!args["no-open"]) {
if (setupAnnounce) {
const moved = await postHandover(setupAnnounce, handle.url);
handoverDone = moved === "ok";
// "moved" or "gone" means the first open already spent the hand-over, so
// the browser fallback is quiet; anything else earns the note.
if (moved !== "ok") openBrowser(handle.url);
if (moved === false) notes.push("Could not move the setup tab; opened a new browser tab.");
} else if (handle.url !== started.opened) {
openBrowser(handle.url);
}
}
const remote = remoteWarning();
if (remote.note) notes.push(remote.note);
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
const inAppReport = await tellApp(inApp, { url: handle.url, sid, workflow: state.workflow });
@@ -497,7 +543,9 @@ export async function cmdOpen() {
session: dir,
url: handle.url,
embed: EMBED_API,
...(state.setup && state.setup.token ? { setup: { url: handle.url, token: state.setup.token } } : {}),
...inAppReport,
...(handoverDone ? { handover: true } : {}),
port: handle.port,
pid: handle.pid,
...(carried ? { pendingResult: true } : {}),
@@ -522,6 +570,58 @@ async function tellApp(signal, page) {
return { inApp: true, announced };
}
/**
* POST this session's sign-in link to the setup console that asked for it
* (PLAN2CODE_SETUP_ANNOUNCE / _TOKEN): its /handover then moves the
* launcher's own tab here instead of a second browser opening. Loopback http
* only, like in-app.mjs's request(): a foreign or https target is no
* hand-over at all. Resolves "ok" on a 2xx, "moved" on the route's already-
* moved 409, "gone" when nothing answers (the setup console already went
* away, so the fallback is a quiet browser open) and false on any other
* answer, which earns the caller's fallback note. Never throws.
*/
function postHandover(setup, url) {
return new Promise((resolve) => {
let target;
try {
target = new URL("/handover", setup.announce);
} catch {
return resolve(false);
}
if (target.protocol !== "http:" || !["127.0.0.1", "localhost"].includes(target.hostname)) {
return resolve(false);
}
const body = JSON.stringify({ url });
const req = http.request(
target,
{
method: "POST",
timeout: 1500,
headers: {
"x-plan2code-token": setup.token,
"content-type": "application/json",
"content-length": Buffer.byteLength(body),
},
},
(res) => {
res.resume();
res.on("end", () =>
resolve(
res.statusCode === 409
? "moved"
: res.statusCode && res.statusCode >= 200 && res.statusCode < 300
? "ok"
: false
)
);
}
);
req.on("timeout", () => req.destroy());
req.on("error", () => resolve("gone"));
req.end(body);
});
}
/**
* The workspace as `open` hands it to the agent, and the cursor seeded to
* match: the agent now has the whole list, so no change up to here is owed.
@@ -563,7 +663,7 @@ function isFolder(p) {
* boot: a process's first listen() blocks for ~50ms on Windows while the
* socket stack loads, which is time the server spends booting anyway.
*/
async function startServer(project, worktree, sid, dir, { handoff = true } = {}) {
async function startServer(project, worktree, sid, dir, { handoff = true, noBrowser = false } = {}) {
const token = newToken();
const handlePath = handleFile(project, sid);
ensureDir(path.dirname(handlePath));
@@ -616,7 +716,9 @@ async function startServer(project, worktree, sid, dir, { handoff = true } = {})
// No socket to give (the bind failed): the server binds its own, and the
// channel is let go once it has.
released = handOff(child, pre);
if (pre && !args["no-open"]) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
// noBrowser: a setup hand-over replaces the early tab; the caller POSTs
// only the final url to the launcher console's /handover instead.
if (pre && !args["no-open"] && !noBrowser) opened = `http://127.0.0.1:${pre.address().port}/s/${token}/`;
} else child.unref();
// Each spawn blocks for a moment (tens of ms for cmd.exe on Windows), so
// the browser's comes after the server's: the server's boot is what the
@@ -701,7 +803,7 @@ function openBrowser(url) {
// Linux and friends. WSL first: xdg-open there either is absent or opens a
// Linux browser that cannot reach the Windows host.
if (isWsl()) {
const exe = which("wslview") ? "wslview" : "powershell.exe";
const exe = findAgent({ command: "wslview" }).state === "found" ? "wslview" : "powershell.exe";
const argsFor = exe === "wslview" ? [url] : ["-NoProfile", "-Command", "Start-Process", `"${url}"`];
spawn(exe, argsFor, { detached: true, stdio: "ignore" }).unref();
return;
@@ -721,15 +823,3 @@ function isWsl() {
return false;
}
}
function which(bin) {
const dirs = (process.env.PATH || "").split(path.delimiter);
return dirs.some((d) => {
try {
fs.accessSync(path.join(d, bin), fs.constants.X_OK);
return true;
} catch {
return false;
}
});
}
+1 -1
View File
@@ -115,7 +115,7 @@ if (!cmd || !Object.hasOwn(COMMANDS, cmd)) {
// A flag given with no value parses as `true`, and a boolean handed on as a
// path or a name crashes somewhere deep (path.basename(true) throws). Every
// flag that takes a value is checked once, here, and refused as bad usage.
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms"];
const VALUE_FLAGS = ["session", "sid", "resume", "file", "spec", "title", "workflow", "skill", "handoff", "upload", "name", "from", "seconds", "limit", "idle-ms", "for-cli"];
for (const flag of VALUE_FLAGS) {
if (flag in args && typeof args[flag] !== "string") die(`--${flag} needs a value`, 2);
}
+3
View File
@@ -39,6 +39,9 @@ export const SESSIONS_DIR = path.join(HOME_DIR, "sessions");
// theirs. The launcher reads both. PLAN2CODE_MODELS_DIR moves them, for tests.
export const PLAN2CODE_DIR = process.env.PLAN2CODE_MODELS_DIR || path.join(os.homedir(), ".plan2code");
export const SHIPPED_MODELS_FILE = path.join(PLAN2CODE_DIR, "bin", "models.json");
// The shipped agent list (builtins + starter templates), same override
// mechanism: install.js drops it in bin/ beside models.json.
export const SHIPPED_AGENTS_FILE = path.join(PLAN2CODE_DIR, "bin", "agents.json");
export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
// The person's custom agent CLIs (agents.mjs has the rules). The console is its only
// writer, from User Preferences; the launcher and the desktop app read it.
+5 -18
View File
@@ -12,10 +12,11 @@
//
// Node built-ins only.
import fs from "node:fs";
import path from "node:path";
import { spawn } from "node:child_process";
import { findAgent } from "./agent-lookup.mjs";
const IS_WINDOWS = process.platform === "win32";
const IS_MAC = process.platform === "darwin";
@@ -154,21 +155,6 @@ public static class Plan2CodeFolderPicker {
}
`;
// Resolve a command on PATH the way the shell would, including PATHEXT on Windows.
function findOnPath(command) {
const dirs = (process.env.PATH || "").split(path.delimiter).filter(Boolean);
const extensions = IS_WINDOWS ? (process.env.PATHEXT || ".EXE;.CMD;.BAT;.COM").split(";").filter(Boolean) : [""];
for (const dir of dirs) {
for (const ext of extensions) {
const candidate = path.join(dir.replace(/^"|"$/g, ""), command + ext);
try {
if (fs.statSync(candidate).isFile()) return candidate;
} catch {}
}
}
return null;
}
/**
* The native folder picker for this OS, as a command to run: it prints the
* chosen folder, or nothing when the person cancels. Null when this OS has no
@@ -233,13 +219,14 @@ export function pickerCommand(start, prompt) {
}
if (!process.env.DISPLAY && !process.env.WAYLAND_DISPLAY) return null;
if (findOnPath("zenity")) {
// findAgent is the shared "is this command on PATH" check (agent-lookup.mjs).
if (findAgent({ command: "zenity" }).state === "found") {
return {
command: "zenity",
args: ["--file-selection", "--directory", `--title=${prompt}`, `--filename=${start}${path.sep}`],
};
}
if (findOnPath("kdialog")) {
if (findAgent({ command: "kdialog" }).state === "found") {
return { command: "kdialog", args: ["--title", prompt, "--getexistingdirectory", start] };
}
return null;
+8 -4
View File
@@ -267,7 +267,7 @@ export function workflowLabel(workflow) {
// skill as `additionalReferences`). Any other next step has no browser page
// to open, and asking for one would send the next session looking for
// something that is not there. Derived from skills.js: every entry is one.
export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command);
export const CONSOLE_WORKFLOWS = FLOW_SKILLS.map((s) => s.command).filter(Boolean);
// Rides on the end of the command as part of the skill's argument. Every
// console skill takes it as the answer to "web console or terminal?" instead
@@ -420,8 +420,10 @@ export function resumeCommand({ workflow, specDir } = {}) {
// someone with no way to tell it was wrong.
const dir = /^specs\/[a-z0-9][a-z0-9._-]*$/i.test(raw) ? raw : "";
// What follows the command is the entry's `resume` (skills.js). A workflow
// the console does not know (an old session's) resumes as Pathfinder.
const entry = skillFor(workflow) || skillFor("pathfinder");
// the console does not know (an old session's, or an agent-less one like
// setup, which has no command) resumes as Pathfinder.
let entry = skillFor(workflow);
if (!entry || !entry.command) entry = skillFor("pathfinder");
if (dir && entry.resume === "overview") return `${entry.command} ${dir}/overview.md`;
if (dir && entry.resume === "folder") return `${entry.command} ${dir}/pathfinder`;
return entry.command;
@@ -1036,7 +1038,9 @@ export function noteReplyLines(title, text, attachments) {
* below the page's own threshold, and capped at an hour so a typo cannot hide
* a dead session.
*/
export function quietLimitMs(agent, baseMs) {
export function quietLimitMs(agent, baseMs, agentless = false) {
// An agent-less session has nobody to go quiet: the limit is infinite.
if (agentless) return Number.POSITIVE_INFINITY;
if (!agent || agent.status !== "working") return baseMs;
const m = Number(agent.quietMinutes);
if (!Number.isFinite(m) || m <= 0) return baseMs;
+8
View File
@@ -87,6 +87,14 @@ export async function startNewSession(command = "") {
tellApp("new-session");
}
/**
* Tell the app an agent was just found on the setup page: it returns to the
* screen it came from, rechecks, and picks that agent on the launch card.
*/
export function agentFound(id) {
tellApp("agent-found", { id });
}
/** Post `message` to the frame's parent, as `{ plan2code: kind, ...extra }`; nothing outside a frame. */
export function tellApp(kind, extra = {}) {
if (!framed()) return;
+4 -2
View File
@@ -237,8 +237,10 @@ export function chatAnswering(frameChat) {
* adrift (anything else), which is also the only signal left once the server
* is gone. An Ask message in hand (`answering`) stretches either to ASK_BUSY_MS.
*/
export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false }) {
export function chatOffline({ finish, agent, agentLastSeenMs, now, answering = false, agentless = false }) {
// An agent-less session never goes "offline": there is nobody to hear silence.
if (agentless) return false;
const silent = now - agentLastSeenMs;
const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS);
const limit = quietLimitMs(agent, agent && agent.status === "working" ? STALE_MS : ADRIFT_MS, agentless);
return silent > (answering ? Math.max(limit, ASK_BUSY_MS) : limit);
}
+2
View File
@@ -29,6 +29,7 @@ export const HELP_TABS = Object.freeze([
tab("activities", "Activities", false),
tab("finishing", "Stopping and finishing", false),
tab("prefs", "Keyboard and preferences", false),
tab("setup", "Setting up an agent", false),
tab("privacy", "Privacy and where things are saved", false),
]);
@@ -46,6 +47,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
if (workspace) return "workspace";
if (v === "ask") return "ask";
if (v === "subagents") return "subagents";
if (workflow === "setup") return "setup";
if (dashboard && meterRed) return "meter";
if (dashboard) return "dashboard";
if (v === "overview" || v === "map" || v === "draft" || v.startsWith("doc:")) return "docs";
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,110 @@
// Plan2Code Web Console - the agents view's pure data helpers.
//
// Everything the agents view computes without touching the page: draft keys,
// saved lookups, dirty checks, summary rows, an agent's shape on the way in
// or out. No DOM access and no imports at module scope, so the page and
// `node --test` both import this file.
// The CLIs the launcher reads a model list for, in table order (the shipped bin/agents.json list).
export const MODEL_CLIS = ["claude", "devin", "codex"];
// What the table calls each built-in, and the command it runs (the launcher's CLIS ids).
export const BUILT_IN = { claude: "Claude", devin: "Devin", codex: "Codex" };
export function emptyLists() {
return Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []]));
}
export function newAgent() {
return { name: "", command: "", args: [], prompt: "/plan2code", bypassArgs: [], modelArgs: ["--model", "{model}"], models: [] };
}
export function normalizeAgent(agent) {
for (const key of ["args", "bypassArgs", "modelArgs", "models"]) if (!Array.isArray(agent[key])) agent[key] = [];
return agent;
}
// A form's draft key: "cli:<cli>" for a built-in's own models, "agent:<id>"
// for an added agent, "agent:new" for one being added.
export const cliOf = (key) => key.slice("cli:".length);
export const agentId = (key) => key.slice("agent:".length);
// What a draft is checked against in `saved`: a built-in's own models for a
// cli key, a fresh newAgent for "agent:new", the added agent for "agent:<id>".
export function savedEntry(saved, key) {
if (key.startsWith("cli:")) return saved.user[cliOf(key)] || [];
if (key === "agent:new") return newAgent();
return saved.agents.find((a) => a.id === agentId(key));
}
// JSON with object keys sorted, so a label removed and typed back counts as unchanged.
export function canonical(value) {
return JSON.stringify(value, (_, v) =>
v && typeof v === "object" && !Array.isArray(v) ? Object.fromEntries(Object.keys(v).sort().map((k) => [k, v[k]])) : v
);
}
export function isDirty(saved, drafts, key) {
return drafts.has(key) && canonical(drafts.get(key)) !== canonical(savedEntry(saved, key));
}
export function nameOf(saved, drafts, key) {
if (key.startsWith("cli:")) return BUILT_IN[cliOf(key)];
const draft = drafts.get(key);
return String((draft && draft.name) || "").trim() || savedEntry(saved, key)?.name || "a new agent";
}
export function modelNames(list) {
return list.map((m) => m.label || m.id);
}
// One row per agent, in order: the built-ins, then the added agents (the
// view appends the v3 orchestrator row itself).
export function summaryRows(saved) {
return [
...MODEL_CLIS.map((cli) => ({
key: "cli:" + cli,
name: BUILT_IN[cli],
command: cli,
models: [...saved.shipped[cli], ...saved.user[cli]],
noneShip: saved.shipped[cli].length === 0,
})),
...saved.agents.map((a) => ({ key: "agent:" + a.id, name: a.name, command: a.command, models: a.models })),
];
}
// The state GET /agents already worked out for a summary row's entry:
// "ok" or "missing" as drawBadge understands them, or null when the entry
// carries no state (an older server), which falls back to a live check.
export function serverStateFor(saved, row) {
const entry = row.key.startsWith("cli:")
? saved.builtins.find((b) => b.id === cliOf(row.key))
: saved.agents.find((a) => a.id === agentId(row.key));
if (!entry || !entry.state) return null;
return entry.state === "found" ? "ok" : "missing";
}
// The list as the server wants it: blank rows and models without an id dropped.
export function cleanAgent(a) {
return {
...a,
args: a.args.filter((v) => v !== ""),
bypassArgs: a.bypassArgs.filter((v) => v !== ""),
modelArgs: a.modelArgs.filter((v) => v !== ""),
models: a.models.filter((m) => m.id),
};
}
// A template's shape as a new-agent draft, so its Use opens the same form
// a hand-typed agent gets, prefilled rather than saved behind the back.
export function templateDraft(t) {
return {
name: t.name,
command: t.command,
prompt: t.prompt || "/plan2code",
args: t.args || [],
bypassArgs: t.bypassArgs || [],
modelArgs: t.modelArgs && t.modelArgs.length ? t.modelArgs : ["--model", "{model}"],
models: [],
};
}
@@ -0,0 +1,224 @@
// Plan2Code Web Console - the agents view's per-agent form, the detail pane.
//
// What the right pane draws while a draft is being edited: the built-in's
// models fold or an added agent's fields (identity inline, Models and
// Command-line arguments folded), the foot (Save, Discard, the Unsaved
// badge, Save anyway after a 409, Delete with its inline confirm), error
// marking, and the focus save/restore that keeps a redraw from stealing
// where the person was. It only draws and listens: state and fetches live
// in the mount, reached through `ctx`.
import { el } from "../../render.js";
import { listEditor } from "./agents-list-editor.js";
import { BUILT_IN, cliOf, savedEntry, isDirty } from "./agents-data.js";
function agentField(label, field, child) {
const wrap = el("div", "agent-field");
wrap.dataset.field = field;
wrap.append(el("span", null, label), child);
return wrap;
}
function agentInput(ctx, agent, key, label, placeholder, trim) {
const input = el("input");
input.value = agent[key] || "";
input.placeholder = placeholder;
input.setAttribute("aria-label", label);
input.dataset.field = key;
input.addEventListener("input", () => {
agent[key] = trim ? input.value.trim() : input.value;
ctx.edited();
});
return input;
}
// The command's Test: where it would run from. Never saves.
function agentTest(ctx, agent) {
const wrap = el("div", "prefs-agents-test");
const test = el("button", "btn small", "Test");
test.type = "button";
const result = el("span", "help agent-test-result");
result.setAttribute("role", "status");
test.addEventListener("click", async () => {
const command = String(agent.command || "").trim();
if (!command) {
result.textContent = "Type a command first.";
return;
}
result.textContent = "Looking...";
result.textContent = await ctx.testCommand(command);
});
wrap.append(test, result);
return wrap;
}
// A folded section: `<details>` whose open state lives on the mount (`which`
// is "modelsOpen" or "argsOpen") so a redraw keeps it where the person left it.
function fold(ctx, which, title, cls, kids) {
const d = el("details", cls);
d.open = ctx[which];
d.addEventListener("toggle", () => (ctx[which] = d.open));
d.append(el("summary", null, title), ...kids);
return d;
}
// A built-in's whole form is its models, so the one fold holds the note, the
// locked shipped list and the editor for the person's own additions.
function builtInFields(ctx, cli, draft) {
const shipped = el("div", "models-list prefs-agents-shipped");
shipped.setAttribute("aria-label", "Comes with Plan2Code");
for (const m of ctx.saved.shipped[cli]) {
const row = el("div", "models-row locked");
row.append(el("span", null, m.id), el("span", null, m.label || ""));
shipped.appendChild(row);
}
const note = el("div", "models-note");
note.innerHTML =
"<ul>" +
"<li>Restart <code>plan2code</code> to see a change in its model menu.</li>" +
"<li>At any time, run <code>plan2code --model &lt;id&gt;</code>, or pick your model inside your agent before running a skill.</li>" +
"<li>Updating Plan2Code refreshes the built-in list. Models you added stay, unless the built-in list now includes them.</li>" +
"<li>Devin models are limited to Low, Medium and High effort.</li>" +
"</ul>";
const comes = el("div", "agent-field");
comes.append(el("span", null, "Comes with Plan2Code"));
if (ctx.saved.shipped[cli].length) comes.append(shipped);
else comes.append(el("p", "help prefs-agents-none", `No models ship for ${BUILT_IN[cli]} yet; add your own below.`));
const yours = agentField(
"Models you added",
"models",
listEditor({ list: draft, kind: "models", field: "models", optionalName: false, addLabel: "Add a model", onChange: ctx.edited })
);
return [fold(ctx, "modelsOpen", "Models", "agent-fold", [note, comes, yours])];
}
function addedFields(ctx, draft) {
const command = agentField("Command", "command", agentInput(ctx, draft, "command", "Command", "Program to run, such as myagent", true));
command.append(agentTest(ctx, draft));
const models = fold(ctx, "modelsOpen", "Models", "agent-fold", [
agentField(
"Models",
"models",
listEditor({ list: draft.models, kind: "models", field: "models", addLabel: "Add a model", onChange: ctx.edited })
),
]);
const args = fold(ctx, "argsOpen", "Command-line arguments", "agent-fold prefs-agents-args", [
agentField("Arguments", "args", listEditor({ list: draft.args, field: "args", placeholder: "--message={prompt}", addLabel: "Add an argument", aria: "Arguments", onChange: ctx.edited })),
agentField("Bypass arguments", "bypassArgs", listEditor({ list: draft.bypassArgs, field: "bypassArgs", placeholder: "--yes-always", addLabel: "Add an argument", aria: "Bypass arguments", onChange: ctx.edited })),
agentField("Model arguments", "modelArgs", listEditor({ list: draft.modelArgs, field: "modelArgs", placeholder: "--model={model}", addLabel: "Add an argument", aria: "Model arguments", onChange: ctx.edited })),
]);
return [
agentField("Name", "name", agentInput(ctx, draft, "name", "Name", "Name shown in the menu", true)),
command,
agentField("Start prompt", "prompt", agentInput(ctx, draft, "prompt", "Start prompt", "/plan2code (blank starts with nothing typed)", false)),
models,
args,
];
}
// Save, Discard and the Unsaved badge (shown only while the draft differs),
// the Saved mark's spot, Save anyway after a 409, and Delete agent with its
// confirm on the form itself (never the browser's confirm()).
function formFoot(ctx, key) {
const foot = el("div", "agent-foot prefs-agents-foot");
const save = el("button", "btn small primary prefs-agents-save", "Save");
save.type = "button";
save.addEventListener("click", () => ctx.save(key));
const discard = el("button", "btn small ghost prefs-agents-discard", "Discard");
discard.type = "button";
discard.addEventListener("click", () => ctx.discard());
const badge = el("span", "prefs-unsaved-badge", "Unsaved");
foot.append(save, discard, badge);
if (ctx.formReplace) {
const anyway = el("button", "btn small danger prefs-agents-replace", "Save anyway");
anyway.type = "button";
anyway.addEventListener("click", () => ctx.save(key, { replace: true }));
foot.append(anyway);
}
if (key.startsWith("agent:") && key !== "agent:new") {
if (ctx.confirming) {
const yes = el("button", "btn small danger", "Yes, delete");
yes.type = "button";
yes.addEventListener("click", () => ctx.deleteAgent(key));
const keep = el("button", "btn small ghost", "Keep");
keep.type = "button";
keep.addEventListener("click", () => {
ctx.confirming = false;
ctx.drawForm();
});
foot.append(el("span", "help", "Delete this agent?"), yes, keep);
} else {
const del = el("button", "btn small ghost danger prefs-agents-delete", "Delete agent");
del.type = "button";
del.addEventListener("click", () => {
ctx.confirming = true;
ctx.drawForm();
});
foot.append(del);
}
}
return foot;
}
// The Unsaved badge and the Save/Discard buttons appear only while the open
// draft differs from what is saved.
export function renderDirty(ctx, key) {
const foot = ctx.$("form").querySelector(".prefs-agents-foot");
if (!foot || key !== ctx.openKey) return;
const dirty = isDirty(ctx.saved, ctx.drafts, key);
for (const sel of [".prefs-agents-save", ".prefs-agents-discard", ".prefs-unsaved-badge"]) foot.querySelector(sel).hidden = !dirty;
}
// Which field or button has focus, so a redraw (an id assigned, an error
// marked) puts the person back where they were: { nth, start, end }. What
// they typed is already in the draft the redraw reads.
const FORM_FOCUSABLE = "input, button, summary";
function formFocus(form) {
const active = document.activeElement;
if (!active || !form.contains(active)) return null;
const at = { nth: [...form.querySelectorAll(FORM_FOCUSABLE)].indexOf(active) };
if (active instanceof HTMLInputElement) Object.assign(at, { start: active.selectionStart, end: active.selectionEnd });
return at;
}
function restoreFormFocus(form, at) {
if (!at) return;
const target = form.querySelectorAll(FORM_FOCUSABLE)[at.nth];
// A button the redraw hid (Save, once saved) hands focus to the heading.
if (!target || target.closest("[hidden]")) return form.querySelector(".prefs-agents-title")?.focus();
target.focus();
if (target instanceof HTMLInputElement && at.start !== undefined) {
try {
target.setSelectionRange(at.start, at.end);
} catch {}
}
}
export function drawForm(ctx) {
const pane = ctx.$("form");
const key = ctx.openKey;
const draft = ctx.drafts.get(key);
const focus = formFocus(pane);
pane.replaceChildren();
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.tabIndex = -1;
if (key.startsWith("cli:")) title.append(el("span", null, BUILT_IN[cliOf(key)]), el("code", null, cliOf(key)));
else title.append(el("span", null, key === "agent:new" ? "New agent" : savedEntry(ctx.saved, key).name));
head.appendChild(title);
pane.appendChild(head);
const fields = el("div", "prefs-agents-fields");
fields.append(...(key.startsWith("cli:") ? builtInFields(ctx, cliOf(key), draft) : addedFields(ctx, draft)));
pane.appendChild(fields);
if (ctx.formError) {
for (const input of pane.querySelectorAll("input")) {
if (input.dataset.field === ctx.formError.field) input.classList.add("invalid");
}
pane.appendChild(el("p", "agent-error", ctx.formError.error));
}
if (ctx.formReplace && ctx.formReplace.length) pane.appendChild(el("p", "agent-error", ctx.formReplace.join(" ")));
pane.appendChild(formFoot(ctx, key));
renderDirty(ctx, key);
restoreFormFocus(pane, focus);
}
@@ -0,0 +1,74 @@
// Plan2Code Web Console - the agents form's row-list editor (arguments and models).
//
// The shared editor behind the three argument lists (args, bypassArgs,
// modelArgs) and the models list. Text rows hold one input; model rows hold an
// id and a name for the menu. Which list it edits and how its rows look come
// from the options, so each field configures its own copy.
import { el } from "../../render.js";
// `list` is the live array being edited (strings, or {id, label?} models).
// `kind` "text" | "models". `onChange` runs after every edit, add or remove.
export function listEditor({ list, kind = "text", field = kind === "models" ? "models" : "", placeholder = "", addLabel = "Add", optionalName = true, aria = "", onChange = () => {} }) {
const box = el("div", "agent-rows");
box.dataset.field = field;
const draw = () => {
box.replaceChildren();
list.forEach((item, i) => {
const row = el("div", kind === "models" ? "agent-row model" : "agent-row");
const remove = el("button", "btn small ghost", "Remove");
remove.type = "button";
remove.addEventListener("click", () => {
list.splice(i, 1);
draw();
onChange();
});
if (kind === "models") {
const id = el("input");
id.value = item.id || "";
id.placeholder = optionalName ? "Model id, for {model}" : "Model id";
id.setAttribute("aria-label", "Model id");
id.dataset.field = "models";
const label = el("input");
label.value = item.label || "";
label.placeholder = optionalName ? "Name shown in the menu (optional)" : "Name shown in the menu";
label.setAttribute("aria-label", "Name shown in the menu");
label.dataset.field = "models";
id.addEventListener("input", () => {
item.id = id.value.trim();
onChange();
});
label.addEventListener("input", () => {
const text = label.value.trim();
if (text || !optionalName) item.label = text;
else delete item.label;
onChange();
});
row.append(id, label, remove);
} else {
const input = el("input");
input.value = item;
input.placeholder = placeholder;
input.setAttribute("aria-label", aria);
input.dataset.field = field;
input.addEventListener("input", () => {
list[i] = input.value.trim();
onChange();
});
row.append(input, remove);
}
box.appendChild(row);
});
const add = el("button", "btn small ghost", addLabel);
add.type = "button";
add.addEventListener("click", () => {
list.push(kind === "models" ? (optionalName ? { id: "" } : { id: "", label: "" }) : "");
draw();
onChange();
box.querySelector(".agent-row:last-of-type input")?.focus();
});
box.appendChild(add);
};
draw();
return box;
}
@@ -0,0 +1,256 @@
// Plan2Code Web Console - the agents view's collection side.
//
// The master-detail's left column for both mounts: Preferences draws one
// pickable row per agent (name, command, found badge, its models) plus the
// v3 orchestrator placeholder; the setup page draws the same rows with their
// found/outside/missing badges and the starter templates. While no form is
// open the right pane is this module's too: the empty text, or the picked
// entry's state and way forward (Start, Use it from here, the install lines).
// It only draws and listens: every fetch and every piece of state lives in
// the mount, reached through `ctx`.
import { el, copyButton } from "../../render.js";
import { summaryRows, serverStateFor, modelNames, agentId, templateDraft } from "./agents-data.js";
/* ------------------------------------------------------------- badges */
export const BADGES = {
ok: "Found",
missing: "Not found on PATH",
unknown: "Not checked",
};
export function drawBadge(badge, state) {
badge.textContent = BADGES[state];
badge.classList.remove("ok", "missing");
if (state !== "unknown") badge.classList.add(state);
}
/* --------------------------------------------------------- the prefs rows */
// One pickable row: the whole row is the Edit button, so it carries the
// data-key and the "Edit <name>" aria-label the flows rely on.
function prefsRow(ctx, row, check) {
const r = el("button", "split-row");
r.type = "button";
r.dataset.key = row.key;
r.setAttribute("aria-label", "Edit " + row.name);
r.setAttribute("aria-current", ctx.openKey === row.key ? "true" : "false");
r.addEventListener("click", () => ctx.pick(row.key));
r.appendChild(el("span", "row-name", row.name));
const sub = el("span", "row-sub");
sub.id = "row-sub-" + row.key;
r.setAttribute("aria-describedby", sub.id);
sub.appendChild(el("code", null, row.command));
const badge = el("span", "prefs-badge");
const known = serverStateFor(ctx.saved, row);
if (known) {
ctx.found.set(row.key, { command: row.command, state: known });
drawBadge(badge, known);
} else {
const last = ctx.found.get(row.key);
if (last && last.command === row.command) drawBadge(badge, last.state);
else {
badge.textContent = "Checking...";
check.push(row);
}
}
sub.appendChild(badge);
const names = modelNames(row.models);
sub.appendChild(el("span", "row-models", names.length ? `${names.length}: ${names.join(", ")}` : "None"));
r.appendChild(sub);
if (row.noneShip) r.appendChild(el("span", "help row-note", `No models ship for ${row.name} yet; open this row to add your own.`));
return r;
}
/* --------------------------------------------------------- the setup rows */
// The badge a setup row's state gets: the glanceable half, with the pane
// beside it saying what the state means and what can be done about it.
function setupStateBadge(entry) {
const badge = el("span", "prefs-badge");
if (entry.state === "found") {
badge.textContent = "Found";
badge.classList.add("ok");
} else if (entry.state === "outside") {
badge.textContent = "Found outside PATH";
badge.classList.add("missing");
} else if (entry.state === "missing") {
badge.textContent = "Not found";
badge.classList.add("missing");
} else {
badge.textContent = "Not checked";
}
return badge;
}
// A pickable setup row: selecting it fills the pane with the entry's state,
// not a form (custom agents get an Edit in that pane).
function setupRow(ctx, entry, key, badgeFor) {
const r = el("button", "split-row");
r.type = "button";
r.dataset.key = key;
r.setAttribute("aria-current", ctx.setupSel === key ? "true" : "false");
r.addEventListener("click", () => ctx.pickSetup(key));
r.appendChild(el("span", "row-name", entry.name || entry.id));
const sub = el("span", "row-sub");
sub.appendChild(el("code", null, entry.command));
if (badgeFor) sub.appendChild(badgeFor(entry));
r.appendChild(sub);
return r;
}
/* ---------------------------------------------------------- the list itself */
// The left column, whichever the mode: rows, the placeholder or templates,
// then the scaffold's Add agent button pinned last (grabbed before the list
// is cleared: a live query for it after replaceChildren finds nothing).
export function renderSummary(ctx) {
const list = ctx.$("table");
const add = ctx.$("add");
list.replaceChildren();
if (ctx.mode === "setup") {
const cli = ctx.forCli();
const builtins = [...ctx.saved.builtins].sort((a, b) => (a.id === cli ? -1 : b.id === cli ? 1 : 0));
for (const b of builtins) list.appendChild(setupRow(ctx, b, "setup:" + b.id, setupStateBadge));
for (const a of ctx.saved.agents) list.appendChild(setupRow(ctx, a, "setup:" + a.id, setupStateBadge));
if (ctx.saved.templates.length) {
list.appendChild(el("div", "split-list-head", "Or start from a template"));
for (const t of ctx.saved.templates) list.appendChild(setupRow(ctx, t, "setup:" + t.name));
}
} else {
const check = [];
for (const row of summaryRows(ctx.saved)) list.appendChild(prefsRow(ctx, row, check));
if (ctx.saved.templates.length) {
list.appendChild(el("div", "split-list-head", "Or start from a template"));
for (const t of ctx.saved.templates) list.appendChild(setupRow(ctx, t, "setup:" + t.name));
}
const soon = el("div", "split-row soon");
soon.append(el("span", "row-name", "v3 orchestrator"), el("span", "row-sub", "Nothing to set yet."));
list.appendChild(soon);
if (check.length) ctx.checkFound(check);
}
if (add) list.appendChild(add);
}
/* ------------------------------------------------ the pane while nothing is open */
// How the person puts the found folder on PATH themselves, for the OS their
// browser reports. The server already knows where the agent is; this is the
// alternative to letting Plan2Code save that location for it.
function pathNote(folder) {
const os = navigator.platform || navigator.userAgent || "";
if (/win/i.test(os)) {
return "Or add its folder to your PATH: Settings > System > About > Advanced system settings > Environment Variables.";
}
if (/mac/i.test(os)) return `Or add its folder to PATH in ~/.zshrc: export PATH="${folder}:$PATH"`;
return `Or add its folder to PATH in ~/.bashrc: export PATH="${folder}:$PATH"`;
}
// The state area of a picked setup entry: the badge, what the state means,
// and the one thing to do about it (Start, Use it from here, the install lines).
function setupStateArea(ctx, entry) {
const area = el("div", "setup-agent-state");
const badge = setupStateBadge(entry);
if (entry.state === "found") {
const line = el("p", "setup-agent-line");
line.appendChild(badge);
if (entry.path) line.append(" ", el("span", "help", entry.path));
area.appendChild(line);
// A session opened for one CLI only offers that one's Start.
if (ctx.onStart && (!ctx.forCli() || entry.id === ctx.forCli())) {
const start = el("button", "btn small primary", "Start with this agent");
start.type = "button";
start.addEventListener("click", () => ctx.onStart(entry));
area.appendChild(start);
}
} else if (entry.state === "outside") {
const line = el("p", "setup-agent-line");
line.append(badge, ` Found at ${entry.path || ""}, but not on PATH`);
area.appendChild(line);
const use = el("button", "btn small", "Use it from here");
use.type = "button";
use.addEventListener("click", () => ctx.useFromHere(entry));
area.appendChild(use);
area.appendChild(el("p", "help", entry.folder ? pathNote(entry.folder) : "Or add its folder to your PATH yourself."));
} else {
area.appendChild(badge);
if (entry.state === "missing") {
for (const inst of Array.isArray(entry.install) ? entry.install : []) {
const d = el("div", "setup-install");
d.append(el("span", null, inst.label), el("code", null, inst.run));
if (inst.note) d.appendChild(el("span", "help", inst.note));
d.appendChild(copyButton(inst.run));
area.appendChild(d);
}
if (entry.installUrl) {
const a = el("a", null, "Install page");
a.href = entry.installUrl;
a.target = "_blank";
a.rel = "noopener";
area.appendChild(a);
}
}
}
return area;
}
// A template's pane half: its name, command and note with a Use that opens
// the new-agent form prefilled, shared by both mounts.
function templatePane(ctx, template) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.append(el("span", null, template.name), el("code", null, template.command));
head.appendChild(title);
box.appendChild(head);
if (template.note) box.appendChild(el("p", "help", template.note));
const use = el("button", "btn small", "Use this template");
use.type = "button";
use.addEventListener("click", () => {
// Cloned: the form edits the draft in place, and saved.templates is
// the server's copy the next load draws from.
ctx.drafts.set("agent:new", structuredClone(templateDraft(template)));
ctx.pick("agent:new");
});
box.appendChild(use);
return box;
}
// The detail pane with no form open: the picked entry's state and way
// forward, a template's note and Use, or the empty text. In Preferences a
// template row drives the same pane; every other row opens a form.
export function drawSummaryPane(ctx) {
const pane = ctx.$("form");
pane.replaceChildren();
const sel = ctx.setupSel;
const all = [...ctx.saved.builtins, ...ctx.saved.agents];
const entry = sel && all.find((e) => "setup:" + e.id === sel);
const template = sel && !entry && ctx.saved.templates.find((t) => "setup:" + t.name === sel);
if (ctx.mode !== "setup") {
pane.appendChild(template ? templatePane(ctx, template) : el("div", "split-empty", "Pick an agent on the left to edit it here."));
return;
}
if (entry) {
const box = el("div", "setup-detail");
const head = el("div", "form-head");
const title = el("h3", "prefs-agents-title");
title.append(el("span", null, entry.name || entry.id), el("code", null, entry.command));
head.appendChild(title);
box.append(head, setupStateArea(ctx, entry));
if (ctx.saved.agents.includes(entry)) {
const edit = el("button", "btn small", "Edit");
edit.type = "button";
edit.setAttribute("aria-label", "Edit " + (entry.name || entry.id));
edit.addEventListener("click", () => ctx.pick("agent:" + entry.id));
box.appendChild(edit);
}
pane.appendChild(box);
return;
}
if (template) {
pane.appendChild(templatePane(ctx, template));
return;
}
pane.appendChild(el("div", "split-empty", "Pick an agent on the left to see its state and the way forward."));
}
@@ -66,7 +66,7 @@ export function openPrefs(tab) {
}
// The unsaved prompt on screen: { resolve, promise, from }, or null. `from`
// is what had focus when it asked (the tab, Close, Back to summary, a field).
// is what had focus when it asked (the tab, Close, another agent's row, a field).
let asking = null;
// Everything in the dialog but the prompt, kept out of reach while it asks.
@@ -85,7 +85,7 @@ function endAsking(go) {
}
// Before anything leaves an agent form with an unsaved edit (Close, Esc, a
// backdrop click, another tab, Back to summary): Save, Discard or Keep
// backdrop click, another tab, another agent's row): Save, Discard or Keep
// editing, asked inside the dialog. Resolves true when it may go on.
export function confirmUnsaved() {
if (!hooks.hasUnsaved()) return Promise.resolve(true);
+182
View File
@@ -0,0 +1,182 @@
// Plan2Code Web Console - the agent-less setup screen: pick or install an
// agent, then hand the session to it. Only defines.
//
// `plan2code` opens this page when no agent can run. The list it draws is the
// same agents view User Preferences drives (mountAgentsView, handed in by
// core.js because a screen never imports a screen), in its "setup" mode: a
// row per agent with its found state and the one thing to do about it.
// Start posts the pick as a session action the waiting launcher collects;
// the new agent's console then calls /handover, which sends this page the
// `move` event that carries it across. The grace line only shows if that
// move never comes.
import { agentFound, framed } from "../app-bridge.js";
import { el } from "../render.js";
import { hooks, page, redraw, saveNow } from "../state.js";
const $ = (id) => document.getElementById(id);
// The screen, its mounted agents view, and the start it is waiting on. All
// module-level because renderMain clears the column every pass: re-attaching
// the SAME root keeps the DOM, the open form and every typed character.
let root = null;
let view = null;
let moved = false;
let graceTimer = null;
// Once the grace wait has ended the line stays drawn: a redraw rebuilds the
// pane from this flag rather than the element.
let graceShown = false;
// How long the starting pane waits for the `move` event before it points at
// the terminal. Overridable in tests through window.__P2C_SETUP_GRACE_MS.
const GRACE_MS = () => Number(window.__P2C_SETUP_GRACE_MS) || 120000;
// The skill's own Planny acting out "setup", cloned from the template in
// index.html so the drawing stays markup; the dock's Planny is the fallback.
function setupStage() {
const stage = el("div", "setup-stage");
const art = $("start-poses")?.content.querySelector('[data-pose="setup"]');
if (art) stage.appendChild(art.cloneNode(true));
else {
const bot = $("planny")?.cloneNode(true);
if (bot) {
bot.removeAttribute("id");
stage.appendChild(bot);
}
}
return stage;
}
// The pick is sent: the launcher turns it into a session that hands this
// tab over. `entry` is the agent row's object ({ id, name, ... }).
async function onStart(entry) {
const label = entry.name || entry.id;
page.local.setupStart = { id: entry.id, label, at: Date.now() };
saveNow();
try {
const res = await fetch("/submit", {
method: "POST",
headers: { "content-type": "application/json" },
body: JSON.stringify({ actions: [{ i: "__start", type: "start", agent: entry.id }], reply: "Start with " + label }),
});
if (!res.ok) throw new Error("refused");
} catch {
// The send never landed, so the wait never starts: put the list back.
delete page.local.setupStart;
saveNow();
hooks.banner("That did not go through, but the console is still up. Nothing was lost, try again.", "warn");
redraw();
return;
}
redraw();
armGrace();
}
// The grace wait for the `move` event: the new session should take this tab
// over itself, and only a wait that ends unmoved earns the terminal hint.
function armGrace() {
clearTimeout(graceTimer);
graceTimer = setTimeout(() => {
graceTimer = null;
if (moved || !page.local.setupStart) return;
graceShown = true;
for (const note of document.querySelectorAll(".setup-no-page, .setup-back")) note.hidden = false;
}, GRACE_MS());
}
// The `move` event reached the page (core.js follows the url itself); this
// only stands the grace wait down so the hint can never appear mid-handover.
export function setupMoved(url) {
moved = true;
clearTimeout(graceTimer);
graceTimer = null;
}
// The pick-list pane, built once and re-attached every render. mountAgents
// is core.js's copy of mountAgentsView (a screen never imports a screen), so
// a bare import under a test simply leaves the list unmounted.
function buildRoot(mountAgents) {
const box = el("div", "setup-screen");
box.appendChild(setupStage());
box.appendChild(el("p", "card-kicker", "Agent setup"));
box.appendChild(el("h2", null, "No agent yet"));
box.appendChild(
el(
"p",
"help",
"Plan2Code runs your AI agent for you, but it could not find one on this computer. Pick one below, or install one and press Check again."
)
);
const agents = el("div", "setup-agents");
box.appendChild(agents);
const actions = el("div", "setup-actions");
const again = el("button", "btn small", "Check again");
again.type = "button";
again.addEventListener("click", () => view?.load());
actions.appendChild(again);
box.appendChild(actions);
if (mountAgents) {
// The setup page has no unsaved prompt of its own: picking a row is
// always free. The pick itself, not the dialog, is what can be lost.
view = mountAgents(agents, {
mode: "setup",
// A getter, not a snapshot: use-path on the asked-for built-in rewrites
// state.setup.forCli to the saved id, and the Start gate must see it.
forCli: () => (page.S && page.S.setup && page.S.setup.forCli) || null,
// In the app's window there is no waiting launcher to Start for: the
// app picks the found agent on its own launch card instead, and hears
// of it through agent-found.
onStart: framed() ? null : onStart,
onFound: framed() ? (entry) => agentFound(entry.id) : null,
confirmUnsaved: () => Promise.resolve(true),
});
view.wire();
view.load();
}
return box;
}
// The waiting pane: same bones as the starting screens, plus the hint the
// grace timer reveals if the new session never calls back.
function startingPane(started) {
const pane = el("div", "launching setup-starting");
pane.appendChild(setupStage());
pane.appendChild(el("p", "card-kicker", "On it"));
pane.appendChild(el("h2", "launch-title", `Starting ${started.label}…`));
pane.appendChild(el("p", "launch-hint", "This page moves to your session the moment it opens. No need to touch anything."));
const noPage = el("p", "help setup-no-page", `${started.label} did not open a page. Look at the terminal where you ran plan2code.`);
noPage.hidden = !graceShown;
pane.appendChild(noPage);
// A wait that died unmoved should not park the page on "Starting" forever:
// once the grace hint is up, the way back to the pick list shows beside it.
const back = el("button", "btn small setup-back", "Show the agent list again");
back.type = "button";
back.hidden = !graceShown;
back.addEventListener("click", () => {
delete page.local.setupStart;
graceShown = false;
saveNow();
redraw();
});
pane.appendChild(back);
return pane;
}
// The agent-less session's whole main column. The root is persistent rather
// than drawn each pass, so an in-progress form survives every re-render.
export function renderSetup(main, mountAgents) {
const started = page.local.setupStart;
if (started) {
// A reload mid-wait starts the wait over: the move may have gone unheard
// while the page was down, and the hint is its fallback.
if (!graceTimer && !moved && !graceShown) armGrace();
main.appendChild(startingPane(started));
return;
}
if (graceTimer) {
clearTimeout(graceTimer);
graceTimer = null;
}
if (!root) root = buildRoot(mountAgents);
main.appendChild(root);
}
+5 -1
View File
@@ -6,6 +6,7 @@
import { page, redraw } from "./state.js";
import { boardAwaiting } from "./git-board.js";
import { defaultSpec, reviewOffer, dashboardOffer, submittedAwaiting, quietLimitMs } from "./answers.js";
import { isAgentless } from "./skills.js";
import { activityLabel, workingLine } from "./labels.js";
import { ASK_BUSY_MS, chatAnswering } from "./chat.js";
@@ -203,7 +204,7 @@ export function workingMs() {
// The three silence thresholds below, stretched while the agent has said a
// long quiet stretch is normal (a build task). See quietLimitMs.
export const patience = (baseMs) => quietLimitMs(page.S && page.S.agent, baseMs);
export const patience = (baseMs) => quietLimitMs(page.S && page.S.agent, baseMs, isAgentless(page.S && page.S.workflow));
// What the agent says it is doing right now, when it has said: "Task 3 of 9:
// the user service". Only meaningful while it is working. A build's line is
@@ -232,6 +233,8 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page
// An agent answering an Ask message is out of `wait` too, and busy rather than
// gone, so it gets ASK_BUSY_MS before anything calls it adrift.
export function agentAdrift() {
// An agent-less session has nobody to be adrift: silence means nothing there.
if (isAgentless(page.S && page.S.workflow)) return false;
if (!page.agentLastSeen || page.gone || finish()) return false;
const silent = Date.now() - Date.parse(page.agentLastSeen);
const limit = page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS);
@@ -266,6 +269,7 @@ export const stranded = () => page.pendingResult && agentAdrift();
// turn ended while the person was away) and the press sits saved until it
// is woken.
export function pressStranded() {
if (isAgentless(page.S && page.S.workflow)) return false;
if (!finish() || page.gone || !page.pendingResult || !page.agentLastSeen) return false;
if (!page.local.afterBuild || page.local.afterBuild === "done") return false;
return Date.now() - Date.parse(page.agentLastSeen) > UNCOLLECTED_MS;
+25 -2
View File
@@ -64,7 +64,7 @@ function skill(entry) {
const card = entry.card ? Object.freeze({ ...entry.card }) : null;
const states = Array.isArray(entry.states) ? Object.freeze([...entry.states]) : entry.states;
const greyed = entry.greyed ? Object.freeze({ ...entry.greyed }) : null;
return Object.freeze({ marksNext: false, ...entry, command: "/" + entry.skill, states, greyed, card });
return Object.freeze({ marksNext: false, ...entry, command: entry.skill ? "/" + entry.skill : null, states, greyed, card });
}
export const SKILLS = Object.freeze([
@@ -446,6 +446,26 @@ export const SKILLS = Object.freeze([
"Writes down everything a new session would need, as a single document: what was decided, what is done, what is left. Use it when a conversation got long, a machine changed, or tomorrow-you deserves the context today-you has.",
},
}),
// The agent-less setup page: opened by the `plan2code` command (or the app)
// when no agent can run. It is a workflow, not a skill: no command, no card,
// and every list derived from FLOW_SKILLS leaves it out (no card, no command,
// no resume, metered false). `agentless` switches off the agent-silence
// states, the Ask and Subagents tabs, the Notebook send and most of the top
// bar, all checked through isAgentless().
skill({
skill: null,
workflow: "setup",
agentless: true,
label: "Agent setup",
name: "Setup",
pose: "setup",
builds: false, phased: false, metered: false, templates: false,
weight: null, started: null, ran: null, resume: null,
subagents: null,
states: null,
greyed: null,
card: null,
}),
skill({
skill: "plan2code",
workflow: "dashboard",
@@ -466,7 +486,8 @@ export const SKILLS = Object.freeze([
export const FLOW_SKILLS = Object.freeze(SKILLS.filter((s) => !s.appOnly));
const BY_WORKFLOW = new Map(FLOW_SKILLS.map((s) => [s.workflow, s]));
const BY_SKILL = new Map(FLOW_SKILLS.map((s) => [s.skill, s]));
// Entries with no skill (the agent-less setup page) are not looked up by one.
const BY_SKILL = new Map(FLOW_SKILLS.filter((s) => s.skill).map((s) => [s.skill, s]));
// Every workflow name the console knows, in SKILLS order.
export const WORKFLOWS = Object.freeze(FLOW_SKILLS.map((s) => s.workflow));
@@ -490,6 +511,8 @@ export const isBuild = (workflow) => Boolean(skillFor(workflow)?.builds);
export const isPhased = (workflow) => Boolean(skillFor(workflow)?.phased);
export const isMetered = (workflow) => Boolean(skillFor(workflow)?.metered);
export const takesTemplates = (workflow) => Boolean(skillFor(workflow)?.templates);
/** A session with no agent behind it: silence states, Ask and helpers stay off. */
export const isAgentless = (workflow) => Boolean(skillFor(workflow)?.agentless);
/** The Subagents switch's instruction for a workflow, or null when it is not offered. */
export function subagentsFor(workflow) {
+157
View File
@@ -0,0 +1,157 @@
/* agents.css: the Agents & models view - a master-detail split shared by User
Preferences' tab and the agent-less setup page. The list is pinned left;
the right pane holds the picked agent's form (prefs), the picked entry's
state and way forward (setup), or the empty text. Every rule that used to
be spread over prefs.css and responsive.css lives here. */
/* ------------------------------------------------------------- the mount */
.prefs-agents { display: grid; gap: 10px; }
.prefs-agents > .help { margin: 0; }
.prefs-agents [hidden], .setup-agents [hidden] { display: none; }
[data-av="status"]:empty { display: none; }
[data-av="status"].error { color: var(--danger, #d64545); }
/* ----------------------------------------------------------- the split */
.split {
display: grid;
grid-template-columns: 250px minmax(0, 1fr);
border: 1px solid var(--rule-2);
border-radius: var(--radius);
overflow: hidden;
background: var(--panel);
}
.split-list {
border-right: 1px solid var(--rule);
display: flex;
flex-direction: column;
min-width: 0;
background: var(--panel-2);
}
.split-list-head { padding: 8px 12px 2px; color: var(--ink-3); font-size: 13px; }
.split-row {
appearance: none;
font: inherit;
text-align: left;
border: 0;
border-bottom: 1px solid var(--rule);
background: transparent;
color: var(--ink);
padding: 10px 12px;
cursor: pointer;
display: grid;
gap: 2px;
}
.split-row:hover { background: var(--accent-soft); }
.split-row[aria-current="true"] { background: var(--accent-soft); box-shadow: inset 3px 0 0 var(--accent); }
.split-row .row-name { font-weight: 600; font-size: 13.5px; }
.split-row .row-sub { display: flex; align-items: center; gap: 6px; font-size: 12px; color: var(--ink-3); flex-wrap: wrap; }
.split-row .row-sub code { color: var(--ink-3); }
.split-row .row-models { color: var(--ink-2); overflow-wrap: anywhere; }
.split-row .row-note { display: block; margin-top: 2px; font-size: 12px; }
.split-row.soon { color: var(--ink-3); font-style: italic; cursor: default; }
.split-add { margin: 8px; align-self: flex-start; }
.split-pane {
padding: 16px 18px 30px;
display: grid;
gap: 12px;
align-content: start;
min-width: 0;
}
.split-empty { color: var(--ink-3); display: grid; place-items: center; min-height: 240px; text-align: center; }
/* ------------------------------------------------------------- badges */
.prefs-badge, .prefs-unsaved-badge {
display: inline-block;
font-size: 11.5px;
line-height: 1.5;
padding: 0 7px;
border-radius: 10px;
background: var(--panel-2);
color: var(--ink-3);
white-space: nowrap;
}
.split-row .prefs-badge { background: var(--panel); }
.prefs-badge.ok { color: var(--ok); }
.prefs-badge.missing { color: var(--warn); }
.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); }
/* -------------------------------------------------------------- the form */
.form-head { display: flex; align-items: baseline; gap: 8px; flex-wrap: wrap; }
.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; }
.prefs-agents-title code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-title:focus { outline: none; }
.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr); gap: 12px; }
.prefs-agents-fields input { min-width: 0; }
.prefs-agents-fields input.invalid, .split-pane input.invalid { border-color: var(--danger, #d64545); }
.agent-field { display: grid; gap: 4px; min-width: 0; }
.agent-field > span, .agent-field > label { font-size: 0.85em; opacity: 0.85; }
.agent-rows { display: grid; gap: 4px; }
.agent-row { display: grid; grid-template-columns: minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.agent-row.model { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; }
.agent-foot { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.agent-foot .help { margin: 0; }
.prefs-agents-test .agent-test-result { flex: 1 1 auto; }
.agent-error { margin: 0; color: var(--danger, #d64545); font-size: 0.9em; }
.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.prefs-agents-test .help { margin: 0; }
.prefs-agents-none { margin: 0; }
/* A folded section (Models, Command-line arguments): the picked design keeps
both behind a summary line until opened. */
.agent-fold { display: grid; gap: 8px; }
.agent-fold > summary { cursor: pointer; color: var(--accent); font-size: 13px; }
.agent-fold[open] > summary { margin-bottom: 4px; }
.agent-fold > .agent-field + .agent-field, .agent-fold > .models-note + .agent-field { margin-top: 8px; }
.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; }
/* The Saved mark sits in the form's foot, in the flow, after the buttons. */
.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; }
/* ------------------------------------------------------------- models lists */
.models-note { font-size: 0.9em; opacity: 0.85; }
.models-note p, .models-note ul { margin: 0 0 6px; }
.models-note ul { padding-left: 18px; }
.models-list { display: grid; gap: 4px; max-height: 160px; overflow: auto; }
.models-list:empty { display: none; }
.models-row { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr) auto; gap: 6px; align-items: center; }
.models-row.locked { grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); font-size: 0.88em; opacity: 0.75; }
.models-row input { min-width: 0; }
/* --------------------------------------------------------- the setup pane */
.setup-detail { display: grid; gap: 12px; align-content: start; }
.setup-agent-state { display: grid; gap: 6px; }
.setup-agent-line {
margin: 0;
color: var(--ink-2);
font-size: 13px;
}
.setup-install {
display: flex;
align-items: center;
gap: 8px;
margin: 4px 0 0;
flex-wrap: wrap;
}
.setup-install code {
background: var(--panel-2);
border-radius: 6px;
padding: 2px 7px;
font-size: 12px;
}
/* --------------------------------------------------------- narrow screens */
@media (max-width: 720px) {
.split { grid-template-columns: 1fr; }
.split-list { border-right: 0; border-bottom: 1px solid var(--rule); max-height: 260px; overflow: auto; }
}
+8 -2
View File
@@ -126,11 +126,12 @@
they carry view-box origins rather than their own boxes. */
.planny .arms { display: none; }
.planny .a-rest { display: inline; }
.planny:is(.is-point, .is-work, .is-done, .is-gone, .is-adrift) .a-rest { display: none; }
.planny:is(.is-point, .is-work, .is-done, .is-gone, .is-adrift, .is-setup) .a-rest { display: none; }
.planny.is-point .a-point,
.planny.is-work .a-work,
.planny.is-done .a-done,
.planny.is-gone .a-gone { display: inline; }
.planny.is-gone .a-gone,
.planny.is-setup .a-setup { display: inline; }
.planny .arm.wave,
.planny .arm.pump-l,
.planny .arm.pump-r { transform-box: view-box; }
@@ -182,6 +183,11 @@
.planny.is-gone { opacity: 0.5; }
.planny.is-gone .eye { fill: var(--warn); animation: none; transform: scaleY(0.12); }
/* The setup page, waiting on a pick: the point look without the work
spinner -- a friendly lean and wave, star lit, while nothing runs yet. */
.planny.is-setup { animation: planny-lean 2.6s ease-in-out infinite; }
.planny.is-setup .eye { fill: var(--accent); }
/* ------------------------------------------------------ mood variants
Each mood above is a family, not a single drawing: app.js rolls a v0/v1/v2
+26 -66
View File
@@ -1,5 +1,6 @@
/* prefs.css: User Preferences' tabs (the side list, the narrow strip), the Saved
mark, the Agents & models table and form, and the unsaved prompt. */
mark, and the unsaved prompt. The Agents & models view's rules moved to
agents.css when it became a master-detail split. */
/* --------------------------------------------------------- tabs and panels */
@@ -73,69 +74,6 @@
.prefs-saved.is-saved { opacity: 1; }
}
/* --------------------------------------------------------- Agents & models */
.prefs-agents { display: grid; gap: 10px; }
.prefs-agents > .help { margin: 0; }
.prefs-agents [hidden] { display: none; }
#agents-status:empty { display: none; }
#agents-status.error { color: var(--danger, #d64545); }
#agents-add { justify-self: start; }
.prefs-agents-table { width: 100%; border-collapse: collapse; font-size: 13.5px; }
.prefs-agents-table th {
text-align: left;
font-weight: 600;
font-size: 12px;
color: var(--ink-3);
padding: 4px 8px;
border-bottom: 1px solid var(--rule-2);
}
.prefs-agents-table td { padding: 8px; border-bottom: 1px solid var(--rule-2); vertical-align: top; }
.prefs-agents-name span, .prefs-agents-name code { display: block; }
.prefs-agents-name code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-name .help { margin-top: 2px; font-size: 12px; }
.prefs-agents-models { color: var(--ink-2); overflow-wrap: anywhere; }
.prefs-agents-edit { text-align: right; }
.prefs-agents-soon td { color: var(--ink-3); font-style: italic; }
.prefs-badge, .prefs-unsaved-badge {
display: inline-block;
font-size: 11.5px;
line-height: 1.5;
padding: 0 7px;
border-radius: 10px;
background: var(--panel-2);
color: var(--ink-3);
white-space: nowrap;
}
.prefs-badge.ok { color: var(--ok); }
.prefs-badge.missing { color: var(--warn); }
.prefs-unsaved-badge { background: none; border: 1px solid var(--warn); color: var(--warn); }
.prefs-agents-form { display: grid; gap: 10px; }
.prefs-agents-back { justify-self: start; }
.prefs-agents-title { display: flex; align-items: baseline; gap: 8px; margin: 0; font-size: 15px; }
.prefs-agents-title code { font-size: 12px; color: var(--ink-3); }
.prefs-agents-title:focus { outline: none; }
.prefs-agents-fields { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 10px 14px; }
.prefs-agents-fields > .models-note,
.prefs-agents-fields > [data-field="models"],
.prefs-agents-fields > .prefs-agents-args,
.prefs-agents-fields > .agent-field:has(> .models-list),
.prefs-agents-fields > .agent-field:has(> .prefs-agents-none) { grid-column: 1 / -1; }
.prefs-agents-form input { min-width: 0; }
.prefs-agents-form input.invalid { border-color: var(--danger, #d64545); }
.prefs-agents-test { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
.prefs-agents-test .help { margin: 0; }
.prefs-agents-none { margin: 0; }
.prefs-agents-args { display: grid; gap: 8px; }
.prefs-agents-args > summary { cursor: pointer; color: var(--accent); font-size: 13px; }
.prefs-agents-args[open] > summary { margin-bottom: 4px; }
.prefs-agents-args > .agent-field + .agent-field { margin-top: 8px; }
/* The Saved mark sits in the form's foot, in the flow, after the buttons. */
.prefs-agents-foot > .prefs-saved { position: static; max-width: none; text-align: left; }
/* --------------------------------------------------------- unsaved prompt */
/* Over the dialog, inside it: never the browser's confirm(). */
@@ -183,6 +121,28 @@
}
.prefs-tab[aria-selected="true"] { border-bottom-color: var(--accent); }
.prefs-tab-hint { display: none; }
.prefs-agents-models { display: none; }
.prefs-agents-fields { grid-template-columns: 1fr; }
}
/* ------------------------------------------------------- the setup page
The agent-less setup screen (workflow "setup"): Planny's pose over the
agents view, which now draws its own split inside .setup-agents. */
.setup-screen {
max-width: 640px;
margin: 0 auto;
padding: 24px 16px 40px;
display: flex;
flex-direction: column;
gap: 8px;
}
.setup-stage { display: flex; justify-content: center; }
.setup-stage .pose { width: 150px; height: auto; }
.setup-screen h2 { margin: 0; }
.setup-actions {
display: flex;
align-items: center;
gap: 10px;
margin: 14px 0 0;
}
.setup-no-page { margin: 10px 0 0; }
.setup-no-page[hidden] { display: none; }
+169 -10
View File
@@ -14,6 +14,7 @@ import crypto from "node:crypto";
import {
LOOKS_FILE,
PUBLIC_DIR,
SHIPPED_AGENTS_FILE,
SHIPPED_MODELS_FILE,
USER_AGENTS_FILE,
USER_MODELS_FILE,
@@ -23,10 +24,12 @@ import {
nowIso,
readJson,
readText,
updateState,
withStateLock,
writeJsonAtomic,
} from "./files.mjs";
import { AGENTS_SCHEMA, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
import { AGENTS_SCHEMA, makeId, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
import { findAgent, loadAgentList } from "./agent-lookup.mjs";
import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./sessions.mjs";
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
@@ -75,6 +78,9 @@ const WORKSPACE_EDITS = { "/workspace/add": "addFolder", "/workspace/edit": "edi
const ROUTES = [
{ path: "/health", open: true, run: health },
{ match: (p) => p.startsWith("/s/"), open: true, run: signIn },
// Open on purpose: the caller is another Plan2Code process handing the
// setup tab over, not a cookied browser. It has its own token (state.setup).
{ path: "/handover", method: "POST", open: true, run: handover },
{ path: "/", method: "GET", run: page },
{ match: (p, req) => req.method === "GET" && SERVABLE.has(p.slice(1)), run: publicFile },
{ path: "/overview", method: "GET", run: overview },
@@ -92,6 +98,7 @@ const ROUTES = [
{ path: "/agents", method: "GET", run: agentsGet },
{ path: "/agents", method: "POST", origin: true, run: agentsPost },
{ path: "/agents/test", method: "POST", origin: true, run: agentsTest },
{ path: "/agents/use-path", method: "POST", origin: true, run: agentsUsePath },
{ path: "/cleanup", method: "POST", origin: true, run: cleanup },
{ path: "/upload", method: "POST", origin: true, run: upload },
{ path: "/notepad", method: "GET", run: notepadGet },
@@ -178,6 +185,45 @@ function signIn(req, res, ctx, url) {
return res.end();
}
// The setup session's hand-over: a launcher process opened this session's
// /s/ link in its own web view, then POSTs here so the launcher's setup page
// (the caller's own console) can move that tab to the new session. Only a
// setup session answers, and only for the per-session setup token that
// `open` printed for the launcher, never the browser cookie. On success the
// page gets a `move` SSE event carrying the url to hand itself to.
function handover(req, res, ctx) {
const state = ctx.readState();
if (!state || state.workflow !== "setup" || !state.setup || !state.setup.token) {
return json(res, 404, { error: "not-found" });
}
if (!timingSafeEq(req.headers["x-plan2code-token"] || "", state.setup.token)) {
return json(res, 403, { error: "forbidden" });
}
ctx.touch();
// The tab moved once; a second open in the same conversation is not a
// hand-over, so the caller can open a browser without a failure note.
if (state.setup.moved) return json(res, 409, { error: "moved" });
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "bad-url" });
const target = typeof body?.url === "string" ? body.url : "";
// Only another console's sign-in link is a legal destination.
if (!/^http:\/\/(127\.0\.0\.1|localhost):\d+\/s\/[A-Za-z0-9_-]+\/?$/.test(target)) {
return json(res, 400, { error: "bad-url" });
}
try {
updateState(ctx.dir, (fresh) => {
if (!fresh) return null;
fresh.setup = { ...(fresh.setup || {}), moved: { url: target, at: nowIso() } };
return fresh;
});
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
ctx.broadcast("move", { url: target });
return send(res, 204, "");
});
}
/* -------------------------------------------------------- the page itself */
// PLAN2CODE_EMBED_ORIGIN is an opt-in widening of frame-ancestors for a shell
@@ -525,8 +571,16 @@ function prHost(req, res, ctx) {
});
}
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js listModels).
const MODEL_CLIS = ["claude", "devin", "codex"];
// The CLIs the launcher reads a model list for (src/launcher/plan2code.js
// listModels): the shipped agent list's built-ins. Worked out per call so a
// bin/agents.json written after server boot is picked up; the hard-coded
// trio is only the fallback for a missing or bad file.
const MODEL_CLI_FALLBACK = ["claude", "devin", "codex"];
function modelClis() {
const { builtins } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE) });
const ids = builtins.map((a) => a && a.id).filter((id) => typeof id === "string" && id);
return ids.length ? ids : MODEL_CLI_FALLBACK;
}
const MODEL_ID = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,99}$/;
// Devin's XHigh and Max efforts are never offered, curated or added.
const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
@@ -539,7 +593,7 @@ const MODEL_EFFORT_BLOCKED = /-(xhigh|max)$/i;
function cleanModels(input) {
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "models must be an object" };
const models = {};
for (const cli of MODEL_CLIS) {
for (const cli of modelClis()) {
const list = input[cli] == null ? [] : input[cli];
if (!Array.isArray(list) || list.length > 50) return { error: `${cli} must be a list of at most 50 models` };
const seen = new Set();
@@ -561,7 +615,7 @@ function cleanModels(input) {
function shippedModels() {
const file = readJson(SHIPPED_MODELS_FILE, null) || {};
const out = {};
for (const cli of MODEL_CLIS) {
for (const cli of modelClis()) {
out[cli] = (Array.isArray(file[cli]) ? file[cli] : []).filter((m) => m && typeof m.id === "string");
}
return out;
@@ -571,7 +625,7 @@ function shippedModels() {
function modelsGet(req, res) {
const saved = readJson(USER_MODELS_FILE, null) || {};
const { models } = cleanModels(saved);
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(MODEL_CLIS.map((cli) => [cli, []])) });
return json(res, 200, { shipped: shippedModels(), user: models || Object.fromEntries(modelClis().map((cli) => [cli, []])) });
}
function modelsPost(req, res) {
@@ -589,12 +643,41 @@ function modelsPost(req, res) {
});
}
// The person's custom agents (agents.mjs has the rules). Read as text, not
// with readJson: a half-written or broken file has to come back as a warning,
// which readJson would turn into the same nothing as a missing file.
// This OS's key in the shipped install instructions / installDirs.
const OS_KEY = process.platform === "win32" ? "win" : process.platform === "darwin" ? "mac" : "linux";
// The person's custom agents (agents.mjs has the rules) plus the shipped
// list: built-ins with only this OS's install lines and their found state,
// and the starter templates as-is. The custom file is read as text, not with
// readJson: a half-written or broken file has to come back as a warning,
// which readJson would turn into the same nothing as a missing file. Each
// entry's {state,path,where,folder} is the "found badge" data, from
// findAgent (a bare name searches PATH + saved PATH + npm + installDirs; a
// path is a file check).
function agentsGet(req, res) {
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
return json(res, 200, normalizeAgents(raw));
const { agents, warnings } = normalizeAgents(raw);
const agentsWithState = agents.map((a) => ({ ...a, ...findAgent({ command: a.command }) }));
const { builtins, templates, warnings: shippedWarnings } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE), optional: true });
warnings.push(...shippedWarnings);
const builtinsForOs = builtins.map((entry) => ({
id: entry.id,
name: entry.name,
command: entry.command,
prompt: entry.prompt,
args: entry.args,
bypassArgs: entry.bypassArgs,
modelArgs: entry.modelArgs,
installUrl: entry.installUrl,
install: (entry.install && entry.install[OS_KEY]) || [],
...findAgent(entry),
}));
const TEMPLATE_FIELDS = ["id", "name", "command", "prompt", "args", "bypassArgs", "modelArgs", "note"];
const templatesAsIs = templates.map((entry) =>
Object.fromEntries(TEMPLATE_FIELDS.filter((f) => entry[f] !== undefined).map((f) => [f, entry[f]]))
);
return json(res, 200, { agents: agentsWithState, warnings, builtins: builtinsForOs, templates: templatesAsIs });
}
// The whole list from User Preferences, checked, then written atomically. The
@@ -638,6 +721,82 @@ function agentsTest(req, res) {
});
}
// "Use this path instead": findAgent found the command off this process's
// PATH (saved Windows PATH, npm's global folder, an install dir), so the
// found location becomes the agent's command. Only findAgent's result is
// ever saved, never a path the request carried. A built-in is materialized
// as a new custom entry; a custom agent gets its command rewritten.
function agentsUsePath(req, res, ctx) {
return readBody(req, (err, body) => {
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
const id = typeof body?.id === "string" ? body.id.trim() : "";
if (!id) return json(res, 400, { error: "id is required" });
const { builtins } = loadAgentList({ dir: path.dirname(SHIPPED_AGENTS_FILE) });
const builtin = builtins.find((a) => a && a.id === id);
const raw = fs.existsSync(USER_AGENTS_FILE) ? readText(USER_AGENTS_FILE) : undefined;
const { agents: customAgents, warnings } = normalizeAgents(raw);
// Same guard as agentsPost: a rewrite would drop the entries it skipped.
if (warnings.length) {
return json(res, 409, { error: "agents.json holds entries this page could not read. Saving replaces them.", warnings });
}
const custom = builtin ? null : customAgents.find((a) => a.id === id);
const entry = builtin || custom;
if (!entry) return json(res, 404, { error: "not-found" });
const found = findAgent(entry);
if (found.state === "missing") return json(res, 409, { error: "not-found" });
// Already on PATH: nothing to write, the badge can just say so.
if (found.state === "found") return json(res, 200, { ok: true, id, command: found.path || entry.command });
const list = customAgents.map((a) => ({ ...a }));
let savedId;
if (builtin) {
savedId = makeId(entry.name || id, list.map((a) => a.id));
list.push({
id: savedId,
name: entry.name,
command: found.path,
prompt: entry.prompt,
args: entry.args,
bypassArgs: entry.bypassArgs,
modelArgs: entry.modelArgs,
models: [],
});
} else {
savedId = id;
list.find((a) => a.id === id).command = found.path;
}
const { agents, error, index, field } = validateForSave(list);
if (error) return json(res, 400, { error, index, field });
// Same write as agentsPost: top-level keys the file already had are kept.
const saved = readJson(USER_AGENTS_FILE, null);
const kept = saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
try {
ensureDir(path.dirname(USER_AGENTS_FILE));
writeJsonAtomic(USER_AGENTS_FILE, { ...kept, schema: AGENTS_SCHEMA, agents });
} catch (e) {
return json(res, 500, { error: String(e.message) });
}
// A --for-cli setup asked for this built-in: the materialized entry carries
// its id over, or the page's Start gate would never match it again. Done
// after the write so a failed save never leaves a dangling forCli.
const setup = ctx && ctx.readState && ctx.readState()?.setup;
if (builtin && setup && setup.forCli === id) {
try {
updateState(ctx.dir, (fresh) => {
if (!fresh) return null;
fresh.setup = { ...(fresh.setup || {}), forCli: savedId };
return fresh;
});
} catch {
return json(res, 500, { error: "could not update the session" });
}
}
return json(res, 200, { ok: true, id: savedId, command: found.path });
});
}
// User Preferences -> System -> Cleanup. `{ scan: true }` lists what is not needed in
// ~/.plan2code and the project's old completed specs; `{ delete: [id] }`
// removes those of the ids a fresh scan still finds. Never this session,
+5 -1
View File
@@ -47,6 +47,7 @@ import { serverWorkspace } from "./workspace.mjs";
import { serverSubagents } from "./settings.mjs";
import { inAppSignal } from "./in-app.mjs";
import { chatAnswering, chatOffline } from "./public/chat.js";
import { isAgentless } from "./public/skills.js";
import { meterView } from "./public/meter.js";
import { SERVABLE, asset } from "./static.mjs";
import { handle } from "./routes.mjs";
@@ -185,6 +186,7 @@ function chatOfflineNow(state, chat = chatNow(state)) {
agentLastSeenMs: agentSeenAt,
now: Date.now(),
answering: chatAnswering(chat),
agentless: isAgentless(state && state.workflow),
});
}
@@ -250,7 +252,9 @@ function stateFrame(state) {
const chat = chatNow(state);
return {
rev,
state,
// The setup hand-over token is for the launcher only: the page gets
// forCli, which is all the setup screen reads.
state: state.setup ? { ...state, setup: { forCli: state.setup.forCli || null } } : state,
agentLastSeen: agentLastSeen(),
pendingResult: pending,
pendingStop: stop,