From 33f1783979a99f69ff2297d7404e0a539a91d405 Mon Sep 17 00:00:00 2001 From: Justin Parker Date: Tue, 3 Nov 2026 04:08:27 -0800 Subject: [PATCH] Add the agent-less setup page, a shared agent list and the split Agents & models tab AI Assisted --- .../skills/plan2code-launcher-update/SKILL.md | 156 +++ .../skills/plan2code-model-update/SKILL.md | 116 -- install.js | 8 + package.json | 2 +- plan2code-app/src-tauri/src/agents.rs | 1169 +++++++++++++---- .../src-tauri/src/console_supervisor.rs | 30 +- plan2code-app/src-tauri/src/lib.rs | 1 + plan2code-app/src-tauri/src/main.rs | 199 ++- plan2code-app/src-tauri/src/models.rs | 237 ++++ plan2code-app/src-tauri/src/node_check.rs | 20 +- plan2code-app/src-tauri/src/project.rs | 7 +- plan2code-app/src-tauri/src/versions.rs | 2 +- .../src-tauri/tests/agent_manager.rs | 8 +- plan2code-app/ui/app.js | 130 +- plan2code-app/ui/index.html | 22 +- plan2code-app/ui/meter.js | 16 + scripts/fixtures/agent-lookup-cases.json | 170 +++ scripts/fixtures/agents-cases.json | 225 +++- scripts/test-agent-lookup.mjs | 126 ++ scripts/test-web-console-in-app.mjs | 13 + scripts/test-web-console-lifecycle.mjs | 2 +- scripts/test-web-console-page-prefs.mjs | 118 +- scripts/test-web-console-page-setup.mjs | 402 ++++++ scripts/test-web-console-server.mjs | 405 +++++- scripts/test-web-console-session.mjs | 14 +- scripts/test-web-console-shape.mjs | 11 +- scripts/test-web-console-skills.mjs | 32 +- scripts/test-web-console-source.mjs | 35 +- src/launcher/agents.json | 129 ++ src/launcher/models.json | 68 +- src/web-console/agent-lookup.mjs | 235 ++++ src/web-console/agents.mjs | 64 +- src/web-console/cmd-help.mjs | 9 +- src/web-console/cmd-open.mjs | 132 +- src/web-console/console.mjs | 2 +- src/web-console/files.mjs | 3 + src/web-console/picker.mjs | 23 +- src/web-console/public/answers.js | 12 +- src/web-console/public/app-bridge.js | 8 + src/web-console/public/chat.js | 6 +- src/web-console/public/help.js | 2 + src/web-console/public/screens/agents-view.js | 1102 +++++++--------- .../public/screens/agents/agents-data.js | 110 ++ .../public/screens/agents/agents-form.js | 224 ++++ .../screens/agents/agents-list-editor.js | 74 ++ .../public/screens/agents/agents-summary.js | 256 ++++ .../public/screens/prefs-dialog.js | 4 +- src/web-console/public/screens/setup.js | 182 +++ src/web-console/public/selectors.js | 6 +- src/web-console/public/skills.js | 27 +- src/web-console/public/styles/agents.css | 157 +++ src/web-console/public/styles/planny.css | 10 +- src/web-console/public/styles/prefs.css | 92 +- src/web-console/routes.mjs | 179 ++- src/web-console/server.mjs | 6 +- 55 files changed, 5453 insertions(+), 1345 deletions(-) create mode 100644 .claude/skills/plan2code-launcher-update/SKILL.md delete mode 100644 .claude/skills/plan2code-model-update/SKILL.md create mode 100644 plan2code-app/src-tauri/src/models.rs create mode 100644 scripts/fixtures/agent-lookup-cases.json create mode 100644 scripts/test-agent-lookup.mjs create mode 100644 scripts/test-web-console-page-setup.mjs create mode 100644 src/launcher/agents.json create mode 100644 src/web-console/agent-lookup.mjs create mode 100644 src/web-console/public/screens/agents/agents-data.js create mode 100644 src/web-console/public/screens/agents/agents-form.js create mode 100644 src/web-console/public/screens/agents/agents-list-editor.js create mode 100644 src/web-console/public/screens/agents/agents-summary.js create mode 100644 src/web-console/public/screens/setup.js create mode 100644 src/web-console/public/styles/agents.css diff --git a/.claude/skills/plan2code-launcher-update/SKILL.md b/.claude/skills/plan2code-launcher-update/SKILL.md new file mode 100644 index 0000000..78fe4d4 --- /dev/null +++ b/.claude/skills/plan2code-launcher-update/SKILL.md @@ -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: | + +- **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 | | +| added | `cursor` | new template | | template entry | | +| 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). diff --git a/.claude/skills/plan2code-model-update/SKILL.md b/.claude/skills/plan2code-model-update/SKILL.md deleted file mode 100644 index 8d04f9f..0000000 --- a/.claude/skills/plan2code-model-update/SKILL.md +++ /dev/null @@ -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: | - -- **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). diff --git a/install.js b/install.js index d69ad3b..70c3713 100644 --- a/install.js +++ b/install.js @@ -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}`); diff --git a/package.json b/package.json index b34d1b0..e7b88ab 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/plan2code-app/src-tauri/src/agents.rs b/plan2code-app/src-tauri/src/agents.rs index 9925d6c..889efc1 100644 --- a/plan2code-app/src-tauri/src/agents.rs +++ b/plan2code-app/src-tauri/src/agents.rs @@ -1,96 +1,239 @@ //! The agents the app can run and the command line each one starts with. The -//! flags are the ones `src/launcher/plan2code.js` uses today, so the app and -//! `plan2code` start an agent the same way. Knows nothing about Tauri. +//! built-ins come from the one shipped agent list (`src/launcher/agents.json`, +//! installed to `~/.plan2code/bin/`), and where an agent's command is found +//! follows the one lookup rule `src/web-console/agent-lookup.mjs` states, so +//! the app, `plan2code` and the console agree on every agent's state. Knows +//! nothing about Tauri. use std::path::{Path, PathBuf}; use std::collections::HashSet; +use std::sync::{Arc, Mutex}; use serde::{Deserialize, Serialize}; use serde_json::Value; -/// Tests only: run this program instead of the real agent, for any `AgentKind`, +/// Tests only: run this program instead of the real agent, for any built-in, /// so the fake agent stands in for Claude, Devin and Codex. pub const AGENT_BIN_ENV: &str = "PLAN2CODE_APP_AGENT_BIN"; -#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)] -#[serde(rename_all = "lowercase")] -pub enum AgentKind { - Claude, - Devin, - Codex, +/* ------------------------------------------------------------ the agent list */ + +/// The agents.json schema this reader knows. +const AGENT_LIST_SCHEMA: f64 = 1.0; + +/// One install line for one OS ("PowerShell", "Terminal", "npm"). +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct InstallLine { + pub label: String, + pub run: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, } -impl AgentKind { - pub const ALL: [AgentKind; 3] = [AgentKind::Claude, AgentKind::Devin, AgentKind::Codex]; +/// A value per OS key (`win`, `mac`, `linux`), as `install` and `installDirs` +/// are shaped in agents.json. +#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +pub struct PerOs { + #[serde(default)] + pub win: Vec, + #[serde(default)] + pub mac: Vec, + #[serde(default)] + pub linux: Vec, +} - /// The id the page and the settings file use. - pub fn id(self) -> &'static str { - match self { - AgentKind::Claude => "claude", - AgentKind::Devin => "devin", - AgentKind::Codex => "codex", +impl PerOs { + /// The entries for `platform` ("win" | "mac" | "linux"). + pub fn for_platform(&self, platform: &str) -> &[T] { + match platform { + "win" => &self.win, + "mac" => &self.mac, + _ => &self.linux, } } +} - pub fn from_id(id: &str) -> Option { - AgentKind::ALL.into_iter().find(|kind| kind.id() == id) +/// One entry of the shipped agent list (agents.json schema 1): a built-in the +/// app can run (`kind: "builtin"`) or a starter template for the setup page's +/// custom-agent form. The console is the list's only writer; a `modelArgs` of +/// `["--model", "{model}"]` is the file's own default when the key is absent. +#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AgentEntry { + // The fields are lenient on purpose: the JS reader lists any object whose + // `kind` names a slot, and a builtin missing `command` then looks up as + // `missing`, the same broken row the console would show. + #[serde(default)] + pub id: String, + #[serde(default)] + pub name: String, + #[serde(default)] + pub kind: String, + #[serde(default)] + pub command: String, + #[serde(default = "default_custom_prompt")] + pub prompt: String, + #[serde(default)] + pub args: Vec, + #[serde(default)] + pub bypass_args: Vec, + #[serde(default)] + pub model_args: Vec, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub install_url: Option, + #[serde(default)] + pub install: PerOs, + #[serde(default)] + pub install_dirs: PerOs, + #[serde(default, skip_serializing_if = "Option::is_none")] + pub note: Option, +} + +/// The shipped agent list, split the way `loadAgentList()` splits it. +#[derive(Clone, Debug, Default)] +pub struct AgentList { + pub builtins: Vec, + pub templates: Vec, + pub warnings: Vec, +} + +/// The copy baked into the app: the fallback when the installed file is +/// missing, unreadable or the wrong schema. +const BAKED_AGENTS: &str = include_str!("../../../src/launcher/agents.json"); + +/// `~/.plan2code/bin/agents.json`, beside the launcher (`versions.rs` builds +/// the same `bin` path for `plan2code.js` and `version.json`). +fn agent_list_file() -> Option { + crate::versions::launcher_dir().map(|dir| dir.join("agents.json")) +} + +/// The entries and warnings in one agents.json text. A text that is not a +/// schema-1 object is an error (the caller then falls back to the baked copy). +pub fn parse_agent_list(text: &str) -> Result { + let Ok(file) = serde_json::from_str::(text) else { + return Err("agents.json is not valid JSON".to_string()); + }; + if !file.is_object() { + return Err("agents.json is not an object".to_string()); } - - pub fn label(self) -> &'static str { - match self { - AgentKind::Claude => "Claude Code", - AgentKind::Devin => "Devin", - AgentKind::Codex => "Codex", + if file.get("schema").and_then(Value::as_f64) != Some(AGENT_LIST_SCHEMA) { + let shown = file + .get("schema") + .map_or("undefined".to_string(), |v| v.to_string()); + return Err(format!( + "agents.json has schema {shown}, not {}", + AGENT_LIST_SCHEMA as u64 + )); + } + let mut out = AgentList::default(); + let empty = Vec::new(); + let list = file + .get("agents") + .and_then(Value::as_array) + .unwrap_or(&empty); + for (index, entry) in list.iter().enumerate() { + if !entry.is_object() { + out.warnings + .push(format!("agents[{index}] skipped: not an object")); + continue; + } + let Ok(agent) = serde_json::from_value::(entry.clone()) else { + out.warnings.push(format!( + "agents[{index}] skipped: missing or mistyped fields" + )); + continue; + }; + match agent.kind.as_str() { + "builtin" => out.builtins.push(agent), + "template" => out.templates.push(agent), + other => out + .warnings + .push(format!("agents[{index}] skipped: unknown kind {other:?}")), } } + Ok(out) +} - /// What a first start types: the skill that opens the dashboard. Codex - /// mentions a skill with `$name`. - pub fn default_prompt(self) -> &'static str { - match self { - AgentKind::Codex => "$plan2code", - _ => "/plan2code", +/// Read the installed list, or the baked copy with one warning when the file +/// is missing, unreadable or the wrong schema. Never panics; the baked copy +/// always parses (a test pins it to `src/launcher/agents.json`). +fn load_agent_list_uncached() -> AgentList { + let text = agent_list_file().and_then(|file| std::fs::read_to_string(file).ok()); + match text.as_deref().map(|text| (text, parse_agent_list(text))) { + Some((_, Ok(list))) => list, + why => { + let mut list = parse_agent_list(BAKED_AGENTS).unwrap_or_default(); + let reason = match why { + Some((_, Err(error))) => error, + _ => "agents.json is missing".to_string(), + }; + list.warnings + .push(format!("{reason}; the copy built into the app is used")); + list } } +} - /// The program this agent runs as, before any PATH resolution. - pub fn program_name(self) -> &'static str { - match self { - AgentKind::Claude => "claude", - AgentKind::Devin => "devin", - AgentKind::Codex => "codex", - } - } +static AGENT_LIST: Mutex>> = Mutex::new(None); - /// Whether this agent takes a separate reasoning effort. Devin's model - /// ids already carry effort (`swe-2-high`), so it has none of its own. - pub fn has_effort(self) -> bool { - matches!(self, AgentKind::Claude | AgentKind::Codex) - } +/// The shipped agent list, loaded once and kept: the file changes on a skills +/// update, which restarts the app anyway; `refresh_agent_list` re-reads it +/// early for "Check again". +pub fn agent_list() -> Arc { + let mut cached = AGENT_LIST.lock().unwrap_or_else(|e| e.into_inner()); + cached + .get_or_insert_with(|| Arc::new(load_agent_list_uncached())) + .clone() +} - /// Where to install this agent: an npm command or, with no package of its - /// own, the site to install from. The same text `src/launcher/plan2code.js` - /// shows for a missing CLI. - pub fn install_hint(self) -> &'static str { - match self { - AgentKind::Claude => "npm i -g @anthropic-ai/claude-code", - AgentKind::Devin => "https://devin.ai", - AgentKind::Codex => "npm i -g @openai/codex", - } - } +/// Drop the cached list so the next `agent_list()` reads the file again. +pub fn refresh_agent_list() { + *AGENT_LIST.lock().unwrap_or_else(|e| e.into_inner()) = None; +} - /// The official page to install this agent from. The same links as the - /// launcher's `CLIS` and the overview's Quick Reference: change all together. - pub fn install_url(self) -> &'static str { - match self { - AgentKind::Claude => "https://code.claude.com/docs/en/setup", - AgentKind::Devin => "https://docs.devin.ai/work-with-devin/devin-cli", - AgentKind::Codex => "https://github.com/openai/codex", - } +/// The built-in entries, in file order. +pub fn builtin_entries() -> Vec { + agent_list().builtins.clone() +} + +/// The built-in entry `id` names, or none (a custom agent, a typo). +pub fn builtin_entry(id: &str) -> Option { + agent_list() + .builtins + .iter() + .find(|entry| entry.id == id) + .cloned() +} + +/// Whether this agent takes a separate reasoning effort. Devin's model ids +/// already carry effort (`swe-2-high`), so it has none of its own; agents.json +/// has no effort field, so the two that take one are named here. +pub fn has_effort(id: &str) -> bool { + matches!(id, "claude" | "codex") +} + +/// The extra arguments `effort` becomes for this agent, or none: Claude's own +/// flag, Codex's config override. +fn effort_args(id: &str, effort: &str) -> Vec { + match id { + "claude" => vec!["--effort".to_string(), effort.to_string()], + "codex" => vec!["-c".to_string(), format!("model_reasoning_effort={effort}")], + _ => Vec::new(), } } +/// How a person installs `entry`: this OS's lead install line, else its +/// install page, for the launch card's one-line hint. +pub fn install_hint(entry: &AgentEntry) -> Option { + entry + .install + .for_platform(lookup_platform()) + .first() + .map(|line| line.run.clone()) + .or_else(|| entry.install_url.clone()) +} + /// Whether permission checks run while the agent works. Bypass is always an /// explicit pick, shown with a banner while it runs; it is never the silent /// default. @@ -120,42 +263,342 @@ impl PermissionMode { } } -/// Whether `program` exists on `path_var`: an exact file on macOS and Linux, -/// or with `.exe`, `.cmd` or `.bat` on Windows (as `windows_command` resolves -/// a program to run). -pub fn find_on_path(program: &str, path_var: &str) -> Option { - let exts: &[&str] = if cfg!(windows) { - &["exe", "cmd", "bat"] +/* ---------------------------------------------------------- the lookup rule */ +// `findAgent` in src/web-console/agent-lookup.mjs, kept to the same answers by +// the shared cases in scripts/fixtures/agent-lookup-cases.json (the test at +// the bottom of this file runs them all). + +/// Where `entry`'s command can run from, mirroring the JS `findAgent`'s +/// `{ state, path, where, folder }`: "found" on the searched PATH, "outside" +/// on the saved Windows PATH, in npm's global folder or in one of the entry's +/// installDirs, "missing" nowhere. `folder` is the directory it was found in. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct LookupResult { + pub state: &'static str, + pub path: Option, + pub where_: Option<&'static str>, + pub folder: Option, +} + +fn missing() -> LookupResult { + LookupResult { + state: "missing", + path: None, + where_: None, + folder: None, + } +} + +fn hit(state: &'static str, where_: &'static str, path: PathBuf) -> LookupResult { + LookupResult { + state, + path: Some(path.clone()), + where_: Some(where_), + folder: path.parent().map(Path::to_path_buf), + } +} + +/// The OS the lookup answers for: "win" | "mac" | "linux", as agents.json +/// keys its per-OS fields. +pub fn lookup_platform() -> &'static str { + if cfg!(windows) { + "win" + } else if cfg!(target_os = "macos") { + "mac" } else { - &[""] - }; + "linux" + } +} + +/// Everything the lookup reads from the environment, as named inputs so a +/// test can drive it on any platform's rules. `None` fields read the real +/// process values. +#[derive(Clone, Debug, Default)] +pub struct LookupEnv { + pub path: Option, + pub saved_path: Option, + pub npm_bin: Option, + pub pathext: Option, + pub platform: Option, + pub home: Option, + /// `%NAME%` expansions for installDirs, checked case-insensitively like + /// Windows; the process environment answers a name not listed here. + pub vars: Vec<(String, String)>, +} + +/// The folders a PATH-like string names, quotes stripped. The delimiter is +/// the host's, as `path.delimiter` is on the Node side: a PATH a case drives +/// is written for the machine it runs on, not for the platform it names. +fn path_dirs(path_var: &str) -> Vec { path_var .split(if cfg!(windows) { ';' } else { ':' }) .filter(|dir| !dir.is_empty()) - .find_map(|dir| { - exts.iter().find_map(|ext| { - let name = if ext.is_empty() { - program.to_string() - } else { - format!("{program}.{ext}") - }; - let candidate = Path::new(dir).join(name); - candidate.is_file().then_some(candidate) - }) - }) + .map(|dir| Path::new(dir.trim_matches('"')).to_path_buf()) + .collect() } -/// Where `kind`'s CLI runs from: the test override when it is set, else its -/// program name on PATH. `None` means it cannot be run. -pub fn installed_at(kind: AgentKind) -> Option { +/// `command` (a bare name) in `dir`, each extension tried. A name that +/// already carries an extension (goose.cmd) is tried as written first, then +/// with each extension; extensions come in uppercase from PATHEXT while +/// files are usually lowercase, so both cases are tried and the path names +/// the file as written. +fn find_in_dir(command: &str, dir: &Path, extensions: &[String]) -> Option { + let has_ext = Path::new(command).extension().is_some(); + let exts: Vec<&str> = if has_ext { + std::iter::once("") + .chain(extensions.iter().map(String::as_str)) + .collect() + } else { + extensions.iter().map(String::as_str).collect() + }; + for ext in exts { + let mut names = vec![format!("{command}{}", ext.to_lowercase())]; + let original = format!("{command}{ext}"); + if original != names[0] { + names.push(original); + } + for name in names { + let candidate = dir.join(name); + if candidate.is_file() { + return Some(candidate); + } + } + } + None +} + +fn find_in_dirs(command: &str, dirs: &[PathBuf], extensions: &[String]) -> Option { + dirs.iter() + .find_map(|dir| find_in_dir(command, dir, extensions)) +} + +/// `~` at the start (alone or before a separator) replaced with `home`. +fn expand_home(text: &str, home: &str) -> String { + if text == "~" { + return home.to_string(); + } + text.strip_prefix("~/") + .or_else(|| text.strip_prefix("~\\")) + .map_or_else(|| text.to_string(), |rest| format!("{home}/{rest}")) +} + +/// 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. +fn npm_global_bin(windows: bool) -> Option { + static CACHED: Mutex>> = Mutex::new(None); + let mut cached = CACHED.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(value) = cached.as_ref() { + return value.clone(); + } + let found = npm_global_bin_uncached(windows); + *cached = Some(found.clone()); + found +} + +fn npm_global_bin_uncached(windows: bool) -> Option { + if let Ok(prefix) = std::env::var("npm_config_prefix") { + if !prefix.is_empty() { + return Some(if windows { + prefix + } else { + format!("{prefix}/bin") + }); + } + } + if windows { + if let Ok(appdata) = std::env::var("APPDATA") { + if !appdata.is_empty() { + return Some(format!("{appdata}\\npm")); + } + } + } + let child = std::process::Command::new("npm") + .args(["config", "get", "prefix"]) + .stdin(std::process::Stdio::null()) + .stdout(std::process::Stdio::piped()) + .stderr(std::process::Stdio::null()) + .env("PATH", crate::node_check::resolved_path()) + .spawn(); + let child = match child { + Ok(child) => child, + Err(_) => return None, + }; + let (tx, rx) = std::sync::mpsc::channel(); + std::thread::spawn(move || { + let _ = tx.send(child.wait_with_output()); + }); + match rx.recv_timeout(std::time::Duration::from_secs(3)) { + Ok(Ok(out)) => { + let got = String::from_utf8_lossy(&out.stdout).trim().to_string(); + (!got.is_empty()).then(|| if windows { got } else { format!("{got}/bin") }) + } + _ => None, + } +} + +/// `entry`'s command under the real environment: the process PATH on Windows +/// (the saved PATH is then checked separately so the answer can say +/// `saved-path`), the app's resolved PATH elsewhere (its login-shell merge is +/// the honest "on PATH" there). +pub fn lookup_agent(entry: &AgentEntry) -> LookupResult { + let env = LookupEnv::default(); + lookup_agent_in(entry, &env) +} + +/// `findAgent(entry, env)`, on `entry`'s `command` and `installDirs`. +pub fn lookup_agent_in(entry: &AgentEntry, env: &LookupEnv) -> LookupResult { + let command = clean_command(entry.command.trim()); + if command.is_empty() { + return missing(); + } + let platform = env + .platform + .clone() + .unwrap_or_else(|| lookup_platform().to_string()); + let windows = platform == "win"; + let pathext = env + .pathext + .clone() + .or_else(|| std::env::var("PATHEXT").ok()) + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| ".EXE;.CMD;.BAT;.COM".to_string()); + let extensions: Vec = if windows { + pathext + .split(';') + .filter(|e| !e.is_empty()) + .map(String::from) + .collect() + } else { + vec![String::new()] + }; + + // A command written as a path is checked as a file, never looked up. + if has_separator(command, windows) { + let full = if Path::new(command).is_absolute() { + PathBuf::from(command) + } else { + std::env::current_dir() + .unwrap_or_else(|_| PathBuf::from(".")) + .join(command) + }; + let tries: Vec = if windows && full.extension().is_none() { + extensions + .iter() + .map(|ext| PathBuf::from(format!("{}{ext}", full.to_string_lossy()))) + .collect() + } else { + vec![full] + }; + return match tries.iter().find(|t| t.is_file()) { + Some(found) => hit("found", "path", found.clone()), + None => missing(), + }; + } + + let search_path = env.path.clone().unwrap_or_else(real_lookup_path); + if let Some(found) = find_in_dirs(command, &path_dirs(&search_path), &extensions) { + return hit("found", "path", found); + } + + let saved = env + .saved_path + .clone() + .unwrap_or_else(crate::node_check::saved_path_value); + if let Some(found) = find_in_dirs(command, &path_dirs(&saved), &extensions) { + return hit("outside", "saved-path", found); + } + + let npm_bin = env.npm_bin.clone().or_else(|| npm_global_bin(windows)); + if let Some(bin) = npm_bin { + if !bin.is_empty() { + if let Some(found) = find_in_dir(command, Path::new(&bin), &extensions) { + return hit("outside", "npm", found); + } + } + } + + let home = env + .home + .clone() + .or_else(|| std::env::home_dir().map(|h| h.to_string_lossy().into_owned())) + .unwrap_or_default(); + // A `vars` map that is given stands alone, as `env.vars || process.env` + // says on the JS side: the process environment is consulted only when no + // map was supplied at all. + let vars = |name: &str| { + if env.vars.is_empty() { + return std::env::var(name).ok(); + } + env.vars + .iter() + .find(|(key, _)| key.eq_ignore_ascii_case(name)) + .map(|(_, value)| value.clone()) + }; + for dir in entry.install_dirs.for_platform(&platform) { + let expanded = crate::node_check::expand_percent_vars(&expand_home(dir, &home), vars); + if let Some(found) = find_in_dir(command, Path::new(&expanded), &extensions) { + return hit("outside", "install-dir", found); + } + } + + missing() +} + +/// What the lookup's PATH input is with no override: the inherited process +/// PATH on Windows (the saved PATH is its own input so `saved-path` can be +/// told apart), the app's resolved PATH elsewhere. +fn real_lookup_path() -> String { + if cfg!(windows) { + std::env::var("PATH").unwrap_or_default() + } else { + crate::node_check::resolved_path() + } +} + +/// The extension list `find_on_path` tries on Windows: the real PATHEXT, or +/// the usual default when it is unset. +fn pathext_list(windows: bool, pathext: Option<&str>) -> Vec { + if !windows { + return vec![String::new()]; + } + pathext + .map(String::from) + .or_else(|| std::env::var("PATHEXT").ok()) + .filter(|p| !p.is_empty()) + .unwrap_or_else(|| ".EXE;.CMD;.BAT;.COM".to_string()) + .split(';') + .filter(|e| !e.is_empty()) + .map(String::from) + .collect() +} + +/// Whether `program` exists on `path_var`: an exact file on macOS and Linux, +/// or with any PATHEXT extension on Windows (the lookup rule's search order). +pub fn find_on_path(program: &str, path_var: &str) -> Option { + find_in_dirs( + program, + &path_dirs(path_var), + &pathext_list(cfg!(windows), None), + ) +} + +/// Where `entry`'s CLI runs from: the test override when it is set, else the +/// lookup's `found` answer (on the searched PATH). `None` means it cannot be +/// run without setup, whatever the other states found. +pub fn installed_at(entry: &AgentEntry) -> Option { let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty()); - let program = bin.unwrap_or_else(|| kind.program_name().to_string()); - find_on_path(&program, &crate::node_check::resolved_path()) + if let Some(program) = bin { + return find_on_path(&program, &crate::node_check::resolved_path()); + } + let found = lookup_agent(entry); + (found.state == "found").then_some(found.path).flatten() } -/// Whether `kind`'s CLI can be run at all. -pub fn is_installed(kind: AgentKind) -> bool { - installed_at(kind).is_some() +/// Whether `entry`'s CLI can be run at all. +pub fn is_installed(entry: &AgentEntry) -> bool { + installed_at(entry).is_some() } /// A command to run in the pseudo-terminal. @@ -167,10 +610,10 @@ pub struct LaunchSpec { pub cwd: PathBuf, } -/// How to start `kind` in `folder`. An empty `prompt` starts the agent with +/// How to start `entry` in `folder`. An empty `prompt` starts the agent with /// nothing typed. `PLAN2CODE_APP_AGENT_BIN` replaces the program (tests only). pub fn launch_spec( - kind: AgentKind, + entry: &AgentEntry, folder: &Path, model: Option<&str>, effort: Option<&str>, @@ -180,7 +623,7 @@ pub fn launch_spec( let bin = std::env::var(AGENT_BIN_ENV) .ok() .filter(|bin| !bin.is_empty()); - let mut spec = launch_spec_with(kind, folder, model, effort, mode, prompt, bin.as_deref()); + let mut spec = launch_spec_with(entry, folder, model, effort, mode, prompt, bin.as_deref()); // The override names a program to run as it is; a real agent is looked up on PATH. if cfg!(windows) && bin.is_none() { let (program, args) = windows_command( @@ -195,7 +638,7 @@ pub fn launch_spec( } fn launch_spec_with( - kind: AgentKind, + entry: &AgentEntry, folder: &Path, model: Option<&str>, effort: Option<&str>, @@ -213,62 +656,27 @@ fn launch_spec_with( }; } - let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::>(); - let model_args = |args: &mut Vec| { - if let Some(model) = model { - args.push("--model".to_string()); - args.push(model.to_string()); - } - }; let bypass = mode == PermissionMode::Bypass; - let mut args = Vec::new(); - let program = match kind { - AgentKind::Claude => { - if !prompt.is_empty() { - args.push(prompt.to_string()); - } - if bypass { - args.extend(strings(&["--permission-mode", "bypassPermissions"])); - } - model_args(&mut args); - if let Some(effort) = effort { - args.push("--effort".to_string()); - args.push(effort.to_string()); - } - "claude" - } - AgentKind::Devin => { - if bypass { - args.extend(strings(&["--permission-mode", "bypass"])); - } - model_args(&mut args); - if !prompt.is_empty() { - args.push("--".to_string()); - args.push(prompt.to_string()); - } - "devin" - } - AgentKind::Codex => { - if bypass { - args.extend(strings(&["--dangerously-bypass-approvals-and-sandbox"])); - } - model_args(&mut args); - if let Some(effort) = effort { - args.push("-c".to_string()); - args.push(format!("model_reasoning_effort={effort}")); - } - if !prompt.is_empty() { - args.push(prompt.to_string()); - } - "codex" - } - }; + let effort_args = effort + .filter(|e| !e.is_empty()) + .map(|e| effort_args(&entry.id, e)) + .unwrap_or_default(); + let args = build_args( + &entry.args, + &entry.prompt, + Some(prompt), + model, + bypass, + &entry.bypass_args, + &entry.model_args, + &effort_args, + ); // A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's // directories (Task 9.9): the agent CLI itself, and anything it shells // out to, needs a PATH that finds them anyway. let env = vec![("PATH".to_string(), crate::node_check::resolved_path())]; LaunchSpec { - program: program.to_string(), + program: clean_command(&entry.command).to_string(), args, env, cwd, @@ -303,7 +711,6 @@ pub fn windows_command(program: &str, args: Vec, path_var: &str) -> (Str /* ------------------------------------------------------------ custom agents */ pub const MAX_CUSTOM_AGENTS: usize = 50; -const BUILTIN_IDS: [&str; 3] = ["claude", "devin", "codex"]; const MAX_NAME: usize = 60; const DEFAULT_CUSTOM_PROMPT: &str = "/plan2code"; @@ -453,7 +860,7 @@ fn check_entry( Some(id) if !id.is_empty() => id, _ => return Err("id is missing".to_string()), }; - if BUILTIN_IDS.contains(&id) { + if builtin_entry(id).is_some() { return Err(format!("id \"{id}\" belongs to a built-in agent")); } if !valid_agent_id(id) { @@ -536,67 +943,125 @@ fn check_entry( }) } -/// The arguments that start a custom agent, in order (`buildArgs` in -/// agents.mjs): `args` with `{prompt}` filled (the prompt appended when no -/// argument holds it), then `model_args` when a model is chosen, then -/// `bypass_args` when checks are off. `prompt` defaults to the entry's own; a -/// blank one drops an argument that is exactly `{prompt}`. Plain text only. +/// The arguments that start an agent, in order (`buildArgs` in agents.mjs): +/// `args` with `{prompt}` filled (the prompt appended when no argument holds +/// it), then `model_args` when a model is chosen, then `bypass_args` when +/// checks are off. An argument that is exactly `{bypass}` or `{model}` +/// expands to `bypass_args` / `model_args` in place (nothing when off / +/// unset) and that flag is no longer appended at the end; `extra_after_model` +/// (a built-in's effort flags) follows each `{model}` expansion. +/// `prompt` defaults to `own_prompt`; a blank one drops an argument that is +/// exactly `{prompt}`. Plain text only. +#[allow(clippy::too_many_arguments)] +fn build_args( + args: &[String], + own_prompt: &str, + prompt: Option<&str>, + model: Option<&str>, + bypass: bool, + bypass_args: &[String], + model_args: &[String], + extra_after_model: &[String], +) -> Vec { + let text = prompt.unwrap_or(own_prompt); + let blank = text.trim().is_empty(); + let model = model.filter(|m| !m.is_empty()); + let mut out = Vec::new(); + let mut placed = false; + let mut has_bypass = false; + let mut has_model = false; + for arg in args { + if arg == "{bypass}" { + has_bypass = true; + if bypass { + out.extend(bypass_args.iter().cloned()); + } + continue; + } + if arg == "{model}" { + has_model = true; + if let Some(m) = model { + out.extend(model_args.iter().map(|a| a.replace("{model}", m))); + } + out.extend(extra_after_model.iter().cloned()); + continue; + } + if arg.contains("{bypass}") { + has_bypass = true; + } + if arg.contains("{model}") { + has_model = true; + } + if !arg.contains("{prompt}") && !arg.contains("{model}") { + out.push(arg.clone()); + continue; + } + if arg == "{prompt}" && blank { + placed = true; + continue; + } + let mut next = arg.clone(); + if next.contains("{prompt}") { + placed = true; + next = next.replace("{prompt}", text); + } + if next.contains("{model}") { + next = next.replace("{model}", model.unwrap_or("")); + } + out.push(next); + } + if !placed && !blank { + out.push(text.to_string()); + } + if !has_model { + if let Some(m) = model { + out.extend(model_args.iter().map(|arg| arg.replace("{model}", m))); + } + out.extend(extra_after_model.iter().cloned()); + } + if bypass && !has_bypass { + out.extend(bypass_args.iter().cloned()); + } + out +} + +/// `build_args` for a custom agent (`build_custom_args`). pub fn build_custom_args( agent: &CustomAgent, prompt: Option<&str>, model: Option<&str>, bypass: bool, ) -> Vec { - let text = prompt.unwrap_or(&agent.prompt); - let blank = text.trim().is_empty(); - let mut out = Vec::new(); - let mut placed = false; - for arg in &agent.args { - if !arg.contains("{prompt}") { - out.push(arg.clone()); - continue; - } - placed = true; - if arg == "{prompt}" && blank { - continue; - } - out.push(arg.replace("{prompt}", text)); - } - if !placed && !blank { - out.push(text.to_string()); - } - if let Some(model) = model.filter(|m| !m.is_empty()) { - out.extend( - agent - .model_args - .iter() - .map(|arg| arg.replace("{model}", model)), - ); - } - if bypass { - out.extend(agent.bypass_args.iter().cloned()); - } - out + build_args( + &agent.args, + &agent.prompt, + prompt, + model, + bypass, + &agent.bypass_args, + &agent.model_args, + &[], + ) } -/// An agent the app can run: one of the three built-ins or a custom entry. +/// An agent the app can run: one of the shipped built-ins or a custom entry. #[derive(Clone, Debug, PartialEq, Eq)] pub enum Agent { - Builtin(AgentKind), + Builtin(AgentEntry), Custom(CustomAgent), } impl Agent { pub fn id(&self) -> &str { match self { - Agent::Builtin(kind) => kind.id(), + Agent::Builtin(entry) => &entry.id, Agent::Custom(agent) => &agent.id, } } pub fn label(&self) -> &str { match self { - Agent::Builtin(kind) => kind.label(), + Agent::Builtin(entry) => &entry.name, Agent::Custom(agent) => &agent.name, } } @@ -604,21 +1069,21 @@ impl Agent { /// What a first start types. pub fn default_prompt(&self) -> &str { match self { - Agent::Builtin(kind) => kind.default_prompt(), + Agent::Builtin(entry) => &entry.prompt, Agent::Custom(agent) => &agent.prompt, } } /// A custom agent has no effort of its own. pub fn has_effort(&self) -> bool { - matches!(self, Agent::Builtin(kind) if kind.has_effort()) + matches!(self, Agent::Builtin(entry) if has_effort(&entry.id)) } /// Where this agent's program runs from, or `None` when it cannot be run. /// `PLAN2CODE_APP_AGENT_BIN` still overrides the program (tests only). pub fn installed_at(&self) -> Option { match self { - Agent::Builtin(kind) => installed_at(*kind), + Agent::Builtin(entry) => installed_at(entry), Agent::Custom(agent) => { let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|b| !b.is_empty()); let command = bin.as_deref().unwrap_or(&agent.command); @@ -635,8 +1100,8 @@ pub fn find_agent(id: &str) -> Option { /// `find_agent` against a given agents file (`None`: built-ins only). pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option { - if let Some(kind) = AgentKind::from_id(id) { - return Some(Agent::Builtin(kind)); + if let Some(entry) = builtin_entry(id) { + return Some(Agent::Builtin(entry)); } let (agents, _) = load_custom_agents(file?); agents @@ -716,7 +1181,7 @@ pub fn agent_launch_spec( prompt: &str, ) -> LaunchSpec { match agent { - Agent::Builtin(kind) => launch_spec(*kind, folder, model, effort, mode, prompt), + Agent::Builtin(entry) => launch_spec(entry, folder, model, effort, mode, prompt), Agent::Custom(custom) => { if let Some(bin) = std::env::var(AGENT_BIN_ENV) .ok() @@ -830,9 +1295,9 @@ fn quote_for_cmd(arg: &str) -> String { } /// The page a built-in agent installs from; any other id is an error. -pub fn install_page_url(id: &str) -> Result<&'static str, String> { - AgentKind::from_id(id) - .map(AgentKind::install_url) +pub fn install_page_url(id: &str) -> Result { + builtin_entry(id) + .and_then(|entry| entry.install_url) .ok_or_else(|| format!("no install page for agent: {id}")) } @@ -840,23 +1305,28 @@ pub fn install_page_url(id: &str) -> Result<&'static str, String> { mod tests { use super::*; + /// A shipped built-in's entry from the baked list: deterministic in tests. + fn entry(id: &str) -> AgentEntry { + parse_agent_list(BAKED_AGENTS) + .unwrap() + .builtins + .into_iter() + .find(|e| e.id == id) + .unwrap_or_else(|| panic!("no baked entry {id}")) + } + fn folder() -> PathBuf { PathBuf::from("project") } - fn args( - kind: AgentKind, - model: Option<&str>, - mode: PermissionMode, - prompt: &str, - ) -> Vec { - launch_spec_with(kind, &folder(), model, None, mode, prompt, None).args + fn args(id: &str, model: Option<&str>, mode: PermissionMode, prompt: &str) -> Vec { + launch_spec_with(&entry(id), &folder(), model, None, mode, prompt, None).args } #[test] fn claude_puts_the_prompt_first() { let spec = launch_spec_with( - AgentKind::Claude, + &entry("claude"), &folder(), None, None, @@ -878,7 +1348,7 @@ mod tests { fn claude_with_a_model() { assert_eq!( args( - AgentKind::Claude, + "claude", Some("sonnet"), PermissionMode::Bypass, "/plan2code" @@ -896,12 +1366,7 @@ mod tests { #[test] fn claude_checked_mode_skips_the_bypass_flag() { assert_eq!( - args( - AgentKind::Claude, - None, - PermissionMode::Checked, - "/plan2code" - ), + args("claude", None, PermissionMode::Checked, "/plan2code"), ["/plan2code"] ); } @@ -909,7 +1374,7 @@ mod tests { #[test] fn claude_with_an_effort() { let spec = launch_spec_with( - AgentKind::Claude, + &entry("claude"), &folder(), None, Some("high"), @@ -932,7 +1397,7 @@ mod tests { #[test] fn a_full_launch_card_choice_carries_model_effort_and_mode_together() { let spec = launch_spec_with( - AgentKind::Claude, + &entry("claude"), &folder(), Some("opus"), Some("xhigh"), @@ -953,7 +1418,7 @@ mod tests { ] ); let checked = launch_spec_with( - AgentKind::Codex, + &entry("codex"), &folder(), Some("gpt-5"), Some("medium"), @@ -976,7 +1441,7 @@ mod tests { #[test] fn devin_puts_the_prompt_after_a_double_dash() { let spec = launch_spec_with( - AgentKind::Devin, + &entry("devin"), &folder(), None, None, @@ -994,12 +1459,7 @@ mod tests { #[test] fn devin_with_a_model_keeps_the_prompt_last() { assert_eq!( - args( - AgentKind::Devin, - Some("opus"), - PermissionMode::Bypass, - "/plan2code" - ), + args("devin", Some("opus"), PermissionMode::Bypass, "/plan2code"), [ "--permission-mode", "bypass", @@ -1014,26 +1474,21 @@ mod tests { #[test] fn devin_checked_mode_skips_the_bypass_flag() { assert_eq!( - args( - AgentKind::Devin, - None, - PermissionMode::Checked, - "/plan2code" - ), + args("devin", None, PermissionMode::Checked, "/plan2code"), ["--", "/plan2code"] ); } #[test] fn codex_uses_its_own_flag_and_dollar_prompt() { - let prompt = AgentKind::Codex.default_prompt(); + let prompt = entry("codex").prompt; let spec = launch_spec_with( - AgentKind::Codex, + &entry("codex"), &folder(), None, None, PermissionMode::Bypass, - prompt, + &prompt, None, ); assert_eq!(spec.program, "codex"); @@ -1046,12 +1501,7 @@ mod tests { #[test] fn codex_with_a_model() { assert_eq!( - args( - AgentKind::Codex, - Some("gpt-5"), - PermissionMode::Bypass, - "$plan2code" - ), + args("codex", Some("gpt-5"), PermissionMode::Bypass, "$plan2code"), [ "--dangerously-bypass-approvals-and-sandbox", "--model", @@ -1064,7 +1514,7 @@ mod tests { #[test] fn codex_with_an_effort_uses_a_config_override() { let spec = launch_spec_with( - AgentKind::Codex, + &entry("codex"), &folder(), None, Some("low"), @@ -1086,12 +1536,7 @@ mod tests { #[test] fn codex_checked_mode_skips_the_bypass_flag() { assert_eq!( - args( - AgentKind::Codex, - None, - PermissionMode::Checked, - "$plan2code" - ), + args("codex", None, PermissionMode::Checked, "$plan2code"), ["$plan2code"] ); } @@ -1099,15 +1544,15 @@ mod tests { #[test] fn no_prompt_means_nothing_typed() { assert_eq!( - args(AgentKind::Claude, None, PermissionMode::Bypass, ""), + args("claude", None, PermissionMode::Bypass, ""), ["--permission-mode", "bypassPermissions"] ); assert_eq!( - args(AgentKind::Devin, None, PermissionMode::Bypass, ""), - ["--permission-mode", "bypass"] + args("devin", None, PermissionMode::Bypass, ""), + ["--permission-mode", "bypass", "--"] ); assert_eq!( - args(AgentKind::Codex, None, PermissionMode::Bypass, ""), + args("codex", None, PermissionMode::Bypass, ""), ["--dangerously-bypass-approvals-and-sandbox"] ); } @@ -1116,7 +1561,7 @@ mod tests { fn a_custom_prompt_is_passed_through() { assert_eq!( args( - AgentKind::Claude, + "claude", None, PermissionMode::Bypass, "/plan2code pick up the brief" @@ -1131,9 +1576,9 @@ mod tests { #[test] fn devin_has_no_effort_of_its_own() { - assert!(!AgentKind::Devin.has_effort()); - assert!(AgentKind::Claude.has_effort()); - assert!(AgentKind::Codex.has_effort()); + assert!(!has_effort("devin")); + assert!(has_effort("claude")); + assert!(has_effort("codex")); } #[test] @@ -1146,9 +1591,9 @@ mod tests { #[test] fn the_override_replaces_the_program_for_every_kind() { - for kind in AgentKind::ALL { + for entry in [entry("claude"), entry("devin"), entry("codex")] { let spec = launch_spec_with( - kind, + &entry, &folder(), Some("m"), Some("high"), @@ -1168,12 +1613,224 @@ mod tests { std::fs::create_dir_all(&dir).unwrap(); let name = if cfg!(windows) { "tool.exe" } else { "tool" }; std::fs::write(dir.join(name), "").unwrap(); + // A name whose extension PATHEXT never lists is not found, either. + #[cfg(windows)] + std::fs::write(dir.join("other.xyz"), "").unwrap(); let path = dir.to_string_lossy().into_owned(); assert_eq!(find_on_path("tool", &path), Some(dir.join(name))); + #[cfg(windows)] + assert_eq!(find_on_path("other", &path), None); assert_eq!(find_on_path("missing-tool", &path), None); let _ = std::fs::remove_dir_all(&dir); } + #[test] + fn the_baked_list_matches_the_shipped_agents_json() { + // include_str! means the baked copy IS src/launcher/agents.json; this + // pins its schema so a drift between the app's structs and the file + // shows up here, not at runtime. + let list = parse_agent_list(BAKED_AGENTS).expect("the baked list parses"); + assert_eq!( + list.builtins + .iter() + .map(|e| e.id.as_str()) + .collect::>(), + ["claude", "devin", "codex"] + ); + assert_eq!( + list.templates + .iter() + .map(|e| e.id.as_str()) + .collect::>(), + ["copilot", "opencode", "gemini", "pi"] + ); + assert!(list + .builtins + .iter() + .all(|e| !e.command.is_empty() && !e.args.is_empty())); + } + + #[test] + fn the_list_loader_rejects_a_bad_file_and_reads_the_installed_path() { + // Not JSON, not an object, or the wrong schema is an error: the + // caller then falls back to the baked copy with a warning. + assert!(parse_agent_list("not json").is_err()); + assert!(parse_agent_list("[]").is_err()); + assert!(parse_agent_list(r#"{"schema":2,"agents":[]}"#).is_err()); + // The file the loader reads is the launcher's own bin dir, beside + // plan2code.js and version.json. + let file = agent_list_file().expect("a home"); + assert!(file.ends_with(std::path::Path::new("bin").join("agents.json"))); + // Whatever is installed, a shipped built-in resolves to its entry. + assert!(builtin_entry("claude").is_some()); + // Unknown kinds are skipped with a warning, not an error. + let list = parse_agent_list( + r#"{"schema":1,"agents":[{"id":"x","name":"X","kind":"future","command":"x"},{"id":"y","name":"Y","kind":"builtin","command":"y"}]}"#, + ) + .unwrap(); + assert_eq!(list.builtins.len(), 1); + assert_eq!(list.warnings.len(), 1); + } + + /// Every case in the shared lookup fixture, under its own platform's + /// rules (Task 3.4): the same file drives scripts/test-agent-lookup.mjs, + /// so the Node and Rust lookups stay the one rule. + #[test] + fn the_shared_lookup_cases_all_answer_the_same() { + // 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. + std::env::remove_var("NoDefaultCurrentDirectoryInExePath"); + let cases: Value = serde_json::from_str(include_str!( + "../../../scripts/fixtures/agent-lookup-cases.json" + )) + .unwrap(); + for (index, case) in cases["cases"].as_array().unwrap().iter().enumerate() { + let name = case["name"].as_str().unwrap(); + let root = + std::env::temp_dir().join(format!("p2c-lookup-{}-{index}", std::process::id())); + let _ = std::fs::remove_dir_all(&root); + let mut dirs: std::collections::HashMap = Default::default(); + if let Some(map) = case["dirs"].as_object() { + for (dir_name, files) in map { + let dir = root.join(dir_name).to_string_lossy().into_owned(); + for file in files.as_array().into_iter().flatten() { + let target = std::path::Path::new(&dir).join(file.as_str().unwrap()); + std::fs::create_dir_all(target.parent().unwrap()).unwrap(); + std::fs::write(target, b"").unwrap(); + } + let _ = std::fs::create_dir_all(&dir); + dirs.insert(dir_name.clone(), dir); + } + } + // `{name}` in a value expands to that folder's path, making the + // dir on demand as the Node side's fill() does; collecting them + // first keeps `fill` a read. + let mut collect = |text: &str| { + let mut rest = text; + while let Some(at) = rest.find('{') { + let Some(end) = rest[at..].find('}') else { + break; + }; + let key = &rest[at + 1..at + end]; + dirs.entry(key.to_string()) + .or_insert_with(|| root.join(key).to_string_lossy().into_owned()); + rest = &rest[at + end + 1..]; + } + }; + let env_obj = case["env"].as_object().cloned().unwrap_or_default(); + for value in env_obj.values().flat_map(|v| { + let mut all: Vec<&str> = v.as_str().into_iter().collect(); + if let Some(map) = v.as_object() { + all.extend(map.values().filter_map(Value::as_str)); + } + all + }) { + collect(value); + } + for s in [case["entry"]["command"].as_str(), case["folder"].as_str()] + .into_iter() + .flatten() + { + collect(s); + } + if let Some(map) = case["entry"]["installDirs"].as_object() { + for list in map.values() { + for d in list.as_array().into_iter().flatten() { + if let Some(s) = d.as_str() { + collect(s); + } + } + } + } + // `{name}` in a value expands to that folder's path. + let fill = |value: &str| -> String { + let mut out = value.to_string(); + while let Some(at) = out.find('{') { + let Some(end) = out[at..].find('}') else { + break; + }; + let key = &out[at + 1..at + end]; + let dir = dirs.get(key).cloned().unwrap_or_default(); + out = format!("{}{}{}", &out[..at], dir, &out[at + end + 1..]); + } + out + }; + let val = |key: &str| env_obj.get(key).and_then(Value::as_str).map(&fill); + let env = LookupEnv { + path: val("path"), + saved_path: val("savedPath"), + npm_bin: val("npmBin"), + pathext: val("pathext"), + platform: case["platform"].as_str().map(String::from), + home: val("home"), + vars: env_obj + .get("vars") + .and_then(Value::as_object) + .map(|vars| { + vars.iter() + .map(|(k, v)| (k.clone(), fill(v.as_str().unwrap()))) + .collect() + }) + .unwrap_or_default(), + }; + let mut entry = AgentEntry { + id: "case".into(), + name: "case".into(), + kind: "builtin".into(), + command: String::new(), + prompt: String::new(), + args: vec![], + bypass_args: vec![], + model_args: vec![], + install_url: None, + install: PerOs::default(), + install_dirs: PerOs::default(), + note: None, + }; + entry.command = fill(case["entry"]["command"].as_str().unwrap_or_default()); + // The fixture's `\` in installDirs names a Windows folder; the + // temp file was made the host's way, so spell the dir the same + // (Windows itself takes either separator). + if let Some(map) = case["entry"]["installDirs"].as_object() { + for (os, list) in map { + let dirs_list: Vec = list + .as_array() + .into_iter() + .flatten() + .map(|d| fill(&d.as_str().unwrap_or_default().replace('\\', "/"))) + .collect(); + match os.as_str() { + "win" => entry.install_dirs.win = dirs_list, + "mac" => entry.install_dirs.mac = dirs_list, + _ => entry.install_dirs.linux = dirs_list, + } + } + } + let got = lookup_agent_in(&entry, &env); + let want_state = case["state"].as_str().unwrap(); + assert_eq!(got.state, want_state, "{name}: state"); + assert_eq!(got.where_, case["where"].as_str(), "{name}: where"); + if want_state == "missing" { + assert_eq!(got.path, None, "{name}: path"); + assert_eq!(got.folder, None, "{name}: folder"); + } else { + let hit = got.path.clone().expect("a path for a found entry"); + assert!(hit.is_file(), "{name}: path is a real file"); + if let Some(file) = case["file"].as_str() { + assert_eq!(hit.file_name().unwrap().to_str(), Some(file), "{name}"); + } + if let Some(folder) = case["folder"].as_str() { + assert_eq!( + got.folder.as_deref(), + Some(std::path::Path::new(&fill(folder))), + "{name}: folder" + ); + } + } + let _ = std::fs::remove_dir_all(&root); + } + } + #[test] fn a_cmd_shim_runs_through_cmd_and_the_extensionless_script_is_ignored() { let dir = std::env::temp_dir().join(format!("plan2code-shim-{}", std::process::id())); @@ -1209,10 +1866,10 @@ mod tests { #[test] fn ids_round_trip() { - for kind in AgentKind::ALL { - assert_eq!(AgentKind::from_id(kind.id()), Some(kind)); + for entry in [entry("claude"), entry("devin"), entry("codex")] { + assert_eq!(builtin_entry(&entry.id), Some(entry)); } - assert_eq!(AgentKind::from_id("nope"), None); + assert!(builtin_entry("nope").is_none()); } /* ------------------------------------------------------ custom agents */ @@ -1300,7 +1957,7 @@ mod tests { std::fs::write(&file, GOOSE).unwrap(); assert_eq!( find_agent_in("claude", Some(&file)), - Some(Agent::Builtin(AgentKind::Claude)) + Some(Agent::Builtin(entry("claude"))) ); let goose = find_agent_in("goose", Some(&file)).unwrap(); assert_eq!( @@ -1489,8 +2146,8 @@ mod tests { "https://github.com/openai/codex" ); assert!(install_page_url("goose").is_err()); - for kind in AgentKind::ALL { - assert!(kind.install_url().starts_with("https://")); + for entry in [entry("claude"), entry("devin"), entry("codex")] { + assert!(entry.install_url.unwrap().starts_with("https://")); } } } diff --git a/plan2code-app/src-tauri/src/console_supervisor.rs b/plan2code-app/src-tauri/src/console_supervisor.rs index 19af9df..a9f4c4e 100644 --- a/plan2code-app/src-tauri/src/console_supervisor.rs +++ b/plan2code-app/src-tauri/src/console_supervisor.rs @@ -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 { + 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 { 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 { 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) diff --git a/plan2code-app/src-tauri/src/lib.rs b/plan2code-app/src-tauri/src/lib.rs index 2ceb887..9355be0 100644 --- a/plan2code-app/src-tauri/src/lib.rs +++ b/plan2code-app/src-tauri/src/lib.rs @@ -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; diff --git a/plan2code-app/src-tauri/src/main.rs b/plan2code-app/src-tauri/src/main.rs index 900979c..3826ae3 100644 --- a/plan2code-app/src-tauri/src/main.rs +++ b/plan2code-app/src-tauri/src/main.rs @@ -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) -> 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) -> 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(¬ice.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(¬ice.url, ¬ice.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 { 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 { + let origin = window_origin(&app); + console_setup_start_impl(&state, &origin) +} + +fn console_setup_start_impl(state: &AppState, origin: &str) -> Result { + 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. diff --git a/plan2code-app/src-tauri/src/models.rs b/plan2code-app/src-tauri/src/models.rs new file mode 100644 index 0000000..ff8d84e --- /dev/null +++ b/plan2code-app/src-tauri/src/models.rs @@ -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 { + 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 { + 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 { + 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, user: Vec) -> Vec { + let mut seen: HashSet = 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 { + 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 { + 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 { + 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"))] + ); + } +} diff --git a/plan2code-app/src-tauri/src/node_check.rs b/plan2code-app/src-tauri/src/node_check.rs index 403d5cf..7ee04b1 100644 --- a/plan2code-app/src-tauri/src/node_check.rs +++ b/plan2code-app/src-tauri/src/node_check.rs @@ -171,9 +171,27 @@ fn parse_reg_query_value(output: &str) -> Option { }) } +/// 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 { +pub(crate) fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option) -> String { let mut out = String::new(); let mut rest = text; while let Some(start) = rest.find('%') { diff --git a/plan2code-app/src-tauri/src/project.rs b/plan2code-app/src-tauri/src/project.rs index 01d41c3..733cdbb 100644 --- a/plan2code-app/src-tauri/src/project.rs +++ b/plan2code-app/src-tauri/src/project.rs @@ -165,7 +165,6 @@ pub fn remember_folder(dir: &Path) -> Result { #[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 } ); diff --git a/plan2code-app/src-tauri/src/versions.rs b/plan2code-app/src-tauri/src/versions.rs index ab9a432..bb3d623 100644 --- a/plan2code-app/src-tauri/src/versions.rs +++ b/plan2code-app/src-tauri/src/versions.rs @@ -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 { +pub(crate) fn launcher_dir() -> Option { if let Ok(dir) = std::env::var("PLAN2CODE_LAUNCHER_DIR") { return Some(PathBuf::from(dir)); } diff --git a/plan2code-app/src-tauri/tests/agent_manager.rs b/plan2code-app/src-tauri/tests/agent_manager.rs index 4d721a6..22b99da 100644 --- a/plan2code-app/src-tauri/tests/agent_manager.rs +++ b/plan2code-app/src-tauri/tests/agent_manager.rs @@ -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, diff --git a/plan2code-app/ui/app.js b/plan2code-app/ui/app.js index fa5e7fb..c9c3a27 100644 --- a/plan2code-app/ui/app.js +++ b/plan2code-app/ui/app.js @@ -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; diff --git a/plan2code-app/ui/index.html b/plan2code-app/ui/index.html index 6ef1dba..feefb77 100644 --- a/plan2code-app/ui/index.html +++ b/plan2code-app/ui/index.html @@ -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 @@
+