mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-17 04:45:33 -08:00
Compare commits
9
Commits
f968aeded8
..
v2.5.1
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
57bda29db8 | ||
|
|
3343762c70 | ||
|
|
342da7c353 | ||
|
|
da105160a8 | ||
|
|
977e462e76 | ||
|
|
57134cf36e | ||
|
|
c19a072a3a | ||
|
|
cd8a1be568 | ||
|
|
ade74cd636 |
No files matched your search
@@ -59,7 +59,7 @@ plan2code/
|
||||
├── .husky/ # Git hooks (husky)
|
||||
│ └── pre-commit # Runs character count validation
|
||||
├── .claude/ # Repo-local Claude Code config (NOT installed by install.js)
|
||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/
|
||||
│ └── skills/ # Maintainer-only dev skills, e.g. plan2code-publish/, plan2code-model-update/
|
||||
├── .github/ISSUE_TEMPLATE/ # bug.yml, idea.yml, config.yml (target of the console's feedback button)
|
||||
├── .readme/ # User guides linked from README (web-console.md, web-console-design.md, walkthrough.md, autonomous-loop.md, metrics.md, status-line.md, test-bot.md)
|
||||
├── docs/ # Landing page `index.html` served at plan2code.jparkerweb.com (GitHub Pages, `CNAME`) and assets
|
||||
@@ -159,6 +159,7 @@ Maintainer-only skills committed to the repo but deliberately excluded from the
|
||||
|
||||
- `plan2code-publish/` — publishes a GitHub Release after version files agree.
|
||||
- `plan2code-changelog/` — validates release classification and keeps version files synchronized.
|
||||
- `plan2code-model-update/` — refreshes the launcher's curated model menu (`src/launcher/models.json`) from `devin models list` and Claude Code's documented model aliases: shows a diff, applies only the changes the maintainer approves, validates the file and runs `npm test`. Terminal only, and it never commits.
|
||||
- `sync-repo/` — decrypts the protected upstream-sync workflow in memory.
|
||||
|
||||
Do not run `skills add` against the repository root: recursive discovery also finds these maintainer skills. `install.js` targets `skills/` and passes explicit workflow names instead. Global install/uninstall cleanup removes `plan2code-*` workflow skills from user skill directories; it never operates on this repository's `.claude/skills/` directory, and `sync-repo` intentionally has no `plan2code-` prefix.
|
||||
@@ -171,16 +172,18 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
|---|---|
|
||||
| `console.mjs` | the CLI the agent drives: `open`, `post`, `wait`, `chat` (the instant Quick question check), `keep` (copy a cited note attachment into `specs/<idea>/attachments/`), `status`, `stop`, `help` (a compact summary for an agent that found the binary but not `console.md`) |
|
||||
| `server.mjs` | HTTP server, spawned **detached** by `open` (never as a harness background task, which get killed on compaction and at assorted timeouts) |
|
||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()` |
|
||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (16 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `lib.mjs` | session paths, atomic writes, the patch merge, `validate()` (which also allows `templates` only as `"idea"` on a `text` item; anything else exits 3), `attachmentName()` (the kept-file name `<slug>-<id8>.<ext>`: the same upload always gets the same name), `repoRoots()` (returns `{ project, worktree, branch }`), `readOverview()`, and the three sweeps `open` runs fire-and-forget after it prints (see the cleanup design point below): `sweepUploads()`, `staleSessions()` / `removeSessions()` and `staleScratch()` / `removeScratch()`; plus `cleanupFindings()` / `removeCleanup()` for User Preferences → Cleanup |
|
||||
| `public/` | `index.html`, `app.js`, `answers.js`, `labels.js`, `boot.js`, `chat.js`, `help.js`, `starters.js`, `workspace.js`, `meter.js`, `subagents.js`, `mentions.js`, `favicon.js`, `app.css`, `render.js`, `palette.js`, `favicon.svg` (Planny peeking up from the tab bar, served as `image/svg+xml`) with `favicon.png` (the same icon at 192 px, served as `image/png`) as the fallback, `vendor/marked.esm.js`, the chimes (`start-skill.mp3`, `bootup.mp3`, `start-stop.mp3`, `next.mp3`, `insert.mp3`, `sleeping.mp3`; which moment plays which is `SOUND_EVENTS` in `palette.js`, one switch per event saved in `looks.json`), and a `package.json` that only says `"type": "module"`, so Node (the server, `console.mjs`, `lib.mjs` and the tests import several `public/*.js` modules) parses them as ES modules without a reparse warning |
|
||||
| `public/help.js` | the Help dialog's PURE rules: `HELP_TABS` (17 tabs: ids, order, labels, diagram flags; every tab uses the chosen highlight color), `helpTabFor()` (which tab opens, FR-8 order, first match wins: finished → Stopping and finishing, server gone or agent adrift → When something looks stuck, opened from the Workspace dialog → Your workspace, then Ask, the Subagents tab → Helpers (subagents), a red-meter dashboard → Session meter, dashboard, a doc or the Overview, a build, else What this page is) and `helpKeyTarget()` (roving arrow keys, Home, End, wrapping). No module-scope DOM, so `node --test` covers it |
|
||||
| `public/workspace.js` | PURE, no imports: the Workspace's name rules (`nameProblem()`, `NAME_MAX`, `defaultName()`, `freeName()` for the `-2` suggestion), the footer label and its width tiers (`footerLabel()`, `FOOTER_TIERS`) and `changeLine()`, the `Workspace: …` reply line an agent is handed per change. Imported by the server, `console.mjs`, `lib.mjs` and the page |
|
||||
| `public/meter.js` | PURE, no imports: the session meter. `WEIGHTS` (the one place per-event points live; its keys are also `RUN_EVENTS`, the `run` events `post` accepts), `LAUNCH_COUNTED` (workflows whose launch itself scores), the built-phase sizing (`TASK_EVENTS`, the keys of `TASK_BONUS`: `implement-phase` +0 and `implement-review-phase` +1; `isTaskCount()` accepts a whole `tasks` from 1 to `MAX_TASKS` 999; `runPoints()` scores such a run `ceil(tasks / TASKS_PER_POINT)` (3) plus its bonus, and any other run its `WEIGHTS` value), `ANSWERS_PER_POINT` 2 (`answer` entries score per skill run, `floor(count / 2)`), `breakdownFrom()` (the click-the-ring list: one row per scoring entry plus one answers row per skill run), `pointsFrom()` (the count, its sum, folded from `ledger.ndjson` and deduplicated by id, never stored), `levelFor()` with `YELLOW_AT` 5 / `RED_AT` 10, `ringFraction()` (full at `RING_FULL` 15), `WORDS`, `tooltipFor()`, `RED_BANNER` and `meterView()` |
|
||||
| `public/mentions.js` | PURE, no imports: the `@name` popover's logic — `mentionAt()` finds an `@partial` at the caret, `matchNames()` filters the workspace names, `applyMention()` splices a pick in and returns the new caret. Used by the Ask box, notes and text answers |
|
||||
| `public/favicon.js` | The tab icon's status bar. `faviconState({ mood, spin, finished })` (PURE) maps the call `renderStatus()` makes for Planny's line to `busy` (the spinning ring), `ready` (`point`), `attention` (`adrift`, `gone`, or `work` without the ring — the stale line) or `plain` (finished, `happy`); `faviconSvg()` is `FAVICON_BODY` (kept equal to `favicon.svg` by a test) plus a bar along the bottom edge in the `FAVICON_COLORS` color (busy dashed on a white strip, so the states differ by pattern; the rest solid); `setFavicon()` swaps both `<link rel=icon>` hrefs only on a change — the SVG as a data URL, the PNG link drawn through a canvas. Called from `say()` in `renderStatus()`, which runs every second |
|
||||
| `public/subagents.js` | PURE, no imports: the Subagents switch. `SUBAGENT_WORKFLOWS` / `offered()` (the opt-in table: `implement`, `implement-review`, `quick-task`, `review`, `pathfinder`, each with its default instruction), `cleanSetting()` (`{ on, instruction, max }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20), `FRAME_LINES`, `blockFor(setting, told)` (the `Subagents:` lines and `subagents` field an agent is owed, given the session setting and its cursor; never says "off" to an agent not told "on"), `checkHelper()` / `checkHelpers()` (the `helpers` house rule) and the page's view rules `showSwitch()`, `switchLabel()`, `helperRows()`, `showTab()`, `CHECKIN_LINE`. Imported by the server, `console.mjs`, `lib.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `picker.mjs` | the per-OS native folder picker behind **Browse…** (`pickerCommand()` → `{ command, args, env }` or `null`; `pickFolder()` runs it with async `spawn`, so the server keeps serving while the dialog is open). Copied from `src/launcher/plan2code.js` (self-contained CommonJS, so it cannot be shared) with the prompt as a parameter; a drift test keeps the two in step |
|
||||
| `update-check.mjs` | the dashboard's release check, server-only (never in `SERVABLE`): `compareVersions()` (numeric X.Y.Z, `null` otherwise), `latestTag()` (the highest `refs/tags/vX.Y.Z`, peeled `^{}` and pre-release tags skipped), `checkForUpdate({ installed, cacheFile, now, run })` (never throws) and `runLsRemote()` (`git ls-remote --tags` on the repo: no shell, `GIT_TERMINAL_PROMPT=0`, `GCM_INTERACTIVE=never`, SSH `BatchMode` when `GIT_SSH_COMMAND` is unset, `windowsHide`, killed at 10 s; git authenticates itself, the console never touches a credential). The answer, failures included, is cached for an hour in `~/.plan2code/console/update-check.json` (`UPDATE_CHECK_FILE`, in `PROTECTED_CONSOLE_FILES` so no sweep removes it). `server.mjs` starts it after the ready line and never awaits it; `stateFrame()` carries `update: { installed, latest }` only when a newer release exists (its `latest` is part of `haveKey()`, so a page that connected first still gets it), and `GET /version` returns `{ version, latest }`. Tests seed a fresh cached failure in every console home, so no test server reaches the network |
|
||||
| `public/chat.js` | the Quick question chat's PURE rules, shared by the server and the page: `CHAT_LIMIT` / `CHAT_MAX_CHARS` / `CHAT_MAX_ATTACHMENTS` (the combined image + document cap; `CHAT_MAX_IMAGES` is kept as an alias of it), `chatOffline()` (the server's `409 offline` guard), and the page's view model (`chatView`, `sendState`, `nextAbout`, `contextOptions`, `unreadDot` / `shouldChime`). Ask context is the `{ history, about }` model: `nextAbout()` records the last 3 places visited in `history` and sets `about` only when the person picks one from **+ Add context** (`contextOptions()` lists that history plus *This spec*); dropping it or a successful send clears it, so the page never attaches context on its own. Imports only `answers.js`, no module-scope DOM, so `node --test` covers it |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 13 starter templates and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/starters.js` | PURE, no imports: the Role list (`ROLES`, `ROLE_NOT_SET`, `normalizeRole()`, `needsRoleNudge()`: the dashboard banner shows until `looks.json` carries any `role`), the 19 starter templates (Markdown `## heading` sections, shape pinned by a test) and their per-role orders (`TEMPLATES`, `TEMPLATE_ORDERS`, `templatesFor()`, `templateSwap()` for the replace prompt), and the Ask starter sets (`STARTER_SETS`, `STARTER_SET_FOR`, `startersFor()`). Imported by `app.js` and the tests; in `SERVABLE`, preloaded by `index.html` and parse-checked. The page owns the wording; a skill only flags its fresh-idea `text` card with `"templates": "idea"` |
|
||||
| `public/answers.js` | the page's PURE answer-shaping logic (what an answer reads as, what a placeholder offers, whether a send carries an answer at all). Split out of `app.js` because `app.js` cannot be imported outside a browser, so anything left in it is untestable. `scripts/test-web-console.mjs` imports this directly. |
|
||||
| `public/labels.js` | `taskLabel()` / `activityLabel()`: rewrites a build's `Task 4.2 of 6` activity line to `Task 2 of 6` (only for `implement` / `implement-review`; a plan's `Task 2.1` is a real section number). A separate module for the same reason as `answers.js`: pure, so `node --test` can import it |
|
||||
| `public/boot.js` | `playWake()`: the dashboard's first-open wake-up. Self-contained (it owns its timers, the listeners that swallow input mid-run and the one measured glide transform; the page's `stir()` callback times the nudge between the click and the boot, which `app.js` fills with one snore; `skipEl` — the muted Skip button, and Escape — ends the run early with `onSkip` as the cue to silence queued sounds) and free of module-scope DOM access, so it can be imported by the tests and kept out of `app.js`'s render paths; `GLIDE_AT_MS` / `DONE_AT_MS` are its timings |
|
||||
@@ -199,6 +202,7 @@ Key design points:
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `server.mjs`, which paints `data-width` on first load; `app.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honours `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes }], bytes }`, ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `models.json`). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
- **`open` needs no payload, and runs first.** `--file` and `--title` are optional (the title defaults to the folder name). Every skill's Interface line puts `node "<D>/console.mjs" open --workflow <w>` BEFORE reading console.md or the project, and a test (`every skill opens the console before it reads anything`) keeps it that way; a blank session renders a starting screen ("Starting Pathfinder", Planny in flight) until the first post. Every skill replaces the flight with its own animated pose (init — init-update borrows it — pathfinder, plan — revise-plan borrows it — document, implement — implement-review borrows it — finalize, quick-task, review, handoff; only the dashboard keeps the flight), cloned by `startStage()` in `app.js` from `<template id="start-poses">` in `index.html` and animated under `.pose` in `app.css`; `START_POSES`/`startPose()` in `answers.js` is the list, and a test keeps the template in sync with it and every catalog workflow mapped to a pose. The same pose stands above the waiting pane (`.waiting-pane`, agent working with an `activity` and nothing to ask). `posePane()` keeps the pane on screen across renders when the pose is unchanged — `renderMain()` holds any `:scope > [data-pose]` child back from the clear — so the SVG never leaves the DOM, its animations never restart on a state frame, and Planny carries unbroken from launching → starting → waiting. The dashboard's launch hand-off resumes first and reads the launched skill's file after.
|
||||
- **The start path is timed, and `open` is built around it.** Measure with `node scripts/bench-web-console.mjs` (`--browser-delay 900` for a real Chrome launch, `--roundtrip` for Send→agent and post→page, `PLAN2CODE_CONSOLE_TRACE=1` on `open` for a step timeline). Four things make it fast, and each is load-bearing:
|
||||
@@ -214,7 +218,17 @@ Key design points:
|
||||
| `ledger.ndjson` | `console.mjs` | append-only, one JSON line per entry. Meter events: `launch` (every fresh `open` and every resume into another workflow), `run` (a post's `run`, id scoped by launch, with `tasks` when a built phase reports one) and `answer` (one per item the person answered in a collected send, written by `ledgerAnswers()`, id `<launch>:answer:<send stamp>:<item>`). Also `folder-issue` reports |
|
||||
| `workspace-cursor.json` | `console.mjs` | the last workspace `version` handed to the agent; advanced after the print, never backwards |
|
||||
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
The page changes the workspace only through five routes: `GET /workspace` (`?check=1` re-stats every folder first), `POST /workspace/add` (path resolved against `state.worktree`, `~` expanded, case-insensitive duplicate check on win32/darwin; `not-a-folder`, `duplicate`, `bad-name`, `name-taken` + `suggest`), `POST /workspace/edit`, `POST /workspace/remove` (the original folder refuses) and `POST /workspace/browse` (one picker at a time, 409 `busy`; 404 `no-picker` when `remote` is set or no picker exists; `PLAN2CODE_PICKER_ECHO` stands in for the dialog in tests). `stateFrame()` carries `workspace` (folders, `missing`, `remote`, the current launch's folder `issues`) and `meter` (`meterView()` over the ledger), and both files are on the 1s poll; it also carries an optional `update` once the boot-time release check (`update-check.mjs`) finds a newer release. The agent hears of the workspace through `open` output (`workspace: { folders, missing? }`, which also seeds the cursor) and then each change once, as `workspace: [...]` plus `Workspace: …` reply lines on `wait` exit 0 or `chat`; a change alone never ends a `wait` slice (`pendingWorkspace` on exit 10). `post` and `open --file` lift `run` and `folderIssue` out of the patch into the ledger, never into `state.json`; an unknown event or a malformed issue is exit 3. **Remembered workspaces.** `lib.mjs` keeps `~/.plan2code/console/workspaces.json` (`WORKSPACES_FILE`, under `PLAN2CODE_CONSOLE_HOME` in tests): `projects[<case-folded worktree>] = { path, project, specs: { "specs/<name>": … } }`, each entry `{ original: { name, description }, folders: [{ path, name, description, nested? }], at }`. `rememberedWorkspace()` answers spec, else project, else nothing; `initialWorkspace(worktree, entry)` builds from it, both in the server's first `workspaceNow()` and in `open`'s read-only `workspaceOnOpen()`, so they agree. `workspace.json` carries `scope` (the spec key or `""`). Every user change (`bumpWorkspace`, not `missing`/`found`) calls `rememberWorkspace()`. `setScope()` swaps the list, logging `removed`/`added`/`renamed`/`described` changes so the cursor stays truthful; `POST /workspace/scope { spec }` (the dashboard picker, on selection and before a launch) seeds an unsaved spec from the project's list, and `followSpecDir()` (state poll, boot) moves the scope to a posted `specDir`, saving the current list as an unsaved spec's. Two writers, each a read-modify-write of one key: the server and `console.mjs forget --spec` (Finalize Step 6). The contract is in `console.md` (Workspace; Posting an update → Session meter) and `building.md` (per-phase `run`), so the skill prompts stay unchanged.
|
||||
- **The Subagents switch is a standing instruction, injected only on change.** The page's icon button (`#btn-subagents`, after Write a brief) and `#subagents-modal` show only when the frame's `subagents` block says `offered && supported`. `offered` comes from `public/subagents.js`; `supported` means the latest `{ "type": "open" }` line in `events.ndjson` carries `caps: ["subagents"]` (`latestOpenCaps()`), so an older skill copy's `open` hides the button. Four places hold it, one writer each:
|
||||
|
||||
| File | Writer | Holds |
|
||||
|---|---|---|
|
||||
| `~/.plan2code/console/subagents.json` | `server.mjs` | per project folder → workflow: `{ on, instruction, max }`, `instruction: null` being the shipped default; on `PROTECTED_CONSOLE_FILES` |
|
||||
| `<session>/subagents-setting.json` | `server.mjs` | `{ workflow, on, instruction, max, revision }`: synced from the store at boot and on any workflow change (`syncSubagentSetting()`), `revision` bumped only by a real change |
|
||||
| `<session>/subagents-cursor.json` | `console.mjs` | `{ revision, state }`, the last block handed over; `open` resets it, and it moves only after the print |
|
||||
| `state.json` → `helpers` | `console.mjs post` | the helpers the agent reports, merged by `id`, checked by `checkHelpers()` plus the prose scan; dropped by `switchWorkflow()` on a dashboard hop |
|
||||
|
||||
`POST /subagents` (origin-checked; `400` `not-offered` / `bad` / `too-long` / `max`) saves the store and bumps the session setting. `consume()`, `cmdChat()`, `deliverChat()` and `open` append `blockFor()`'s lines last in `reply` and the `subagents` field; a change alone never ends a `wait` slice. The page's Subagents tab (before Ask) draws `state.helpers` through `helperRows()`. Helpers never reach the meter ledger. Contract: `console.md` → Standing instructions.
|
||||
- **The filesystem is the transport.** Sessions live in `~/.plan2code/console/sessions/<sid>/`, deliberately not under `specs/`, so the console cannot trip the metrics scraper or the loop's marker parser, and survives `git clean`. A result written after the agent dies is picked up by the next session.
|
||||
- **Attachments on notes and quick questions live in `<sid>/uploads/`**, never in the project: images as `<uuid>.jpg`, documents as `<uuid>.<ext>` with `ext` from `DOC_TYPES` in `answers.js` (text, code, PDF). The browser re-encodes images to JPEG and sends raw bytes to `POST /upload` as `image/jpeg`; documents go as-is as `application/octet-stream`, the extension taken by `docExt()` from the uncut `x-p2c-name`. `readRaw(req, limit, cb)` in `server.mjs` caps images at `MAX_BODY` (4 MB) and documents at `MAX_DOC_BYTES` (10 MB), and drains rather than destroys so the client gets its 413. Images need the `FF D8 FF` magic; documents pass `checkDocument()` in `lib.mjs` (`%PDF-` for PDF, strict UTF-8 with no NUL for text), else 415. The server names the file with `crypto.randomUUID()`. `GET /uploads/<id>.<ext>` serves images as `image/jpeg` and documents under a fixed type (`application/pdf`, else `text/plain`) with `nosniff` and, on text, CSP `sandbox` (a sandboxed PDF cannot open in the viewer), so a browser can show but never run one; `recordSubmitted()` writes every send's note onto its item as `sentNote { at, text, images, files }` (paths and names only), which `noteAwaiting()` in `answers.js` turns into the Sent box's attachment links and the Notes pane's pending note until the agent's next thread message; `DELETE /uploads/<id>.<ext>` takes any allowed extension; both stay contained under `uploads/`. `isOwnUpload()` returns the kind (`"image"` / `"file"` / `false`), and `attachmentsOk()` makes `/submit` comments and `/chat` messages carry images only in `images[]` and documents only in `files[]`, this session's uploads only, at most 5 together (`MAX_ATTACHMENTS`). A comment's `reply` gains one ` Image: <path> (<name>)` or ` File: <path> (<name>)` line per attachment, in attach order; a chat entry's lines come from `chatReplyLines()`, its images first, then its files. `sweepUploads()` bounds disk growth, and the session sweep removes the whole session a month after that. A note attachment a spec file cites is copied out first by `console.mjs keep` (`--session --upload --name --spec [--from]`): it checks both paths (the upload must sit under the session's `uploads/`, and the spec folder under `state.project`, real paths included, so a symlinked folder cannot carry the copy outside), copies with `COPYFILE_EXCL` and reuses an existing copy, prints `{ ok, path, link, image, reused }` with a forward-slash link relative to `--from`, and logs a `keep` event. It is the agent's hand, not the server's: it runs in the agent's shell only when the agent decides to cite a file, so the server still never writes into a project.
|
||||
- **Answers carry their terminal token.** Each item ships `fallbackText` and `token`, so a click resolves to the literal word the prompt already expects (`approved`, `a`, `skip`). No workflow needs a second code path, and declining the console degrades to prose with nothing lost.
|
||||
@@ -225,7 +239,7 @@ Key design points:
|
||||
- **The Quick question chat is a second, append-only channel beside the card slot.** The page's **Ask** tab (always last, every workflow, still there after a finish) posts to `POST /chat` (a message, or `{ reset: true }` for New conversation) and `POST /chat/decision` (Approve / Decline on an edit the agent proposed). The server is the only writer of `<sid>/chat.ndjson` (one JSON line per `message` / `decision` / `reset`, each with a `seq`; `appendChat()` in `lib.mjs`); `console.mjs` is the only writer of `<sid>/chat-cursor.json` (the last seq handed over, advanced only after printing) and of the agent's replies in `state.json` → `chat.replies` (merged by `id`, checked by `validateChat()`: real `re`, proposal paths outside the running `specs/<idea>/`). The server never writes chat into `state.json` — `post` read-modify-writes it under `withStateLock()` — and `stateFrame()` merges inbox and replies into the frame's `chat` block (`conversation`, `messages`, `typed`, `limit`, `offline`) in memory. `/chat` never checks `pendingResult()`, so neither channel can block the other. `wait` keeps its exit codes 0/10/20/30: exit 0 gains `chat` (or is `type: "chat"` with no actions), and the instant `console.mjs chat` answers 0/10/20 without touching `result.json`, which builds run after every task. Guards: 10 typed messages per conversation (`409 limit`), 4,000 characters (`400 too-long`), own uploads only, of the right kind (`400 image`, `400 file`), `409 offline` when `chatOffline()` says no agent is there, `409 stale` for an old conversation. A hop through the dashboard (checked on every state change and at server start, so a restart still sees it) appends a `reset` and starts a new conversation. A lone reset never ends a `wait` slice (`deliverableChat()`); it rides along with the next message.
|
||||
- **`validate()` in `lib.mjs` enforces four workflow rules mechanically**: max three open required questions, no internal vocabulary in a title, one recommended option, and no loop markers or metrics-scraper bait.
|
||||
- **The palette is written twice for dark, and that duplication is the mechanism.** `@media (prefers-color-scheme: dark) :root:not([data-theme="light"])` follows the system; `:root[data-theme="dark"]` is the explicit choice from the colors panel. Drop the `:not()` and a system-dark browser overrides someone who asked for light. A chosen accent is applied as an inline custom property on `:root` (CSSOM, which the CSP allows), and the default is applied by REMOVING that override so the stylesheet's own per-theme values win. The server's `data-looks-accent` stand-in only lasts until `applyLooks()` runs, which removes it first thing — left on, its rule would beat "Back to default".
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 16 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Help is in the page, built on first open.** The **?** button (`#btn-about`) opens `<dialog id="help-modal">`, which replaced the old "What this page is" About dialog. Its 17 panels and their icon sheet are hand-written HTML and SVG in `<template id="help-content">` in `index.html` (after `#start-poses`), cloned into `#help-panels` the first time **?** is pressed, so first load builds nothing and Help still reads fully once the server is gone. `help.js` supplies the tab list and rules, `app.js` the wiring (tab buttons, roving focus, `renderAbout()` for the live connection line on tab 1, `lightDismiss()`, and a Ctrl/⌘+Enter guard scoped to this dialog). SVG is styled by class and CSS variables only — a `style=` attribute is dropped by the CSP, and a test fails on one — and every number the prose quotes sits in a `data-fact` span a test checks against the constant it comes from.
|
||||
- **Markdown is rendered to DOM nodes, never to an HTML string** (`public/render.js`), so agent-authored text that quotes a hostile source cannot execute. Only `marked.lexer()` is used.
|
||||
|
||||
Tests: `npm test` runs, in order, `validate-char-count.js`, `install.js --verify-skills`, `parse-check.mjs`, `check-skill-table.mjs`, then `node --test scripts/test-web-console.mjs scripts/test-launcher.mjs scripts/test-skill-scripts.mjs scripts/test-script-pathfinder.mjs scripts/test-script-finalize.mjs scripts/test-script-handoff.mjs`. The parse check exists because `node --check` parses a `.js` file as a CommonJS script and has already let a browser-fatal string literal through; it imports each shipped module as a real ES module instead. They live in `scripts/`, not `src/web-console/`, because everything under the latter ships into every skill.
|
||||
@@ -265,7 +279,7 @@ Typing `plan2code` in any directory opens the dashboard skill against the curren
|
||||
| Claude Code | `claude /plan2code --permission-mode bypassPermissions [args]` |
|
||||
| Devin | `devin --permission-mode bypass [args] -- /plan2code` |
|
||||
|
||||
With both on `PATH` it asks `Which CLI should open Plan2Code?` as a numbered menu, the last pick pre-selected (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking; with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed), and it only prints which model will be used. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
|
||||
On a terminal it first prints a Planny banner (`renderBanner()`). With both on `PATH` it asks `Plan2Code opens inside an AI coding agent. Pick which one to use:` as a numbered menu, the last pick pre-selected and marked `(last used)` (Enter keeps it; a number, `claude` or `devin` also work); with one installed it uses that without asking, printing `Opening with <CLI>…` (as does a `--cli` pick); with neither it exits 127 naming both. `--cli claude` / `--cli devin` (or `--cli=<name>`) skips the menu and is never forwarded; an unknown name exits 2, an uninstalled one 127. The pick is saved as `lastCli` in `~/.plan2code/launcher.json`, merged beside `lastFolder`. Before spawning, unless the forwarded args carry `--model` / `--model=`, it asks `Which model should <CLI> use?` from the curated `src/launcher/models.json` (copied to `~/.plan2code/bin/models.json`, overwritten by every install) merged with the user's additions in `~/.plan2code/models.json` (edited in the console's User Preferences → Models). Enter keeps the model the CLI last used; a pick appends `--model <id>`. Ctrl+C at any launcher prompt exits 130. With no TTY on stdin there is no menu (last pick, else the first installed) and no model question: it prints that the CLI will use the model last used in it (switch it in that CLI on its own, or pass `--model <name>`). Headings, numbers, defaults, retry lines and the `plan2code:` error prefixes are colored with `paint()` (the escape values of `install.js`'s `COLORS`, copied), stdout only when stdout is a TTY and stderr only when stderr is, and never when `NO_COLOR` is set; piped runs print plain text and no banner. Other arguments are forwarded to the CLI (`plan2code --model opus`), and its exit code is passed back. Tests: `scripts/test-launcher.mjs` (run by `npm test`) spawns the launcher against stand-in `claude`/`devin` commands and a temp home.
|
||||
|
||||
**Design constraints:**
|
||||
- **Stable copy, not the package dir** — the installer normally runs from an npx cache directory npm may delete, so `installLauncher()` copies `src/launcher/plan2code.js` to `~/.plan2code/bin/plan2code.js` and the shims point there. (The loop/metrics/bot wrappers point into `__dirname` and don't have this protection.)
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
---
|
||||
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` |
|
||||
| relabelled | `same-id` | Old label | New label | Claude Code docs: <page> |
|
||||
|
||||
- **added:** offered by the CLI, not in the file.
|
||||
- **gone:** in the file, no longer offered.
|
||||
- **relabelled:** same `id`, a better or changed label. Propose a label in the file's existing style.
|
||||
|
||||
Summarise 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 **relabelled** 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).
|
||||
@@ -1 +1 @@
|
||||
U0VOQwGHvlBAKBpANryoCdXbfPtfW6rftbEVcNYHSx1rwcmt5mK1z/0SJkc5SXJbEZQl6q639HxyFiGyLv13negwgwNcvEFOSnlhqVcClGqjZMXz0vavtWKpCqZP4B+OudqsaKbx7q4dd8FM6UWpP1h6lTlTG7DyNBgpWgfE9BQuOMJ0iE1L8xLoW49+hQh4of0T23jz1l00GHzaZwtaK1fH8QKV8SU2ENQGqMgY/WcJqoBcgq4yi+P5RHKdT2QxTuK8Hph9mFjaEbh5jbkmtuwrl5lzty3bqSHBFILZ+lJcicjKwrfbKowhYEEpK6LFrODIWCr/IhOoXfxVGzg1rwGVoAoEphjEq1S+LhnUciWJoghHfwPZtrDWnpoUSJ7SBLCKcDew8zPXUre3A9NHmd3G+FrDYKybDts8zGCKovJtOIff3U+6h0T3wy4UmKai4RSWR+LOvCFaPgHxGI49PtR5Bqtv9bhcW1LBUzjcv00vLsUQRcOqV7q5Dj6mq+pzm3ReD3J0HgUzFwE2sZPENtUJhTjPsWPI3llQlgcNT0u5knKvT2ERy5OVrSJK963Pl9vRqCGtVcBRPWidRY8EeH6vOFFuzS/FqsFGcLYPK6MGks9W/RNI/aQQN1eTANJgsnuKIT/RAlABgwh+l2X8JKTsH97/8DCakJVw4qPKWccysIYPNc3Ra4szlz/B71Z96FmgOA1xFE2S+j74vAKKwEmguFhdVIvjw16OQY0CIMpaK1rDl9MVfvRVVKHd8mDZI6I8jZr2MulFBpvWCpoUWFMGdfmNTfbvUFEt1Bd6idKFvy+E/chg54K+CdY7Ua4sOdTC3sx2+uIUYAPa40N42f8Nvi6gnmtMQK5+f4anQ7b5HrQ/PkVcrXEiG6VzMcd6s5wuPi0mqJ1P1g0Tqg15uIhu5fIr8YdbdouuWX59yptkPCTEVwkvYSS1UrpH2Zuhm7EHU6o008Iw0EpH2/V0IZxNGrbw8YvzeGBSg3yB2z5rZ5Mpw5NXzf1mtPaUAGQwRfL3gF5u863lqZYtDm4t10mYQ8Mq/SolCUelkiagpxG/MdAo5tA9Bql+8sRUbCxXEl7WGLrW8Skm5ls2y9mJ4pluw6N9vByyGUmHCB6Tr48rFzdEH5OMA4IRrIrXm99p/KamebSksoX1ahi2/Vf19Osq6sENF/sOHJSMxj+BOi4oIjaLlefIM35KsymXCzB3Nr+OLAXWkpjMAmt3ve8cvNYhXS85t+LqtCLhv8h38wmA1Sx+VSKqoMF9cjBlAhXo59flIMaxV5c1PGZc4+lPtWtb9SlK6xE5OKweehe49KZOCIKJxhO6yy9kAJC6CexnbfjYfWz0tFn98SYagZt4V55nqSp+6xtAUSp2CeIjlaBoKWQjD8xLALSxeZJO2HYfgJ/+acwEFKTnDdxYEVzhHOENpc5DD8IPeqUEHMEzzIuR4iTq75XGmPREmltAWq3xVulYHMjTc9svXi4S2ZeA8RzXvTx+wH5hPQ5lu1w9OaAxpqfHbxSRqM5tgEwhc1FoielbBdDpbg5kzHLP3sEi8fYWbBwcb5muWtz2d59ldGLM0XSSCojQC9Jpq4QpEeq0ziK9tTAELziJ/lFf9FpPPN9n+b6WBCgGgLX5yXt9FD+kNTR6rRgXY+YvTpSJLGZtXT0mwV7ejq0AqG59s+2mc1Cn/SwdKYnYTgaofnZDKDbGRVuoeC7i00DOaa2xL1Lpm1UA7pQRbvAh1C7lFc5P/ThdU9KVSFnW3nip6WSBYsKnAV82Q6yPVPWwoWaTsxAmpwMk7fRnZ+UdvmRgpYxr0XQYXa01twCxb38otzXf/BGQ9d+yGUVRjFtKbzPuFvRMIdJ1ZIpXXUedvifPOTay1KPps7DCfv+0BMaDPMQBnDH+WU4tQ4qgG/5PSxS0LVK1Em3+4C1pIe3j/nDmENRrdZA4a23pG2Pdexzi6tXWNq2a/jWyVKtyKnamJj245MegILjDiePkjGUgcCXty1/fRd72b480CWBqLt6zqARI7javJ/Q7bZuLIvZRxCMMq0SACnDq7eFj4Lhf59sg4qtMIay/55tS/lkcebGc/WSA4VeP7/A8R/f3OpCQ1UuBz4KkSDS/HE5TMCXIHOQ9dVGCJCPPAcxWtz8DiNBmOm3UoxQXo3C3on4eznlDd9/NLt1bE6chFXSwxRXf2zMVWymXQh7MCx4iijgMJN/V+zFag3aT8BZKFnPb7cSxJwSEmZRph/xLNctcyDmdOMpJSdYKN6LyRacfb6JohC1oNQVFrgCETWhmXbPfIf+ERCH4w/JycXO433CrRRWXVcGRidhMIZ5xeOzCWjz9uRpDuzKJfQFU71eBMZM5hubHGB65fYCBKJ9DllzdFQSbPtUq2RLPFTUHsIIyt3YIJy+/MR51U1Almf7lGqM5N4tZwU228H1g4lzxO53mul8c7p1T8/uZCM2bB6BOVmMXrunOeD5nvHm1CYP3Sd4iBBtORyEkEMaf+hKy5ZGfexP6xhWzU8LzsvRbIig87WvM0kkMW8plIN/g75HjlEycDhAuf+3QYp7vvb8FxF7gq9t67bkivMPqfj2YacL2Ip3GEJ8nJJZMtFePWDsThDI2BcvLfZPwEK/szxKBjJjz0r9HxU2rebpq4a7KnnayBg5Mr0l+iHTvx5bCfq74NYWcmrwp7kT45OhsA8lmO6I2dBFpq7nUUkGl3mNzGlJJzAWVdKWhQcGJJ19tT8AsKOXE7gED3hzcn89DqgW59mO5xpwdvmZOu5jdQ6kEpT2+sQqa7Y1Lrfa5EqG3hT1vByYuM7K8syo7ftO0qSi8NIO/h/9qY5oJWrS6GaDmKZZGvrSDDsM1A47dy/kavqYEszIeQUlg4VGFWXmP2WqRNRV/Kiee2P0ri9AysQY4gj8cknljNV8kKwIPpZNl4Vk+mx5rCEHFLG5C0CnvEq0UprzObyUaJ+jTHcURf12kqvWYiDCzpU4E8+GqqsEfknyLgWPn7YODJH7Elx9XxkRvoGSg5BM4OwN9mrBdpHmy6OYF/QGKc2tHBxD3B9cxT3auNA7Z0uyUi+erq1DrjIbpEukatpp8P0iIeQNsIDuJWBTz/Ybfw/ZhwPNbd85Y+QqviPPfhEFjYjFqZD1j/zHe68q6cR4ke50f9DYxzzZ1jyAdKYP2vRqTi8yggrtTEcQcXdY6OG6ckhwiV3ygaHLFLY+xrfONaWKHsPW5t5apn6VZV1jIpX+jEZIkDgkAWZAx8skZ/2eVUnElZ4I+gM+ButsUZeCX7qfpXsaI6P76P0bzOP88Yg+68spjxKZRef3qCaeVW3kEF+nSXk0L2fY552uwJDz4GA28U8LOWtALa/kHoA5zdisUndqF6PKmb7y2Xw+TgaY41M/Eqrolv9jka3WRi2WxRXj9LvmsUPUydgKltww9G3dnqEA4IuPDwLWB73oENQA5tz4FZ1IIZg3ccf2Zl12mrdSUTo7D5G+W7o2NQERSdby3T75CjAcOkAzKxngF7dhVtEBAWLdb4wsnhvE//R0qVKIWCm4iQ7SJDsejgHeYNMhZQh8EKGDQjBwA8MT9tgHsT/W1ycowsWoWleZ0F9KkGCOLVeUmFkJCi8Fzb980fF/LwwR3mvC9UB0ztDK7A5tsUA9/iczy+nAQz4DJatowGAEHzgr3hsJl1InH7dXdpdi53CstfqUf58DfQI3Ax5pJqvLVr6J5tZJe8ZkmcZAoqrDveizHlwZkE3voTB9HbwTDXr7KeEv0xB6muFrta07KAgrMS15EBSiGVKsguw4/UYUMOtF/Sh4nJVF0F6cPkFldBZnW5c2oKcy0dtMrtspdgBkXCDjAKp6bJoFocxmiwlGrkBUhN55H7dlyAyoG1ddAcAL8861QCSEbldHbBLKIKblGroTQzFMrX1XGwU/UYyGrkGf+1u/rYq0lJt3Nm6ozQGszpnQ5Bi4UrLyScY5vLYuYvzNEoIM0vrQ2T75TneK06CP4NlyoRqzuBm50ufCnTpWbH/NNmjB1M1w4bgU0QAuQQISqCqSSyROE/klQCde7vB9ogHBgestE/+wWOC7zJxleraQCGYwtQTzuSxJyiQzKcVxDSgcBI8As1Ksf/g1kpUbeOQjdnCVgERRYSOQzuLt4KBMkiplpWf0TeV7/05puNKijIpLoiQQYWYMLMaUBSQyjdQfF+TNJSeUfX86yI68iXtkwD1M46oDmzc0T9Yk5HfCEYKU8jfe679JoKg3F4axRHzi7M9VUi8gP03ovKzXicl/ajNQUXr951aqWHSDYyiRAhLU+ZwJC1l1ku71YrHFrkBi/tZEjhdbFSq2Oiu9118S9zMEKvO7Q96bg7BJztH2aygOW5TiTwM1Vm+Z5/KhSM4K70HVQZoTn8xu7wJeWLwteV7ZQrlE19WT2dpHnrqgiLvpOzZP++2N1ls3vulvrfDvF+GPlSqiCPr5qJ/m1liqkfl+f6ataFtljNnRXxrFu0MuoKTmensfrTT/RcFAcCZe7NmA0UqAQTTPlazmUMDapSYkyQ8lWlF5AoxpsfiwD82MxCbpfCVBSundpwfAQQQgGVQ+HVUhgsus9QIqTchOzZxxGfJ5Wk9GJCNKvzDz03svzwb1q7R3r6RBakU52jl/diFbPXVwqRC/TeiDSJGSqyBhWXOmpjO8NlrLVV4BhNhHTtB6Z0wukA0aixVkBzozTvmgEk0b2NLCy4a0CQ0pqhLsviq+/NSH5l2rzfQZxVllgo7mcv+FCKYQRbIXjNjfeSkgq+pGq7+qbUhL0c2cPLiIZ5sy7AQNLixBbdeowQCqYJZNUxy8Bt7zfo0Gbdjnt3CoaUFiPk0WjLu45/FvpQgL3LE8ML7SbAmto1LadKhK9WsgC7sBa0PR8SeT80tUu/Yz/hdiHfZgYpArE2K8J7ZZFF2W9+9+DVFNeCJZduqNoj73/rZGxtxQcFu0qAGkbVbP8FKV9VX16RGexD6En5Sx89MjdkGDIdAcnSUFkXjRh62ZLine truncated
|
||||
U0VOQwGXVSGXI36GSw72BYVsi/4ONgA24308DH4YD+cAxK7y8sA5FELtBHEOS9Afj/6nBCRvL156GKEdmKfri1gtkU2XYz/x1lJBa15+a3TWTqeQrPUKLxSW0Ah0UGuPPQVxwoIBXMz9ADPlbG+qpsw/behYXr491MJC8qqRNqrQA/I0bAkLvxer4AZPz/SGohCbpQy3EmmwYOUshDm8QLEp+VjkUZfJmbjWSPXsNRhyKuMzAEHQI3OiWA/MR/qqkOzjhGHb98erQhu3Ebz3fbeR9qSDyezBoBOJN8dRb7K5HFh8IRVFhKsX5CltpO1zEcisJUN0kcI7cz6GCYDt1v+L2KVfJNFVbfveB7vZvDVUTdQ2Gu87M1GFr4bQqUjRp9TM5VpPRuUkv3IDrIcXgdc1I9lQgHki74tVmt1QBtzyOznRd4BN+8dekrE/PRlH99gPTrvCk2WRZkrddlXsBlj+qUYHOwdmldf+b2HAcFjmYu6j/585evlOvbJgMkg+Mhhbr0q7TJcSDGfF8tCRLURMA+p1bvhbZ28fRm74KKTStT85JND+4AUQQXtFxi2r98pY+1fkA8i7Gz8lNR6s0SqaJPOV0NPue0SMqeD37G7LUvmoBz7f6BhmX7O3XcTC+2ewcH4FmZH8qCSeNDGhuyMZJZxjSWyAjrCGPjBVE4IYCnLcaA8A4ZIjbAldtMNAGgfUEMNbwZpuX0ox9LzkZuOHyPICg7IIwXkP1V7HZcejYiAdmqyY8RxNdqtC4QhAjBE5GCcixqY+UwiG3tA0n4a0+Z33u9O+7wHIQ2/C22mjzwbqWoX7R8zqIcUoiY9UB69NFOb23FQTTb3nhm/KwvVlj7jE0B0Bjm+rha+KcetU6GmY3bWvfMmdSF8l2XWdlYVvSlIgHCZ9Pv/ftrBZbdf552tVOOqZgv0HOhBH+gb2DxOlFRRyfOg7BpQzUr3B1CAV2o9aZ3Q7nb02r2658HE51eIftyYfWxpmRLRlrcSkiUXhTEwFSYptH29qIhu2jgzPZ75yUXmWCNa20mddUOjwd+SOroprx7fpkiEta27UC1jBg4IabC3U4sgwd3xy3JUYd9S819bqUhjUlRqGTT89hzPdCFWOP+Ym4R6VZAcAzXgoWhFP2EANONmTRoijJs5UFYfeaazXTjJNDoDU18u1T9a9WWSY5nu5KMrON1Xwpy/uOQZ/YwyTN9PJ3mQRLr4Ohb0ZVUH/BKoNk1iuX9ex5qJlhE+PaFkOdsE1fDL1xncAdsP/Byy2MipW+J/0Bsg8Cxuudi+rL1N/ZoI2lef/zAzx20Op/fYeAL8xebbT3kNCnBC5Re4ui5ccm/n9k6RF4UO+/asNd3fPVtTVkXtETAn3yHcDdZXx37vgnEeCrPRtNUaFkVvrayuEeM2wohkKn7qriEcOrhW/bIu2BW8SKYKmNqS6oMmT4xCFLjTYcYZgzcreWlJ0PjpHYXY0SdJG5iQdPCTYyL1iAitCRnAIYKPH8gMitwcCHeibMvtfso7dncZzcoH1zxkitorzGzpTM/HUbrl+vCuG0NRSyuwlD0r0tSwnBjziK03G5zoKJ6XW4kwcZkMuucDh/W1jKyZdf30NaxlEckscWbnOcpq7pbdrOYejcWxtJaB/7tJXc0mO/LAqrRrCL3k7xoGcmVtTEZJqfwEKxPfJb3k9GWZl2UL87MbZNfTR/aVEYQKbM68/KkdmjSPlF80rJYKLP4WPGobWKEy+AwUMrHFhCQSEV+1AjU8EaWjWbO2TBytbTDC8yHXvFTUJItBpB9rAXZFT4iUCaDVarY3GuOxIiTXVWS6N6hWxz4ev/cxQep1klOhnOtS19bVQAFnmNBKGB8zi8cHxvRo+GHGed8X/k1EF9lDbtFDRIL6Z7HkPzu7qdGgCPfM5eziYafyQKps62jFYzA47+MiHvk68ngqCKihondqeHNOTr+p+QIpn8Al9W1zMETlthjpACxWyFgmVjuHsXscpsu7tOOIM87/HYqXiaybI+GmsOhsa7zTor9UGV0mrRaZvIhd5fpeTWze6pJe66KU7Yji/2swSLBn9oLjHk+x+8qCKoZybD0hVUJKftR7YUEpfZmMeeI07gCArXp48ND0D2+o/Ju2oxabsO9X5UXmhU7vkd3QwB5GwbvDV0OfMIgSvQ0BDntPmVnXFPhPqh6lr41FX0tQ5FTLtjph70QqAv6f7MCV90zS/XMH2vduOgyyuEHxeXVxeAN6QA64cns2yo+p+Xc+8oX2F6B6OUsxMMTwRpR2RHNImx0WRy/yLT342RsgCZpZgQcgglkaSIBbvFMMmaME3t+n8M3LgX7bM/7beod26A4KxZW2y/mffBnfcycoSEvvygcPqy04Dbk8j0XUOUN84VzW5MDfkR1OQmR1Ql3dwSH4d4yLljzg4WDVIC9icDAUGvTvZfK6yjTXD/4gp1IWS9J0W7P/Aeiab1b+pmJxXHi3WO9aUCDyrCkbxyPMOLSiydMFmux9JMeyMXOVQBjJYiT3hn4/U3HTWXwWYEIozauHY6/CqJmVogSGaWWLcJJBd5BANfE9DqJgDqUqoz5tC+Ger0pX1EU91OF0NE+QPWmXxdk/Ah8p2c0A0+4hKOL6xFa7wG6Sq8bJipcuqo5DnxtXhqhi00YQo3fyDG/gCOvgJjEoGaE2NI3+5krNzOqFkpT2vR2goiM2cERxi9z/uTURdqWt/H1yJup/RJUpKvr06YvgzPgm+SGLCf4IOi+VGOdOPbXjLcjmkBZ+to/7+ODKx72XYubVxToCjIf7KaIZkWWQOXwkoIa3ceFoZXaMKT/hIKy4/SXAcDcQqKwHVVl0zXaoVLXsH0qpMHOkb6iVpGGdNsVYebmaz7yWJwUIJu+vVzEs2gPrIZXD2f4c/+5t5UWDb9tybDw1XombuH2TUnmXA6v6bNzDCUU2rPfnoz3GozOOPkCLtI0Yog8MLefPMYbRGi9gKSMqdl+Uc4MMtZd89YNXvTKG1EE6t3pXio6YUoRDwPhibEvvOSszqhdm8NYitOdmRK7NRoBgEdzCJJZ9N/YoItPLXrsiGqRTx6x7x6f2IbBkK202nbRD7EM5yud8NBOm55QFmgK4X/msLNbBzAuBtQawUyOFu5fZREs0/ar7ALGM8c8gzwFp5v4sUypVVk44zTDMcR2/UjcvbAQBl3aqJkFwdATGi2zOrDJ1eeLYIh1p7p+lZB6VhKzJFxCq5s/qcptUBt/rc6jRk42BDqb8opMNJOCZdbLTX5wC8y55JZZpNX5jnesXMnXrCxVnbXe7JrsG8Ea/qneUBCejI9/qzMwS3MYB/usANyOHr2A2ctF8GXVCvE5v1wasr1om/WlFx7gjbAqQORiBNunJih1PFREuyZJUE2XB6foUJupGnbfn1cLGKJuIX32aIPI+Oy89mWcr9+RoaxVuZfL7ztGcB2a1XaCPeU+xR+t41+ArIEkW0X0dTiYV8JINmAyWzNBIHZLABtjOfs/9M1qmlOX7xjuTJZgQdHMz8vuxHtbt2pYrskMoQ4gKzhJ7uoCjChgZx4qG/JQ1iNlDYYsyX66wQiC6CcITx4xmJTX5K9/78uks/WO2H0r8/g+i126U3qy7SITEpvERkgOSfhHxP43aL2443uK67EZ9DH52mEtl4RLU5ulLzMvo1qpHbU5YVaIJYSjscIiyvPwu5onjaFp+JR5VJa7Gb9Pv7MLVR+NUBtK6DDuwxE82HTVAX6qiiOAcpLnvfbgsAXzFvrXNu+KroRxd4JYOZT9NNtiVprLPdV+g9y17iD061IcRMADggiQZY9NbO1TRCrm13JJy7xtC7K5FfBy8jA1x+Y4M7ht/lj2b4toepkfn1WyFVa4z34Zy9JOGomU5eR4cdW13KXGoufaWKp/jxD8DzTlQlb+9/rLfgIzzChvdbvZq6Kh2bHe1psgiojLbu0WXZzWke5LTA3mAt+/slGZyHGBBpxUaeFC6LGCRX548dkJHK1erjF86sfgbw22MCdQiIqR61TxFYdyQjVIvvR2qbxijhHVruwvUd7MyDeH6dA6wqaxqlUa6sNty+0RNFll9SKWsfyzeQWTu9kuD+vTE8USxPfRtWY0eEk1U4lG42XIVaOtEuC1h3RaCJuBX+B82oJL9TLirqc+zTNKU8dZACRhdtoB1y4S5U2qWfz1+wKVlWs1ru0NJiXNrn+ctyqVCAqkk1rUujtAEzYVlHCDviF99xOwF44e/OxhaaLaMO/ZagDm5EXqgdH3nkSRywQc3e6ot4WKCcyQ3+M2PVCDIVw+DvcUlTAAIsvrIfqL1C4KmrjPNVxny+UlA+39bYnIKAoN1yhiEXqV+o1BZVMtDvH2ESx5/sCjoO+cVZMUyiopOP3xYJrJeGvRLjfTV5VXBHdQ/ewzAdxxNcjCOm9iCA8RIBs4Sv5SAcBFVOcKi/YyCgH7sTVueKp3wFF3bf1Y3mKZ0z13iiqAa9N+hssNScEPtWcf1sLCj1sE5h/MBmc5b5NsoQA1nrUbj3rYQ1og9jOCOK+W1QGaRFthylTSYMdw6AEAjz+rWC2BogvfVazc8+O4ekUivkkhXoDqdb+q852KPOXI6b17/b45BK88VUO8WCGmVvtJOPiXaasLik7VOYZZr8E+HfxhCk6JddLXDrV+9Us8vT5f7n6M0RDeGAmL/8CoQy7vhMMgRuC18x8g0LRBdE3KsuGusIdX+FuvThIUQJav9W3cOovCjXnI6PtXQIs6+0WVlCBnh+neMg9OcX1lTHg81pBfKJJaNtmuUeMTz0eQ+drV8BdqDUosShP0ie0082aEcKG6yAQKmfcrEvdnqSvMJxJISYKqN8JvclavMAO22Lg9NugprLEWOjoD7gsgQg89EZihdHNbABEvJJ3HMY8xdyQXUE4iXxe4JvHLdSXIfhV0e3eVTTEXrJEn47LtDE0M90Ne/OhGEAfG44Md2J8esgEfqsmgJdoJ8CADZq3jxRmrBRzmTao1vqrnTtloPWPbvLine truncated
|
||||
+62
-5
@@ -153,7 +153,7 @@ it opens on the page without asking.
|
||||
states differ by pattern, not only color). A finished session goes back to
|
||||
the plain icon, so a console left in a background tab can be checked at a
|
||||
glance.
|
||||
- **Help.** The **?** at the top right opens a Help dialog with 16 topics,
|
||||
- **Help.** The **?** at the top right opens a Help dialog with 17 topics,
|
||||
one per tab down the left (across the top on a narrow window), opening on
|
||||
the one for where you are. It is part of the page itself, so it still reads
|
||||
fully when the page has lost its program.
|
||||
@@ -264,9 +264,12 @@ pressing *Not now* puts it away for good.
|
||||
The first "What's the idea?" box in Pathfinder, Plan and Quick Task has a row
|
||||
of starter templates above it: **Blank** first, then outlines to fill in (an
|
||||
engineering spec, product requirements, a design decision, a bug
|
||||
investigation, and so on), in the order your role puts
|
||||
them. With a role chosen, the first one carries a *For your role* pill. Pick
|
||||
one and the box fills with editable text, `[blanks]` marked; if you have
|
||||
investigation, a refactor, a data migration, and so on), in the order your
|
||||
role puts them. With a role chosen, the first one carries a *For your role*
|
||||
pill. Pick one and the box fills with editable Markdown, one `## heading` per
|
||||
answer with the answer on the lines under it, and the first `[blank]` is
|
||||
selected so you can type straight over it. Brackets mark only the parts you
|
||||
fill in; everything else is a default you can keep or edit. If you have
|
||||
already typed something, a strip asks **Replace** or **Keep mine** first.
|
||||
Only what is in the box is sent, exactly as if you had typed it.
|
||||
|
||||
@@ -339,6 +342,33 @@ it is remembered for next time:
|
||||
the spec's list and runs `console.mjs forget --spec specs/<name>` after the
|
||||
move.
|
||||
|
||||
### Subagents
|
||||
|
||||
On a build (Implement, Implement + review, Quick task), a review and
|
||||
Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
(subagents) while it keeps the conversation with you.
|
||||
|
||||
- **The button.** An icon in the top bar, after Stop session (and Write a
|
||||
brief on Pathfinder): one larger node linked to three smaller ones, lit in
|
||||
your highlight color while helpers are on. It shows only on those skills,
|
||||
and only when the skill's copy of the console can pass the setting on.
|
||||
- **The dialog.** A click opens it; the button never switches anything by
|
||||
itself. **Use helpers** or **Work alone**, the instruction the agent follows
|
||||
(**Reset to default** puts the shipped one back), and how many helpers may
|
||||
run at once (1 to 20; your agent's own limit still applies). **Save** sends
|
||||
it; the agent hears of it at its next check-in, as a setting, not as
|
||||
something you typed.
|
||||
- **Saved per project and per skill**, off by default, in
|
||||
`~/.plan2code/console/subagents.json`. The next session of the same skill
|
||||
in the same folder starts the same way.
|
||||
- **The Subagents tab.** With the first helper the agent reports, a tab
|
||||
appears before Ask: one row per helper with what it was asked and whether it
|
||||
is running, done or failed, plus a one-line result at the end. Rows change at
|
||||
the agent's check-ins, not live. *Working alone* means your agent has no way
|
||||
to start helpers here. The tab clears when you go back to the dashboard.
|
||||
- **Pathfinder's research** always uses helpers, whatever the switch says, and
|
||||
they show in the tab too.
|
||||
|
||||
### Session meter
|
||||
|
||||
A small ring pill in the top bar — **Session: fresh** (green), **Session:
|
||||
@@ -523,6 +553,19 @@ send never holds up a question.
|
||||
A reply that lands while you are on another tab puts a dot on **Ask** and
|
||||
chimes once (if sounds are on).
|
||||
|
||||
### When an update is out
|
||||
|
||||
When a newer Plan2Code release is out, the dashboard shows an **UPDATE
|
||||
AVAILABLE** banner at the top. Click it for the details: the version you
|
||||
have, the new one (linked to its Releases page) and the exact command that
|
||||
updates you, with a Copy button. **×** hides the banner for this session; the
|
||||
next dashboard shows it again until you update.
|
||||
|
||||
The check uses your own git login to read the repo's release tags, once an
|
||||
hour at most. If git cannot reach the repo (no git, no access, offline), you
|
||||
simply see no banner, and nothing waits on it. The version in Help always
|
||||
links to the Releases page.
|
||||
|
||||
### Keyboard
|
||||
|
||||
| Key | Does |
|
||||
@@ -538,7 +581,7 @@ keyboard-only navigation work.
|
||||
|
||||
## Models in User Preferences
|
||||
|
||||
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused.
|
||||
The `plan2code` launcher's model menu comes from `models.json`, which every install overwrites with the authors' curated list. **User Preferences → Models** (Claude and Devin tabs) lets you add a model that came out before Plan2Code was updated; additions are kept in `~/.plan2code/models.json`, and **Reset to default** removes them. Restart `plan2code` to see a change. You can always run `plan2code --model <id>`, or switch model inside your agent before running a skill. Devin ids ending `-xhigh` or `-max` are refused. Maintainers refresh the curated list with the repo-local `/plan2code-model-update` skill, which shows a diff and changes only what they approve.
|
||||
|
||||
---
|
||||
|
||||
@@ -608,6 +651,8 @@ exception being the note attachments the agent keeps for a spec, above):
|
||||
| `~/.plan2code/console/sessions/<id>/workspace.json`, `ledger.ndjson`, `workspace-cursor.json` | the workspace's folders (paths, names, descriptions — never their contents), the session meter's events, and how far the agent has been told of workspace changes. Kept beside the session, so they outlive every dashboard hop | with the session |
|
||||
| `~/.plan2code/console/sessions/<id>/uploads/` | images and documents attached to notes and quick questions | 30 days after the session was last touched |
|
||||
| `~/.plan2code/console/looks.json` | your role, theme, colors, sounds and card width | always |
|
||||
| `~/.plan2code/console/subagents.json` | your Subagents switch, instruction and limit, per project folder and skill | always |
|
||||
| `~/.plan2code/console/sessions/<id>/subagents-setting.json`, `subagents-cursor.json` | this session's copy of the switch, and how far the agent has been told of it | with the session |
|
||||
| your system temp directory | the port, process id and session token | until reboot |
|
||||
|
||||
Each of the workspace and meter files has exactly one writer: the server owns
|
||||
@@ -629,6 +674,17 @@ Your `looks.json` and the `console-dir` pointer are never touched, and neither
|
||||
is the session being opened. Nothing of value goes with them: the page is
|
||||
never the record, `specs/` in your project is.
|
||||
|
||||
**Or clean up on demand.** *User Preferences → Cleanup* → **Find files to
|
||||
clean up** lists, with sizes, everything in `~/.plan2code/` that is not
|
||||
needed: sessions untouched for 30 days (never the one you are in), anything at
|
||||
the top of `~/.plan2code/console/` other than `sessions/`, `looks.json`,
|
||||
`workspaces.json`, `subagents.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` other than
|
||||
`console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed once
|
||||
it has sat untouched for an hour, so a lock or temp file another session is
|
||||
writing right now is never caught. **Delete these** removes
|
||||
that list and nothing else. A console running from another home
|
||||
(`PLAN2CODE_CONSOLE_HOME`) only ever looks inside that home.
|
||||
|
||||
---
|
||||
|
||||
## Security
|
||||
@@ -677,6 +733,7 @@ origin.
|
||||
| `POST /workspace/edit` | `{ id, name?, description? }`. Renames or re-describes one folder: 400 `bad-name` / `name-taken`, 404 `unknown`. |
|
||||
| `POST /workspace/remove` | `{ id }`. 400 `original` for the folder the session started in, 404 `unknown`. |
|
||||
| `POST /workspace/browse` | Opens the system folder picker and answers `{ path }` or `{ cancelled: true }`; never adds anything itself. 409 `busy` while one is open, 404 `no-picker` when the session looks remote or no picker exists. |
|
||||
| `POST /subagents` | `{ on, instruction, max }` (`instruction: null` for the shipped default). Saves the switch for this project and skill and answers `{ ok, setting }`; 400 `not-offered` on a skill without the switch, `bad`, `too-long` (over 2,000 characters) or `max` (outside 1 to 20). |
|
||||
|
||||
## For maintainers
|
||||
|
||||
|
||||
@@ -40,7 +40,7 @@ Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Status Line
|
||||
|
||||
## Web Console
|
||||
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a built-in 16-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. The agent-facing contract is `console.md` / `building.md`; the server never writes into a project.
|
||||
Optional local browser UI (`src/web-console/`, zero dependencies, detached `node` server on `127.0.0.1`) bundled into every skill via `additionalReferences`. The bare `plan2code` skill opens its dashboard, a card menu that launches any skill in the same session. Pages cover questions, sign-off gates (with an in-page code review), build progress, the living document, an **Ask** chat, a read-only **Workspace** of extra folders (remembered per folder and spec in `~/.plan2code/console/workspaces.json`), a session meter, a built-in 17-topic Help, a first-run Welcome, User Preferences (gear) and a bug/idea link to GitHub issues. On opted-in skills (builds, review, Pathfinder) a **Subagents** button in the top bar turns helpers on or off per project and skill (off by default, saved in `~/.plan2code/console/subagents.json`); the agent hears of it as a standing instruction only when it changes, and reports its helpers in a **Subagents** tab beside Ask (contract in `console.md` → Standing instructions). The agent-facing contract is `console.md` / `building.md`; the server never writes into a project.
|
||||
|
||||
Details: [Architecture](./.agents-docs/AGENTS-architecture.md) (see Web Console section) and [.readme/web-console.md](./.readme/web-console.md)
|
||||
|
||||
|
||||
+65
-6
@@ -2,6 +2,71 @@
|
||||
|
||||
All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
## v2.5.1
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web-console**: six new starter templates, each slotted into every role's order. **Refactor** (Plan, Quick Task) asks what behaviour must not change. **Performance problem** (Plan, Quick Task) asks for today's number and the target. **Dependency upgrade** (Quick Task) asks for the known breaking changes. **Spike** (Pathfinder) is a time-boxed question with an "answered when". **Integration** (Pathfinder, Plan) covers the other side's auth and limits and what happens when it fails. **Data migration** (Plan) asks for a rollback plan. Pathfinder now offers 8 templates, Plan 10 and Quick Task 10, 19 in all.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **web-console**: the starter templates on the fresh-idea card (Pathfinder, Plan, Quick Task) are now Markdown sections. Each one is a `## heading` with its answer on the lines under it, instead of `Label: [blank]` lines run together. You get room to write, and the agent gets clear sections. Brackets mark only the parts you fill in, so the lines already written for you (who reads it, what it should pin down) read as defaults. **Bug investigation** splits Expected and Actual into their own sections and numbers its steps. **Add a test** lists its cases. Picking a template now selects its first `[blank]`, so you type straight over it instead of starting at the end of the box. Ids, labels and which skills see the existing templates are unchanged. A new test in `scripts/test-web-console.mjs` pins the shape.
|
||||
- **web-console**: template content, revised against design-doc, PRD, ADR (MADR) and bug-report guidance. **Engineering spec** gains *Out of scope* and asks for the simpler options turned down. **Product requirements** gains *Not doing* and asks for evidence and a measure of success. **Test strategy** leads with what costs most if it breaks. **Scoping and rollout** asks who sees it first and how it rolls back. **Bug investigation** gains *How often* and *Error or logs*. **Small change** gains *Leave alone*, and its *Done when* asks for a command or check. **Add a test** names the failure case. **Record a decision**'s *Why* asks what forced the choice.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web-console**: a "working alone" report no longer hides helpers reported after it (or beside it). A real helper report now removes the marker (`applyPatch` in `lib.mjs`, `helperRows()` in `subagents.js`), the standing instruction and `console.md` say to post `alone` only when the agent's tools cannot start helpers at all, and Help's **Helpers (subagents)** topic says the note goes away once a helper shows.
|
||||
|
||||
## v2.5.0
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web-console**: a **Subagents** switch for the skills that can hand work to helpers (Implement, Implement + review, Quick task, Review, Pathfinder). An icon button after Write a brief, lit while helpers are on, opens a **Subagents** dialog: **Use helpers** or **Work alone**, an editable instruction with **Reset to default**, and an advisory "at most N at once" (1 to 20). It is off by default and saved per project folder and skill in `~/.plan2code/console/subagents.json` (`POST /subagents`, on Cleanup's keep-list). The button shows only when the skill opts in (`public/subagents.js`) and the agent's console copy reported support (`caps: ["subagents"]` on its `open` event), so an older skill copy never shows a switch it cannot serve.
|
||||
- **web-console**: the switch reaches the agent as a standing instruction, and only when it changes. `wait` exit 0, `chat` and `open` carry a `subagents` field and `Subagents: on (revision N)` lines last in `reply`. A higher revision replaces a lower one, "off" goes only to an agent that was told "on", and a resume or dashboard launch with the switch on states it once. The per-session cursor moves only after the print, so a killed `wait` repeats a change rather than losing it. Contract: `console.md` → Standing instructions; `building.md` points at it.
|
||||
- **web-console**: a **Subagents** tab before Ask, from the first helper the agent reports through `post` (`helpers: [{ id, title, ask, state, result? }]`, merged by `id`, or one `{ id: "alone", alone: true }` entry when it has no way to start helpers). One row per helper with its ask, a Running / Done / Failed pill and a one-line result. It clears on a dashboard hop, and helper reports add no session meter points. `validate()` refuses malformed entries with exit 3 (house rule 8). Help gains a 17th topic, **Helpers (subagents)**.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **review**: run on its own with nothing named (no argument, no conversation work, not from a build's review button), `plan2code-review` no longer assumes the branch diff. It does a quick scan (branch changes, uncommitted changes, specs) and asks what to review, each option with its size; on the web console that is the first scope question, a `choice`. A build's review keeps its already-decided scope.
|
||||
- **web-console**: `post` and `open --file` refuse a patch that sends a doc a lower `version` than the page already holds (exit 3, naming the doc and both versions; house rule 9). A version going back is almost always a stale or copied payload, which the page would otherwise show quietly under the new run's name. `building.md` now says a later phase in the same session continues `phase`, `phasefile`, `report` and `review` from the version the page holds instead of restarting at 1.
|
||||
- **web-console**: the project name in the footer's `<project> · <branch>` label now shows in your highlight color, and the browser tab title starts with it (`<project> · <title> · #<sid> · Plan2Code`), so consoles for different projects are easy to tell apart.
|
||||
|
||||
## v2.4.2
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **web-console**: the Questions and Ask tabs show a small spinner left of their name while Plan2Code is on it. Questions (Dashboard on the dashboard) spins from Send until the answers are picked up, the same wait as *Sent. Waiting for Plan2Code.*; Ask spins while a question the agent picked up has no answer yet, exactly when the conversation's own ring does. Neither turns once the agent goes quiet or offline, so a dead session never reads as a slow one.
|
||||
- **web-console**: **User Preferences → Cleanup**, above Models. **Find files to clean up** lists, with sizes, what `~/.plan2code` does not need: sessions untouched for 30 days (never the one serving the page), anything at the top of `~/.plan2code/console/` but `sessions/`, `looks.json`, `workspaces.json`, `console-dir` and `update-check.json`, and anything at the top of `~/.plan2code/` but `console/`, `bin/`, `launcher.json` and `models.json`. A stray is listed only after an hour untouched (`STRAY_GRACE_MS`), so a held lock or a temp file mid-rename never is. **Delete these** removes exactly that list and reports what went and the space freed. The server builds the list (`POST /cleanup`, `cleanupFindings()` in `lib.mjs`), sends no paths to the page, and on delete re-scans and removes only ids still found (`removeCleanup()`), unlinking symlinks without following them. A console running from `PLAN2CODE_CONSOLE_HOME` never looks outside that home. Help's User Preferences topic describes it.
|
||||
- **web-console**: the dashboard shows an **UPDATE AVAILABLE · v<latest>** banner when a newer release is out. The console server finds the newest `vX.Y.Z` tag with `git ls-remote --tags` when it starts (no shell, prompts off, a 10 s limit, never waited on), caches the answer for an hour in `~/.plan2code/console/update-check.json`, and adds `update` to the state frame only when that release is newer. The banner opens a dialog with both versions, a Releases link and the update command with Copy; × hides it for that session. `GET /version` also returns `latest`, and the version in Help links to the Releases page.
|
||||
- **launcher**: `plan2code` opens with a colored Planny banner and a plain-English intro, then the agent menu with cyan numbers, a `(last used)` marker on the remembered pick and a green default. With one CLI installed, or a `--cli` pick, it prints `Opening with <CLI>…` instead. The model menu, the folder prompt and every `plan2code:` error get the same styling. Color is used only on a terminal with `NO_COLOR` unset, so piped runs print plain text and no banner.
|
||||
- **maintainer**: a repo-local `/plan2code-model-update` skill (`.claude/skills/`, never installed) refreshes `src/launcher/models.json` from `devin models list` and Claude Code's documented model aliases. It shows a diff, applies only the changes the maintainer approves, checks the file against the launcher's rules, runs `npm test` and never commits.
|
||||
- **tests**: `scripts/test-web-console.mjs` covers Cleanup, the update check and the note thread; `scripts/test-launcher.mjs` covers the banner and color handling.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **document**: `overview.md` puts the Phase Checklist and Parallel Execution Groups directly under the Summary, ahead of the Tech Stack, Architecture, Risks and Success Criteria, so the phases are found without scrolling. Every script finds these sections by heading, so specs written in the old order keep working.
|
||||
- **web-console**: while a build runs, the waiting screen's pointer to the tasks list is now clickable. **Task** and the tab's own name (say **Phase 6 tasks**) show bold in the highlight color, and either one opens that phase's tasks tab.
|
||||
- **web-console**: the session meter counts a build while it runs instead of only once the phase is approved. `console.mjs` writes a `progress` ledger entry whenever an Implement or Implement + Review post raises `headline.cleared`, and the build's row (*Implement + Review: 9 tasks built so far*) scores one point per 3 tasks done. The phase's final `run` takes that row over in place, so nothing counts twice and the meter never drops. A second phase in the same run starts its own count once its headline is back at `cleared: 0`.
|
||||
- **web-console**: the **UPDATE AVAILABLE** banner and **Send to Plan2Code** (while enabled) carry a soft glow in the picked highlight color; with reduced motion Send's pulse stops and the glow stays.
|
||||
- **web-console**: a request body over the size cap now gets `413 too large` from every JSON route instead of a connection reset or a `400`.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web-console**: Implement + Review's built-in review no longer scores twice on the session meter. Its `review` run now scores the phase's 1-point review bonus as the review starts (not a standalone Review's 2), and the phase's final `run` leaves that point out. A 17-task phase now ends at 7 points, not 9. The breakdown also stops repeating the unit in "Code review run: review".
|
||||
- **web-console**: Send no longer stays disabled when an agent posts a question mid-build while still marked `working` (seen on Implement + Review, where the question said "I'm carrying on while you decide"). Once an open question has an answer or a note staged, Send unlocks at once with "Still working · it reads this next", instead of waiting out the agent's `quietMinutes` (up to an hour); the server holds the send until the agent next looks. `building.md` now says a question stops the build: set `waiting` in the same post as the question and wait, never keep working with a question open.
|
||||
- **web-console**: **Notes on this** showed the agent's replies as empty "Plan2Code" bubbles and dropped the person's own notes once they were picked up. The server now writes every note into the item's `thread` as it arrives, `post` lifts `from` / `role` and `md` / `body` / `content` into `{ who, text }` (and drops an echoed copy of the person's note), and an entry with no text is rejected with exit 3. Older `{ from, md }` entries still render. `console.md` gains a **Replying to a note** section.
|
||||
- **web-console**: dropped the `comments` list on docs, which `post` appended and time-stamped but nothing ever displayed.
|
||||
- **web-console**: a dashboard launch could strand the hand-off when the agent called a skill-invocation tool on the picked skill instead of reading its `SKILL.md` (every skill below the dashboard ships `disable-model-invocation: true`). `plan2code.md` and `console.md` now say to open the next skill's file with a file-read tool.
|
||||
- **web-console**: the waiting pane pointed Document and other skills with no task list at a tasks tab that never exists there. The pointer now appears only when a build's `phase` or a quick task's `tasks` tab is posted. The nav tab spinner also gets its 7px gap back from the tab's name.
|
||||
- **web-console**: skipping a question dropped a note already typed for it; the note now goes with the skip as `skip; <note>`. Ticking a checklist step after a skip now ends the skip instead of still sending `skip`.
|
||||
- **web-console**: reconnecting cleared every banner, including a warning that arrived while offline; it now clears only the *Lost contact* banner. An open Overview tab now refreshes during a build.
|
||||
- **web-console**: a `409` on Home, Stop or **Write the brief** now marks the page busy the way Send does, and the brief dialog says why it could not go.
|
||||
- **web-console**: arrowing through a menu question kept dropping keyboard focus to the page body; menu radios now carry stable ids, a `value` and an `aria-label`. `@` mentions typed with a capital letter now match, and the attachment-limit banner uses `MAX_ATTACHMENTS` / `CHAT_MAX_ATTACHMENTS` instead of a hard-coded 5.
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
- **web console guide**: new *When an update is out* section, Cleanup under the session cleanup notes, and a pointer to `/plan2code-model-update` for the curated model list.
|
||||
|
||||
## v2.4.1
|
||||
|
||||
### ✨ Added
|
||||
@@ -19,7 +84,6 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **commit-msg.mjs**, **review-scope.mjs**, **agents-md.mjs**, **agent-files.mjs**, **handoff-path.mjs**: the commit command from the branch's ticket, Review's git scope and doc share, AGENTS.md's structure and orphans, the AI agent file sync, and the handoff's timestamped path and git ignore check.
|
||||
- **tests**: `scripts/test-skill-scripts.mjs` and `scripts/test-script-<skill>.mjs`, run by `npm test` against the built `skills/` tree. One test fails if a `SKILL.md` names a script its skill does not ship.
|
||||
- **web console**: the Workspace dialog's folders are remembered across console sessions, in `~/.plan2code/console/workspaces.json` beside `looks.json` (never in the project), keyed by the folder a session runs in and then by spec. Every change is saved. *Start from scratch* on the dashboard shows the project's list; picking a spec loads its own, which starts as a copy of the project's and is separate after that, and a spec created mid-run takes the list in force with it. The dialog says whose list it is. New `console.mjs forget --spec specs/<name>`, which Finalize's Spec Cleanup runs after archiving a spec.
|
||||
- **web-console**: the Questions and Ask tabs show a small spinner left of their name while Plan2Code is on it. Questions (Dashboard on the dashboard) spins from Send until the answers are picked up, the same wait as *Sent. Waiting for Plan2Code.*; Ask spins while a question the agent picked up has no answer yet, exactly when the conversation's own ring does. Neither turns once the agent goes quiet or offline, so a dead session never reads as a slow one.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
@@ -38,7 +102,6 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **finalize**: `feedback-payload.mjs` counts the same phase files `specs.mjs` does, `submit` refuses an oversize URL when `gh` is unavailable (`oversize`), and a bare spec name present in both `specs/` and `specs--completed/` is refused as ambiguous.
|
||||
- Every script was checked against real specs and Pathfinder maps in other repositories and by four independent reviews; each issue found has a regression test.
|
||||
|
||||
- **document**: `overview.md` puts the Phase Checklist and Parallel Execution Groups directly under the Summary, ahead of the Tech Stack, Architecture, Risks and Success Criteria, so the phases are found without scrolling. Every script finds these sections by heading, so specs written in the old order keep working.
|
||||
- **install.js**: the closing message beside Planny now names the dashboard first: `plan2code` from any project, or `/plan2code` in your agent when the command could not be installed. The docs link moves to the line under it.
|
||||
- **web-console**: User Preferences opens from a gear button instead of the three swatches, and the default highlight color is now ocean blue instead of rust.
|
||||
- **web-console**: the dashboard rail marks the suggested next step with a small dot, since the center pane's Suggested pill can scroll out of view. Send pulses only while it is the primary button.
|
||||
@@ -48,15 +111,11 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **Windows**: the folder picker (the launcher's desktop shortcut and the Workspace **Browse…** button) now opens centred and in front of other windows instead of behind the terminal.
|
||||
- **Launcher**: before asking which CLI to use, `plan2code` says what it is about to do and that running `/plan2code` inside your agent works too.
|
||||
- **web-console**: the session meter now weighs the work a session actually did instead of a flat amount per step. A built phase scores one point per 3 tasks it completed (rounded up), plus 1 for Implement + Review, so a twelve-task phase weighs four times a three-task one; the agent reports the count as `run.tasks`. Every 2 questions you answer on the page add a point to the skill you answered them in, so a long back-and-forth in Plan or Pathfinder counts for more than a short one. Each Pathfinder research question adds 1 through a new `pathfinder-research` event, since research fills the context with nobody answering anything. The levels move to match: yellow from 5 points, red from 10, and the ring is full at 15.
|
||||
- **web-console**: while a build runs, the waiting screen's pointer to the tasks list is now clickable. **Task** and the tab's own name (say **Phase 6 tasks**) show bold in the highlight color, and either one opens that phase's tasks tab.
|
||||
- **web-console**: the session meter counts a build while it runs instead of only once the phase is approved. `console.mjs` writes a `progress` ledger entry whenever an Implement or Implement + Review post raises `headline.cleared`, and the build's row (*Implement + Review: 9 tasks built so far*) scores one point per 3 tasks done. The phase's final `run` takes that row over in place, so nothing counts twice and the meter never drops. A second phase in the same run starts its own count once its headline is back at `cleared: 0`.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web-console**: Implement + Review's built-in review no longer scores twice on the session meter. Its `review` run now scores the phase's 1-point review bonus as the review starts (not a standalone Review's 2), and the phase's final `run` leaves that point out. A 17-task phase now ends at 7 points, not 9. The breakdown also stops repeating the unit in "Code review run: review".
|
||||
- **pathfinder**: charting no longer ends the session, or shows "Session ended" in the web console, while its research subagents are still running. They live in the terminal's process, so closing it on a "done" page killed them mid-write. The session now waits for every one (the page shows a running count), each subagent ends `## Evidence` with a `**Research complete:**` line, and Work Step 2 re-fires any research question missing it. `console.md` makes the same rule general: no `finish` while any subagent or background job is still out.
|
||||
- **web-console**: reusing a settled question id for a different kind of question (say a multi-select turned confirm) now opens it as a new question instead of keeping the old answer.
|
||||
- **web-console**: Send no longer stays disabled when an agent posts a question mid-build while still marked `working` (seen on Implement + Review, where the question said "I'm carrying on while you decide"). Once an open question has an answer or a note staged, Send unlocks at once with "Still working · it reads this next", instead of waiting out the agent's `quietMinutes` (up to an hour); the server holds the send until the agent next looks. `building.md` now says a question stops the build: set `waiting` in the same post as the question and wait, never keep working with a question open.
|
||||
|
||||
### 📚 Documentation
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
**A spec-driven workflow for AI coding agents.**
|
||||
|
||||
<img src="docs/banner.jpg" alt="Plan2Code: plan and build with your AI agent, on one page. Planny, the mascot, acts out the five steps: Pathfinder, Plan, Document, Implement and Finalize." data="object-fit:contain;" style="max-width:1024px;">
|
||||
<img src="docs/banner.jpg" alt="banner" data="object-fit:contain;" style="max-width:1024px;">
|
||||
|
||||
You work through Plan2Code on a page in your browser. The dashboard lists every step as a card, and
|
||||
each step's questions, progress and sign-offs arrive on that same page while your agent does the
|
||||
@@ -13,7 +13,7 @@ the next engineer all start from the same specs.
|
||||
|
||||
One command opens it, every step is a card, and the terminal is always there if you prefer it.
|
||||
|
||||
Version 2.4.1 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 2.5.1 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
|
||||
+1
-1
@@ -375,7 +375,7 @@ footer a { color: inherit; }
|
||||
<div class="wrap">
|
||||
<a href="https://github.com/jparkerweb/plan2code">Plan2Code on GitHub</a>
|
||||
<span>MIT license</span>
|
||||
<span>Version 2.4.1</span>
|
||||
<a href="https://github.com/jparkerweb/plan2code/releases">Releases</a>
|
||||
</div>
|
||||
</footer>
|
||||
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "plan2code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"private": true,
|
||||
"bin": {
|
||||
"plan2code-install": "./install.js"
|
||||
|
||||
@@ -40,6 +40,9 @@ const CWD = path.resolve(args.cwd || ROOT);
|
||||
|
||||
const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-bench-"));
|
||||
const ENV = { ...process.env, PLAN2CODE_CONSOLE_HOME: HOME, PLAN2CODE_NO_BROWSER: "1" };
|
||||
// A fresh cached failure: the boot-time release check stays off the network,
|
||||
// so a slow GitHub never colours the timings.
|
||||
fs.writeFileSync(path.join(HOME, "update-check.json"), JSON.stringify({ checkedAt: Date.now(), latest: null }));
|
||||
|
||||
function findBrowser() {
|
||||
if (args.browser === "none") return null;
|
||||
|
||||
@@ -174,3 +174,35 @@ test("launcher: the CLI's non-zero exit code is passed through", (t) => {
|
||||
assert.equal(result.status, 7, result.stderr);
|
||||
assert.notEqual(box.argsOf("claude"), null);
|
||||
});
|
||||
test("launcher: renderBanner draws Planny and the name, colored only through paint", () => {
|
||||
const { renderBanner, paint } = require(LAUNCHER);
|
||||
const plain = renderBanner(paint(false));
|
||||
assert.doesNotMatch(plain, /\x1b/);
|
||||
for (const part of ["╭───╮", "╰┬─┬╯", "★", "Plan2Code"]) assert.ok(plain.includes(part), part);
|
||||
assert.ok(plain.split("\n").length >= 4);
|
||||
const colored = renderBanner(paint(true));
|
||||
assert.ok(colored.includes("\x1b["));
|
||||
assert.ok(colored.includes("\x1b[0m"));
|
||||
});
|
||||
|
||||
test("launcher: paint wraps text in the escape codes only when color is on", () => {
|
||||
const { paint } = require(LAUNCHER);
|
||||
assert.equal(paint(false).red("x"), "x");
|
||||
assert.equal(paint(true).red("x"), "\x1b[31mx\x1b[0m");
|
||||
});
|
||||
|
||||
test("launcher: a piped run prints no escape codes, with or without NO_COLOR", (t) => {
|
||||
const box = sandbox(["claude"]);
|
||||
t.after(box.cleanup);
|
||||
const none = sandbox([]);
|
||||
t.after(none.cleanup);
|
||||
for (const env of [{}, { NO_COLOR: "1" }]) {
|
||||
const runs = [box.run([], env), box.run(["--cli", "bogus"], env), none.run([], env)];
|
||||
assert.deepEqual(runs.map((r) => r.status), [0, 2, 127]);
|
||||
for (const r of runs) {
|
||||
assert.doesNotMatch(r.stdout, /\x1b/);
|
||||
assert.doesNotMatch(r.stderr, /\x1b/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
+1015
-14
File diff suppressed because it is too large.
Load diff
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -243,7 +243,7 @@ summarise it back.
|
||||
Then, in ONE `post`, do all of:
|
||||
|
||||
- mark each answered item `"status": "answered"` and record its `answer`
|
||||
- add your replies to any comment threads
|
||||
- reply to every note in that item's `thread` (shape below)
|
||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||
questions)
|
||||
- publish the next batch of questions
|
||||
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
|
||||
|
||||
One post is one atomic update, so the page never shows a half-changed state.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
A `comment` is the person talking to you about that card, often asking
|
||||
something. It shows in the card's **Notes on this** panel, and so does your
|
||||
answer:
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
||||
- The server writes their note into the thread as it arrives. Do not repeat
|
||||
it, and send only your new entries: `thread` appends.
|
||||
- Answer what they asked, in the thread, even when you also change a doc or
|
||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
||||
panel with no answer under it.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||
@@ -627,6 +647,87 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -661,9 +762,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
||||
run inline from another (a quick task's review) keeps the page it was
|
||||
handed. A
|
||||
fresh `open` would strand the page the person is watching on the dashboard's
|
||||
session while your questions went to a page nobody has open. Then run the
|
||||
skill normally: its Interface question was already answered by being
|
||||
launched, so start where its real work starts.
|
||||
session while your questions went to a page nobody has open.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
||||
> purpose — it exists to be read and followed inline, not launched as a
|
||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
||||
> strands the hand-off mid-launch.
|
||||
|
||||
Its Interface step is already answered by having been launched, so start
|
||||
where its real work starts.
|
||||
|
||||
The menu itself is the page's own list — you never send it. The page knows
|
||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||
@@ -735,7 +844,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -769,6 +881,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -829,6 +943,12 @@ know:
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
— the specs are untouched until Step 3's summary write — so a stop's finish
|
||||
@@ -859,7 +979,7 @@ question or doc lands:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
||||
what changed. A whole-file rewrite would put the entire session back into your
|
||||
context on every turn.
|
||||
|
||||
@@ -1112,6 +1232,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1133,7 +1263,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
@@ -1239,7 +1371,7 @@ answers were submitted but never picked up.
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -48,6 +49,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
@@ -487,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -536,6 +548,148 @@ export async function removeScratch(consoleDir, names) {
|
||||
return removed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- cleanup */
|
||||
|
||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
// rename -- and removing one mid-write loses another session's change.
|
||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
||||
|
||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
||||
async function diskBytes(p) {
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
if (!st.isDirectory()) return st.size;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
||||
* not kept, and -- only when the console runs from its default home inside
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
plan2codeDir = PLAN2CODE_DIR,
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
} catch {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||
@@ -871,7 +1025,7 @@ export function handOff(child, pre) {
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
@@ -896,7 +1050,7 @@ function mergeOne(target, patch, where) {
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread/comments append.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
@@ -955,11 +1109,60 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -996,12 +1199,23 @@ export function applyPatch(state, patch) {
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1048,15 +1262,11 @@ function stampTimes(before, next) {
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
for (const list of [next.items, next.docs]) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const entry of list) {
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
if (Array.isArray(entry.comments)) {
|
||||
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
@@ -1289,7 +1499,10 @@ export function validate(state) {
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
@@ -1297,6 +1510,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1553,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1353,6 +1581,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1808,6 +2038,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
|
||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||
* Any thread message from the send onwards, or none with a clock to compare,
|
||||
* means it has been picked up.
|
||||
* Any agent message from the send onwards, or one with no clock to compare,
|
||||
* means it has been picked up. The person's own entries never count: the
|
||||
* server writes their note into the thread as it arrives.
|
||||
*/
|
||||
export function noteAwaiting(item) {
|
||||
const n = item && item.sentNote;
|
||||
if (!n || typeof n !== "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
||||
return picked ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
||||
* and the server lifts anything else into it, but sessions written before that
|
||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
||||
*/
|
||||
export function threadWho(m) {
|
||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
||||
}
|
||||
|
||||
export function threadText(m) {
|
||||
if (!m) return "";
|
||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
--warn-soft: #fbe7e3;
|
||||
--focus: #1f6feb;
|
||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||
/* A soft accent halo for the things that want noticing: the update banner
|
||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||
@@ -61,6 +64,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +89,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -203,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1097,10 +1122,11 @@ h1 {
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. */
|
||||
.view-tab .tab-spin {
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
@@ -1424,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1657,11 +1707,13 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* Send breathes while there is something to send: a soft accent ring that
|
||||
spreads and fades. Off under reduced motion, below. */
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
||||
@keyframes send-pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: 0 0 0 6px transparent; }
|
||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
||||
}
|
||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
@@ -1963,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
@@ -2219,6 +2273,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal.help[open] { display: flex; }
|
||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||
.help-version a { color: inherit; }
|
||||
|
||||
.help-layout {
|
||||
display: grid;
|
||||
@@ -2668,6 +2723,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
@@ -3394,6 +3517,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
||||
.cleanup-list:empty { display: none; }
|
||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
||||
.cleanup-more { display: grid; gap: 4px; }
|
||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
||||
#cleanup-delete[hidden] { display: none; }
|
||||
|
||||
/* A word the person has to type, bold and in their highlight color so it
|
||||
does not get lost in the status sentence. */
|
||||
.agent-key {
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
submittedAwaiting,
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
threadText,
|
||||
threadWho,
|
||||
THUMB_EDGE,
|
||||
turnGate,
|
||||
verdictText,
|
||||
@@ -101,6 +103,15 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
||||
import { RED_BANNER } from "./meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||
import { faviconState, setFavicon } from "./favicon.js";
|
||||
import {
|
||||
CHECKIN_LINE,
|
||||
PATHFINDER_RESEARCH_LINE,
|
||||
defaultInstruction,
|
||||
helperRows,
|
||||
showSwitch,
|
||||
showTab,
|
||||
switchLabel,
|
||||
} from "./subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -446,6 +457,10 @@ document.addEventListener("click", (e) => {
|
||||
|
||||
|
||||
const GONE_AFTER_MS = 8000;
|
||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
||||
// failure, a refused send).
|
||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
@@ -521,6 +536,12 @@ let chatFrame = null;
|
||||
// sends them.
|
||||
let wsFrame = null;
|
||||
let meterFrame = null;
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
let updateFrame = null;
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
let subagentsFrame = null;
|
||||
let chatDot = false;
|
||||
let chatSending = false;
|
||||
let chatResetting = false;
|
||||
@@ -566,7 +587,6 @@ function fresh() {
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
sentAt: null,
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
@@ -870,10 +890,14 @@ function adopt(body) {
|
||||
chatFrame = body.chat || null;
|
||||
if (body.workspace) wsFrame = body.workspace;
|
||||
if (body.meter) meterFrame = body.meter;
|
||||
// Always replaced: an absent key means no update.
|
||||
updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
subagentsFrame = body.subagents || null;
|
||||
lastContact = Date.now();
|
||||
if (gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
}
|
||||
if (firstLoad) {
|
||||
load();
|
||||
@@ -1016,7 +1040,9 @@ function adopt(body) {
|
||||
render();
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
tellFolderIssues();
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||
// The Overview tab's file changes under a build, so a tab you are watching
|
||||
// refetches on every new frame too, not only on the click that opened it.
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
||||
if (announce) showArrival(announce);
|
||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||
// leaving the list parked where it was while it grew underneath.
|
||||
@@ -1149,15 +1175,12 @@ function markGone() {
|
||||
// of the server means there, and a banner promising a reconnect would
|
||||
// argue with it.
|
||||
if (!finish() && !stopInProgress()) {
|
||||
banner(
|
||||
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||
"warn"
|
||||
);
|
||||
banner(GONE_BANNER, "warn");
|
||||
}
|
||||
render();
|
||||
} else if (!bad && gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -1182,7 +1205,6 @@ function connect() {
|
||||
} catch {}
|
||||
});
|
||||
es.addEventListener("submitted", (e) => {
|
||||
local.sentAt = Date.now();
|
||||
// Drop only what was actually sent.
|
||||
//
|
||||
// This event fires for a send from ANY tab of this session, which is why it
|
||||
@@ -1293,6 +1315,7 @@ function render() {
|
||||
renderChrome();
|
||||
renderStatus();
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
@@ -1558,7 +1581,7 @@ function renderChrome() {
|
||||
renderMeter();
|
||||
$("title").textContent = S.title || "Session";
|
||||
$("badge").textContent = workflowLabel(S.workflow);
|
||||
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
renderTabTitle();
|
||||
|
||||
const h = S.headline || {};
|
||||
// On a finished session an open item is frozen: the send on it counts as
|
||||
@@ -1799,14 +1822,19 @@ async function sendBrief() {
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => banner(null), 5000);
|
||||
pendingResult = true;
|
||||
render();
|
||||
} catch {
|
||||
why.textContent = "That did not go through. Try again in a moment.";
|
||||
} catch (err) {
|
||||
if (err && err.pending) pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
@@ -1822,6 +1850,69 @@ function renderBriefButton() {
|
||||
if (offer) btn.disabled = gone || pendingResult;
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
function openSubagents() {
|
||||
if (!showSwitch(subagentsFrame)) return;
|
||||
const on = Boolean(subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
||||
$("subagents-max").value = String(subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
function renderViews() {
|
||||
const nav = $("views");
|
||||
nav.replaceChildren();
|
||||
@@ -1837,6 +1928,14 @@ function renderViews() {
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (view === "overview") view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
if (showTab(subagentsFrame, S.helpers)) {
|
||||
// From the rows the tab draws, so the badge never counts helpers the
|
||||
// working-alone note hides.
|
||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
||||
} else if (view === "subagents") view = "questions";
|
||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
||||
// a question the agent picked up and has not answered yet.
|
||||
@@ -2117,6 +2216,7 @@ function paintMain(main) {
|
||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||
if (view === "overview") return renderOverview(main);
|
||||
if (view === "ask") return renderAsk(main);
|
||||
if (view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
// the top of the rail. The hand-off lives here alone now, rather than
|
||||
@@ -2515,6 +2615,51 @@ function roleNudge() {
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function releasesLink(text) {
|
||||
const a = el("a", null, text);
|
||||
a.href = RELEASES_URL;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
return a;
|
||||
}
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
function renderDashboard(main) {
|
||||
maybeWake();
|
||||
const menu = (S && S.menu) || {};
|
||||
@@ -2526,6 +2671,25 @@ function renderDashboard(main) {
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
||||
} catch {}
|
||||
render();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||
@@ -3223,7 +3387,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
||||
function skipAndMoveOn(id) {
|
||||
cancelSkipMove();
|
||||
local.skipFlash = id;
|
||||
stage(id, { type: "skip", skipped: true });
|
||||
// A note already typed goes along: skipping the question is not retracting
|
||||
// the comment. Dropping it would leave the text in the box but out of the
|
||||
// send, which looks kept and is not.
|
||||
const cur = local.staged[id];
|
||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
||||
skipTimer = setTimeout(() => {
|
||||
skipTimer = null;
|
||||
local.skipFlash = null;
|
||||
@@ -3340,19 +3508,24 @@ function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"), a quick task as `tasks`; with neither the words stay plain.
|
||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
if (!list) return el("strong", "waiting-jump", word);
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
@@ -3366,8 +3539,8 @@ function renderWaiting(main) {
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump((list && list.title) || "Phase tasks"),
|
||||
" tab. If Plan2Code needs you, the question appears here on its own."
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
@@ -3505,8 +3678,8 @@ function renderSettled(card, item) {
|
||||
// would misreport which of the two was the answer.
|
||||
let prose = text;
|
||||
if (!prose && !lines.length) {
|
||||
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
||||
}
|
||||
|
||||
const nothing = !lines.length && !prose;
|
||||
@@ -4172,8 +4345,11 @@ function templateRow(item, input, entries, check) {
|
||||
save();
|
||||
paint();
|
||||
input.focus();
|
||||
const start = text.indexOf("[");
|
||||
const end = start < 0 ? -1 : text.indexOf("]", start);
|
||||
try {
|
||||
input.setSelectionRange(text.length, text.length);
|
||||
if (end > start) input.setSelectionRange(start, end + 1);
|
||||
else input.setSelectionRange(text.length, text.length);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
@@ -4322,6 +4498,10 @@ function buildChecklist(card, item, staged) {
|
||||
const commitList = (change) => {
|
||||
const cur = local.staged[item.id];
|
||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
||||
// card showed ticked steps on their way.
|
||||
delete next.skipped;
|
||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||
stage(item.id, empty ? null : next);
|
||||
};
|
||||
@@ -4371,7 +4551,7 @@ function buildChecklist(card, item, staged) {
|
||||
function buildMenu(card, item, staged) {
|
||||
const list = el("ul", "options");
|
||||
const name = "menu-" + item.id;
|
||||
for (const o of item.options || []) {
|
||||
for (const [i, o] of (item.options || []).entries()) {
|
||||
const picked = staged && staged.k === o.k;
|
||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||
const label = el("label");
|
||||
@@ -4379,7 +4559,13 @@ function buildMenu(card, item, staged) {
|
||||
const radio = el("input");
|
||||
radio.type = "radio";
|
||||
radio.name = name;
|
||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
||||
// input by id after the render this change() sets off, and without one a
|
||||
// keyboard user arrowing through the menu lands on <body> every time.
|
||||
radio.id = optionId(item, o, i);
|
||||
radio.value = o.k;
|
||||
radio.checked = Boolean(picked);
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||
const body = el("div", "option-body");
|
||||
const head = el("div", "option-label");
|
||||
@@ -4678,6 +4864,42 @@ function renderOverview(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ask */
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
@@ -5276,20 +5498,30 @@ function renderAside() {
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
box.appendChild(md(m.text, "md"));
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A note that has been sent but not yet picked up: shown at once, so the
|
||||
// send is seen to have gone, and gone when the agent replies.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
if (waiting) {
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
@@ -5589,7 +5821,10 @@ async function attachFiles(itemId, files) {
|
||||
const taken = wanted.slice(0, room);
|
||||
// One banner at a time, so every refusal goes into it, each by name.
|
||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||
if (taken.length < wanted.length)
|
||||
said.push(
|
||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
||||
);
|
||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||
await Promise.all(
|
||||
taken.map(async (file) => {
|
||||
@@ -5847,10 +6082,30 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
||||
// session opened before the server wrote `worktree` has nothing to show, so
|
||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||
// touched when the labels change, or when a resize clears the key.
|
||||
// The project's name: the workspace's original folder, or the session's
|
||||
// worktree folder before a frame carries the workspace.
|
||||
function projectName() {
|
||||
const folders = workspaceFolders();
|
||||
if (folders.length && folders[0].name) return folders[0].name;
|
||||
const path = (S && S.worktree) || "";
|
||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
||||
}
|
||||
|
||||
// The browser tab's title, led by the project so tabs from different
|
||||
// projects are told apart. Called from the chrome and the footer, since the
|
||||
// workspace frame can arrive after either.
|
||||
function renderTabTitle() {
|
||||
if (!S) return;
|
||||
const name = projectName();
|
||||
document.title =
|
||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
}
|
||||
|
||||
function renderWhere() {
|
||||
const b = $("footer-where");
|
||||
const folders = workspaceFolders();
|
||||
const path = S.worktree || "";
|
||||
renderTabTitle();
|
||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||
const labels = folders.length
|
||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||
@@ -5863,7 +6118,16 @@ function renderWhere() {
|
||||
let label = labels[0];
|
||||
for (const text of labels) {
|
||||
label = text;
|
||||
b.textContent = text;
|
||||
// The project name takes the highlight color, so several consoles side by
|
||||
// side tell apart at a glance; the rest of the label stays quiet.
|
||||
const name = projectName();
|
||||
b.textContent = "";
|
||||
if (name && text.startsWith(name)) {
|
||||
b.appendChild(el("span", "where-project", name));
|
||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
||||
} else {
|
||||
b.textContent = text;
|
||||
}
|
||||
if (alert) {
|
||||
const dot = el("span", "where-alert");
|
||||
dot.setAttribute("aria-hidden", "true");
|
||||
@@ -6439,6 +6703,10 @@ async function goHome() {
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
@@ -6499,6 +6767,7 @@ async function stopSession() {
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
@@ -6653,7 +6922,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||
}
|
||||
local.staged = {};
|
||||
local.sentAt = Date.now();
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -6706,7 +6974,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
||||
// something the agent never hears.
|
||||
function tokenFor(item, v) {
|
||||
const map = item.token || {};
|
||||
if (v.skipped) return "skip";
|
||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
||||
const parts = [];
|
||||
if (v.k) parts.push(map[v.k] || v.k);
|
||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||
@@ -6938,14 +7206,14 @@ function renderAbout() {
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const el = $("help-version");
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
el.textContent = version ? "Plan2Code v" + version : "";
|
||||
el.hidden = !version;
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
el.hidden = true;
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7053,6 +7321,7 @@ function openHelpOn(id) {
|
||||
}
|
||||
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
@@ -7083,6 +7352,7 @@ function lightDismiss(dlg) {
|
||||
});
|
||||
}
|
||||
lightDismiss($("looks-modal"));
|
||||
lightDismiss($("subagents-modal"));
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("workspace-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
@@ -7132,6 +7402,7 @@ $("btn-looks").addEventListener("click", () => {
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
resetCleanup();
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
@@ -7278,7 +7549,119 @@ $("models-reset").addEventListener("click", () => {
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const strays = items.length - sessions;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
||||
}
|
||||
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
@@ -39,6 +40,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
@@ -172,6 +173,18 @@
|
||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||
Write a brief
|
||||
</button>
|
||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
||||
opens the Subagents dialog and never toggles them itself. -->
|
||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -580,6 +593,13 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
<circle cx="18" cy="12" r="2" />
|
||||
<circle cx="18" cy="19" r="2" />
|
||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
||||
</symbol>
|
||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||
<path d="M8 9.5h8M8 12.5h5" />
|
||||
@@ -1291,6 +1311,14 @@
|
||||
come back, and you can change your role any time from the swatch
|
||||
button.
|
||||
</p>
|
||||
<h4>When an update is out</h4>
|
||||
<p>
|
||||
When a newer Plan2Code release is out, the dashboard shows
|
||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
||||
to run in your terminal; × hides it until the next
|
||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
||||
the Releases page.
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
@@ -1469,7 +1497,62 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 12: Ask a quick question -->
|
||||
<!-- Tab 12: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
||||
never switches helpers on or off by itself. Pick <strong>Use
|
||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
||||
shipped one back), and say how many may run at once.
|
||||
</li>
|
||||
<li>
|
||||
It is off by default and saved for this project and this skill, so
|
||||
the next session of the same skill here starts the same way.
|
||||
</li>
|
||||
<li>
|
||||
The change reaches Plan2Code at its next check-in, as a setting,
|
||||
not as something you typed. How many helpers it can really start is
|
||||
up to your agent; some have no helpers at all.
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
||||
Ask: one row each, with what it was asked, whether it is running, done
|
||||
or failed, and a one-line result at the end. The number on the tab is
|
||||
how many are still running.
|
||||
</li>
|
||||
<li>
|
||||
Helpers report through Plan2Code, so the rows change at its
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Working alone</strong> means your agent reported it has no
|
||||
way to start helpers here. If it starts one after all, the note
|
||||
goes away and the helper's row shows instead.
|
||||
</li>
|
||||
<li>
|
||||
Pathfinder always uses helpers for its research questions, whatever
|
||||
the switch says, and they show here too.
|
||||
</li>
|
||||
<li>The tab clears when you go back to the dashboard.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1560,7 +1643,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Stopping and finishing -->
|
||||
<!-- Tab 14: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1642,7 +1725,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: When something looks stuck -->
|
||||
<!-- Tab 15: When something looks stuck -->
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1764,7 +1847,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Keyboard and preferences -->
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1845,6 +1928,15 @@
|
||||
joining the strip. Keep only the ones you want; ticking a box plays
|
||||
its sound.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Back to default</strong> puts everything back as it was, and
|
||||
sets Role back to Not set.
|
||||
@@ -1871,7 +1963,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Privacy and where things are saved -->
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1908,7 +2000,11 @@
|
||||
</li>
|
||||
<li>
|
||||
your role, theme, colors, card width and sounds, in
|
||||
<code>looks.json</code>.
|
||||
<code>looks.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -1983,6 +2079,16 @@
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
@@ -2012,6 +2118,46 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
||||
its own, only a themed number box. -->
|
||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
||||
<h2 id="subagents-title">Subagents</h2>
|
||||
<p class="modal-blurb">
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
@@ -2181,6 +2327,24 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
||||
the copy row are filled by app.js; the update itself runs in a
|
||||
terminal, never from this page. -->
|
||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
||||
<p class="modal-blurb" id="update-versions"></p>
|
||||
<ol class="update-steps">
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||
Nothing to send yet.
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
// popover; this file owns the rules. No DOM access at module scope and no
|
||||
// imports: the page and `node --test` both import this file.
|
||||
|
||||
const NAME_CHAR = /[a-z0-9-]/;
|
||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
||||
// nothing and opens no suggestions at all.
|
||||
const NAME_CHAR = /[a-z0-9-]/i;
|
||||
const MAX_MATCHES = 6;
|
||||
|
||||
/**
|
||||
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
|
||||
}
|
||||
|
||||
// Names starting with the query first, then names containing it, in the
|
||||
// order given, at most six.
|
||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
||||
export function matchNames(names, query) {
|
||||
const q = String(query || "");
|
||||
const prefix = names.filter((n) => n.startsWith(q));
|
||||
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||
const q = String(query || "").toLowerCase();
|
||||
const fold = (n) => String(n).toLowerCase();
|
||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,85 +36,271 @@ export function needsRoleNudge(looks) {
|
||||
return !Object.hasOwn(looks, "role");
|
||||
}
|
||||
|
||||
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
|
||||
// The wording was revised in v2.5.1 (Markdown sections); a change is a page change.
|
||||
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
|
||||
|
||||
export const TEMPLATES = Object.freeze({
|
||||
"engineering-spec": template("engineering-spec", "Engineering spec", [
|
||||
"Engineering spec for: [the feature or change, in a sentence]",
|
||||
"Who reads it: the engineers who will build and review it.",
|
||||
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
|
||||
"What I already know: [constraints, links, earlier attempts]",
|
||||
"## Engineering spec",
|
||||
"[the feature or change, in a sentence]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineers who will build and review it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The behaviour, the parts of the code it touches, the interfaces between them, the simpler options we're turning down, and how we'll know it works.",
|
||||
"",
|
||||
"## Out of scope",
|
||||
"[what this deliberately won't do]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[constraints, links, earlier attempts]",
|
||||
]),
|
||||
"product-requirements": template("product-requirements", "Product requirements", [
|
||||
"Product requirements for: [the feature, in a sentence]",
|
||||
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
|
||||
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
|
||||
"What I already know: [customer asks, data, deadlines]",
|
||||
"## Product requirements",
|
||||
"[the feature, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"[the users], and the product, design and engineering people deciding on it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The problem, who has it, the evidence it's real, and how we'll measure success.",
|
||||
"",
|
||||
"## Not doing",
|
||||
"[what this release leaves out]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[customer asks, data, deadlines]",
|
||||
]),
|
||||
"design-decision": template("design-decision", "Design decision", [
|
||||
"A design decision to work out: [the choice we're facing, in a sentence]",
|
||||
"Who it's for: the engineers and architects who will live with it.",
|
||||
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"Constraints: [performance, compatibility, deadlines, team skills]",
|
||||
"## Design decision",
|
||||
"[the choice we're facing, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"The engineers and architects who will live with it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[performance, compatibility, deadlines, team skills]",
|
||||
]),
|
||||
"test-strategy": template("test-strategy", "Test strategy", [
|
||||
"Test strategy for: [the feature or area]",
|
||||
"Who reads it: QA and the engineers writing the tests.",
|
||||
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"What exists today: [current tests, known gaps]",
|
||||
"## Test strategy",
|
||||
"[the feature or area]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"QA and the engineers writing the tests.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
'What\'s riskiest, meaning what costs most if it breaks, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"",
|
||||
"## What exists today",
|
||||
"[current tests, known gaps]",
|
||||
]),
|
||||
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
|
||||
"Scoping and rollout for: [the feature or project]",
|
||||
"Who reads it: the engineering manager, the product lead and the team.",
|
||||
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
|
||||
"Constraints: [dates, people, dependencies]",
|
||||
"## Scoping and rollout",
|
||||
"[the feature or project]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineering manager, the product lead and the team.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"What's in the first release and what waits, the build order, risks to the timeline, how it reaches users (flags, stages, who sees it first), and how we roll it back.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[dates, people, dependencies]",
|
||||
]),
|
||||
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
|
||||
"Brainstorm to turn into curated notes: [the topic or rough idea]",
|
||||
"Who reads the notes: [the team or people this goes to]",
|
||||
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"Starting thoughts: [anything already on your mind]",
|
||||
"## Brainstorm to curated notes",
|
||||
"[the topic or rough idea]",
|
||||
"",
|
||||
"## Who reads the notes",
|
||||
"[the team or people this goes to]",
|
||||
"",
|
||||
"## What I want out of it",
|
||||
"The ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"",
|
||||
"## Starting thoughts",
|
||||
"[anything already on your mind]",
|
||||
]),
|
||||
"bug-investigation": template("bug-investigation", "Bug investigation", [
|
||||
"Bug to investigate: [what's going wrong, in a sentence]",
|
||||
"Steps to reproduce: [1. ... 2. ...]",
|
||||
"Expected: [what should happen]. Actual: [what happens instead]",
|
||||
"Where and since when: [environment, version, first seen]",
|
||||
"## Bug investigation",
|
||||
"[what's going wrong, in a sentence]",
|
||||
"",
|
||||
"## Steps to reproduce",
|
||||
"1. [first step]",
|
||||
"2. [next step]",
|
||||
"",
|
||||
"## Expected",
|
||||
"[what should happen]",
|
||||
"",
|
||||
"## Actual",
|
||||
"[what happens instead]",
|
||||
"",
|
||||
"## How often",
|
||||
"[every time, sometimes, once]",
|
||||
"",
|
||||
"## Error or logs",
|
||||
"[paste the exact text]",
|
||||
"",
|
||||
"## Where and since when",
|
||||
"[environment, version, first seen]",
|
||||
]),
|
||||
"small-change": template("small-change", "Small change", [
|
||||
"Small change: [what to change, in a sentence]",
|
||||
"Where: [the file, screen or command, if you know it]",
|
||||
"Done when: [how you'll tell it worked]",
|
||||
"## Small change",
|
||||
"[what to change, in a sentence]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the file, screen or command, if you know it]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not change]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the command to run or the thing to check]",
|
||||
]),
|
||||
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
|
||||
"Change the wording of: [the screen, message, email or doc]",
|
||||
"Current text: [paste it]",
|
||||
"New text: [paste it, or describe the tone you want]",
|
||||
"Who reads it: [the people who see it]",
|
||||
"## Copy or content tweak",
|
||||
"[the screen, message, email or doc]",
|
||||
"",
|
||||
"## Current text",
|
||||
"[paste it]",
|
||||
"",
|
||||
"## New text",
|
||||
"[paste it, or describe the tone you want]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"[the people who see it]",
|
||||
]),
|
||||
"ui-polish": template("ui-polish", "UI polish", [
|
||||
"UI polish on: [the screen or component]",
|
||||
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
|
||||
"What good looks like: [a reference, screenshot or description]",
|
||||
"Leave alone: [anything that must not move]",
|
||||
"## UI polish",
|
||||
"[the screen or component]",
|
||||
"",
|
||||
"## What looks or feels off",
|
||||
"[spacing, alignment, colour, states, small screens]",
|
||||
"",
|
||||
"## What good looks like",
|
||||
"[a reference, screenshot or description]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not move]",
|
||||
]),
|
||||
"visual-prototype": template("visual-prototype", "Visual prototype", [
|
||||
"A throwaway visual prototype of: [the screen or component]",
|
||||
"What to show: [the states or flows to click through]",
|
||||
"What I want to learn: [the question it should answer]",
|
||||
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
"## Visual prototype",
|
||||
"[the screen or component to mock up]",
|
||||
"",
|
||||
"## What to show",
|
||||
"[the states or flows to click through]",
|
||||
"",
|
||||
"## What I want to learn",
|
||||
"[the question it should answer]",
|
||||
"",
|
||||
"## Where it lives",
|
||||
"A prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
]),
|
||||
"add-a-test": template("add-a-test", "Add a test", [
|
||||
"Add a test for: [the function, behaviour or bug]",
|
||||
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
|
||||
"Where tests live: [the test file or folder, if you know it]",
|
||||
"## Add a test",
|
||||
"[the function, behaviour or bug]",
|
||||
"",
|
||||
"## Cases to cover",
|
||||
"- [the normal case]",
|
||||
"- [the edge cases]",
|
||||
"- [the failure or bug it guards against]",
|
||||
"",
|
||||
"## Where tests live",
|
||||
"[the test file or folder, if you know it]",
|
||||
]),
|
||||
"record-decision": template("record-decision", "Record a decision", [
|
||||
"Record a decision we've already made: [the decision, in a sentence]",
|
||||
"Why: [the reasons, and what we turned down]",
|
||||
"What it commits us to: [the consequences]",
|
||||
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
|
||||
"## Record a decision",
|
||||
"[the decision we've already made, in a sentence]",
|
||||
"",
|
||||
"## Why",
|
||||
"[what forced the choice, and the options we turned down]",
|
||||
"",
|
||||
"## What it commits us to",
|
||||
"[the consequences]",
|
||||
"",
|
||||
"## Save it in",
|
||||
"docs/adr/ [or wherever this repo keeps them]",
|
||||
]),
|
||||
refactor: template("refactor", "Refactor", [
|
||||
"## Refactor",
|
||||
"[what to restructure, in a sentence]",
|
||||
"",
|
||||
"## Why now",
|
||||
"[what the current shape makes hard]",
|
||||
"",
|
||||
"## Behaviour that must not change",
|
||||
"[the public API, outputs or tests that must stay the same]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the tests that must still pass, and the shape it ends in]",
|
||||
]),
|
||||
"performance-problem": template("performance-problem", "Performance problem", [
|
||||
"## Performance problem",
|
||||
"[what's slow, in a sentence]",
|
||||
"",
|
||||
"## How it's measured today",
|
||||
"[the number, and how you got it]",
|
||||
"",
|
||||
"## Target",
|
||||
"[the number that counts as fixed]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the endpoint, page, query or job]",
|
||||
]),
|
||||
"dependency-upgrade": template("dependency-upgrade", "Dependency upgrade", [
|
||||
"## Dependency upgrade",
|
||||
"[the package, from version to version]",
|
||||
"",
|
||||
"## Why",
|
||||
"[security fix, a feature we need, end of support]",
|
||||
"",
|
||||
"## Known breaking changes",
|
||||
'[release notes link, or "not checked yet"]',
|
||||
"",
|
||||
"## Done when",
|
||||
"[the build, tests or checks that must pass]",
|
||||
]),
|
||||
spike: template("spike", "Spike", [
|
||||
"## Spike",
|
||||
"[the question to answer, in a sentence]",
|
||||
"",
|
||||
"## Why it matters",
|
||||
"[the decision waiting on the answer]",
|
||||
"",
|
||||
"## Time box",
|
||||
"[how long before we stop and decide anyway]",
|
||||
"",
|
||||
"## Answered when",
|
||||
"[the evidence that would settle it]",
|
||||
]),
|
||||
integration: template("integration", "Integration", [
|
||||
"## Integration",
|
||||
"[the system we're connecting to, and why]",
|
||||
"",
|
||||
"## What flows",
|
||||
"[the data or events, and in which direction]",
|
||||
"",
|
||||
"## Their side",
|
||||
"[API docs, auth method, rate limits, test sandbox]",
|
||||
"",
|
||||
"## When it fails",
|
||||
"[what should happen if they're down or slow]",
|
||||
]),
|
||||
"data-migration": template("data-migration", "Data migration", [
|
||||
"## Data migration",
|
||||
"[what moves or changes shape]",
|
||||
"",
|
||||
"## Size and downtime",
|
||||
"[row counts, and whether users can stay on while it runs]",
|
||||
"",
|
||||
"## Rollback",
|
||||
"[how we undo it if it goes wrong]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the checks that prove nothing was lost]",
|
||||
]),
|
||||
});
|
||||
|
||||
@@ -123,28 +309,28 @@ const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRol
|
||||
// One full order per role per skill. No "none" row: Not set reads Engineer's.
|
||||
export const TEMPLATE_ORDERS = Object.freeze({
|
||||
pathfinder: orders({
|
||||
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
|
||||
engineer: ["engineering-spec", "design-decision", "spike", "integration", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "spike", "engineering-spec", "design-decision", "integration", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "integration", "spike", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "spike", "engineering-spec", "scoping-rollout", "integration", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "spike", "product-requirements", "integration", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "spike", "test-strategy", "design-decision", "integration", "brainstorm-notes"],
|
||||
}),
|
||||
plan: orders({
|
||||
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
|
||||
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
|
||||
engineer: ["engineering-spec", "bug-investigation", "refactor", "performance-problem", "integration", "data-migration", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "integration", "test-strategy", "design-decision", "performance-problem", "bug-investigation", "data-migration", "refactor"],
|
||||
architect: ["design-decision", "engineering-spec", "data-migration", "integration", "refactor", "scoping-rollout", "performance-problem", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "performance-problem", "test-strategy", "bug-investigation", "integration", "refactor", "data-migration"],
|
||||
qa: ["test-strategy", "bug-investigation", "performance-problem", "engineering-spec", "data-migration", "integration", "product-requirements", "scoping-rollout", "refactor", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "data-migration", "product-requirements", "test-strategy", "integration", "bug-investigation", "performance-problem", "refactor", "design-decision"],
|
||||
}),
|
||||
"quick-task": orders({
|
||||
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
|
||||
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
engineer: ["small-change", "bug-investigation", "refactor", "add-a-test", "dependency-upgrade", "performance-problem", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "performance-problem", "add-a-test", "record-decision", "dependency-upgrade", "refactor"],
|
||||
architect: ["record-decision", "refactor", "small-change", "dependency-upgrade", "performance-problem", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "performance-problem", "add-a-test", "refactor", "dependency-upgrade", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "performance-problem", "small-change", "dependency-upgrade", "ui-polish", "refactor", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "dependency-upgrade", "add-a-test", "bug-investigation", "performance-problem", "refactor", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
||||
//
|
||||
// The source of truth for which workflows offer the switch, the instruction
|
||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
||||
// import this file.
|
||||
|
||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
||||
implement: Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"implement-review": Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"quick-task": Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
}),
|
||||
review: Object.freeze({
|
||||
instruction:
|
||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
||||
}),
|
||||
pathfinder: Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
}),
|
||||
});
|
||||
|
||||
export function offered(workflow) {
|
||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
||||
}
|
||||
|
||||
export const MAX_MIN = 1;
|
||||
export const MAX_MAX = 20;
|
||||
export const DEFAULT_MAX = 3;
|
||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
||||
export const HELPER_TITLE_MAX = 80;
|
||||
export const HELPER_ASK_MAX = 400;
|
||||
export const HELPER_RESULT_MAX = 200;
|
||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
export function defaultInstruction(workflow) {
|
||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
||||
}
|
||||
|
||||
// The person's own text when they wrote some, else the workflow's default.
|
||||
export function effectiveInstruction(setting) {
|
||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
||||
return own || defaultInstruction(setting && setting.workflow);
|
||||
}
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
export function cleanSetting(input) {
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
||||
let instruction = null;
|
||||
if (input.instruction !== null && input.instruction !== undefined) {
|
||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
||||
const trimmed = input.instruction.trim();
|
||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
||||
instruction = trimmed || null;
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// Only the first line of a block starts at column 0, so no line inside it can
|
||||
// be read as an entry of its own (NFR-5).
|
||||
export function onLines({ revision, replaces, max, instruction }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is owed at a pickup, given the session setting and the
|
||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
||||
* where `cursor` is what to write once the lines are printed. Never says
|
||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
||||
*/
|
||||
export function blockFor(setting, told) {
|
||||
const last = told || { revision: 0, state: "none" };
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
||||
|
||||
// The problems with one reported helper, [] when it is fine.
|
||||
export function checkHelper(entry) {
|
||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
||||
const who = `helper "${entry.id}"`;
|
||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
||||
const problems = [];
|
||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
||||
if (entry.result !== undefined) {
|
||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The problems with a whole merged list.
|
||||
export function checkHelpers(list) {
|
||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
let alone = 0;
|
||||
for (const entry of list) {
|
||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
||||
seen.add(entry.id);
|
||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
||||
}
|
||||
problems.push(...checkHelper(entry));
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the page */
|
||||
|
||||
// The page's rules for the button, the modal and the tab, kept here so they
|
||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
||||
// block; app.js only renders what these say.
|
||||
|
||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
||||
|
||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
||||
|
||||
// The switch shows only where the skill opts in AND the agent's console copy
|
||||
// said it can deliver it (FR-3).
|
||||
export function showSwitch(frame) {
|
||||
return Boolean(frame && frame.offered && frame.supported);
|
||||
}
|
||||
|
||||
// The button's tooltip and accessible name (FR-2).
|
||||
export function switchLabel(frame) {
|
||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
||||
}
|
||||
|
||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
||||
// in the order the agent reported them. A real helper supersedes the
|
||||
// working-alone marker, so the note only draws when no helper was ever
|
||||
// reported. A result shows once the helper ended.
|
||||
export function helperRows(helpers) {
|
||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
||||
const real = list.filter((h) => h.alone !== true);
|
||||
if (!real.length) return { alone: list.some((h) => h.alone === true), rows: [] };
|
||||
const rows = real.map(({ id, title, ask, state, result }) => ({
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
}));
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
||||
// helpers show even with the switch off (FR-11, FR-12).
|
||||
export function showTab(frame, helpers) {
|
||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
||||
}
|
||||
@@ -25,17 +25,21 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
SUBAGENTS_SETTING_FILE,
|
||||
UPDATE_CHECK_FILE,
|
||||
USER_MODELS_FILE,
|
||||
WORKSPACE_FILE,
|
||||
appendChat,
|
||||
appendEvent,
|
||||
chatForFrame,
|
||||
checkDocument,
|
||||
cleanupFindings,
|
||||
currentConversation,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
handleFile,
|
||||
initialWorkspace,
|
||||
latestOpenCaps,
|
||||
nowIso,
|
||||
parseArgs,
|
||||
pendingChatCount,
|
||||
@@ -44,21 +48,28 @@ import {
|
||||
readJson,
|
||||
readLedger,
|
||||
readOverview,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
writeSubagentSetting,
|
||||
writeWorkspace,
|
||||
} from "./lib.mjs";
|
||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
@@ -208,6 +219,7 @@ const SERVABLE = new Set([
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"start-stop.mp3",
|
||||
@@ -597,6 +609,48 @@ function ensureConversation(state) {
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
|
||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
||||
// says whether the agent's console copy can carry it. Both re-read only when
|
||||
// their file has moved.
|
||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
||||
|
||||
let subagentSettingSeen = { stamp: null, setting: null };
|
||||
function subagentSettingNow() {
|
||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
||||
return subagentSettingSeen.setting;
|
||||
}
|
||||
|
||||
let capsSeen = { stamp: null, caps: [] };
|
||||
function openCapsNow() {
|
||||
const stamp = fileStamp(EVENTS_PATH);
|
||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
||||
return capsSeen.caps;
|
||||
}
|
||||
|
||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
|
||||
/**
|
||||
* Turn the per-project store into this session's setting, for the workflow
|
||||
* the session is in now. The only place that happens (FR-7): a session an
|
||||
* older server ran has no setting file, so nothing is ever injected into it.
|
||||
* A record that already matches is left alone, revision and all, so a
|
||||
* restart alone never re-tells the agent anything.
|
||||
*/
|
||||
function syncSubagentSetting(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const current = readSubagentSetting(DIR);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
}
|
||||
|
||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||
// `have` names that exact view, for the page to hand back when it opens its
|
||||
// stream (see /events).
|
||||
@@ -611,19 +665,33 @@ function stateFrame(state) {
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
workspace: workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagentsView(state),
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
}
|
||||
|
||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
||||
// frame says both and leaves combining them to the page. `instruction: null`
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function subagentsView(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
||||
}
|
||||
|
||||
function haveKey() {
|
||||
const { pending, stop } = resultFlags();
|
||||
chatEntries();
|
||||
chatPickedUp();
|
||||
workspaceNow();
|
||||
ledgerEntries();
|
||||
subagentSettingNow();
|
||||
openCapsNow();
|
||||
return (
|
||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -648,6 +716,12 @@ function recordSubmitted(state, actions) {
|
||||
if (action.type === "comment") {
|
||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||
// The person's side of the Notes thread. Left to the agent it was never
|
||||
// written, so a question asked in a note vanished once it was picked up
|
||||
// and the reply under it answered nothing on the page.
|
||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const { i, type, ...rest } = action;
|
||||
@@ -933,6 +1007,38 @@ function pushState() {
|
||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- update check */
|
||||
|
||||
// The version this console was installed as: install.js writes version.json
|
||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
||||
function installedVersion() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return version;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filled in once the boot-time check answers; until then, and whenever it
|
||||
// fails, the frame carries no `update` and the page shows no banner.
|
||||
let updateInfo = null;
|
||||
let updateLatest = null;
|
||||
|
||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
||||
function startUpdateCheck() {
|
||||
const installed = installedVersion();
|
||||
if (!installed) return;
|
||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
||||
.then((result) => {
|
||||
updateLatest = result?.latest ?? null;
|
||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
||||
if (updateInfo) pushState();
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
let agentSeenAt = Date.now();
|
||||
function agentLastSeen() {
|
||||
return new Date(agentSeenAt).toISOString();
|
||||
@@ -1039,10 +1145,8 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
if (pathname === "/version" && req.method === "GET") {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||
}
|
||||
const version = installedVersion();
|
||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
||||
return json(res, 404, { error: "no version" });
|
||||
}
|
||||
|
||||
@@ -1090,7 +1194,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/draft" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||
// of someone's structured answers must not die with a closed tab.
|
||||
try {
|
||||
@@ -1115,7 +1219,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/looks" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// `set` carries only the keys one tab changed, merged onto what is on
|
||||
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||
@@ -1131,6 +1235,39 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// The Subagents switch for the session's workflow. Saved per project folder
|
||||
// for the next session, and applied to this one with a bumped revision, which
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
if (pathname === "/subagents" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
const clean = cleanSetting(body);
|
||||
if (clean.error) return json(res, 400, { error: clean.error });
|
||||
const { on, instruction, max } = clean;
|
||||
const current = readSubagentSetting(DIR);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
// The store is per project, so another session may have moved it since
|
||||
// this one synced: it always takes the person's latest pick. Only a
|
||||
// real change to this session's setting bumps what the agent hears.
|
||||
const unchanged = Boolean(current && sameSetting(current, next));
|
||||
try {
|
||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(DIR);
|
||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
||||
pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
@@ -1141,7 +1278,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
try {
|
||||
@@ -1154,6 +1291,24 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname === "/upload" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
const contentType = String(req.headers["content-type"] || "");
|
||||
@@ -1260,7 +1415,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/submit" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||
}
|
||||
@@ -1341,6 +1496,9 @@ const server = http.createServer((req, res) => {
|
||||
try {
|
||||
ensureConversation(written.state);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(written.state);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// Name the items that went. A page with OTHER answers staged should drop
|
||||
@@ -1361,6 +1519,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const state = readState() || {};
|
||||
const current = currentConversation(chatEntries()).conversation;
|
||||
@@ -1424,6 +1583,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||
@@ -1472,6 +1632,7 @@ const server = http.createServer((req, res) => {
|
||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
let answer;
|
||||
try {
|
||||
@@ -1489,6 +1650,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
||||
@@ -1589,15 +1751,19 @@ function readBody(req, cb) {
|
||||
let tooBig = false;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
||||
// never run and the page would see a reset instead of the 413 that names
|
||||
// the problem.
|
||||
if (size > MAX_BODY) {
|
||||
tooBig = true;
|
||||
req.destroy();
|
||||
chunks.length = 0;
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(new Error("too large"));
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
try {
|
||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (e) {
|
||||
@@ -1659,6 +1825,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
@@ -1833,7 +2002,13 @@ function onListening(port) {
|
||||
try {
|
||||
bootWorkspace();
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
} catch {}
|
||||
try {
|
||||
process.send?.({ type: "listening", port });
|
||||
} catch {}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
||||
//
|
||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
||||
// release tag is "latest". The server
|
||||
// starts this at boot and never waits on it; the answer, failures included, is
|
||||
// cached for an hour so a burst of sessions asks GitHub once.
|
||||
//
|
||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
||||
// with every prompt turned off so a missing login fails fast instead of
|
||||
// opening a window nobody asked for.
|
||||
//
|
||||
// Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
export const CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
||||
export function compareVersions(a, b) {
|
||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
||||
const x = a.split(".").map(Number);
|
||||
const y = b.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
||||
*/
|
||||
export function latestTag(text) {
|
||||
if (typeof text !== "string") return null;
|
||||
let best = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = TAG_REF.exec(line.trim());
|
||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readCache(cacheFile, now) {
|
||||
try {
|
||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
||||
return typeof cached.latest === "string" ? cached.latest : null;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(cacheFile, data) {
|
||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
||||
fs.renameSync(tmp, cacheFile);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
||||
* window, no prompt.
|
||||
*/
|
||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
||||
let child;
|
||||
try {
|
||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
env,
|
||||
});
|
||||
} catch {
|
||||
return resolve(null);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
done(null);
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
let out = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
out += chunk;
|
||||
});
|
||||
child.on("error", () => done(null));
|
||||
child.on("close", (code) => done(code === 0 ? out : null));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
||||
* not retried until the hour is up. Never throws.
|
||||
*/
|
||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
||||
try {
|
||||
let latest = readCache(cacheFile, now);
|
||||
if (latest === undefined) {
|
||||
latest = latestTag(await run());
|
||||
writeCache(cacheFile, { checkedAt: now, latest });
|
||||
}
|
||||
const order = compareVersions(installed, latest);
|
||||
if (latest === null || order === null) return null;
|
||||
return { installed, latest, updateAvailable: order < 0 };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -243,7 +243,7 @@ summarise it back.
|
||||
Then, in ONE `post`, do all of:
|
||||
|
||||
- mark each answered item `"status": "answered"` and record its `answer`
|
||||
- add your replies to any comment threads
|
||||
- reply to every note in that item's `thread` (shape below)
|
||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||
questions)
|
||||
- publish the next batch of questions
|
||||
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
|
||||
|
||||
One post is one atomic update, so the page never shows a half-changed state.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
A `comment` is the person talking to you about that card, often asking
|
||||
something. It shows in the card's **Notes on this** panel, and so does your
|
||||
answer:
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
||||
- The server writes their note into the thread as it arrives. Do not repeat
|
||||
it, and send only your new entries: `thread` appends.
|
||||
- Answer what they asked, in the thread, even when you also change a doc or
|
||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
||||
panel with no answer under it.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||
@@ -627,6 +647,87 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -661,9 +762,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
||||
run inline from another (a quick task's review) keeps the page it was
|
||||
handed. A
|
||||
fresh `open` would strand the page the person is watching on the dashboard's
|
||||
session while your questions went to a page nobody has open. Then run the
|
||||
skill normally: its Interface question was already answered by being
|
||||
launched, so start where its real work starts.
|
||||
session while your questions went to a page nobody has open.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
||||
> purpose — it exists to be read and followed inline, not launched as a
|
||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
||||
> strands the hand-off mid-launch.
|
||||
|
||||
Its Interface step is already answered by having been launched, so start
|
||||
where its real work starts.
|
||||
|
||||
The menu itself is the page's own list — you never send it. The page knows
|
||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||
@@ -735,7 +844,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -769,6 +881,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -829,6 +943,12 @@ know:
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
— the specs are untouched until Step 3's summary write — so a stop's finish
|
||||
@@ -859,7 +979,7 @@ question or doc lands:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
||||
what changed. A whole-file rewrite would put the entire session back into your
|
||||
context on every turn.
|
||||
|
||||
@@ -1112,6 +1232,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1133,7 +1263,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
@@ -1239,7 +1371,7 @@ answers were submitted but never picked up.
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -48,6 +49,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
@@ -487,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -536,6 +548,148 @@ export async function removeScratch(consoleDir, names) {
|
||||
return removed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- cleanup */
|
||||
|
||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
// rename -- and removing one mid-write loses another session's change.
|
||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
||||
|
||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
||||
async function diskBytes(p) {
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
if (!st.isDirectory()) return st.size;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
||||
* not kept, and -- only when the console runs from its default home inside
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
plan2codeDir = PLAN2CODE_DIR,
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
} catch {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||
@@ -871,7 +1025,7 @@ export function handOff(child, pre) {
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
@@ -896,7 +1050,7 @@ function mergeOne(target, patch, where) {
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread/comments append.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
@@ -955,11 +1109,60 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -996,12 +1199,23 @@ export function applyPatch(state, patch) {
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1048,15 +1262,11 @@ function stampTimes(before, next) {
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
for (const list of [next.items, next.docs]) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const entry of list) {
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
if (Array.isArray(entry.comments)) {
|
||||
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
@@ -1289,7 +1499,10 @@ export function validate(state) {
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
@@ -1297,6 +1510,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1553,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1353,6 +1581,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1808,6 +2038,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
|
||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||
* Any thread message from the send onwards, or none with a clock to compare,
|
||||
* means it has been picked up.
|
||||
* Any agent message from the send onwards, or one with no clock to compare,
|
||||
* means it has been picked up. The person's own entries never count: the
|
||||
* server writes their note into the thread as it arrives.
|
||||
*/
|
||||
export function noteAwaiting(item) {
|
||||
const n = item && item.sentNote;
|
||||
if (!n || typeof n !== "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
||||
return picked ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
||||
* and the server lifts anything else into it, but sessions written before that
|
||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
||||
*/
|
||||
export function threadWho(m) {
|
||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
||||
}
|
||||
|
||||
export function threadText(m) {
|
||||
if (!m) return "";
|
||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
--warn-soft: #fbe7e3;
|
||||
--focus: #1f6feb;
|
||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||
/* A soft accent halo for the things that want noticing: the update banner
|
||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||
@@ -61,6 +64,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +89,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -203,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1097,10 +1122,11 @@ h1 {
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. */
|
||||
.view-tab .tab-spin {
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
@@ -1424,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1657,11 +1707,13 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* Send breathes while there is something to send: a soft accent ring that
|
||||
spreads and fades. Off under reduced motion, below. */
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
||||
@keyframes send-pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: 0 0 0 6px transparent; }
|
||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
||||
}
|
||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
@@ -1963,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
@@ -2219,6 +2273,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal.help[open] { display: flex; }
|
||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||
.help-version a { color: inherit; }
|
||||
|
||||
.help-layout {
|
||||
display: grid;
|
||||
@@ -2668,6 +2723,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
@@ -3394,6 +3517,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
||||
.cleanup-list:empty { display: none; }
|
||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
||||
.cleanup-more { display: grid; gap: 4px; }
|
||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
||||
#cleanup-delete[hidden] { display: none; }
|
||||
|
||||
/* A word the person has to type, bold and in their highlight color so it
|
||||
does not get lost in the status sentence. */
|
||||
.agent-key {
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
submittedAwaiting,
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
threadText,
|
||||
threadWho,
|
||||
THUMB_EDGE,
|
||||
turnGate,
|
||||
verdictText,
|
||||
@@ -101,6 +103,15 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
||||
import { RED_BANNER } from "./meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||
import { faviconState, setFavicon } from "./favicon.js";
|
||||
import {
|
||||
CHECKIN_LINE,
|
||||
PATHFINDER_RESEARCH_LINE,
|
||||
defaultInstruction,
|
||||
helperRows,
|
||||
showSwitch,
|
||||
showTab,
|
||||
switchLabel,
|
||||
} from "./subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -446,6 +457,10 @@ document.addEventListener("click", (e) => {
|
||||
|
||||
|
||||
const GONE_AFTER_MS = 8000;
|
||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
||||
// failure, a refused send).
|
||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
@@ -521,6 +536,12 @@ let chatFrame = null;
|
||||
// sends them.
|
||||
let wsFrame = null;
|
||||
let meterFrame = null;
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
let updateFrame = null;
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
let subagentsFrame = null;
|
||||
let chatDot = false;
|
||||
let chatSending = false;
|
||||
let chatResetting = false;
|
||||
@@ -566,7 +587,6 @@ function fresh() {
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
sentAt: null,
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
@@ -870,10 +890,14 @@ function adopt(body) {
|
||||
chatFrame = body.chat || null;
|
||||
if (body.workspace) wsFrame = body.workspace;
|
||||
if (body.meter) meterFrame = body.meter;
|
||||
// Always replaced: an absent key means no update.
|
||||
updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
subagentsFrame = body.subagents || null;
|
||||
lastContact = Date.now();
|
||||
if (gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
}
|
||||
if (firstLoad) {
|
||||
load();
|
||||
@@ -1016,7 +1040,9 @@ function adopt(body) {
|
||||
render();
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
tellFolderIssues();
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||
// The Overview tab's file changes under a build, so a tab you are watching
|
||||
// refetches on every new frame too, not only on the click that opened it.
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
||||
if (announce) showArrival(announce);
|
||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||
// leaving the list parked where it was while it grew underneath.
|
||||
@@ -1149,15 +1175,12 @@ function markGone() {
|
||||
// of the server means there, and a banner promising a reconnect would
|
||||
// argue with it.
|
||||
if (!finish() && !stopInProgress()) {
|
||||
banner(
|
||||
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||
"warn"
|
||||
);
|
||||
banner(GONE_BANNER, "warn");
|
||||
}
|
||||
render();
|
||||
} else if (!bad && gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -1182,7 +1205,6 @@ function connect() {
|
||||
} catch {}
|
||||
});
|
||||
es.addEventListener("submitted", (e) => {
|
||||
local.sentAt = Date.now();
|
||||
// Drop only what was actually sent.
|
||||
//
|
||||
// This event fires for a send from ANY tab of this session, which is why it
|
||||
@@ -1293,6 +1315,7 @@ function render() {
|
||||
renderChrome();
|
||||
renderStatus();
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
@@ -1558,7 +1581,7 @@ function renderChrome() {
|
||||
renderMeter();
|
||||
$("title").textContent = S.title || "Session";
|
||||
$("badge").textContent = workflowLabel(S.workflow);
|
||||
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
renderTabTitle();
|
||||
|
||||
const h = S.headline || {};
|
||||
// On a finished session an open item is frozen: the send on it counts as
|
||||
@@ -1799,14 +1822,19 @@ async function sendBrief() {
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => banner(null), 5000);
|
||||
pendingResult = true;
|
||||
render();
|
||||
} catch {
|
||||
why.textContent = "That did not go through. Try again in a moment.";
|
||||
} catch (err) {
|
||||
if (err && err.pending) pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
@@ -1822,6 +1850,69 @@ function renderBriefButton() {
|
||||
if (offer) btn.disabled = gone || pendingResult;
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
function openSubagents() {
|
||||
if (!showSwitch(subagentsFrame)) return;
|
||||
const on = Boolean(subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
||||
$("subagents-max").value = String(subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
function renderViews() {
|
||||
const nav = $("views");
|
||||
nav.replaceChildren();
|
||||
@@ -1837,6 +1928,14 @@ function renderViews() {
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (view === "overview") view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
if (showTab(subagentsFrame, S.helpers)) {
|
||||
// From the rows the tab draws, so the badge never counts helpers the
|
||||
// working-alone note hides.
|
||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
||||
} else if (view === "subagents") view = "questions";
|
||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
||||
// a question the agent picked up and has not answered yet.
|
||||
@@ -2117,6 +2216,7 @@ function paintMain(main) {
|
||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||
if (view === "overview") return renderOverview(main);
|
||||
if (view === "ask") return renderAsk(main);
|
||||
if (view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
// the top of the rail. The hand-off lives here alone now, rather than
|
||||
@@ -2515,6 +2615,51 @@ function roleNudge() {
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function releasesLink(text) {
|
||||
const a = el("a", null, text);
|
||||
a.href = RELEASES_URL;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
return a;
|
||||
}
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
function renderDashboard(main) {
|
||||
maybeWake();
|
||||
const menu = (S && S.menu) || {};
|
||||
@@ -2526,6 +2671,25 @@ function renderDashboard(main) {
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
||||
} catch {}
|
||||
render();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||
@@ -3223,7 +3387,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
||||
function skipAndMoveOn(id) {
|
||||
cancelSkipMove();
|
||||
local.skipFlash = id;
|
||||
stage(id, { type: "skip", skipped: true });
|
||||
// A note already typed goes along: skipping the question is not retracting
|
||||
// the comment. Dropping it would leave the text in the box but out of the
|
||||
// send, which looks kept and is not.
|
||||
const cur = local.staged[id];
|
||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
||||
skipTimer = setTimeout(() => {
|
||||
skipTimer = null;
|
||||
local.skipFlash = null;
|
||||
@@ -3340,19 +3508,24 @@ function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"), a quick task as `tasks`; with neither the words stay plain.
|
||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
if (!list) return el("strong", "waiting-jump", word);
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
@@ -3366,8 +3539,8 @@ function renderWaiting(main) {
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump((list && list.title) || "Phase tasks"),
|
||||
" tab. If Plan2Code needs you, the question appears here on its own."
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
@@ -3505,8 +3678,8 @@ function renderSettled(card, item) {
|
||||
// would misreport which of the two was the answer.
|
||||
let prose = text;
|
||||
if (!prose && !lines.length) {
|
||||
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
||||
}
|
||||
|
||||
const nothing = !lines.length && !prose;
|
||||
@@ -4172,8 +4345,11 @@ function templateRow(item, input, entries, check) {
|
||||
save();
|
||||
paint();
|
||||
input.focus();
|
||||
const start = text.indexOf("[");
|
||||
const end = start < 0 ? -1 : text.indexOf("]", start);
|
||||
try {
|
||||
input.setSelectionRange(text.length, text.length);
|
||||
if (end > start) input.setSelectionRange(start, end + 1);
|
||||
else input.setSelectionRange(text.length, text.length);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
@@ -4322,6 +4498,10 @@ function buildChecklist(card, item, staged) {
|
||||
const commitList = (change) => {
|
||||
const cur = local.staged[item.id];
|
||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
||||
// card showed ticked steps on their way.
|
||||
delete next.skipped;
|
||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||
stage(item.id, empty ? null : next);
|
||||
};
|
||||
@@ -4371,7 +4551,7 @@ function buildChecklist(card, item, staged) {
|
||||
function buildMenu(card, item, staged) {
|
||||
const list = el("ul", "options");
|
||||
const name = "menu-" + item.id;
|
||||
for (const o of item.options || []) {
|
||||
for (const [i, o] of (item.options || []).entries()) {
|
||||
const picked = staged && staged.k === o.k;
|
||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||
const label = el("label");
|
||||
@@ -4379,7 +4559,13 @@ function buildMenu(card, item, staged) {
|
||||
const radio = el("input");
|
||||
radio.type = "radio";
|
||||
radio.name = name;
|
||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
||||
// input by id after the render this change() sets off, and without one a
|
||||
// keyboard user arrowing through the menu lands on <body> every time.
|
||||
radio.id = optionId(item, o, i);
|
||||
radio.value = o.k;
|
||||
radio.checked = Boolean(picked);
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||
const body = el("div", "option-body");
|
||||
const head = el("div", "option-label");
|
||||
@@ -4678,6 +4864,42 @@ function renderOverview(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ask */
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
@@ -5276,20 +5498,30 @@ function renderAside() {
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
box.appendChild(md(m.text, "md"));
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A note that has been sent but not yet picked up: shown at once, so the
|
||||
// send is seen to have gone, and gone when the agent replies.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
if (waiting) {
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
@@ -5589,7 +5821,10 @@ async function attachFiles(itemId, files) {
|
||||
const taken = wanted.slice(0, room);
|
||||
// One banner at a time, so every refusal goes into it, each by name.
|
||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||
if (taken.length < wanted.length)
|
||||
said.push(
|
||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
||||
);
|
||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||
await Promise.all(
|
||||
taken.map(async (file) => {
|
||||
@@ -5847,10 +6082,30 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
||||
// session opened before the server wrote `worktree` has nothing to show, so
|
||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||
// touched when the labels change, or when a resize clears the key.
|
||||
// The project's name: the workspace's original folder, or the session's
|
||||
// worktree folder before a frame carries the workspace.
|
||||
function projectName() {
|
||||
const folders = workspaceFolders();
|
||||
if (folders.length && folders[0].name) return folders[0].name;
|
||||
const path = (S && S.worktree) || "";
|
||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
||||
}
|
||||
|
||||
// The browser tab's title, led by the project so tabs from different
|
||||
// projects are told apart. Called from the chrome and the footer, since the
|
||||
// workspace frame can arrive after either.
|
||||
function renderTabTitle() {
|
||||
if (!S) return;
|
||||
const name = projectName();
|
||||
document.title =
|
||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
}
|
||||
|
||||
function renderWhere() {
|
||||
const b = $("footer-where");
|
||||
const folders = workspaceFolders();
|
||||
const path = S.worktree || "";
|
||||
renderTabTitle();
|
||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||
const labels = folders.length
|
||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||
@@ -5863,7 +6118,16 @@ function renderWhere() {
|
||||
let label = labels[0];
|
||||
for (const text of labels) {
|
||||
label = text;
|
||||
b.textContent = text;
|
||||
// The project name takes the highlight color, so several consoles side by
|
||||
// side tell apart at a glance; the rest of the label stays quiet.
|
||||
const name = projectName();
|
||||
b.textContent = "";
|
||||
if (name && text.startsWith(name)) {
|
||||
b.appendChild(el("span", "where-project", name));
|
||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
||||
} else {
|
||||
b.textContent = text;
|
||||
}
|
||||
if (alert) {
|
||||
const dot = el("span", "where-alert");
|
||||
dot.setAttribute("aria-hidden", "true");
|
||||
@@ -6439,6 +6703,10 @@ async function goHome() {
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
@@ -6499,6 +6767,7 @@ async function stopSession() {
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
@@ -6653,7 +6922,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||
}
|
||||
local.staged = {};
|
||||
local.sentAt = Date.now();
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -6706,7 +6974,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
||||
// something the agent never hears.
|
||||
function tokenFor(item, v) {
|
||||
const map = item.token || {};
|
||||
if (v.skipped) return "skip";
|
||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
||||
const parts = [];
|
||||
if (v.k) parts.push(map[v.k] || v.k);
|
||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||
@@ -6938,14 +7206,14 @@ function renderAbout() {
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const el = $("help-version");
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
el.textContent = version ? "Plan2Code v" + version : "";
|
||||
el.hidden = !version;
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
el.hidden = true;
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7053,6 +7321,7 @@ function openHelpOn(id) {
|
||||
}
|
||||
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
@@ -7083,6 +7352,7 @@ function lightDismiss(dlg) {
|
||||
});
|
||||
}
|
||||
lightDismiss($("looks-modal"));
|
||||
lightDismiss($("subagents-modal"));
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("workspace-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
@@ -7132,6 +7402,7 @@ $("btn-looks").addEventListener("click", () => {
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
resetCleanup();
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
@@ -7278,7 +7549,119 @@ $("models-reset").addEventListener("click", () => {
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const strays = items.length - sessions;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
||||
}
|
||||
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
@@ -39,6 +40,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
@@ -172,6 +173,18 @@
|
||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||
Write a brief
|
||||
</button>
|
||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
||||
opens the Subagents dialog and never toggles them itself. -->
|
||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -580,6 +593,13 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
<circle cx="18" cy="12" r="2" />
|
||||
<circle cx="18" cy="19" r="2" />
|
||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
||||
</symbol>
|
||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||
<path d="M8 9.5h8M8 12.5h5" />
|
||||
@@ -1291,6 +1311,14 @@
|
||||
come back, and you can change your role any time from the swatch
|
||||
button.
|
||||
</p>
|
||||
<h4>When an update is out</h4>
|
||||
<p>
|
||||
When a newer Plan2Code release is out, the dashboard shows
|
||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
||||
to run in your terminal; × hides it until the next
|
||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
||||
the Releases page.
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
@@ -1469,7 +1497,62 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 12: Ask a quick question -->
|
||||
<!-- Tab 12: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
||||
never switches helpers on or off by itself. Pick <strong>Use
|
||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
||||
shipped one back), and say how many may run at once.
|
||||
</li>
|
||||
<li>
|
||||
It is off by default and saved for this project and this skill, so
|
||||
the next session of the same skill here starts the same way.
|
||||
</li>
|
||||
<li>
|
||||
The change reaches Plan2Code at its next check-in, as a setting,
|
||||
not as something you typed. How many helpers it can really start is
|
||||
up to your agent; some have no helpers at all.
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
||||
Ask: one row each, with what it was asked, whether it is running, done
|
||||
or failed, and a one-line result at the end. The number on the tab is
|
||||
how many are still running.
|
||||
</li>
|
||||
<li>
|
||||
Helpers report through Plan2Code, so the rows change at its
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Working alone</strong> means your agent reported it has no
|
||||
way to start helpers here. If it starts one after all, the note
|
||||
goes away and the helper's row shows instead.
|
||||
</li>
|
||||
<li>
|
||||
Pathfinder always uses helpers for its research questions, whatever
|
||||
the switch says, and they show here too.
|
||||
</li>
|
||||
<li>The tab clears when you go back to the dashboard.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1560,7 +1643,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Stopping and finishing -->
|
||||
<!-- Tab 14: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1642,7 +1725,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: When something looks stuck -->
|
||||
<!-- Tab 15: When something looks stuck -->
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1764,7 +1847,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Keyboard and preferences -->
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1845,6 +1928,15 @@
|
||||
joining the strip. Keep only the ones you want; ticking a box plays
|
||||
its sound.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Back to default</strong> puts everything back as it was, and
|
||||
sets Role back to Not set.
|
||||
@@ -1871,7 +1963,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Privacy and where things are saved -->
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1908,7 +2000,11 @@
|
||||
</li>
|
||||
<li>
|
||||
your role, theme, colors, card width and sounds, in
|
||||
<code>looks.json</code>.
|
||||
<code>looks.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -1983,6 +2079,16 @@
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
@@ -2012,6 +2118,46 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
||||
its own, only a themed number box. -->
|
||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
||||
<h2 id="subagents-title">Subagents</h2>
|
||||
<p class="modal-blurb">
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
@@ -2181,6 +2327,24 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
||||
the copy row are filled by app.js; the update itself runs in a
|
||||
terminal, never from this page. -->
|
||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
||||
<p class="modal-blurb" id="update-versions"></p>
|
||||
<ol class="update-steps">
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||
Nothing to send yet.
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
// popover; this file owns the rules. No DOM access at module scope and no
|
||||
// imports: the page and `node --test` both import this file.
|
||||
|
||||
const NAME_CHAR = /[a-z0-9-]/;
|
||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
||||
// nothing and opens no suggestions at all.
|
||||
const NAME_CHAR = /[a-z0-9-]/i;
|
||||
const MAX_MATCHES = 6;
|
||||
|
||||
/**
|
||||
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
|
||||
}
|
||||
|
||||
// Names starting with the query first, then names containing it, in the
|
||||
// order given, at most six.
|
||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
||||
export function matchNames(names, query) {
|
||||
const q = String(query || "");
|
||||
const prefix = names.filter((n) => n.startsWith(q));
|
||||
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||
const q = String(query || "").toLowerCase();
|
||||
const fold = (n) => String(n).toLowerCase();
|
||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,85 +36,271 @@ export function needsRoleNudge(looks) {
|
||||
return !Object.hasOwn(looks, "role");
|
||||
}
|
||||
|
||||
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
|
||||
// The wording was revised in v2.5.1 (Markdown sections); a change is a page change.
|
||||
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
|
||||
|
||||
export const TEMPLATES = Object.freeze({
|
||||
"engineering-spec": template("engineering-spec", "Engineering spec", [
|
||||
"Engineering spec for: [the feature or change, in a sentence]",
|
||||
"Who reads it: the engineers who will build and review it.",
|
||||
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
|
||||
"What I already know: [constraints, links, earlier attempts]",
|
||||
"## Engineering spec",
|
||||
"[the feature or change, in a sentence]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineers who will build and review it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The behaviour, the parts of the code it touches, the interfaces between them, the simpler options we're turning down, and how we'll know it works.",
|
||||
"",
|
||||
"## Out of scope",
|
||||
"[what this deliberately won't do]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[constraints, links, earlier attempts]",
|
||||
]),
|
||||
"product-requirements": template("product-requirements", "Product requirements", [
|
||||
"Product requirements for: [the feature, in a sentence]",
|
||||
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
|
||||
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
|
||||
"What I already know: [customer asks, data, deadlines]",
|
||||
"## Product requirements",
|
||||
"[the feature, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"[the users], and the product, design and engineering people deciding on it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The problem, who has it, the evidence it's real, and how we'll measure success.",
|
||||
"",
|
||||
"## Not doing",
|
||||
"[what this release leaves out]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[customer asks, data, deadlines]",
|
||||
]),
|
||||
"design-decision": template("design-decision", "Design decision", [
|
||||
"A design decision to work out: [the choice we're facing, in a sentence]",
|
||||
"Who it's for: the engineers and architects who will live with it.",
|
||||
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"Constraints: [performance, compatibility, deadlines, team skills]",
|
||||
"## Design decision",
|
||||
"[the choice we're facing, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"The engineers and architects who will live with it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[performance, compatibility, deadlines, team skills]",
|
||||
]),
|
||||
"test-strategy": template("test-strategy", "Test strategy", [
|
||||
"Test strategy for: [the feature or area]",
|
||||
"Who reads it: QA and the engineers writing the tests.",
|
||||
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"What exists today: [current tests, known gaps]",
|
||||
"## Test strategy",
|
||||
"[the feature or area]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"QA and the engineers writing the tests.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
'What\'s riskiest, meaning what costs most if it breaks, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"",
|
||||
"## What exists today",
|
||||
"[current tests, known gaps]",
|
||||
]),
|
||||
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
|
||||
"Scoping and rollout for: [the feature or project]",
|
||||
"Who reads it: the engineering manager, the product lead and the team.",
|
||||
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
|
||||
"Constraints: [dates, people, dependencies]",
|
||||
"## Scoping and rollout",
|
||||
"[the feature or project]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineering manager, the product lead and the team.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"What's in the first release and what waits, the build order, risks to the timeline, how it reaches users (flags, stages, who sees it first), and how we roll it back.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[dates, people, dependencies]",
|
||||
]),
|
||||
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
|
||||
"Brainstorm to turn into curated notes: [the topic or rough idea]",
|
||||
"Who reads the notes: [the team or people this goes to]",
|
||||
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"Starting thoughts: [anything already on your mind]",
|
||||
"## Brainstorm to curated notes",
|
||||
"[the topic or rough idea]",
|
||||
"",
|
||||
"## Who reads the notes",
|
||||
"[the team or people this goes to]",
|
||||
"",
|
||||
"## What I want out of it",
|
||||
"The ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"",
|
||||
"## Starting thoughts",
|
||||
"[anything already on your mind]",
|
||||
]),
|
||||
"bug-investigation": template("bug-investigation", "Bug investigation", [
|
||||
"Bug to investigate: [what's going wrong, in a sentence]",
|
||||
"Steps to reproduce: [1. ... 2. ...]",
|
||||
"Expected: [what should happen]. Actual: [what happens instead]",
|
||||
"Where and since when: [environment, version, first seen]",
|
||||
"## Bug investigation",
|
||||
"[what's going wrong, in a sentence]",
|
||||
"",
|
||||
"## Steps to reproduce",
|
||||
"1. [first step]",
|
||||
"2. [next step]",
|
||||
"",
|
||||
"## Expected",
|
||||
"[what should happen]",
|
||||
"",
|
||||
"## Actual",
|
||||
"[what happens instead]",
|
||||
"",
|
||||
"## How often",
|
||||
"[every time, sometimes, once]",
|
||||
"",
|
||||
"## Error or logs",
|
||||
"[paste the exact text]",
|
||||
"",
|
||||
"## Where and since when",
|
||||
"[environment, version, first seen]",
|
||||
]),
|
||||
"small-change": template("small-change", "Small change", [
|
||||
"Small change: [what to change, in a sentence]",
|
||||
"Where: [the file, screen or command, if you know it]",
|
||||
"Done when: [how you'll tell it worked]",
|
||||
"## Small change",
|
||||
"[what to change, in a sentence]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the file, screen or command, if you know it]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not change]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the command to run or the thing to check]",
|
||||
]),
|
||||
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
|
||||
"Change the wording of: [the screen, message, email or doc]",
|
||||
"Current text: [paste it]",
|
||||
"New text: [paste it, or describe the tone you want]",
|
||||
"Who reads it: [the people who see it]",
|
||||
"## Copy or content tweak",
|
||||
"[the screen, message, email or doc]",
|
||||
"",
|
||||
"## Current text",
|
||||
"[paste it]",
|
||||
"",
|
||||
"## New text",
|
||||
"[paste it, or describe the tone you want]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"[the people who see it]",
|
||||
]),
|
||||
"ui-polish": template("ui-polish", "UI polish", [
|
||||
"UI polish on: [the screen or component]",
|
||||
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
|
||||
"What good looks like: [a reference, screenshot or description]",
|
||||
"Leave alone: [anything that must not move]",
|
||||
"## UI polish",
|
||||
"[the screen or component]",
|
||||
"",
|
||||
"## What looks or feels off",
|
||||
"[spacing, alignment, colour, states, small screens]",
|
||||
"",
|
||||
"## What good looks like",
|
||||
"[a reference, screenshot or description]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not move]",
|
||||
]),
|
||||
"visual-prototype": template("visual-prototype", "Visual prototype", [
|
||||
"A throwaway visual prototype of: [the screen or component]",
|
||||
"What to show: [the states or flows to click through]",
|
||||
"What I want to learn: [the question it should answer]",
|
||||
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
"## Visual prototype",
|
||||
"[the screen or component to mock up]",
|
||||
"",
|
||||
"## What to show",
|
||||
"[the states or flows to click through]",
|
||||
"",
|
||||
"## What I want to learn",
|
||||
"[the question it should answer]",
|
||||
"",
|
||||
"## Where it lives",
|
||||
"A prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
]),
|
||||
"add-a-test": template("add-a-test", "Add a test", [
|
||||
"Add a test for: [the function, behaviour or bug]",
|
||||
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
|
||||
"Where tests live: [the test file or folder, if you know it]",
|
||||
"## Add a test",
|
||||
"[the function, behaviour or bug]",
|
||||
"",
|
||||
"## Cases to cover",
|
||||
"- [the normal case]",
|
||||
"- [the edge cases]",
|
||||
"- [the failure or bug it guards against]",
|
||||
"",
|
||||
"## Where tests live",
|
||||
"[the test file or folder, if you know it]",
|
||||
]),
|
||||
"record-decision": template("record-decision", "Record a decision", [
|
||||
"Record a decision we've already made: [the decision, in a sentence]",
|
||||
"Why: [the reasons, and what we turned down]",
|
||||
"What it commits us to: [the consequences]",
|
||||
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
|
||||
"## Record a decision",
|
||||
"[the decision we've already made, in a sentence]",
|
||||
"",
|
||||
"## Why",
|
||||
"[what forced the choice, and the options we turned down]",
|
||||
"",
|
||||
"## What it commits us to",
|
||||
"[the consequences]",
|
||||
"",
|
||||
"## Save it in",
|
||||
"docs/adr/ [or wherever this repo keeps them]",
|
||||
]),
|
||||
refactor: template("refactor", "Refactor", [
|
||||
"## Refactor",
|
||||
"[what to restructure, in a sentence]",
|
||||
"",
|
||||
"## Why now",
|
||||
"[what the current shape makes hard]",
|
||||
"",
|
||||
"## Behaviour that must not change",
|
||||
"[the public API, outputs or tests that must stay the same]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the tests that must still pass, and the shape it ends in]",
|
||||
]),
|
||||
"performance-problem": template("performance-problem", "Performance problem", [
|
||||
"## Performance problem",
|
||||
"[what's slow, in a sentence]",
|
||||
"",
|
||||
"## How it's measured today",
|
||||
"[the number, and how you got it]",
|
||||
"",
|
||||
"## Target",
|
||||
"[the number that counts as fixed]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the endpoint, page, query or job]",
|
||||
]),
|
||||
"dependency-upgrade": template("dependency-upgrade", "Dependency upgrade", [
|
||||
"## Dependency upgrade",
|
||||
"[the package, from version to version]",
|
||||
"",
|
||||
"## Why",
|
||||
"[security fix, a feature we need, end of support]",
|
||||
"",
|
||||
"## Known breaking changes",
|
||||
'[release notes link, or "not checked yet"]',
|
||||
"",
|
||||
"## Done when",
|
||||
"[the build, tests or checks that must pass]",
|
||||
]),
|
||||
spike: template("spike", "Spike", [
|
||||
"## Spike",
|
||||
"[the question to answer, in a sentence]",
|
||||
"",
|
||||
"## Why it matters",
|
||||
"[the decision waiting on the answer]",
|
||||
"",
|
||||
"## Time box",
|
||||
"[how long before we stop and decide anyway]",
|
||||
"",
|
||||
"## Answered when",
|
||||
"[the evidence that would settle it]",
|
||||
]),
|
||||
integration: template("integration", "Integration", [
|
||||
"## Integration",
|
||||
"[the system we're connecting to, and why]",
|
||||
"",
|
||||
"## What flows",
|
||||
"[the data or events, and in which direction]",
|
||||
"",
|
||||
"## Their side",
|
||||
"[API docs, auth method, rate limits, test sandbox]",
|
||||
"",
|
||||
"## When it fails",
|
||||
"[what should happen if they're down or slow]",
|
||||
]),
|
||||
"data-migration": template("data-migration", "Data migration", [
|
||||
"## Data migration",
|
||||
"[what moves or changes shape]",
|
||||
"",
|
||||
"## Size and downtime",
|
||||
"[row counts, and whether users can stay on while it runs]",
|
||||
"",
|
||||
"## Rollback",
|
||||
"[how we undo it if it goes wrong]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the checks that prove nothing was lost]",
|
||||
]),
|
||||
});
|
||||
|
||||
@@ -123,28 +309,28 @@ const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRol
|
||||
// One full order per role per skill. No "none" row: Not set reads Engineer's.
|
||||
export const TEMPLATE_ORDERS = Object.freeze({
|
||||
pathfinder: orders({
|
||||
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
|
||||
engineer: ["engineering-spec", "design-decision", "spike", "integration", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "spike", "engineering-spec", "design-decision", "integration", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "integration", "spike", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "spike", "engineering-spec", "scoping-rollout", "integration", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "spike", "product-requirements", "integration", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "spike", "test-strategy", "design-decision", "integration", "brainstorm-notes"],
|
||||
}),
|
||||
plan: orders({
|
||||
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
|
||||
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
|
||||
engineer: ["engineering-spec", "bug-investigation", "refactor", "performance-problem", "integration", "data-migration", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "integration", "test-strategy", "design-decision", "performance-problem", "bug-investigation", "data-migration", "refactor"],
|
||||
architect: ["design-decision", "engineering-spec", "data-migration", "integration", "refactor", "scoping-rollout", "performance-problem", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "performance-problem", "test-strategy", "bug-investigation", "integration", "refactor", "data-migration"],
|
||||
qa: ["test-strategy", "bug-investigation", "performance-problem", "engineering-spec", "data-migration", "integration", "product-requirements", "scoping-rollout", "refactor", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "data-migration", "product-requirements", "test-strategy", "integration", "bug-investigation", "performance-problem", "refactor", "design-decision"],
|
||||
}),
|
||||
"quick-task": orders({
|
||||
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
|
||||
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
engineer: ["small-change", "bug-investigation", "refactor", "add-a-test", "dependency-upgrade", "performance-problem", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "performance-problem", "add-a-test", "record-decision", "dependency-upgrade", "refactor"],
|
||||
architect: ["record-decision", "refactor", "small-change", "dependency-upgrade", "performance-problem", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "performance-problem", "add-a-test", "refactor", "dependency-upgrade", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "performance-problem", "small-change", "dependency-upgrade", "ui-polish", "refactor", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "dependency-upgrade", "add-a-test", "bug-investigation", "performance-problem", "refactor", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
||||
//
|
||||
// The source of truth for which workflows offer the switch, the instruction
|
||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
||||
// import this file.
|
||||
|
||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
||||
implement: Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"implement-review": Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"quick-task": Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
}),
|
||||
review: Object.freeze({
|
||||
instruction:
|
||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
||||
}),
|
||||
pathfinder: Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
}),
|
||||
});
|
||||
|
||||
export function offered(workflow) {
|
||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
||||
}
|
||||
|
||||
export const MAX_MIN = 1;
|
||||
export const MAX_MAX = 20;
|
||||
export const DEFAULT_MAX = 3;
|
||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
||||
export const HELPER_TITLE_MAX = 80;
|
||||
export const HELPER_ASK_MAX = 400;
|
||||
export const HELPER_RESULT_MAX = 200;
|
||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
export function defaultInstruction(workflow) {
|
||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
||||
}
|
||||
|
||||
// The person's own text when they wrote some, else the workflow's default.
|
||||
export function effectiveInstruction(setting) {
|
||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
||||
return own || defaultInstruction(setting && setting.workflow);
|
||||
}
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
export function cleanSetting(input) {
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
||||
let instruction = null;
|
||||
if (input.instruction !== null && input.instruction !== undefined) {
|
||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
||||
const trimmed = input.instruction.trim();
|
||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
||||
instruction = trimmed || null;
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// Only the first line of a block starts at column 0, so no line inside it can
|
||||
// be read as an entry of its own (NFR-5).
|
||||
export function onLines({ revision, replaces, max, instruction }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is owed at a pickup, given the session setting and the
|
||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
||||
* where `cursor` is what to write once the lines are printed. Never says
|
||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
||||
*/
|
||||
export function blockFor(setting, told) {
|
||||
const last = told || { revision: 0, state: "none" };
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
||||
|
||||
// The problems with one reported helper, [] when it is fine.
|
||||
export function checkHelper(entry) {
|
||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
||||
const who = `helper "${entry.id}"`;
|
||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
||||
const problems = [];
|
||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
||||
if (entry.result !== undefined) {
|
||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The problems with a whole merged list.
|
||||
export function checkHelpers(list) {
|
||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
let alone = 0;
|
||||
for (const entry of list) {
|
||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
||||
seen.add(entry.id);
|
||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
||||
}
|
||||
problems.push(...checkHelper(entry));
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the page */
|
||||
|
||||
// The page's rules for the button, the modal and the tab, kept here so they
|
||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
||||
// block; app.js only renders what these say.
|
||||
|
||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
||||
|
||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
||||
|
||||
// The switch shows only where the skill opts in AND the agent's console copy
|
||||
// said it can deliver it (FR-3).
|
||||
export function showSwitch(frame) {
|
||||
return Boolean(frame && frame.offered && frame.supported);
|
||||
}
|
||||
|
||||
// The button's tooltip and accessible name (FR-2).
|
||||
export function switchLabel(frame) {
|
||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
||||
}
|
||||
|
||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
||||
// in the order the agent reported them. A real helper supersedes the
|
||||
// working-alone marker, so the note only draws when no helper was ever
|
||||
// reported. A result shows once the helper ended.
|
||||
export function helperRows(helpers) {
|
||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
||||
const real = list.filter((h) => h.alone !== true);
|
||||
if (!real.length) return { alone: list.some((h) => h.alone === true), rows: [] };
|
||||
const rows = real.map(({ id, title, ask, state, result }) => ({
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
}));
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
||||
// helpers show even with the switch off (FR-11, FR-12).
|
||||
export function showTab(frame, helpers) {
|
||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
||||
}
|
||||
@@ -25,17 +25,21 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
SUBAGENTS_SETTING_FILE,
|
||||
UPDATE_CHECK_FILE,
|
||||
USER_MODELS_FILE,
|
||||
WORKSPACE_FILE,
|
||||
appendChat,
|
||||
appendEvent,
|
||||
chatForFrame,
|
||||
checkDocument,
|
||||
cleanupFindings,
|
||||
currentConversation,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
handleFile,
|
||||
initialWorkspace,
|
||||
latestOpenCaps,
|
||||
nowIso,
|
||||
parseArgs,
|
||||
pendingChatCount,
|
||||
@@ -44,21 +48,28 @@ import {
|
||||
readJson,
|
||||
readLedger,
|
||||
readOverview,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
writeSubagentSetting,
|
||||
writeWorkspace,
|
||||
} from "./lib.mjs";
|
||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
@@ -208,6 +219,7 @@ const SERVABLE = new Set([
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"start-stop.mp3",
|
||||
@@ -597,6 +609,48 @@ function ensureConversation(state) {
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
|
||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
||||
// says whether the agent's console copy can carry it. Both re-read only when
|
||||
// their file has moved.
|
||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
||||
|
||||
let subagentSettingSeen = { stamp: null, setting: null };
|
||||
function subagentSettingNow() {
|
||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
||||
return subagentSettingSeen.setting;
|
||||
}
|
||||
|
||||
let capsSeen = { stamp: null, caps: [] };
|
||||
function openCapsNow() {
|
||||
const stamp = fileStamp(EVENTS_PATH);
|
||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
||||
return capsSeen.caps;
|
||||
}
|
||||
|
||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
|
||||
/**
|
||||
* Turn the per-project store into this session's setting, for the workflow
|
||||
* the session is in now. The only place that happens (FR-7): a session an
|
||||
* older server ran has no setting file, so nothing is ever injected into it.
|
||||
* A record that already matches is left alone, revision and all, so a
|
||||
* restart alone never re-tells the agent anything.
|
||||
*/
|
||||
function syncSubagentSetting(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const current = readSubagentSetting(DIR);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
}
|
||||
|
||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||
// `have` names that exact view, for the page to hand back when it opens its
|
||||
// stream (see /events).
|
||||
@@ -611,19 +665,33 @@ function stateFrame(state) {
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
workspace: workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagentsView(state),
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
}
|
||||
|
||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
||||
// frame says both and leaves combining them to the page. `instruction: null`
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function subagentsView(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
||||
}
|
||||
|
||||
function haveKey() {
|
||||
const { pending, stop } = resultFlags();
|
||||
chatEntries();
|
||||
chatPickedUp();
|
||||
workspaceNow();
|
||||
ledgerEntries();
|
||||
subagentSettingNow();
|
||||
openCapsNow();
|
||||
return (
|
||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -648,6 +716,12 @@ function recordSubmitted(state, actions) {
|
||||
if (action.type === "comment") {
|
||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||
// The person's side of the Notes thread. Left to the agent it was never
|
||||
// written, so a question asked in a note vanished once it was picked up
|
||||
// and the reply under it answered nothing on the page.
|
||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const { i, type, ...rest } = action;
|
||||
@@ -933,6 +1007,38 @@ function pushState() {
|
||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- update check */
|
||||
|
||||
// The version this console was installed as: install.js writes version.json
|
||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
||||
function installedVersion() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return version;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filled in once the boot-time check answers; until then, and whenever it
|
||||
// fails, the frame carries no `update` and the page shows no banner.
|
||||
let updateInfo = null;
|
||||
let updateLatest = null;
|
||||
|
||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
||||
function startUpdateCheck() {
|
||||
const installed = installedVersion();
|
||||
if (!installed) return;
|
||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
||||
.then((result) => {
|
||||
updateLatest = result?.latest ?? null;
|
||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
||||
if (updateInfo) pushState();
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
let agentSeenAt = Date.now();
|
||||
function agentLastSeen() {
|
||||
return new Date(agentSeenAt).toISOString();
|
||||
@@ -1039,10 +1145,8 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
if (pathname === "/version" && req.method === "GET") {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||
}
|
||||
const version = installedVersion();
|
||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
||||
return json(res, 404, { error: "no version" });
|
||||
}
|
||||
|
||||
@@ -1090,7 +1194,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/draft" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||
// of someone's structured answers must not die with a closed tab.
|
||||
try {
|
||||
@@ -1115,7 +1219,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/looks" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// `set` carries only the keys one tab changed, merged onto what is on
|
||||
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||
@@ -1131,6 +1235,39 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// The Subagents switch for the session's workflow. Saved per project folder
|
||||
// for the next session, and applied to this one with a bumped revision, which
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
if (pathname === "/subagents" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
const clean = cleanSetting(body);
|
||||
if (clean.error) return json(res, 400, { error: clean.error });
|
||||
const { on, instruction, max } = clean;
|
||||
const current = readSubagentSetting(DIR);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
// The store is per project, so another session may have moved it since
|
||||
// this one synced: it always takes the person's latest pick. Only a
|
||||
// real change to this session's setting bumps what the agent hears.
|
||||
const unchanged = Boolean(current && sameSetting(current, next));
|
||||
try {
|
||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(DIR);
|
||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
||||
pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
@@ -1141,7 +1278,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
try {
|
||||
@@ -1154,6 +1291,24 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname === "/upload" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
const contentType = String(req.headers["content-type"] || "");
|
||||
@@ -1260,7 +1415,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/submit" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||
}
|
||||
@@ -1341,6 +1496,9 @@ const server = http.createServer((req, res) => {
|
||||
try {
|
||||
ensureConversation(written.state);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(written.state);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// Name the items that went. A page with OTHER answers staged should drop
|
||||
@@ -1361,6 +1519,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const state = readState() || {};
|
||||
const current = currentConversation(chatEntries()).conversation;
|
||||
@@ -1424,6 +1583,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||
@@ -1472,6 +1632,7 @@ const server = http.createServer((req, res) => {
|
||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
let answer;
|
||||
try {
|
||||
@@ -1489,6 +1650,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
||||
@@ -1589,15 +1751,19 @@ function readBody(req, cb) {
|
||||
let tooBig = false;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
||||
// never run and the page would see a reset instead of the 413 that names
|
||||
// the problem.
|
||||
if (size > MAX_BODY) {
|
||||
tooBig = true;
|
||||
req.destroy();
|
||||
chunks.length = 0;
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(new Error("too large"));
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
try {
|
||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (e) {
|
||||
@@ -1659,6 +1825,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
@@ -1833,7 +2002,13 @@ function onListening(port) {
|
||||
try {
|
||||
bootWorkspace();
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
} catch {}
|
||||
try {
|
||||
process.send?.({ type: "listening", port });
|
||||
} catch {}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
||||
//
|
||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
||||
// release tag is "latest". The server
|
||||
// starts this at boot and never waits on it; the answer, failures included, is
|
||||
// cached for an hour so a burst of sessions asks GitHub once.
|
||||
//
|
||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
||||
// with every prompt turned off so a missing login fails fast instead of
|
||||
// opening a window nobody asked for.
|
||||
//
|
||||
// Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
export const CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
||||
export function compareVersions(a, b) {
|
||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
||||
const x = a.split(".").map(Number);
|
||||
const y = b.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
||||
*/
|
||||
export function latestTag(text) {
|
||||
if (typeof text !== "string") return null;
|
||||
let best = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = TAG_REF.exec(line.trim());
|
||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readCache(cacheFile, now) {
|
||||
try {
|
||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
||||
return typeof cached.latest === "string" ? cached.latest : null;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(cacheFile, data) {
|
||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
||||
fs.renameSync(tmp, cacheFile);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
||||
* window, no prompt.
|
||||
*/
|
||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
||||
let child;
|
||||
try {
|
||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
env,
|
||||
});
|
||||
} catch {
|
||||
return resolve(null);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
done(null);
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
let out = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
out += chunk;
|
||||
});
|
||||
child.on("error", () => done(null));
|
||||
child.on("close", (code) => done(code === 0 ? out : null));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
||||
* not retried until the hour is up. Never throws.
|
||||
*/
|
||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
||||
try {
|
||||
let latest = readCache(cacheFile, now);
|
||||
if (latest === undefined) {
|
||||
latest = latestTag(await run());
|
||||
writeCache(cacheFile, { checkedAt: now, latest });
|
||||
}
|
||||
const order = compareVersions(installed, latest);
|
||||
if (latest === null || order === null) return null;
|
||||
return { installed, latest, updateAvailable: order < 0 };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -243,7 +243,7 @@ summarise it back.
|
||||
Then, in ONE `post`, do all of:
|
||||
|
||||
- mark each answered item `"status": "answered"` and record its `answer`
|
||||
- add your replies to any comment threads
|
||||
- reply to every note in that item's `thread` (shape below)
|
||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||
questions)
|
||||
- publish the next batch of questions
|
||||
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
|
||||
|
||||
One post is one atomic update, so the page never shows a half-changed state.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
A `comment` is the person talking to you about that card, often asking
|
||||
something. It shows in the card's **Notes on this** panel, and so does your
|
||||
answer:
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
||||
- The server writes their note into the thread as it arrives. Do not repeat
|
||||
it, and send only your new entries: `thread` appends.
|
||||
- Answer what they asked, in the thread, even when you also change a doc or
|
||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
||||
panel with no answer under it.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||
@@ -627,6 +647,87 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -661,9 +762,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
||||
run inline from another (a quick task's review) keeps the page it was
|
||||
handed. A
|
||||
fresh `open` would strand the page the person is watching on the dashboard's
|
||||
session while your questions went to a page nobody has open. Then run the
|
||||
skill normally: its Interface question was already answered by being
|
||||
launched, so start where its real work starts.
|
||||
session while your questions went to a page nobody has open.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
||||
> purpose — it exists to be read and followed inline, not launched as a
|
||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
||||
> strands the hand-off mid-launch.
|
||||
|
||||
Its Interface step is already answered by having been launched, so start
|
||||
where its real work starts.
|
||||
|
||||
The menu itself is the page's own list — you never send it. The page knows
|
||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||
@@ -735,7 +844,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -769,6 +881,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -829,6 +943,12 @@ know:
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
— the specs are untouched until Step 3's summary write — so a stop's finish
|
||||
@@ -859,7 +979,7 @@ question or doc lands:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
||||
what changed. A whole-file rewrite would put the entire session back into your
|
||||
context on every turn.
|
||||
|
||||
@@ -1112,6 +1232,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1133,7 +1263,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
@@ -1239,7 +1371,7 @@ answers were submitted but never picked up.
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -48,6 +49,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
@@ -487,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -536,6 +548,148 @@ export async function removeScratch(consoleDir, names) {
|
||||
return removed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- cleanup */
|
||||
|
||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
// rename -- and removing one mid-write loses another session's change.
|
||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
||||
|
||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
||||
async function diskBytes(p) {
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
if (!st.isDirectory()) return st.size;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
||||
* not kept, and -- only when the console runs from its default home inside
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
plan2codeDir = PLAN2CODE_DIR,
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
} catch {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||
@@ -871,7 +1025,7 @@ export function handOff(child, pre) {
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
@@ -896,7 +1050,7 @@ function mergeOne(target, patch, where) {
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread/comments append.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
@@ -955,11 +1109,60 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -996,12 +1199,23 @@ export function applyPatch(state, patch) {
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1048,15 +1262,11 @@ function stampTimes(before, next) {
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
for (const list of [next.items, next.docs]) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const entry of list) {
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
if (Array.isArray(entry.comments)) {
|
||||
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
@@ -1289,7 +1499,10 @@ export function validate(state) {
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
@@ -1297,6 +1510,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1553,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1353,6 +1581,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1808,6 +2038,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
|
||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||
* Any thread message from the send onwards, or none with a clock to compare,
|
||||
* means it has been picked up.
|
||||
* Any agent message from the send onwards, or one with no clock to compare,
|
||||
* means it has been picked up. The person's own entries never count: the
|
||||
* server writes their note into the thread as it arrives.
|
||||
*/
|
||||
export function noteAwaiting(item) {
|
||||
const n = item && item.sentNote;
|
||||
if (!n || typeof n !== "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
||||
return picked ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
||||
* and the server lifts anything else into it, but sessions written before that
|
||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
||||
*/
|
||||
export function threadWho(m) {
|
||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
||||
}
|
||||
|
||||
export function threadText(m) {
|
||||
if (!m) return "";
|
||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
--warn-soft: #fbe7e3;
|
||||
--focus: #1f6feb;
|
||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||
/* A soft accent halo for the things that want noticing: the update banner
|
||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||
@@ -61,6 +64,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +89,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -203,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1097,10 +1122,11 @@ h1 {
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. */
|
||||
.view-tab .tab-spin {
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
@@ -1424,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1657,11 +1707,13 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* Send breathes while there is something to send: a soft accent ring that
|
||||
spreads and fades. Off under reduced motion, below. */
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
||||
@keyframes send-pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: 0 0 0 6px transparent; }
|
||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
||||
}
|
||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
@@ -1963,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
@@ -2219,6 +2273,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal.help[open] { display: flex; }
|
||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||
.help-version a { color: inherit; }
|
||||
|
||||
.help-layout {
|
||||
display: grid;
|
||||
@@ -2668,6 +2723,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
@@ -3394,6 +3517,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
||||
.cleanup-list:empty { display: none; }
|
||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
||||
.cleanup-more { display: grid; gap: 4px; }
|
||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
||||
#cleanup-delete[hidden] { display: none; }
|
||||
|
||||
/* A word the person has to type, bold and in their highlight color so it
|
||||
does not get lost in the status sentence. */
|
||||
.agent-key {
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
submittedAwaiting,
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
threadText,
|
||||
threadWho,
|
||||
THUMB_EDGE,
|
||||
turnGate,
|
||||
verdictText,
|
||||
@@ -101,6 +103,15 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
||||
import { RED_BANNER } from "./meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||
import { faviconState, setFavicon } from "./favicon.js";
|
||||
import {
|
||||
CHECKIN_LINE,
|
||||
PATHFINDER_RESEARCH_LINE,
|
||||
defaultInstruction,
|
||||
helperRows,
|
||||
showSwitch,
|
||||
showTab,
|
||||
switchLabel,
|
||||
} from "./subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -446,6 +457,10 @@ document.addEventListener("click", (e) => {
|
||||
|
||||
|
||||
const GONE_AFTER_MS = 8000;
|
||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
||||
// failure, a refused send).
|
||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
@@ -521,6 +536,12 @@ let chatFrame = null;
|
||||
// sends them.
|
||||
let wsFrame = null;
|
||||
let meterFrame = null;
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
let updateFrame = null;
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
let subagentsFrame = null;
|
||||
let chatDot = false;
|
||||
let chatSending = false;
|
||||
let chatResetting = false;
|
||||
@@ -566,7 +587,6 @@ function fresh() {
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
sentAt: null,
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
@@ -870,10 +890,14 @@ function adopt(body) {
|
||||
chatFrame = body.chat || null;
|
||||
if (body.workspace) wsFrame = body.workspace;
|
||||
if (body.meter) meterFrame = body.meter;
|
||||
// Always replaced: an absent key means no update.
|
||||
updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
subagentsFrame = body.subagents || null;
|
||||
lastContact = Date.now();
|
||||
if (gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
}
|
||||
if (firstLoad) {
|
||||
load();
|
||||
@@ -1016,7 +1040,9 @@ function adopt(body) {
|
||||
render();
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
tellFolderIssues();
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||
// The Overview tab's file changes under a build, so a tab you are watching
|
||||
// refetches on every new frame too, not only on the click that opened it.
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
||||
if (announce) showArrival(announce);
|
||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||
// leaving the list parked where it was while it grew underneath.
|
||||
@@ -1149,15 +1175,12 @@ function markGone() {
|
||||
// of the server means there, and a banner promising a reconnect would
|
||||
// argue with it.
|
||||
if (!finish() && !stopInProgress()) {
|
||||
banner(
|
||||
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||
"warn"
|
||||
);
|
||||
banner(GONE_BANNER, "warn");
|
||||
}
|
||||
render();
|
||||
} else if (!bad && gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -1182,7 +1205,6 @@ function connect() {
|
||||
} catch {}
|
||||
});
|
||||
es.addEventListener("submitted", (e) => {
|
||||
local.sentAt = Date.now();
|
||||
// Drop only what was actually sent.
|
||||
//
|
||||
// This event fires for a send from ANY tab of this session, which is why it
|
||||
@@ -1293,6 +1315,7 @@ function render() {
|
||||
renderChrome();
|
||||
renderStatus();
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
@@ -1558,7 +1581,7 @@ function renderChrome() {
|
||||
renderMeter();
|
||||
$("title").textContent = S.title || "Session";
|
||||
$("badge").textContent = workflowLabel(S.workflow);
|
||||
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
renderTabTitle();
|
||||
|
||||
const h = S.headline || {};
|
||||
// On a finished session an open item is frozen: the send on it counts as
|
||||
@@ -1799,14 +1822,19 @@ async function sendBrief() {
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => banner(null), 5000);
|
||||
pendingResult = true;
|
||||
render();
|
||||
} catch {
|
||||
why.textContent = "That did not go through. Try again in a moment.";
|
||||
} catch (err) {
|
||||
if (err && err.pending) pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
@@ -1822,6 +1850,69 @@ function renderBriefButton() {
|
||||
if (offer) btn.disabled = gone || pendingResult;
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
function openSubagents() {
|
||||
if (!showSwitch(subagentsFrame)) return;
|
||||
const on = Boolean(subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
||||
$("subagents-max").value = String(subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
function renderViews() {
|
||||
const nav = $("views");
|
||||
nav.replaceChildren();
|
||||
@@ -1837,6 +1928,14 @@ function renderViews() {
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (view === "overview") view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
if (showTab(subagentsFrame, S.helpers)) {
|
||||
// From the rows the tab draws, so the badge never counts helpers the
|
||||
// working-alone note hides.
|
||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
||||
} else if (view === "subagents") view = "questions";
|
||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
||||
// a question the agent picked up and has not answered yet.
|
||||
@@ -2117,6 +2216,7 @@ function paintMain(main) {
|
||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||
if (view === "overview") return renderOverview(main);
|
||||
if (view === "ask") return renderAsk(main);
|
||||
if (view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
// the top of the rail. The hand-off lives here alone now, rather than
|
||||
@@ -2515,6 +2615,51 @@ function roleNudge() {
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function releasesLink(text) {
|
||||
const a = el("a", null, text);
|
||||
a.href = RELEASES_URL;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
return a;
|
||||
}
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
function renderDashboard(main) {
|
||||
maybeWake();
|
||||
const menu = (S && S.menu) || {};
|
||||
@@ -2526,6 +2671,25 @@ function renderDashboard(main) {
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
||||
} catch {}
|
||||
render();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||
@@ -3223,7 +3387,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
||||
function skipAndMoveOn(id) {
|
||||
cancelSkipMove();
|
||||
local.skipFlash = id;
|
||||
stage(id, { type: "skip", skipped: true });
|
||||
// A note already typed goes along: skipping the question is not retracting
|
||||
// the comment. Dropping it would leave the text in the box but out of the
|
||||
// send, which looks kept and is not.
|
||||
const cur = local.staged[id];
|
||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
||||
skipTimer = setTimeout(() => {
|
||||
skipTimer = null;
|
||||
local.skipFlash = null;
|
||||
@@ -3340,19 +3508,24 @@ function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"), a quick task as `tasks`; with neither the words stay plain.
|
||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
if (!list) return el("strong", "waiting-jump", word);
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
@@ -3366,8 +3539,8 @@ function renderWaiting(main) {
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump((list && list.title) || "Phase tasks"),
|
||||
" tab. If Plan2Code needs you, the question appears here on its own."
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
@@ -3505,8 +3678,8 @@ function renderSettled(card, item) {
|
||||
// would misreport which of the two was the answer.
|
||||
let prose = text;
|
||||
if (!prose && !lines.length) {
|
||||
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
||||
}
|
||||
|
||||
const nothing = !lines.length && !prose;
|
||||
@@ -4172,8 +4345,11 @@ function templateRow(item, input, entries, check) {
|
||||
save();
|
||||
paint();
|
||||
input.focus();
|
||||
const start = text.indexOf("[");
|
||||
const end = start < 0 ? -1 : text.indexOf("]", start);
|
||||
try {
|
||||
input.setSelectionRange(text.length, text.length);
|
||||
if (end > start) input.setSelectionRange(start, end + 1);
|
||||
else input.setSelectionRange(text.length, text.length);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
@@ -4322,6 +4498,10 @@ function buildChecklist(card, item, staged) {
|
||||
const commitList = (change) => {
|
||||
const cur = local.staged[item.id];
|
||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
||||
// card showed ticked steps on their way.
|
||||
delete next.skipped;
|
||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||
stage(item.id, empty ? null : next);
|
||||
};
|
||||
@@ -4371,7 +4551,7 @@ function buildChecklist(card, item, staged) {
|
||||
function buildMenu(card, item, staged) {
|
||||
const list = el("ul", "options");
|
||||
const name = "menu-" + item.id;
|
||||
for (const o of item.options || []) {
|
||||
for (const [i, o] of (item.options || []).entries()) {
|
||||
const picked = staged && staged.k === o.k;
|
||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||
const label = el("label");
|
||||
@@ -4379,7 +4559,13 @@ function buildMenu(card, item, staged) {
|
||||
const radio = el("input");
|
||||
radio.type = "radio";
|
||||
radio.name = name;
|
||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
||||
// input by id after the render this change() sets off, and without one a
|
||||
// keyboard user arrowing through the menu lands on <body> every time.
|
||||
radio.id = optionId(item, o, i);
|
||||
radio.value = o.k;
|
||||
radio.checked = Boolean(picked);
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||
const body = el("div", "option-body");
|
||||
const head = el("div", "option-label");
|
||||
@@ -4678,6 +4864,42 @@ function renderOverview(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ask */
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
@@ -5276,20 +5498,30 @@ function renderAside() {
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
box.appendChild(md(m.text, "md"));
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A note that has been sent but not yet picked up: shown at once, so the
|
||||
// send is seen to have gone, and gone when the agent replies.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
if (waiting) {
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
@@ -5589,7 +5821,10 @@ async function attachFiles(itemId, files) {
|
||||
const taken = wanted.slice(0, room);
|
||||
// One banner at a time, so every refusal goes into it, each by name.
|
||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||
if (taken.length < wanted.length)
|
||||
said.push(
|
||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
||||
);
|
||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||
await Promise.all(
|
||||
taken.map(async (file) => {
|
||||
@@ -5847,10 +6082,30 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
||||
// session opened before the server wrote `worktree` has nothing to show, so
|
||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||
// touched when the labels change, or when a resize clears the key.
|
||||
// The project's name: the workspace's original folder, or the session's
|
||||
// worktree folder before a frame carries the workspace.
|
||||
function projectName() {
|
||||
const folders = workspaceFolders();
|
||||
if (folders.length && folders[0].name) return folders[0].name;
|
||||
const path = (S && S.worktree) || "";
|
||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
||||
}
|
||||
|
||||
// The browser tab's title, led by the project so tabs from different
|
||||
// projects are told apart. Called from the chrome and the footer, since the
|
||||
// workspace frame can arrive after either.
|
||||
function renderTabTitle() {
|
||||
if (!S) return;
|
||||
const name = projectName();
|
||||
document.title =
|
||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
}
|
||||
|
||||
function renderWhere() {
|
||||
const b = $("footer-where");
|
||||
const folders = workspaceFolders();
|
||||
const path = S.worktree || "";
|
||||
renderTabTitle();
|
||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||
const labels = folders.length
|
||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||
@@ -5863,7 +6118,16 @@ function renderWhere() {
|
||||
let label = labels[0];
|
||||
for (const text of labels) {
|
||||
label = text;
|
||||
b.textContent = text;
|
||||
// The project name takes the highlight color, so several consoles side by
|
||||
// side tell apart at a glance; the rest of the label stays quiet.
|
||||
const name = projectName();
|
||||
b.textContent = "";
|
||||
if (name && text.startsWith(name)) {
|
||||
b.appendChild(el("span", "where-project", name));
|
||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
||||
} else {
|
||||
b.textContent = text;
|
||||
}
|
||||
if (alert) {
|
||||
const dot = el("span", "where-alert");
|
||||
dot.setAttribute("aria-hidden", "true");
|
||||
@@ -6439,6 +6703,10 @@ async function goHome() {
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
@@ -6499,6 +6767,7 @@ async function stopSession() {
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
@@ -6653,7 +6922,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||
}
|
||||
local.staged = {};
|
||||
local.sentAt = Date.now();
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -6706,7 +6974,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
||||
// something the agent never hears.
|
||||
function tokenFor(item, v) {
|
||||
const map = item.token || {};
|
||||
if (v.skipped) return "skip";
|
||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
||||
const parts = [];
|
||||
if (v.k) parts.push(map[v.k] || v.k);
|
||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||
@@ -6938,14 +7206,14 @@ function renderAbout() {
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const el = $("help-version");
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
el.textContent = version ? "Plan2Code v" + version : "";
|
||||
el.hidden = !version;
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
el.hidden = true;
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7053,6 +7321,7 @@ function openHelpOn(id) {
|
||||
}
|
||||
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
@@ -7083,6 +7352,7 @@ function lightDismiss(dlg) {
|
||||
});
|
||||
}
|
||||
lightDismiss($("looks-modal"));
|
||||
lightDismiss($("subagents-modal"));
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("workspace-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
@@ -7132,6 +7402,7 @@ $("btn-looks").addEventListener("click", () => {
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
resetCleanup();
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
@@ -7278,7 +7549,119 @@ $("models-reset").addEventListener("click", () => {
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const strays = items.length - sessions;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
||||
}
|
||||
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
@@ -39,6 +40,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
@@ -172,6 +173,18 @@
|
||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||
Write a brief
|
||||
</button>
|
||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
||||
opens the Subagents dialog and never toggles them itself. -->
|
||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -580,6 +593,13 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
<circle cx="18" cy="12" r="2" />
|
||||
<circle cx="18" cy="19" r="2" />
|
||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
||||
</symbol>
|
||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||
<path d="M8 9.5h8M8 12.5h5" />
|
||||
@@ -1291,6 +1311,14 @@
|
||||
come back, and you can change your role any time from the swatch
|
||||
button.
|
||||
</p>
|
||||
<h4>When an update is out</h4>
|
||||
<p>
|
||||
When a newer Plan2Code release is out, the dashboard shows
|
||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
||||
to run in your terminal; × hides it until the next
|
||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
||||
the Releases page.
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
@@ -1469,7 +1497,62 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 12: Ask a quick question -->
|
||||
<!-- Tab 12: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
||||
never switches helpers on or off by itself. Pick <strong>Use
|
||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
||||
shipped one back), and say how many may run at once.
|
||||
</li>
|
||||
<li>
|
||||
It is off by default and saved for this project and this skill, so
|
||||
the next session of the same skill here starts the same way.
|
||||
</li>
|
||||
<li>
|
||||
The change reaches Plan2Code at its next check-in, as a setting,
|
||||
not as something you typed. How many helpers it can really start is
|
||||
up to your agent; some have no helpers at all.
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
||||
Ask: one row each, with what it was asked, whether it is running, done
|
||||
or failed, and a one-line result at the end. The number on the tab is
|
||||
how many are still running.
|
||||
</li>
|
||||
<li>
|
||||
Helpers report through Plan2Code, so the rows change at its
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Working alone</strong> means your agent reported it has no
|
||||
way to start helpers here. If it starts one after all, the note
|
||||
goes away and the helper's row shows instead.
|
||||
</li>
|
||||
<li>
|
||||
Pathfinder always uses helpers for its research questions, whatever
|
||||
the switch says, and they show here too.
|
||||
</li>
|
||||
<li>The tab clears when you go back to the dashboard.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1560,7 +1643,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Stopping and finishing -->
|
||||
<!-- Tab 14: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1642,7 +1725,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: When something looks stuck -->
|
||||
<!-- Tab 15: When something looks stuck -->
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1764,7 +1847,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Keyboard and preferences -->
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1845,6 +1928,15 @@
|
||||
joining the strip. Keep only the ones you want; ticking a box plays
|
||||
its sound.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Back to default</strong> puts everything back as it was, and
|
||||
sets Role back to Not set.
|
||||
@@ -1871,7 +1963,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Privacy and where things are saved -->
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1908,7 +2000,11 @@
|
||||
</li>
|
||||
<li>
|
||||
your role, theme, colors, card width and sounds, in
|
||||
<code>looks.json</code>.
|
||||
<code>looks.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -1983,6 +2079,16 @@
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
@@ -2012,6 +2118,46 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
||||
its own, only a themed number box. -->
|
||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
||||
<h2 id="subagents-title">Subagents</h2>
|
||||
<p class="modal-blurb">
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
@@ -2181,6 +2327,24 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
||||
the copy row are filled by app.js; the update itself runs in a
|
||||
terminal, never from this page. -->
|
||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
||||
<p class="modal-blurb" id="update-versions"></p>
|
||||
<ol class="update-steps">
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||
Nothing to send yet.
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
// popover; this file owns the rules. No DOM access at module scope and no
|
||||
// imports: the page and `node --test` both import this file.
|
||||
|
||||
const NAME_CHAR = /[a-z0-9-]/;
|
||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
||||
// nothing and opens no suggestions at all.
|
||||
const NAME_CHAR = /[a-z0-9-]/i;
|
||||
const MAX_MATCHES = 6;
|
||||
|
||||
/**
|
||||
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
|
||||
}
|
||||
|
||||
// Names starting with the query first, then names containing it, in the
|
||||
// order given, at most six.
|
||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
||||
export function matchNames(names, query) {
|
||||
const q = String(query || "");
|
||||
const prefix = names.filter((n) => n.startsWith(q));
|
||||
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||
const q = String(query || "").toLowerCase();
|
||||
const fold = (n) => String(n).toLowerCase();
|
||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,85 +36,271 @@ export function needsRoleNudge(looks) {
|
||||
return !Object.hasOwn(looks, "role");
|
||||
}
|
||||
|
||||
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
|
||||
// The wording was revised in v2.5.1 (Markdown sections); a change is a page change.
|
||||
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
|
||||
|
||||
export const TEMPLATES = Object.freeze({
|
||||
"engineering-spec": template("engineering-spec", "Engineering spec", [
|
||||
"Engineering spec for: [the feature or change, in a sentence]",
|
||||
"Who reads it: the engineers who will build and review it.",
|
||||
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
|
||||
"What I already know: [constraints, links, earlier attempts]",
|
||||
"## Engineering spec",
|
||||
"[the feature or change, in a sentence]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineers who will build and review it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The behaviour, the parts of the code it touches, the interfaces between them, the simpler options we're turning down, and how we'll know it works.",
|
||||
"",
|
||||
"## Out of scope",
|
||||
"[what this deliberately won't do]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[constraints, links, earlier attempts]",
|
||||
]),
|
||||
"product-requirements": template("product-requirements", "Product requirements", [
|
||||
"Product requirements for: [the feature, in a sentence]",
|
||||
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
|
||||
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
|
||||
"What I already know: [customer asks, data, deadlines]",
|
||||
"## Product requirements",
|
||||
"[the feature, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"[the users], and the product, design and engineering people deciding on it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The problem, who has it, the evidence it's real, and how we'll measure success.",
|
||||
"",
|
||||
"## Not doing",
|
||||
"[what this release leaves out]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[customer asks, data, deadlines]",
|
||||
]),
|
||||
"design-decision": template("design-decision", "Design decision", [
|
||||
"A design decision to work out: [the choice we're facing, in a sentence]",
|
||||
"Who it's for: the engineers and architects who will live with it.",
|
||||
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"Constraints: [performance, compatibility, deadlines, team skills]",
|
||||
"## Design decision",
|
||||
"[the choice we're facing, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"The engineers and architects who will live with it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[performance, compatibility, deadlines, team skills]",
|
||||
]),
|
||||
"test-strategy": template("test-strategy", "Test strategy", [
|
||||
"Test strategy for: [the feature or area]",
|
||||
"Who reads it: QA and the engineers writing the tests.",
|
||||
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"What exists today: [current tests, known gaps]",
|
||||
"## Test strategy",
|
||||
"[the feature or area]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"QA and the engineers writing the tests.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
'What\'s riskiest, meaning what costs most if it breaks, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"",
|
||||
"## What exists today",
|
||||
"[current tests, known gaps]",
|
||||
]),
|
||||
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
|
||||
"Scoping and rollout for: [the feature or project]",
|
||||
"Who reads it: the engineering manager, the product lead and the team.",
|
||||
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
|
||||
"Constraints: [dates, people, dependencies]",
|
||||
"## Scoping and rollout",
|
||||
"[the feature or project]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineering manager, the product lead and the team.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"What's in the first release and what waits, the build order, risks to the timeline, how it reaches users (flags, stages, who sees it first), and how we roll it back.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[dates, people, dependencies]",
|
||||
]),
|
||||
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
|
||||
"Brainstorm to turn into curated notes: [the topic or rough idea]",
|
||||
"Who reads the notes: [the team or people this goes to]",
|
||||
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"Starting thoughts: [anything already on your mind]",
|
||||
"## Brainstorm to curated notes",
|
||||
"[the topic or rough idea]",
|
||||
"",
|
||||
"## Who reads the notes",
|
||||
"[the team or people this goes to]",
|
||||
"",
|
||||
"## What I want out of it",
|
||||
"The ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"",
|
||||
"## Starting thoughts",
|
||||
"[anything already on your mind]",
|
||||
]),
|
||||
"bug-investigation": template("bug-investigation", "Bug investigation", [
|
||||
"Bug to investigate: [what's going wrong, in a sentence]",
|
||||
"Steps to reproduce: [1. ... 2. ...]",
|
||||
"Expected: [what should happen]. Actual: [what happens instead]",
|
||||
"Where and since when: [environment, version, first seen]",
|
||||
"## Bug investigation",
|
||||
"[what's going wrong, in a sentence]",
|
||||
"",
|
||||
"## Steps to reproduce",
|
||||
"1. [first step]",
|
||||
"2. [next step]",
|
||||
"",
|
||||
"## Expected",
|
||||
"[what should happen]",
|
||||
"",
|
||||
"## Actual",
|
||||
"[what happens instead]",
|
||||
"",
|
||||
"## How often",
|
||||
"[every time, sometimes, once]",
|
||||
"",
|
||||
"## Error or logs",
|
||||
"[paste the exact text]",
|
||||
"",
|
||||
"## Where and since when",
|
||||
"[environment, version, first seen]",
|
||||
]),
|
||||
"small-change": template("small-change", "Small change", [
|
||||
"Small change: [what to change, in a sentence]",
|
||||
"Where: [the file, screen or command, if you know it]",
|
||||
"Done when: [how you'll tell it worked]",
|
||||
"## Small change",
|
||||
"[what to change, in a sentence]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the file, screen or command, if you know it]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not change]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the command to run or the thing to check]",
|
||||
]),
|
||||
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
|
||||
"Change the wording of: [the screen, message, email or doc]",
|
||||
"Current text: [paste it]",
|
||||
"New text: [paste it, or describe the tone you want]",
|
||||
"Who reads it: [the people who see it]",
|
||||
"## Copy or content tweak",
|
||||
"[the screen, message, email or doc]",
|
||||
"",
|
||||
"## Current text",
|
||||
"[paste it]",
|
||||
"",
|
||||
"## New text",
|
||||
"[paste it, or describe the tone you want]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"[the people who see it]",
|
||||
]),
|
||||
"ui-polish": template("ui-polish", "UI polish", [
|
||||
"UI polish on: [the screen or component]",
|
||||
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
|
||||
"What good looks like: [a reference, screenshot or description]",
|
||||
"Leave alone: [anything that must not move]",
|
||||
"## UI polish",
|
||||
"[the screen or component]",
|
||||
"",
|
||||
"## What looks or feels off",
|
||||
"[spacing, alignment, colour, states, small screens]",
|
||||
"",
|
||||
"## What good looks like",
|
||||
"[a reference, screenshot or description]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not move]",
|
||||
]),
|
||||
"visual-prototype": template("visual-prototype", "Visual prototype", [
|
||||
"A throwaway visual prototype of: [the screen or component]",
|
||||
"What to show: [the states or flows to click through]",
|
||||
"What I want to learn: [the question it should answer]",
|
||||
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
"## Visual prototype",
|
||||
"[the screen or component to mock up]",
|
||||
"",
|
||||
"## What to show",
|
||||
"[the states or flows to click through]",
|
||||
"",
|
||||
"## What I want to learn",
|
||||
"[the question it should answer]",
|
||||
"",
|
||||
"## Where it lives",
|
||||
"A prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
]),
|
||||
"add-a-test": template("add-a-test", "Add a test", [
|
||||
"Add a test for: [the function, behaviour or bug]",
|
||||
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
|
||||
"Where tests live: [the test file or folder, if you know it]",
|
||||
"## Add a test",
|
||||
"[the function, behaviour or bug]",
|
||||
"",
|
||||
"## Cases to cover",
|
||||
"- [the normal case]",
|
||||
"- [the edge cases]",
|
||||
"- [the failure or bug it guards against]",
|
||||
"",
|
||||
"## Where tests live",
|
||||
"[the test file or folder, if you know it]",
|
||||
]),
|
||||
"record-decision": template("record-decision", "Record a decision", [
|
||||
"Record a decision we've already made: [the decision, in a sentence]",
|
||||
"Why: [the reasons, and what we turned down]",
|
||||
"What it commits us to: [the consequences]",
|
||||
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
|
||||
"## Record a decision",
|
||||
"[the decision we've already made, in a sentence]",
|
||||
"",
|
||||
"## Why",
|
||||
"[what forced the choice, and the options we turned down]",
|
||||
"",
|
||||
"## What it commits us to",
|
||||
"[the consequences]",
|
||||
"",
|
||||
"## Save it in",
|
||||
"docs/adr/ [or wherever this repo keeps them]",
|
||||
]),
|
||||
refactor: template("refactor", "Refactor", [
|
||||
"## Refactor",
|
||||
"[what to restructure, in a sentence]",
|
||||
"",
|
||||
"## Why now",
|
||||
"[what the current shape makes hard]",
|
||||
"",
|
||||
"## Behaviour that must not change",
|
||||
"[the public API, outputs or tests that must stay the same]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the tests that must still pass, and the shape it ends in]",
|
||||
]),
|
||||
"performance-problem": template("performance-problem", "Performance problem", [
|
||||
"## Performance problem",
|
||||
"[what's slow, in a sentence]",
|
||||
"",
|
||||
"## How it's measured today",
|
||||
"[the number, and how you got it]",
|
||||
"",
|
||||
"## Target",
|
||||
"[the number that counts as fixed]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the endpoint, page, query or job]",
|
||||
]),
|
||||
"dependency-upgrade": template("dependency-upgrade", "Dependency upgrade", [
|
||||
"## Dependency upgrade",
|
||||
"[the package, from version to version]",
|
||||
"",
|
||||
"## Why",
|
||||
"[security fix, a feature we need, end of support]",
|
||||
"",
|
||||
"## Known breaking changes",
|
||||
'[release notes link, or "not checked yet"]',
|
||||
"",
|
||||
"## Done when",
|
||||
"[the build, tests or checks that must pass]",
|
||||
]),
|
||||
spike: template("spike", "Spike", [
|
||||
"## Spike",
|
||||
"[the question to answer, in a sentence]",
|
||||
"",
|
||||
"## Why it matters",
|
||||
"[the decision waiting on the answer]",
|
||||
"",
|
||||
"## Time box",
|
||||
"[how long before we stop and decide anyway]",
|
||||
"",
|
||||
"## Answered when",
|
||||
"[the evidence that would settle it]",
|
||||
]),
|
||||
integration: template("integration", "Integration", [
|
||||
"## Integration",
|
||||
"[the system we're connecting to, and why]",
|
||||
"",
|
||||
"## What flows",
|
||||
"[the data or events, and in which direction]",
|
||||
"",
|
||||
"## Their side",
|
||||
"[API docs, auth method, rate limits, test sandbox]",
|
||||
"",
|
||||
"## When it fails",
|
||||
"[what should happen if they're down or slow]",
|
||||
]),
|
||||
"data-migration": template("data-migration", "Data migration", [
|
||||
"## Data migration",
|
||||
"[what moves or changes shape]",
|
||||
"",
|
||||
"## Size and downtime",
|
||||
"[row counts, and whether users can stay on while it runs]",
|
||||
"",
|
||||
"## Rollback",
|
||||
"[how we undo it if it goes wrong]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the checks that prove nothing was lost]",
|
||||
]),
|
||||
});
|
||||
|
||||
@@ -123,28 +309,28 @@ const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRol
|
||||
// One full order per role per skill. No "none" row: Not set reads Engineer's.
|
||||
export const TEMPLATE_ORDERS = Object.freeze({
|
||||
pathfinder: orders({
|
||||
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
|
||||
engineer: ["engineering-spec", "design-decision", "spike", "integration", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "spike", "engineering-spec", "design-decision", "integration", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "integration", "spike", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "spike", "engineering-spec", "scoping-rollout", "integration", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "spike", "product-requirements", "integration", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "spike", "test-strategy", "design-decision", "integration", "brainstorm-notes"],
|
||||
}),
|
||||
plan: orders({
|
||||
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
|
||||
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
|
||||
engineer: ["engineering-spec", "bug-investigation", "refactor", "performance-problem", "integration", "data-migration", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "integration", "test-strategy", "design-decision", "performance-problem", "bug-investigation", "data-migration", "refactor"],
|
||||
architect: ["design-decision", "engineering-spec", "data-migration", "integration", "refactor", "scoping-rollout", "performance-problem", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "performance-problem", "test-strategy", "bug-investigation", "integration", "refactor", "data-migration"],
|
||||
qa: ["test-strategy", "bug-investigation", "performance-problem", "engineering-spec", "data-migration", "integration", "product-requirements", "scoping-rollout", "refactor", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "data-migration", "product-requirements", "test-strategy", "integration", "bug-investigation", "performance-problem", "refactor", "design-decision"],
|
||||
}),
|
||||
"quick-task": orders({
|
||||
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
|
||||
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
engineer: ["small-change", "bug-investigation", "refactor", "add-a-test", "dependency-upgrade", "performance-problem", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "performance-problem", "add-a-test", "record-decision", "dependency-upgrade", "refactor"],
|
||||
architect: ["record-decision", "refactor", "small-change", "dependency-upgrade", "performance-problem", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "performance-problem", "add-a-test", "refactor", "dependency-upgrade", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "performance-problem", "small-change", "dependency-upgrade", "ui-polish", "refactor", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "dependency-upgrade", "add-a-test", "bug-investigation", "performance-problem", "refactor", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
||||
//
|
||||
// The source of truth for which workflows offer the switch, the instruction
|
||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
||||
// import this file.
|
||||
|
||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
||||
implement: Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"implement-review": Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"quick-task": Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
}),
|
||||
review: Object.freeze({
|
||||
instruction:
|
||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
||||
}),
|
||||
pathfinder: Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
}),
|
||||
});
|
||||
|
||||
export function offered(workflow) {
|
||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
||||
}
|
||||
|
||||
export const MAX_MIN = 1;
|
||||
export const MAX_MAX = 20;
|
||||
export const DEFAULT_MAX = 3;
|
||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
||||
export const HELPER_TITLE_MAX = 80;
|
||||
export const HELPER_ASK_MAX = 400;
|
||||
export const HELPER_RESULT_MAX = 200;
|
||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
export function defaultInstruction(workflow) {
|
||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
||||
}
|
||||
|
||||
// The person's own text when they wrote some, else the workflow's default.
|
||||
export function effectiveInstruction(setting) {
|
||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
||||
return own || defaultInstruction(setting && setting.workflow);
|
||||
}
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
export function cleanSetting(input) {
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
||||
let instruction = null;
|
||||
if (input.instruction !== null && input.instruction !== undefined) {
|
||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
||||
const trimmed = input.instruction.trim();
|
||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
||||
instruction = trimmed || null;
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// Only the first line of a block starts at column 0, so no line inside it can
|
||||
// be read as an entry of its own (NFR-5).
|
||||
export function onLines({ revision, replaces, max, instruction }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is owed at a pickup, given the session setting and the
|
||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
||||
* where `cursor` is what to write once the lines are printed. Never says
|
||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
||||
*/
|
||||
export function blockFor(setting, told) {
|
||||
const last = told || { revision: 0, state: "none" };
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
||||
|
||||
// The problems with one reported helper, [] when it is fine.
|
||||
export function checkHelper(entry) {
|
||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
||||
const who = `helper "${entry.id}"`;
|
||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
||||
const problems = [];
|
||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
||||
if (entry.result !== undefined) {
|
||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The problems with a whole merged list.
|
||||
export function checkHelpers(list) {
|
||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
let alone = 0;
|
||||
for (const entry of list) {
|
||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
||||
seen.add(entry.id);
|
||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
||||
}
|
||||
problems.push(...checkHelper(entry));
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the page */
|
||||
|
||||
// The page's rules for the button, the modal and the tab, kept here so they
|
||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
||||
// block; app.js only renders what these say.
|
||||
|
||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
||||
|
||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
||||
|
||||
// The switch shows only where the skill opts in AND the agent's console copy
|
||||
// said it can deliver it (FR-3).
|
||||
export function showSwitch(frame) {
|
||||
return Boolean(frame && frame.offered && frame.supported);
|
||||
}
|
||||
|
||||
// The button's tooltip and accessible name (FR-2).
|
||||
export function switchLabel(frame) {
|
||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
||||
}
|
||||
|
||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
||||
// in the order the agent reported them. A real helper supersedes the
|
||||
// working-alone marker, so the note only draws when no helper was ever
|
||||
// reported. A result shows once the helper ended.
|
||||
export function helperRows(helpers) {
|
||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
||||
const real = list.filter((h) => h.alone !== true);
|
||||
if (!real.length) return { alone: list.some((h) => h.alone === true), rows: [] };
|
||||
const rows = real.map(({ id, title, ask, state, result }) => ({
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
}));
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
||||
// helpers show even with the switch off (FR-11, FR-12).
|
||||
export function showTab(frame, helpers) {
|
||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
||||
}
|
||||
@@ -25,17 +25,21 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
SUBAGENTS_SETTING_FILE,
|
||||
UPDATE_CHECK_FILE,
|
||||
USER_MODELS_FILE,
|
||||
WORKSPACE_FILE,
|
||||
appendChat,
|
||||
appendEvent,
|
||||
chatForFrame,
|
||||
checkDocument,
|
||||
cleanupFindings,
|
||||
currentConversation,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
handleFile,
|
||||
initialWorkspace,
|
||||
latestOpenCaps,
|
||||
nowIso,
|
||||
parseArgs,
|
||||
pendingChatCount,
|
||||
@@ -44,21 +48,28 @@ import {
|
||||
readJson,
|
||||
readLedger,
|
||||
readOverview,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
writeSubagentSetting,
|
||||
writeWorkspace,
|
||||
} from "./lib.mjs";
|
||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
@@ -208,6 +219,7 @@ const SERVABLE = new Set([
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"start-stop.mp3",
|
||||
@@ -597,6 +609,48 @@ function ensureConversation(state) {
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
|
||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
||||
// says whether the agent's console copy can carry it. Both re-read only when
|
||||
// their file has moved.
|
||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
||||
|
||||
let subagentSettingSeen = { stamp: null, setting: null };
|
||||
function subagentSettingNow() {
|
||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
||||
return subagentSettingSeen.setting;
|
||||
}
|
||||
|
||||
let capsSeen = { stamp: null, caps: [] };
|
||||
function openCapsNow() {
|
||||
const stamp = fileStamp(EVENTS_PATH);
|
||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
||||
return capsSeen.caps;
|
||||
}
|
||||
|
||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
|
||||
/**
|
||||
* Turn the per-project store into this session's setting, for the workflow
|
||||
* the session is in now. The only place that happens (FR-7): a session an
|
||||
* older server ran has no setting file, so nothing is ever injected into it.
|
||||
* A record that already matches is left alone, revision and all, so a
|
||||
* restart alone never re-tells the agent anything.
|
||||
*/
|
||||
function syncSubagentSetting(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const current = readSubagentSetting(DIR);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
}
|
||||
|
||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||
// `have` names that exact view, for the page to hand back when it opens its
|
||||
// stream (see /events).
|
||||
@@ -611,19 +665,33 @@ function stateFrame(state) {
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
workspace: workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagentsView(state),
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
}
|
||||
|
||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
||||
// frame says both and leaves combining them to the page. `instruction: null`
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function subagentsView(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
||||
}
|
||||
|
||||
function haveKey() {
|
||||
const { pending, stop } = resultFlags();
|
||||
chatEntries();
|
||||
chatPickedUp();
|
||||
workspaceNow();
|
||||
ledgerEntries();
|
||||
subagentSettingNow();
|
||||
openCapsNow();
|
||||
return (
|
||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -648,6 +716,12 @@ function recordSubmitted(state, actions) {
|
||||
if (action.type === "comment") {
|
||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||
// The person's side of the Notes thread. Left to the agent it was never
|
||||
// written, so a question asked in a note vanished once it was picked up
|
||||
// and the reply under it answered nothing on the page.
|
||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const { i, type, ...rest } = action;
|
||||
@@ -933,6 +1007,38 @@ function pushState() {
|
||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- update check */
|
||||
|
||||
// The version this console was installed as: install.js writes version.json
|
||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
||||
function installedVersion() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return version;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filled in once the boot-time check answers; until then, and whenever it
|
||||
// fails, the frame carries no `update` and the page shows no banner.
|
||||
let updateInfo = null;
|
||||
let updateLatest = null;
|
||||
|
||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
||||
function startUpdateCheck() {
|
||||
const installed = installedVersion();
|
||||
if (!installed) return;
|
||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
||||
.then((result) => {
|
||||
updateLatest = result?.latest ?? null;
|
||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
||||
if (updateInfo) pushState();
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
let agentSeenAt = Date.now();
|
||||
function agentLastSeen() {
|
||||
return new Date(agentSeenAt).toISOString();
|
||||
@@ -1039,10 +1145,8 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
if (pathname === "/version" && req.method === "GET") {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||
}
|
||||
const version = installedVersion();
|
||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
||||
return json(res, 404, { error: "no version" });
|
||||
}
|
||||
|
||||
@@ -1090,7 +1194,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/draft" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||
// of someone's structured answers must not die with a closed tab.
|
||||
try {
|
||||
@@ -1115,7 +1219,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/looks" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// `set` carries only the keys one tab changed, merged onto what is on
|
||||
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||
@@ -1131,6 +1235,39 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// The Subagents switch for the session's workflow. Saved per project folder
|
||||
// for the next session, and applied to this one with a bumped revision, which
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
if (pathname === "/subagents" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
const clean = cleanSetting(body);
|
||||
if (clean.error) return json(res, 400, { error: clean.error });
|
||||
const { on, instruction, max } = clean;
|
||||
const current = readSubagentSetting(DIR);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
// The store is per project, so another session may have moved it since
|
||||
// this one synced: it always takes the person's latest pick. Only a
|
||||
// real change to this session's setting bumps what the agent hears.
|
||||
const unchanged = Boolean(current && sameSetting(current, next));
|
||||
try {
|
||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(DIR);
|
||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
||||
pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
@@ -1141,7 +1278,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
try {
|
||||
@@ -1154,6 +1291,24 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname === "/upload" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
const contentType = String(req.headers["content-type"] || "");
|
||||
@@ -1260,7 +1415,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/submit" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||
}
|
||||
@@ -1341,6 +1496,9 @@ const server = http.createServer((req, res) => {
|
||||
try {
|
||||
ensureConversation(written.state);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(written.state);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// Name the items that went. A page with OTHER answers staged should drop
|
||||
@@ -1361,6 +1519,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const state = readState() || {};
|
||||
const current = currentConversation(chatEntries()).conversation;
|
||||
@@ -1424,6 +1583,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||
@@ -1472,6 +1632,7 @@ const server = http.createServer((req, res) => {
|
||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
let answer;
|
||||
try {
|
||||
@@ -1489,6 +1650,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
||||
@@ -1589,15 +1751,19 @@ function readBody(req, cb) {
|
||||
let tooBig = false;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
||||
// never run and the page would see a reset instead of the 413 that names
|
||||
// the problem.
|
||||
if (size > MAX_BODY) {
|
||||
tooBig = true;
|
||||
req.destroy();
|
||||
chunks.length = 0;
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(new Error("too large"));
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
try {
|
||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (e) {
|
||||
@@ -1659,6 +1825,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
@@ -1833,7 +2002,13 @@ function onListening(port) {
|
||||
try {
|
||||
bootWorkspace();
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
} catch {}
|
||||
try {
|
||||
process.send?.({ type: "listening", port });
|
||||
} catch {}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
||||
//
|
||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
||||
// release tag is "latest". The server
|
||||
// starts this at boot and never waits on it; the answer, failures included, is
|
||||
// cached for an hour so a burst of sessions asks GitHub once.
|
||||
//
|
||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
||||
// with every prompt turned off so a missing login fails fast instead of
|
||||
// opening a window nobody asked for.
|
||||
//
|
||||
// Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
export const CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
||||
export function compareVersions(a, b) {
|
||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
||||
const x = a.split(".").map(Number);
|
||||
const y = b.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
||||
*/
|
||||
export function latestTag(text) {
|
||||
if (typeof text !== "string") return null;
|
||||
let best = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = TAG_REF.exec(line.trim());
|
||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readCache(cacheFile, now) {
|
||||
try {
|
||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
||||
return typeof cached.latest === "string" ? cached.latest : null;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(cacheFile, data) {
|
||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
||||
fs.renameSync(tmp, cacheFile);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
||||
* window, no prompt.
|
||||
*/
|
||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
||||
let child;
|
||||
try {
|
||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
env,
|
||||
});
|
||||
} catch {
|
||||
return resolve(null);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
done(null);
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
let out = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
out += chunk;
|
||||
});
|
||||
child.on("error", () => done(null));
|
||||
child.on("close", (code) => done(code === 0 ? out : null));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
||||
* not retried until the hour is up. Never throws.
|
||||
*/
|
||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
||||
try {
|
||||
let latest = readCache(cacheFile, now);
|
||||
if (latest === undefined) {
|
||||
latest = latestTag(await run());
|
||||
writeCache(cacheFile, { checkedAt: now, latest });
|
||||
}
|
||||
const order = compareVersions(installed, latest);
|
||||
if (latest === null || order === null) return null;
|
||||
return { installed, latest, updateAvailable: order < 0 };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -243,7 +243,7 @@ summarise it back.
|
||||
Then, in ONE `post`, do all of:
|
||||
|
||||
- mark each answered item `"status": "answered"` and record its `answer`
|
||||
- add your replies to any comment threads
|
||||
- reply to every note in that item's `thread` (shape below)
|
||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||
questions)
|
||||
- publish the next batch of questions
|
||||
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
|
||||
|
||||
One post is one atomic update, so the page never shows a half-changed state.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
A `comment` is the person talking to you about that card, often asking
|
||||
something. It shows in the card's **Notes on this** panel, and so does your
|
||||
answer:
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
||||
- The server writes their note into the thread as it arrives. Do not repeat
|
||||
it, and send only your new entries: `thread` appends.
|
||||
- Answer what they asked, in the thread, even when you also change a doc or
|
||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
||||
panel with no answer under it.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||
@@ -627,6 +647,87 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -661,9 +762,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
||||
run inline from another (a quick task's review) keeps the page it was
|
||||
handed. A
|
||||
fresh `open` would strand the page the person is watching on the dashboard's
|
||||
session while your questions went to a page nobody has open. Then run the
|
||||
skill normally: its Interface question was already answered by being
|
||||
launched, so start where its real work starts.
|
||||
session while your questions went to a page nobody has open.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
||||
> purpose — it exists to be read and followed inline, not launched as a
|
||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
||||
> strands the hand-off mid-launch.
|
||||
|
||||
Its Interface step is already answered by having been launched, so start
|
||||
where its real work starts.
|
||||
|
||||
The menu itself is the page's own list — you never send it. The page knows
|
||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||
@@ -735,7 +844,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -769,6 +881,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -829,6 +943,12 @@ know:
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
— the specs are untouched until Step 3's summary write — so a stop's finish
|
||||
@@ -859,7 +979,7 @@ question or doc lands:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
||||
what changed. A whole-file rewrite would put the entire session back into your
|
||||
context on every turn.
|
||||
|
||||
@@ -1112,6 +1232,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1133,7 +1263,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
@@ -1239,7 +1371,7 @@ answers were submitted but never picked up.
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -48,6 +49,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
@@ -487,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -536,6 +548,148 @@ export async function removeScratch(consoleDir, names) {
|
||||
return removed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- cleanup */
|
||||
|
||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
// rename -- and removing one mid-write loses another session's change.
|
||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
||||
|
||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
||||
async function diskBytes(p) {
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
if (!st.isDirectory()) return st.size;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
||||
* not kept, and -- only when the console runs from its default home inside
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
plan2codeDir = PLAN2CODE_DIR,
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
} catch {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||
@@ -871,7 +1025,7 @@ export function handOff(child, pre) {
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
@@ -896,7 +1050,7 @@ function mergeOne(target, patch, where) {
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread/comments append.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
@@ -955,11 +1109,60 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -996,12 +1199,23 @@ export function applyPatch(state, patch) {
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1048,15 +1262,11 @@ function stampTimes(before, next) {
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
for (const list of [next.items, next.docs]) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const entry of list) {
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
if (Array.isArray(entry.comments)) {
|
||||
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
@@ -1289,7 +1499,10 @@ export function validate(state) {
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
@@ -1297,6 +1510,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1553,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1353,6 +1581,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1808,6 +2038,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
|
||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||
* Any thread message from the send onwards, or none with a clock to compare,
|
||||
* means it has been picked up.
|
||||
* Any agent message from the send onwards, or one with no clock to compare,
|
||||
* means it has been picked up. The person's own entries never count: the
|
||||
* server writes their note into the thread as it arrives.
|
||||
*/
|
||||
export function noteAwaiting(item) {
|
||||
const n = item && item.sentNote;
|
||||
if (!n || typeof n !== "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
||||
return picked ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
||||
* and the server lifts anything else into it, but sessions written before that
|
||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
||||
*/
|
||||
export function threadWho(m) {
|
||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
||||
}
|
||||
|
||||
export function threadText(m) {
|
||||
if (!m) return "";
|
||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
--warn-soft: #fbe7e3;
|
||||
--focus: #1f6feb;
|
||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||
/* A soft accent halo for the things that want noticing: the update banner
|
||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||
@@ -61,6 +64,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +89,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -203,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1097,10 +1122,11 @@ h1 {
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. */
|
||||
.view-tab .tab-spin {
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
@@ -1424,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1657,11 +1707,13 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* Send breathes while there is something to send: a soft accent ring that
|
||||
spreads and fades. Off under reduced motion, below. */
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
||||
@keyframes send-pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: 0 0 0 6px transparent; }
|
||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
||||
}
|
||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
@@ -1963,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
@@ -2219,6 +2273,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal.help[open] { display: flex; }
|
||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||
.help-version a { color: inherit; }
|
||||
|
||||
.help-layout {
|
||||
display: grid;
|
||||
@@ -2668,6 +2723,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
@@ -3394,6 +3517,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
||||
.cleanup-list:empty { display: none; }
|
||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
||||
.cleanup-more { display: grid; gap: 4px; }
|
||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
||||
#cleanup-delete[hidden] { display: none; }
|
||||
|
||||
/* A word the person has to type, bold and in their highlight color so it
|
||||
does not get lost in the status sentence. */
|
||||
.agent-key {
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
submittedAwaiting,
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
threadText,
|
||||
threadWho,
|
||||
THUMB_EDGE,
|
||||
turnGate,
|
||||
verdictText,
|
||||
@@ -101,6 +103,15 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
||||
import { RED_BANNER } from "./meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||
import { faviconState, setFavicon } from "./favicon.js";
|
||||
import {
|
||||
CHECKIN_LINE,
|
||||
PATHFINDER_RESEARCH_LINE,
|
||||
defaultInstruction,
|
||||
helperRows,
|
||||
showSwitch,
|
||||
showTab,
|
||||
switchLabel,
|
||||
} from "./subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -446,6 +457,10 @@ document.addEventListener("click", (e) => {
|
||||
|
||||
|
||||
const GONE_AFTER_MS = 8000;
|
||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
||||
// failure, a refused send).
|
||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
@@ -521,6 +536,12 @@ let chatFrame = null;
|
||||
// sends them.
|
||||
let wsFrame = null;
|
||||
let meterFrame = null;
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
let updateFrame = null;
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
let subagentsFrame = null;
|
||||
let chatDot = false;
|
||||
let chatSending = false;
|
||||
let chatResetting = false;
|
||||
@@ -566,7 +587,6 @@ function fresh() {
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
sentAt: null,
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
@@ -870,10 +890,14 @@ function adopt(body) {
|
||||
chatFrame = body.chat || null;
|
||||
if (body.workspace) wsFrame = body.workspace;
|
||||
if (body.meter) meterFrame = body.meter;
|
||||
// Always replaced: an absent key means no update.
|
||||
updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
subagentsFrame = body.subagents || null;
|
||||
lastContact = Date.now();
|
||||
if (gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
}
|
||||
if (firstLoad) {
|
||||
load();
|
||||
@@ -1016,7 +1040,9 @@ function adopt(body) {
|
||||
render();
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
tellFolderIssues();
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||
// The Overview tab's file changes under a build, so a tab you are watching
|
||||
// refetches on every new frame too, not only on the click that opened it.
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
||||
if (announce) showArrival(announce);
|
||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||
// leaving the list parked where it was while it grew underneath.
|
||||
@@ -1149,15 +1175,12 @@ function markGone() {
|
||||
// of the server means there, and a banner promising a reconnect would
|
||||
// argue with it.
|
||||
if (!finish() && !stopInProgress()) {
|
||||
banner(
|
||||
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||
"warn"
|
||||
);
|
||||
banner(GONE_BANNER, "warn");
|
||||
}
|
||||
render();
|
||||
} else if (!bad && gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -1182,7 +1205,6 @@ function connect() {
|
||||
} catch {}
|
||||
});
|
||||
es.addEventListener("submitted", (e) => {
|
||||
local.sentAt = Date.now();
|
||||
// Drop only what was actually sent.
|
||||
//
|
||||
// This event fires for a send from ANY tab of this session, which is why it
|
||||
@@ -1293,6 +1315,7 @@ function render() {
|
||||
renderChrome();
|
||||
renderStatus();
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
@@ -1558,7 +1581,7 @@ function renderChrome() {
|
||||
renderMeter();
|
||||
$("title").textContent = S.title || "Session";
|
||||
$("badge").textContent = workflowLabel(S.workflow);
|
||||
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
renderTabTitle();
|
||||
|
||||
const h = S.headline || {};
|
||||
// On a finished session an open item is frozen: the send on it counts as
|
||||
@@ -1799,14 +1822,19 @@ async function sendBrief() {
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => banner(null), 5000);
|
||||
pendingResult = true;
|
||||
render();
|
||||
} catch {
|
||||
why.textContent = "That did not go through. Try again in a moment.";
|
||||
} catch (err) {
|
||||
if (err && err.pending) pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
@@ -1822,6 +1850,69 @@ function renderBriefButton() {
|
||||
if (offer) btn.disabled = gone || pendingResult;
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
function openSubagents() {
|
||||
if (!showSwitch(subagentsFrame)) return;
|
||||
const on = Boolean(subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
||||
$("subagents-max").value = String(subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
function renderViews() {
|
||||
const nav = $("views");
|
||||
nav.replaceChildren();
|
||||
@@ -1837,6 +1928,14 @@ function renderViews() {
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (view === "overview") view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
if (showTab(subagentsFrame, S.helpers)) {
|
||||
// From the rows the tab draws, so the badge never counts helpers the
|
||||
// working-alone note hides.
|
||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
||||
} else if (view === "subagents") view = "questions";
|
||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
||||
// a question the agent picked up and has not answered yet.
|
||||
@@ -2117,6 +2216,7 @@ function paintMain(main) {
|
||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||
if (view === "overview") return renderOverview(main);
|
||||
if (view === "ask") return renderAsk(main);
|
||||
if (view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
// the top of the rail. The hand-off lives here alone now, rather than
|
||||
@@ -2515,6 +2615,51 @@ function roleNudge() {
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function releasesLink(text) {
|
||||
const a = el("a", null, text);
|
||||
a.href = RELEASES_URL;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
return a;
|
||||
}
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
function renderDashboard(main) {
|
||||
maybeWake();
|
||||
const menu = (S && S.menu) || {};
|
||||
@@ -2526,6 +2671,25 @@ function renderDashboard(main) {
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
||||
} catch {}
|
||||
render();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||
@@ -3223,7 +3387,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
||||
function skipAndMoveOn(id) {
|
||||
cancelSkipMove();
|
||||
local.skipFlash = id;
|
||||
stage(id, { type: "skip", skipped: true });
|
||||
// A note already typed goes along: skipping the question is not retracting
|
||||
// the comment. Dropping it would leave the text in the box but out of the
|
||||
// send, which looks kept and is not.
|
||||
const cur = local.staged[id];
|
||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
||||
skipTimer = setTimeout(() => {
|
||||
skipTimer = null;
|
||||
local.skipFlash = null;
|
||||
@@ -3340,19 +3508,24 @@ function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"), a quick task as `tasks`; with neither the words stay plain.
|
||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
if (!list) return el("strong", "waiting-jump", word);
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
@@ -3366,8 +3539,8 @@ function renderWaiting(main) {
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump((list && list.title) || "Phase tasks"),
|
||||
" tab. If Plan2Code needs you, the question appears here on its own."
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
@@ -3505,8 +3678,8 @@ function renderSettled(card, item) {
|
||||
// would misreport which of the two was the answer.
|
||||
let prose = text;
|
||||
if (!prose && !lines.length) {
|
||||
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
||||
}
|
||||
|
||||
const nothing = !lines.length && !prose;
|
||||
@@ -4172,8 +4345,11 @@ function templateRow(item, input, entries, check) {
|
||||
save();
|
||||
paint();
|
||||
input.focus();
|
||||
const start = text.indexOf("[");
|
||||
const end = start < 0 ? -1 : text.indexOf("]", start);
|
||||
try {
|
||||
input.setSelectionRange(text.length, text.length);
|
||||
if (end > start) input.setSelectionRange(start, end + 1);
|
||||
else input.setSelectionRange(text.length, text.length);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
@@ -4322,6 +4498,10 @@ function buildChecklist(card, item, staged) {
|
||||
const commitList = (change) => {
|
||||
const cur = local.staged[item.id];
|
||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
||||
// card showed ticked steps on their way.
|
||||
delete next.skipped;
|
||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||
stage(item.id, empty ? null : next);
|
||||
};
|
||||
@@ -4371,7 +4551,7 @@ function buildChecklist(card, item, staged) {
|
||||
function buildMenu(card, item, staged) {
|
||||
const list = el("ul", "options");
|
||||
const name = "menu-" + item.id;
|
||||
for (const o of item.options || []) {
|
||||
for (const [i, o] of (item.options || []).entries()) {
|
||||
const picked = staged && staged.k === o.k;
|
||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||
const label = el("label");
|
||||
@@ -4379,7 +4559,13 @@ function buildMenu(card, item, staged) {
|
||||
const radio = el("input");
|
||||
radio.type = "radio";
|
||||
radio.name = name;
|
||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
||||
// input by id after the render this change() sets off, and without one a
|
||||
// keyboard user arrowing through the menu lands on <body> every time.
|
||||
radio.id = optionId(item, o, i);
|
||||
radio.value = o.k;
|
||||
radio.checked = Boolean(picked);
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||
const body = el("div", "option-body");
|
||||
const head = el("div", "option-label");
|
||||
@@ -4678,6 +4864,42 @@ function renderOverview(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ask */
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
@@ -5276,20 +5498,30 @@ function renderAside() {
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
box.appendChild(md(m.text, "md"));
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A note that has been sent but not yet picked up: shown at once, so the
|
||||
// send is seen to have gone, and gone when the agent replies.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
if (waiting) {
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
@@ -5589,7 +5821,10 @@ async function attachFiles(itemId, files) {
|
||||
const taken = wanted.slice(0, room);
|
||||
// One banner at a time, so every refusal goes into it, each by name.
|
||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||
if (taken.length < wanted.length)
|
||||
said.push(
|
||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
||||
);
|
||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||
await Promise.all(
|
||||
taken.map(async (file) => {
|
||||
@@ -5847,10 +6082,30 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
||||
// session opened before the server wrote `worktree` has nothing to show, so
|
||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||
// touched when the labels change, or when a resize clears the key.
|
||||
// The project's name: the workspace's original folder, or the session's
|
||||
// worktree folder before a frame carries the workspace.
|
||||
function projectName() {
|
||||
const folders = workspaceFolders();
|
||||
if (folders.length && folders[0].name) return folders[0].name;
|
||||
const path = (S && S.worktree) || "";
|
||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
||||
}
|
||||
|
||||
// The browser tab's title, led by the project so tabs from different
|
||||
// projects are told apart. Called from the chrome and the footer, since the
|
||||
// workspace frame can arrive after either.
|
||||
function renderTabTitle() {
|
||||
if (!S) return;
|
||||
const name = projectName();
|
||||
document.title =
|
||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
}
|
||||
|
||||
function renderWhere() {
|
||||
const b = $("footer-where");
|
||||
const folders = workspaceFolders();
|
||||
const path = S.worktree || "";
|
||||
renderTabTitle();
|
||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||
const labels = folders.length
|
||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||
@@ -5863,7 +6118,16 @@ function renderWhere() {
|
||||
let label = labels[0];
|
||||
for (const text of labels) {
|
||||
label = text;
|
||||
b.textContent = text;
|
||||
// The project name takes the highlight color, so several consoles side by
|
||||
// side tell apart at a glance; the rest of the label stays quiet.
|
||||
const name = projectName();
|
||||
b.textContent = "";
|
||||
if (name && text.startsWith(name)) {
|
||||
b.appendChild(el("span", "where-project", name));
|
||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
||||
} else {
|
||||
b.textContent = text;
|
||||
}
|
||||
if (alert) {
|
||||
const dot = el("span", "where-alert");
|
||||
dot.setAttribute("aria-hidden", "true");
|
||||
@@ -6439,6 +6703,10 @@ async function goHome() {
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
@@ -6499,6 +6767,7 @@ async function stopSession() {
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
@@ -6653,7 +6922,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||
}
|
||||
local.staged = {};
|
||||
local.sentAt = Date.now();
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -6706,7 +6974,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
||||
// something the agent never hears.
|
||||
function tokenFor(item, v) {
|
||||
const map = item.token || {};
|
||||
if (v.skipped) return "skip";
|
||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
||||
const parts = [];
|
||||
if (v.k) parts.push(map[v.k] || v.k);
|
||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||
@@ -6938,14 +7206,14 @@ function renderAbout() {
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const el = $("help-version");
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
el.textContent = version ? "Plan2Code v" + version : "";
|
||||
el.hidden = !version;
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
el.hidden = true;
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7053,6 +7321,7 @@ function openHelpOn(id) {
|
||||
}
|
||||
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
@@ -7083,6 +7352,7 @@ function lightDismiss(dlg) {
|
||||
});
|
||||
}
|
||||
lightDismiss($("looks-modal"));
|
||||
lightDismiss($("subagents-modal"));
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("workspace-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
@@ -7132,6 +7402,7 @@ $("btn-looks").addEventListener("click", () => {
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
resetCleanup();
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
@@ -7278,7 +7549,119 @@ $("models-reset").addEventListener("click", () => {
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const strays = items.length - sessions;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
||||
}
|
||||
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
@@ -39,6 +40,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
@@ -172,6 +173,18 @@
|
||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||
Write a brief
|
||||
</button>
|
||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
||||
opens the Subagents dialog and never toggles them itself. -->
|
||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -580,6 +593,13 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
<circle cx="18" cy="12" r="2" />
|
||||
<circle cx="18" cy="19" r="2" />
|
||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
||||
</symbol>
|
||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||
<path d="M8 9.5h8M8 12.5h5" />
|
||||
@@ -1291,6 +1311,14 @@
|
||||
come back, and you can change your role any time from the swatch
|
||||
button.
|
||||
</p>
|
||||
<h4>When an update is out</h4>
|
||||
<p>
|
||||
When a newer Plan2Code release is out, the dashboard shows
|
||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
||||
to run in your terminal; × hides it until the next
|
||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
||||
the Releases page.
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
@@ -1469,7 +1497,62 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 12: Ask a quick question -->
|
||||
<!-- Tab 12: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
||||
never switches helpers on or off by itself. Pick <strong>Use
|
||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
||||
shipped one back), and say how many may run at once.
|
||||
</li>
|
||||
<li>
|
||||
It is off by default and saved for this project and this skill, so
|
||||
the next session of the same skill here starts the same way.
|
||||
</li>
|
||||
<li>
|
||||
The change reaches Plan2Code at its next check-in, as a setting,
|
||||
not as something you typed. How many helpers it can really start is
|
||||
up to your agent; some have no helpers at all.
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
||||
Ask: one row each, with what it was asked, whether it is running, done
|
||||
or failed, and a one-line result at the end. The number on the tab is
|
||||
how many are still running.
|
||||
</li>
|
||||
<li>
|
||||
Helpers report through Plan2Code, so the rows change at its
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Working alone</strong> means your agent reported it has no
|
||||
way to start helpers here. If it starts one after all, the note
|
||||
goes away and the helper's row shows instead.
|
||||
</li>
|
||||
<li>
|
||||
Pathfinder always uses helpers for its research questions, whatever
|
||||
the switch says, and they show here too.
|
||||
</li>
|
||||
<li>The tab clears when you go back to the dashboard.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1560,7 +1643,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Stopping and finishing -->
|
||||
<!-- Tab 14: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1642,7 +1725,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: When something looks stuck -->
|
||||
<!-- Tab 15: When something looks stuck -->
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1764,7 +1847,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Keyboard and preferences -->
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1845,6 +1928,15 @@
|
||||
joining the strip. Keep only the ones you want; ticking a box plays
|
||||
its sound.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Back to default</strong> puts everything back as it was, and
|
||||
sets Role back to Not set.
|
||||
@@ -1871,7 +1963,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Privacy and where things are saved -->
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1908,7 +2000,11 @@
|
||||
</li>
|
||||
<li>
|
||||
your role, theme, colors, card width and sounds, in
|
||||
<code>looks.json</code>.
|
||||
<code>looks.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -1983,6 +2079,16 @@
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
@@ -2012,6 +2118,46 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
||||
its own, only a themed number box. -->
|
||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
||||
<h2 id="subagents-title">Subagents</h2>
|
||||
<p class="modal-blurb">
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
@@ -2181,6 +2327,24 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
||||
the copy row are filled by app.js; the update itself runs in a
|
||||
terminal, never from this page. -->
|
||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
||||
<p class="modal-blurb" id="update-versions"></p>
|
||||
<ol class="update-steps">
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||
Nothing to send yet.
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
// popover; this file owns the rules. No DOM access at module scope and no
|
||||
// imports: the page and `node --test` both import this file.
|
||||
|
||||
const NAME_CHAR = /[a-z0-9-]/;
|
||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
||||
// nothing and opens no suggestions at all.
|
||||
const NAME_CHAR = /[a-z0-9-]/i;
|
||||
const MAX_MATCHES = 6;
|
||||
|
||||
/**
|
||||
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
|
||||
}
|
||||
|
||||
// Names starting with the query first, then names containing it, in the
|
||||
// order given, at most six.
|
||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
||||
export function matchNames(names, query) {
|
||||
const q = String(query || "");
|
||||
const prefix = names.filter((n) => n.startsWith(q));
|
||||
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||
const q = String(query || "").toLowerCase();
|
||||
const fold = (n) => String(n).toLowerCase();
|
||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,85 +36,271 @@ export function needsRoleNudge(looks) {
|
||||
return !Object.hasOwn(looks, "role");
|
||||
}
|
||||
|
||||
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
|
||||
// The wording was revised in v2.5.1 (Markdown sections); a change is a page change.
|
||||
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
|
||||
|
||||
export const TEMPLATES = Object.freeze({
|
||||
"engineering-spec": template("engineering-spec", "Engineering spec", [
|
||||
"Engineering spec for: [the feature or change, in a sentence]",
|
||||
"Who reads it: the engineers who will build and review it.",
|
||||
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
|
||||
"What I already know: [constraints, links, earlier attempts]",
|
||||
"## Engineering spec",
|
||||
"[the feature or change, in a sentence]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineers who will build and review it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The behaviour, the parts of the code it touches, the interfaces between them, the simpler options we're turning down, and how we'll know it works.",
|
||||
"",
|
||||
"## Out of scope",
|
||||
"[what this deliberately won't do]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[constraints, links, earlier attempts]",
|
||||
]),
|
||||
"product-requirements": template("product-requirements", "Product requirements", [
|
||||
"Product requirements for: [the feature, in a sentence]",
|
||||
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
|
||||
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
|
||||
"What I already know: [customer asks, data, deadlines]",
|
||||
"## Product requirements",
|
||||
"[the feature, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"[the users], and the product, design and engineering people deciding on it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The problem, who has it, the evidence it's real, and how we'll measure success.",
|
||||
"",
|
||||
"## Not doing",
|
||||
"[what this release leaves out]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[customer asks, data, deadlines]",
|
||||
]),
|
||||
"design-decision": template("design-decision", "Design decision", [
|
||||
"A design decision to work out: [the choice we're facing, in a sentence]",
|
||||
"Who it's for: the engineers and architects who will live with it.",
|
||||
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"Constraints: [performance, compatibility, deadlines, team skills]",
|
||||
"## Design decision",
|
||||
"[the choice we're facing, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"The engineers and architects who will live with it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[performance, compatibility, deadlines, team skills]",
|
||||
]),
|
||||
"test-strategy": template("test-strategy", "Test strategy", [
|
||||
"Test strategy for: [the feature or area]",
|
||||
"Who reads it: QA and the engineers writing the tests.",
|
||||
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"What exists today: [current tests, known gaps]",
|
||||
"## Test strategy",
|
||||
"[the feature or area]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"QA and the engineers writing the tests.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
'What\'s riskiest, meaning what costs most if it breaks, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"",
|
||||
"## What exists today",
|
||||
"[current tests, known gaps]",
|
||||
]),
|
||||
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
|
||||
"Scoping and rollout for: [the feature or project]",
|
||||
"Who reads it: the engineering manager, the product lead and the team.",
|
||||
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
|
||||
"Constraints: [dates, people, dependencies]",
|
||||
"## Scoping and rollout",
|
||||
"[the feature or project]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineering manager, the product lead and the team.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"What's in the first release and what waits, the build order, risks to the timeline, how it reaches users (flags, stages, who sees it first), and how we roll it back.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[dates, people, dependencies]",
|
||||
]),
|
||||
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
|
||||
"Brainstorm to turn into curated notes: [the topic or rough idea]",
|
||||
"Who reads the notes: [the team or people this goes to]",
|
||||
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"Starting thoughts: [anything already on your mind]",
|
||||
"## Brainstorm to curated notes",
|
||||
"[the topic or rough idea]",
|
||||
"",
|
||||
"## Who reads the notes",
|
||||
"[the team or people this goes to]",
|
||||
"",
|
||||
"## What I want out of it",
|
||||
"The ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"",
|
||||
"## Starting thoughts",
|
||||
"[anything already on your mind]",
|
||||
]),
|
||||
"bug-investigation": template("bug-investigation", "Bug investigation", [
|
||||
"Bug to investigate: [what's going wrong, in a sentence]",
|
||||
"Steps to reproduce: [1. ... 2. ...]",
|
||||
"Expected: [what should happen]. Actual: [what happens instead]",
|
||||
"Where and since when: [environment, version, first seen]",
|
||||
"## Bug investigation",
|
||||
"[what's going wrong, in a sentence]",
|
||||
"",
|
||||
"## Steps to reproduce",
|
||||
"1. [first step]",
|
||||
"2. [next step]",
|
||||
"",
|
||||
"## Expected",
|
||||
"[what should happen]",
|
||||
"",
|
||||
"## Actual",
|
||||
"[what happens instead]",
|
||||
"",
|
||||
"## How often",
|
||||
"[every time, sometimes, once]",
|
||||
"",
|
||||
"## Error or logs",
|
||||
"[paste the exact text]",
|
||||
"",
|
||||
"## Where and since when",
|
||||
"[environment, version, first seen]",
|
||||
]),
|
||||
"small-change": template("small-change", "Small change", [
|
||||
"Small change: [what to change, in a sentence]",
|
||||
"Where: [the file, screen or command, if you know it]",
|
||||
"Done when: [how you'll tell it worked]",
|
||||
"## Small change",
|
||||
"[what to change, in a sentence]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the file, screen or command, if you know it]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not change]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the command to run or the thing to check]",
|
||||
]),
|
||||
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
|
||||
"Change the wording of: [the screen, message, email or doc]",
|
||||
"Current text: [paste it]",
|
||||
"New text: [paste it, or describe the tone you want]",
|
||||
"Who reads it: [the people who see it]",
|
||||
"## Copy or content tweak",
|
||||
"[the screen, message, email or doc]",
|
||||
"",
|
||||
"## Current text",
|
||||
"[paste it]",
|
||||
"",
|
||||
"## New text",
|
||||
"[paste it, or describe the tone you want]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"[the people who see it]",
|
||||
]),
|
||||
"ui-polish": template("ui-polish", "UI polish", [
|
||||
"UI polish on: [the screen or component]",
|
||||
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
|
||||
"What good looks like: [a reference, screenshot or description]",
|
||||
"Leave alone: [anything that must not move]",
|
||||
"## UI polish",
|
||||
"[the screen or component]",
|
||||
"",
|
||||
"## What looks or feels off",
|
||||
"[spacing, alignment, colour, states, small screens]",
|
||||
"",
|
||||
"## What good looks like",
|
||||
"[a reference, screenshot or description]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not move]",
|
||||
]),
|
||||
"visual-prototype": template("visual-prototype", "Visual prototype", [
|
||||
"A throwaway visual prototype of: [the screen or component]",
|
||||
"What to show: [the states or flows to click through]",
|
||||
"What I want to learn: [the question it should answer]",
|
||||
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
"## Visual prototype",
|
||||
"[the screen or component to mock up]",
|
||||
"",
|
||||
"## What to show",
|
||||
"[the states or flows to click through]",
|
||||
"",
|
||||
"## What I want to learn",
|
||||
"[the question it should answer]",
|
||||
"",
|
||||
"## Where it lives",
|
||||
"A prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
]),
|
||||
"add-a-test": template("add-a-test", "Add a test", [
|
||||
"Add a test for: [the function, behaviour or bug]",
|
||||
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
|
||||
"Where tests live: [the test file or folder, if you know it]",
|
||||
"## Add a test",
|
||||
"[the function, behaviour or bug]",
|
||||
"",
|
||||
"## Cases to cover",
|
||||
"- [the normal case]",
|
||||
"- [the edge cases]",
|
||||
"- [the failure or bug it guards against]",
|
||||
"",
|
||||
"## Where tests live",
|
||||
"[the test file or folder, if you know it]",
|
||||
]),
|
||||
"record-decision": template("record-decision", "Record a decision", [
|
||||
"Record a decision we've already made: [the decision, in a sentence]",
|
||||
"Why: [the reasons, and what we turned down]",
|
||||
"What it commits us to: [the consequences]",
|
||||
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
|
||||
"## Record a decision",
|
||||
"[the decision we've already made, in a sentence]",
|
||||
"",
|
||||
"## Why",
|
||||
"[what forced the choice, and the options we turned down]",
|
||||
"",
|
||||
"## What it commits us to",
|
||||
"[the consequences]",
|
||||
"",
|
||||
"## Save it in",
|
||||
"docs/adr/ [or wherever this repo keeps them]",
|
||||
]),
|
||||
refactor: template("refactor", "Refactor", [
|
||||
"## Refactor",
|
||||
"[what to restructure, in a sentence]",
|
||||
"",
|
||||
"## Why now",
|
||||
"[what the current shape makes hard]",
|
||||
"",
|
||||
"## Behaviour that must not change",
|
||||
"[the public API, outputs or tests that must stay the same]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the tests that must still pass, and the shape it ends in]",
|
||||
]),
|
||||
"performance-problem": template("performance-problem", "Performance problem", [
|
||||
"## Performance problem",
|
||||
"[what's slow, in a sentence]",
|
||||
"",
|
||||
"## How it's measured today",
|
||||
"[the number, and how you got it]",
|
||||
"",
|
||||
"## Target",
|
||||
"[the number that counts as fixed]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the endpoint, page, query or job]",
|
||||
]),
|
||||
"dependency-upgrade": template("dependency-upgrade", "Dependency upgrade", [
|
||||
"## Dependency upgrade",
|
||||
"[the package, from version to version]",
|
||||
"",
|
||||
"## Why",
|
||||
"[security fix, a feature we need, end of support]",
|
||||
"",
|
||||
"## Known breaking changes",
|
||||
'[release notes link, or "not checked yet"]',
|
||||
"",
|
||||
"## Done when",
|
||||
"[the build, tests or checks that must pass]",
|
||||
]),
|
||||
spike: template("spike", "Spike", [
|
||||
"## Spike",
|
||||
"[the question to answer, in a sentence]",
|
||||
"",
|
||||
"## Why it matters",
|
||||
"[the decision waiting on the answer]",
|
||||
"",
|
||||
"## Time box",
|
||||
"[how long before we stop and decide anyway]",
|
||||
"",
|
||||
"## Answered when",
|
||||
"[the evidence that would settle it]",
|
||||
]),
|
||||
integration: template("integration", "Integration", [
|
||||
"## Integration",
|
||||
"[the system we're connecting to, and why]",
|
||||
"",
|
||||
"## What flows",
|
||||
"[the data or events, and in which direction]",
|
||||
"",
|
||||
"## Their side",
|
||||
"[API docs, auth method, rate limits, test sandbox]",
|
||||
"",
|
||||
"## When it fails",
|
||||
"[what should happen if they're down or slow]",
|
||||
]),
|
||||
"data-migration": template("data-migration", "Data migration", [
|
||||
"## Data migration",
|
||||
"[what moves or changes shape]",
|
||||
"",
|
||||
"## Size and downtime",
|
||||
"[row counts, and whether users can stay on while it runs]",
|
||||
"",
|
||||
"## Rollback",
|
||||
"[how we undo it if it goes wrong]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the checks that prove nothing was lost]",
|
||||
]),
|
||||
});
|
||||
|
||||
@@ -123,28 +309,28 @@ const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRol
|
||||
// One full order per role per skill. No "none" row: Not set reads Engineer's.
|
||||
export const TEMPLATE_ORDERS = Object.freeze({
|
||||
pathfinder: orders({
|
||||
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
|
||||
engineer: ["engineering-spec", "design-decision", "spike", "integration", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "spike", "engineering-spec", "design-decision", "integration", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "integration", "spike", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "spike", "engineering-spec", "scoping-rollout", "integration", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "spike", "product-requirements", "integration", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "spike", "test-strategy", "design-decision", "integration", "brainstorm-notes"],
|
||||
}),
|
||||
plan: orders({
|
||||
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
|
||||
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
|
||||
engineer: ["engineering-spec", "bug-investigation", "refactor", "performance-problem", "integration", "data-migration", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "integration", "test-strategy", "design-decision", "performance-problem", "bug-investigation", "data-migration", "refactor"],
|
||||
architect: ["design-decision", "engineering-spec", "data-migration", "integration", "refactor", "scoping-rollout", "performance-problem", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "performance-problem", "test-strategy", "bug-investigation", "integration", "refactor", "data-migration"],
|
||||
qa: ["test-strategy", "bug-investigation", "performance-problem", "engineering-spec", "data-migration", "integration", "product-requirements", "scoping-rollout", "refactor", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "data-migration", "product-requirements", "test-strategy", "integration", "bug-investigation", "performance-problem", "refactor", "design-decision"],
|
||||
}),
|
||||
"quick-task": orders({
|
||||
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
|
||||
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
engineer: ["small-change", "bug-investigation", "refactor", "add-a-test", "dependency-upgrade", "performance-problem", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "performance-problem", "add-a-test", "record-decision", "dependency-upgrade", "refactor"],
|
||||
architect: ["record-decision", "refactor", "small-change", "dependency-upgrade", "performance-problem", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "performance-problem", "add-a-test", "refactor", "dependency-upgrade", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "performance-problem", "small-change", "dependency-upgrade", "ui-polish", "refactor", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "dependency-upgrade", "add-a-test", "bug-investigation", "performance-problem", "refactor", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
||||
//
|
||||
// The source of truth for which workflows offer the switch, the instruction
|
||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
||||
// import this file.
|
||||
|
||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
||||
implement: Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"implement-review": Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"quick-task": Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
}),
|
||||
review: Object.freeze({
|
||||
instruction:
|
||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
||||
}),
|
||||
pathfinder: Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
}),
|
||||
});
|
||||
|
||||
export function offered(workflow) {
|
||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
||||
}
|
||||
|
||||
export const MAX_MIN = 1;
|
||||
export const MAX_MAX = 20;
|
||||
export const DEFAULT_MAX = 3;
|
||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
||||
export const HELPER_TITLE_MAX = 80;
|
||||
export const HELPER_ASK_MAX = 400;
|
||||
export const HELPER_RESULT_MAX = 200;
|
||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
export function defaultInstruction(workflow) {
|
||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
||||
}
|
||||
|
||||
// The person's own text when they wrote some, else the workflow's default.
|
||||
export function effectiveInstruction(setting) {
|
||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
||||
return own || defaultInstruction(setting && setting.workflow);
|
||||
}
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
export function cleanSetting(input) {
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
||||
let instruction = null;
|
||||
if (input.instruction !== null && input.instruction !== undefined) {
|
||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
||||
const trimmed = input.instruction.trim();
|
||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
||||
instruction = trimmed || null;
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// Only the first line of a block starts at column 0, so no line inside it can
|
||||
// be read as an entry of its own (NFR-5).
|
||||
export function onLines({ revision, replaces, max, instruction }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is owed at a pickup, given the session setting and the
|
||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
||||
* where `cursor` is what to write once the lines are printed. Never says
|
||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
||||
*/
|
||||
export function blockFor(setting, told) {
|
||||
const last = told || { revision: 0, state: "none" };
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
||||
|
||||
// The problems with one reported helper, [] when it is fine.
|
||||
export function checkHelper(entry) {
|
||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
||||
const who = `helper "${entry.id}"`;
|
||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
||||
const problems = [];
|
||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
||||
if (entry.result !== undefined) {
|
||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The problems with a whole merged list.
|
||||
export function checkHelpers(list) {
|
||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
let alone = 0;
|
||||
for (const entry of list) {
|
||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
||||
seen.add(entry.id);
|
||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
||||
}
|
||||
problems.push(...checkHelper(entry));
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the page */
|
||||
|
||||
// The page's rules for the button, the modal and the tab, kept here so they
|
||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
||||
// block; app.js only renders what these say.
|
||||
|
||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
||||
|
||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
||||
|
||||
// The switch shows only where the skill opts in AND the agent's console copy
|
||||
// said it can deliver it (FR-3).
|
||||
export function showSwitch(frame) {
|
||||
return Boolean(frame && frame.offered && frame.supported);
|
||||
}
|
||||
|
||||
// The button's tooltip and accessible name (FR-2).
|
||||
export function switchLabel(frame) {
|
||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
||||
}
|
||||
|
||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
||||
// in the order the agent reported them. A real helper supersedes the
|
||||
// working-alone marker, so the note only draws when no helper was ever
|
||||
// reported. A result shows once the helper ended.
|
||||
export function helperRows(helpers) {
|
||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
||||
const real = list.filter((h) => h.alone !== true);
|
||||
if (!real.length) return { alone: list.some((h) => h.alone === true), rows: [] };
|
||||
const rows = real.map(({ id, title, ask, state, result }) => ({
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
}));
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
||||
// helpers show even with the switch off (FR-11, FR-12).
|
||||
export function showTab(frame, helpers) {
|
||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
||||
}
|
||||
@@ -25,17 +25,21 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
SUBAGENTS_SETTING_FILE,
|
||||
UPDATE_CHECK_FILE,
|
||||
USER_MODELS_FILE,
|
||||
WORKSPACE_FILE,
|
||||
appendChat,
|
||||
appendEvent,
|
||||
chatForFrame,
|
||||
checkDocument,
|
||||
cleanupFindings,
|
||||
currentConversation,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
handleFile,
|
||||
initialWorkspace,
|
||||
latestOpenCaps,
|
||||
nowIso,
|
||||
parseArgs,
|
||||
pendingChatCount,
|
||||
@@ -44,21 +48,28 @@ import {
|
||||
readJson,
|
||||
readLedger,
|
||||
readOverview,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
writeSubagentSetting,
|
||||
writeWorkspace,
|
||||
} from "./lib.mjs";
|
||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
@@ -208,6 +219,7 @@ const SERVABLE = new Set([
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"start-stop.mp3",
|
||||
@@ -597,6 +609,48 @@ function ensureConversation(state) {
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
|
||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
||||
// says whether the agent's console copy can carry it. Both re-read only when
|
||||
// their file has moved.
|
||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
||||
|
||||
let subagentSettingSeen = { stamp: null, setting: null };
|
||||
function subagentSettingNow() {
|
||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
||||
return subagentSettingSeen.setting;
|
||||
}
|
||||
|
||||
let capsSeen = { stamp: null, caps: [] };
|
||||
function openCapsNow() {
|
||||
const stamp = fileStamp(EVENTS_PATH);
|
||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
||||
return capsSeen.caps;
|
||||
}
|
||||
|
||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
|
||||
/**
|
||||
* Turn the per-project store into this session's setting, for the workflow
|
||||
* the session is in now. The only place that happens (FR-7): a session an
|
||||
* older server ran has no setting file, so nothing is ever injected into it.
|
||||
* A record that already matches is left alone, revision and all, so a
|
||||
* restart alone never re-tells the agent anything.
|
||||
*/
|
||||
function syncSubagentSetting(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const current = readSubagentSetting(DIR);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
}
|
||||
|
||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||
// `have` names that exact view, for the page to hand back when it opens its
|
||||
// stream (see /events).
|
||||
@@ -611,19 +665,33 @@ function stateFrame(state) {
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
workspace: workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagentsView(state),
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
}
|
||||
|
||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
||||
// frame says both and leaves combining them to the page. `instruction: null`
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function subagentsView(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
||||
}
|
||||
|
||||
function haveKey() {
|
||||
const { pending, stop } = resultFlags();
|
||||
chatEntries();
|
||||
chatPickedUp();
|
||||
workspaceNow();
|
||||
ledgerEntries();
|
||||
subagentSettingNow();
|
||||
openCapsNow();
|
||||
return (
|
||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -648,6 +716,12 @@ function recordSubmitted(state, actions) {
|
||||
if (action.type === "comment") {
|
||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||
// The person's side of the Notes thread. Left to the agent it was never
|
||||
// written, so a question asked in a note vanished once it was picked up
|
||||
// and the reply under it answered nothing on the page.
|
||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const { i, type, ...rest } = action;
|
||||
@@ -933,6 +1007,38 @@ function pushState() {
|
||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- update check */
|
||||
|
||||
// The version this console was installed as: install.js writes version.json
|
||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
||||
function installedVersion() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return version;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filled in once the boot-time check answers; until then, and whenever it
|
||||
// fails, the frame carries no `update` and the page shows no banner.
|
||||
let updateInfo = null;
|
||||
let updateLatest = null;
|
||||
|
||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
||||
function startUpdateCheck() {
|
||||
const installed = installedVersion();
|
||||
if (!installed) return;
|
||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
||||
.then((result) => {
|
||||
updateLatest = result?.latest ?? null;
|
||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
||||
if (updateInfo) pushState();
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
let agentSeenAt = Date.now();
|
||||
function agentLastSeen() {
|
||||
return new Date(agentSeenAt).toISOString();
|
||||
@@ -1039,10 +1145,8 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
if (pathname === "/version" && req.method === "GET") {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||
}
|
||||
const version = installedVersion();
|
||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
||||
return json(res, 404, { error: "no version" });
|
||||
}
|
||||
|
||||
@@ -1090,7 +1194,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/draft" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||
// of someone's structured answers must not die with a closed tab.
|
||||
try {
|
||||
@@ -1115,7 +1219,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/looks" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// `set` carries only the keys one tab changed, merged onto what is on
|
||||
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||
@@ -1131,6 +1235,39 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// The Subagents switch for the session's workflow. Saved per project folder
|
||||
// for the next session, and applied to this one with a bumped revision, which
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
if (pathname === "/subagents" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
const clean = cleanSetting(body);
|
||||
if (clean.error) return json(res, 400, { error: clean.error });
|
||||
const { on, instruction, max } = clean;
|
||||
const current = readSubagentSetting(DIR);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
// The store is per project, so another session may have moved it since
|
||||
// this one synced: it always takes the person's latest pick. Only a
|
||||
// real change to this session's setting bumps what the agent hears.
|
||||
const unchanged = Boolean(current && sameSetting(current, next));
|
||||
try {
|
||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(DIR);
|
||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
||||
pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
@@ -1141,7 +1278,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
try {
|
||||
@@ -1154,6 +1291,24 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname === "/upload" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
const contentType = String(req.headers["content-type"] || "");
|
||||
@@ -1260,7 +1415,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/submit" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||
}
|
||||
@@ -1341,6 +1496,9 @@ const server = http.createServer((req, res) => {
|
||||
try {
|
||||
ensureConversation(written.state);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(written.state);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// Name the items that went. A page with OTHER answers staged should drop
|
||||
@@ -1361,6 +1519,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const state = readState() || {};
|
||||
const current = currentConversation(chatEntries()).conversation;
|
||||
@@ -1424,6 +1583,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||
@@ -1472,6 +1632,7 @@ const server = http.createServer((req, res) => {
|
||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
let answer;
|
||||
try {
|
||||
@@ -1489,6 +1650,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
||||
@@ -1589,15 +1751,19 @@ function readBody(req, cb) {
|
||||
let tooBig = false;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
||||
// never run and the page would see a reset instead of the 413 that names
|
||||
// the problem.
|
||||
if (size > MAX_BODY) {
|
||||
tooBig = true;
|
||||
req.destroy();
|
||||
chunks.length = 0;
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(new Error("too large"));
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
try {
|
||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (e) {
|
||||
@@ -1659,6 +1825,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
@@ -1833,7 +2002,13 @@ function onListening(port) {
|
||||
try {
|
||||
bootWorkspace();
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
} catch {}
|
||||
try {
|
||||
process.send?.({ type: "listening", port });
|
||||
} catch {}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
||||
//
|
||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
||||
// release tag is "latest". The server
|
||||
// starts this at boot and never waits on it; the answer, failures included, is
|
||||
// cached for an hour so a burst of sessions asks GitHub once.
|
||||
//
|
||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
||||
// with every prompt turned off so a missing login fails fast instead of
|
||||
// opening a window nobody asked for.
|
||||
//
|
||||
// Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
export const CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
||||
export function compareVersions(a, b) {
|
||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
||||
const x = a.split(".").map(Number);
|
||||
const y = b.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
||||
*/
|
||||
export function latestTag(text) {
|
||||
if (typeof text !== "string") return null;
|
||||
let best = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = TAG_REF.exec(line.trim());
|
||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readCache(cacheFile, now) {
|
||||
try {
|
||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
||||
return typeof cached.latest === "string" ? cached.latest : null;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(cacheFile, data) {
|
||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
||||
fs.renameSync(tmp, cacheFile);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
||||
* window, no prompt.
|
||||
*/
|
||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
||||
let child;
|
||||
try {
|
||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
env,
|
||||
});
|
||||
} catch {
|
||||
return resolve(null);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
done(null);
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
let out = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
out += chunk;
|
||||
});
|
||||
child.on("error", () => done(null));
|
||||
child.on("close", (code) => done(code === 0 ? out : null));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
||||
* not retried until the hour is up. Never throws.
|
||||
*/
|
||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
||||
try {
|
||||
let latest = readCache(cacheFile, now);
|
||||
if (latest === undefined) {
|
||||
latest = latestTag(await run());
|
||||
writeCache(cacheFile, { checkedAt: now, latest });
|
||||
}
|
||||
const order = compareVersions(installed, latest);
|
||||
if (latest === null || order === null) return null;
|
||||
return { installed, latest, updateAvailable: order < 0 };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -39,10 +39,10 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
| Scope | Trigger | Reviews |
|
||||
|-------|---------|---------|
|
||||
| **Focused** | User names files/functions, or conversation work detected | Specified files only |
|
||||
| **Branch** | "review my changes" or no context available | Branch changes vs main |
|
||||
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
|
||||
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
|
||||
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Fallback = `branch`. Ambiguous? Ask.
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
|
||||
|
||||
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
|
||||
|
||||
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
## Process
|
||||
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, use `ask_user_question` — never guess.
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
|
||||
|
||||
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
|
||||
|
||||
@@ -62,7 +62,8 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
1. **User prompt** — use it.
|
||||
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
|
||||
3. **Git fallback** — run `review-scope.mjs`. It compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
|
||||
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
|
||||
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
|
||||
|
||||
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -243,7 +243,7 @@ summarise it back.
|
||||
Then, in ONE `post`, do all of:
|
||||
|
||||
- mark each answered item `"status": "answered"` and record its `answer`
|
||||
- add your replies to any comment threads
|
||||
- reply to every note in that item's `thread` (shape below)
|
||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||
questions)
|
||||
- publish the next batch of questions
|
||||
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
|
||||
|
||||
One post is one atomic update, so the page never shows a half-changed state.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
A `comment` is the person talking to you about that card, often asking
|
||||
something. It shows in the card's **Notes on this** panel, and so does your
|
||||
answer:
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
||||
- The server writes their note into the thread as it arrives. Do not repeat
|
||||
it, and send only your new entries: `thread` appends.
|
||||
- Answer what they asked, in the thread, even when you also change a doc or
|
||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
||||
panel with no answer under it.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||
@@ -627,6 +647,87 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -661,9 +762,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
||||
run inline from another (a quick task's review) keeps the page it was
|
||||
handed. A
|
||||
fresh `open` would strand the page the person is watching on the dashboard's
|
||||
session while your questions went to a page nobody has open. Then run the
|
||||
skill normally: its Interface question was already answered by being
|
||||
launched, so start where its real work starts.
|
||||
session while your questions went to a page nobody has open.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
||||
> purpose — it exists to be read and followed inline, not launched as a
|
||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
||||
> strands the hand-off mid-launch.
|
||||
|
||||
Its Interface step is already answered by having been launched, so start
|
||||
where its real work starts.
|
||||
|
||||
The menu itself is the page's own list — you never send it. The page knows
|
||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||
@@ -735,7 +844,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -769,6 +881,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -829,6 +943,12 @@ know:
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
— the specs are untouched until Step 3's summary write — so a stop's finish
|
||||
@@ -859,7 +979,7 @@ question or doc lands:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
||||
what changed. A whole-file rewrite would put the entire session back into your
|
||||
context on every turn.
|
||||
|
||||
@@ -1112,6 +1232,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1133,7 +1263,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
@@ -1239,7 +1371,7 @@ answers were submitted but never picked up.
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -48,6 +49,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
@@ -487,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -536,6 +548,148 @@ export async function removeScratch(consoleDir, names) {
|
||||
return removed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- cleanup */
|
||||
|
||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
// rename -- and removing one mid-write loses another session's change.
|
||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
||||
|
||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
||||
async function diskBytes(p) {
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
if (!st.isDirectory()) return st.size;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
||||
* not kept, and -- only when the console runs from its default home inside
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
plan2codeDir = PLAN2CODE_DIR,
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
} catch {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||
@@ -871,7 +1025,7 @@ export function handOff(child, pre) {
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
@@ -896,7 +1050,7 @@ function mergeOne(target, patch, where) {
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread/comments append.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
@@ -955,11 +1109,60 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -996,12 +1199,23 @@ export function applyPatch(state, patch) {
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1048,15 +1262,11 @@ function stampTimes(before, next) {
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
for (const list of [next.items, next.docs]) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const entry of list) {
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
if (Array.isArray(entry.comments)) {
|
||||
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
@@ -1289,7 +1499,10 @@ export function validate(state) {
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
@@ -1297,6 +1510,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1553,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1353,6 +1581,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1808,6 +2038,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
|
||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||
* Any thread message from the send onwards, or none with a clock to compare,
|
||||
* means it has been picked up.
|
||||
* Any agent message from the send onwards, or one with no clock to compare,
|
||||
* means it has been picked up. The person's own entries never count: the
|
||||
* server writes their note into the thread as it arrives.
|
||||
*/
|
||||
export function noteAwaiting(item) {
|
||||
const n = item && item.sentNote;
|
||||
if (!n || typeof n !== "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
||||
return picked ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
||||
* and the server lifts anything else into it, but sessions written before that
|
||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
||||
*/
|
||||
export function threadWho(m) {
|
||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
||||
}
|
||||
|
||||
export function threadText(m) {
|
||||
if (!m) return "";
|
||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
--warn-soft: #fbe7e3;
|
||||
--focus: #1f6feb;
|
||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||
/* A soft accent halo for the things that want noticing: the update banner
|
||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||
@@ -61,6 +64,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +89,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -203,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1097,10 +1122,11 @@ h1 {
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. */
|
||||
.view-tab .tab-spin {
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
@@ -1424,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1657,11 +1707,13 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* Send breathes while there is something to send: a soft accent ring that
|
||||
spreads and fades. Off under reduced motion, below. */
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
||||
@keyframes send-pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: 0 0 0 6px transparent; }
|
||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
||||
}
|
||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
@@ -1963,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
@@ -2219,6 +2273,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal.help[open] { display: flex; }
|
||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||
.help-version a { color: inherit; }
|
||||
|
||||
.help-layout {
|
||||
display: grid;
|
||||
@@ -2668,6 +2723,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
@@ -3394,6 +3517,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
||||
.cleanup-list:empty { display: none; }
|
||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
||||
.cleanup-more { display: grid; gap: 4px; }
|
||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
||||
#cleanup-delete[hidden] { display: none; }
|
||||
|
||||
/* A word the person has to type, bold and in their highlight color so it
|
||||
does not get lost in the status sentence. */
|
||||
.agent-key {
|
||||
|
||||
@@ -66,6 +66,8 @@ import {
|
||||
submittedAwaiting,
|
||||
noteAwaiting,
|
||||
suggestionFrom,
|
||||
threadText,
|
||||
threadWho,
|
||||
THUMB_EDGE,
|
||||
turnGate,
|
||||
verdictText,
|
||||
@@ -101,6 +103,15 @@ import { FOOTER_TIERS, footerLabel, nameProblem } from "./workspace.js";
|
||||
import { RED_BANNER } from "./meter.js";
|
||||
import { applyMention, matchNames, mentionAt } from "./mentions.js";
|
||||
import { faviconState, setFavicon } from "./favicon.js";
|
||||
import {
|
||||
CHECKIN_LINE,
|
||||
PATHFINDER_RESEARCH_LINE,
|
||||
defaultInstruction,
|
||||
helperRows,
|
||||
showSwitch,
|
||||
showTab,
|
||||
switchLabel,
|
||||
} from "./subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -446,6 +457,10 @@ document.addEventListener("click", (e) => {
|
||||
|
||||
|
||||
const GONE_AFTER_MS = 8000;
|
||||
// Named so a reconnect can clear only THIS banner: a bare banner(null) would
|
||||
// wipe an unrelated warning that landed while the page was gone (an upload
|
||||
// failure, a refused send).
|
||||
const GONE_BANNER = "Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.";
|
||||
const WORKING_GRACE_MS = 5 * 60 * 1000;
|
||||
// Two minutes with the agent mid-turn, three when it is merely meant to be
|
||||
// listening. The difference is the cost of being wrong: a working agent that
|
||||
@@ -521,6 +536,12 @@ let chatFrame = null;
|
||||
// sends them.
|
||||
let wsFrame = null;
|
||||
let meterFrame = null;
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
let updateFrame = null;
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
let subagentsFrame = null;
|
||||
let chatDot = false;
|
||||
let chatSending = false;
|
||||
let chatResetting = false;
|
||||
@@ -566,7 +587,6 @@ function fresh() {
|
||||
drafts: {},
|
||||
images: {},
|
||||
sent: {},
|
||||
sentAt: null,
|
||||
stopping: null,
|
||||
afterBuild: null,
|
||||
homeward: null,
|
||||
@@ -870,10 +890,14 @@ function adopt(body) {
|
||||
chatFrame = body.chat || null;
|
||||
if (body.workspace) wsFrame = body.workspace;
|
||||
if (body.meter) meterFrame = body.meter;
|
||||
// Always replaced: an absent key means no update.
|
||||
updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
subagentsFrame = body.subagents || null;
|
||||
lastContact = Date.now();
|
||||
if (gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
}
|
||||
if (firstLoad) {
|
||||
load();
|
||||
@@ -1016,7 +1040,9 @@ function adopt(body) {
|
||||
render();
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
tellFolderIssues();
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow) loadOverview();
|
||||
// The Overview tab's file changes under a build, so a tab you are watching
|
||||
// refetches on every new frame too, not only on the click that opened it.
|
||||
if (firstLoad || S.specDir !== prevSpecDir || S.workflow !== prevWorkflow || view === "overview") loadOverview();
|
||||
if (announce) showArrival(announce);
|
||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||
// leaving the list parked where it was while it grew underneath.
|
||||
@@ -1149,15 +1175,12 @@ function markGone() {
|
||||
// of the server means there, and a banner promising a reconnect would
|
||||
// argue with it.
|
||||
if (!finish() && !stopInProgress()) {
|
||||
banner(
|
||||
"Lost contact with Plan2Code. Nothing you have typed is lost. This page reconnects by itself.",
|
||||
"warn"
|
||||
);
|
||||
banner(GONE_BANNER, "warn");
|
||||
}
|
||||
render();
|
||||
} else if (!bad && gone) {
|
||||
gone = false;
|
||||
banner(null);
|
||||
if ($("banner").textContent === GONE_BANNER) banner(null);
|
||||
render();
|
||||
}
|
||||
}
|
||||
@@ -1182,7 +1205,6 @@ function connect() {
|
||||
} catch {}
|
||||
});
|
||||
es.addEventListener("submitted", (e) => {
|
||||
local.sentAt = Date.now();
|
||||
// Drop only what was actually sent.
|
||||
//
|
||||
// This event fires for a send from ANY tab of this session, which is why it
|
||||
@@ -1293,6 +1315,7 @@ function render() {
|
||||
renderChrome();
|
||||
renderStatus();
|
||||
renderBriefButton();
|
||||
renderSubagentsButton();
|
||||
renderStopButton();
|
||||
renderHomeButton();
|
||||
tabAdded = renderViews();
|
||||
@@ -1558,7 +1581,7 @@ function renderChrome() {
|
||||
renderMeter();
|
||||
$("title").textContent = S.title || "Session";
|
||||
$("badge").textContent = workflowLabel(S.workflow);
|
||||
document.title = (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
renderTabTitle();
|
||||
|
||||
const h = S.headline || {};
|
||||
// On a finished session an open item is frozen: the send on it counts as
|
||||
@@ -1799,14 +1822,19 @@ async function sendBrief() {
|
||||
reply: briefPhrase(choice.range),
|
||||
}),
|
||||
});
|
||||
if (res.status === 409) throw Object.assign(new Error("pending"), { pending: true });
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
$("brief-modal").close();
|
||||
banner("Asked for a brief. It will appear as a tab when it is written.", "good");
|
||||
setTimeout(() => banner(null), 5000);
|
||||
pendingResult = true;
|
||||
render();
|
||||
} catch {
|
||||
why.textContent = "That did not go through. Try again in a moment.";
|
||||
} catch (err) {
|
||||
if (err && err.pending) pendingResult = true;
|
||||
why.textContent =
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up. Try again in a moment."
|
||||
: "That did not go through. Try again in a moment.";
|
||||
} finally {
|
||||
go.disabled = false;
|
||||
go.textContent = "Write the brief";
|
||||
@@ -1822,6 +1850,69 @@ function renderBriefButton() {
|
||||
if (offer) btn.disabled = gone || pendingResult;
|
||||
}
|
||||
|
||||
// Shown only where the skill opts in and the agent's console copy can deliver
|
||||
// it. Lit while helpers are on; a click opens the dialog, never toggles.
|
||||
function renderSubagentsButton() {
|
||||
const btn = $("btn-subagents");
|
||||
const offer = showSwitch(subagentsFrame);
|
||||
btn.hidden = !offer;
|
||||
if (!offer) return;
|
||||
const label = switchLabel(subagentsFrame);
|
||||
btn.setAttribute("aria-pressed", String(Boolean(subagentsFrame.on)));
|
||||
btn.title = label;
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.disabled = gone;
|
||||
}
|
||||
|
||||
// The Subagents dialog, filled from the frame each time it opens. A null
|
||||
// instruction is the shipped default, shown as its text so it can be edited.
|
||||
function openSubagents() {
|
||||
if (!showSwitch(subagentsFrame)) return;
|
||||
const on = Boolean(subagentsFrame.on);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) {
|
||||
radio.checked = radio.value === (on ? "on" : "off");
|
||||
}
|
||||
$("subagents-instruction").value = subagentsFrame.instruction ?? defaultInstruction(S.workflow);
|
||||
$("subagents-max").value = String(subagentsFrame.max);
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
research.hidden = S.workflow !== "pathfinder";
|
||||
$("subagents-status").textContent = "";
|
||||
$("subagents-save").disabled = false;
|
||||
$("subagents-modal").showModal();
|
||||
const checked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
const SUBAGENTS_LOST = "Lost contact with Plan2Code. Try again once it's back.";
|
||||
|
||||
async function saveSubagents() {
|
||||
const save = $("subagents-save");
|
||||
const status = $("subagents-status");
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const text = $("subagents-instruction").value.trim();
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
save.disabled = false;
|
||||
// The next state frame redraws the button.
|
||||
if (res.status === 200) return $("subagents-modal").close();
|
||||
if (res.status === 400) status.textContent = SUBAGENTS_ERRORS[res.body && res.body.error] || SUBAGENTS_ERRORS.bad;
|
||||
else if (res.status === 403 || res.status === 0) status.textContent = SUBAGENTS_LOST;
|
||||
else status.textContent = SUBAGENTS_ERRORS.bad;
|
||||
}
|
||||
|
||||
function renderViews() {
|
||||
const nav = $("views");
|
||||
nav.replaceChildren();
|
||||
@@ -1837,6 +1928,14 @@ function renderViews() {
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (view === "overview") view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
if (showTab(subagentsFrame, S.helpers)) {
|
||||
// From the rows the tab draws, so the badge never counts helpers the
|
||||
// working-alone note hides.
|
||||
const running = helperRows(S.helpers).rows.filter((r) => r.state === "running").length;
|
||||
tabs.push({ id: "subagents", label: "Subagents", count: running });
|
||||
} else if (view === "subagents") view = "questions";
|
||||
// Always last, on every workflow and after a finish: the Quick question chat.
|
||||
// The ring left of "Ask" shows exactly when the conversation's own ring does:
|
||||
// a question the agent picked up and has not answered yet.
|
||||
@@ -2117,6 +2216,7 @@ function paintMain(main) {
|
||||
if (view.startsWith("doc:")) return renderDoc(main, view.slice(4));
|
||||
if (view === "overview") return renderOverview(main);
|
||||
if (view === "ask") return renderAsk(main);
|
||||
if (view === "subagents") return renderSubagents(main);
|
||||
|
||||
// The session's own page, reached from the PAUSED / SESSION ENDED item at
|
||||
// the top of the rail. The hand-off lives here alone now, rather than
|
||||
@@ -2515,6 +2615,51 @@ function roleNudge() {
|
||||
return nudge;
|
||||
}
|
||||
|
||||
// × on the update banner hides it for this console session only, and only
|
||||
// for the release it named. Blocked storage means "not dismissed".
|
||||
function updateDismissKey() {
|
||||
try {
|
||||
return "p2c-update-dismissed:" + S.sid;
|
||||
} catch {
|
||||
return "p2c-update-dismissed:";
|
||||
}
|
||||
}
|
||||
|
||||
function updateDismissed() {
|
||||
try {
|
||||
return sessionStorage.getItem(updateDismissKey()) === updateFrame.latest;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
const UPDATE_COMMAND = "npx --allow-git=all git+https://github.com/jparkerweb/plan2code.git";
|
||||
|
||||
function releasesLink(text) {
|
||||
const a = el("a", null, text);
|
||||
a.href = RELEASES_URL;
|
||||
a.target = "_blank";
|
||||
a.rel = "noopener noreferrer";
|
||||
return a;
|
||||
}
|
||||
|
||||
function openUpdateModal() {
|
||||
if (!updateFrame) return;
|
||||
const versions = $("update-versions");
|
||||
versions.replaceChildren(
|
||||
document.createTextNode("Version "),
|
||||
releasesLink("v" + updateFrame.latest),
|
||||
document.createTextNode(" is out — you have "),
|
||||
el("code", null, updateFrame.installed),
|
||||
document.createTextNode(".")
|
||||
);
|
||||
const row = $("update-command");
|
||||
const code = el("code", null, UPDATE_COMMAND);
|
||||
row.replaceChildren(code, copyButton(UPDATE_COMMAND, "btn small ghost handoff-copy", code));
|
||||
$("update-modal").showModal();
|
||||
}
|
||||
|
||||
function renderDashboard(main) {
|
||||
maybeWake();
|
||||
const menu = (S && S.menu) || {};
|
||||
@@ -2526,6 +2671,25 @@ function renderDashboard(main) {
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (updateFrame && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + updateFrame.latest);
|
||||
open.type = "button";
|
||||
open.addEventListener("click", openUpdateModal);
|
||||
const dismiss = el("button", "update-banner-dismiss", "×");
|
||||
dismiss.type = "button";
|
||||
dismiss.setAttribute("aria-label", "Dismiss until next time");
|
||||
dismiss.addEventListener("click", () => {
|
||||
try {
|
||||
sessionStorage.setItem(updateDismissKey(), updateFrame.latest);
|
||||
} catch {}
|
||||
render();
|
||||
});
|
||||
notice.append(open, dismiss);
|
||||
wrap.appendChild(notice);
|
||||
}
|
||||
wrap.appendChild(el("p", "card-kicker", "Plan2Code"));
|
||||
wrap.appendChild(el("h2", "dash-title", "What are we doing today?"));
|
||||
if (typeof menu.note === "string" && menu.note.trim()) {
|
||||
@@ -3223,7 +3387,11 @@ document.addEventListener("keydown", cancelSkipMove, true);
|
||||
function skipAndMoveOn(id) {
|
||||
cancelSkipMove();
|
||||
local.skipFlash = id;
|
||||
stage(id, { type: "skip", skipped: true });
|
||||
// A note already typed goes along: skipping the question is not retracting
|
||||
// the comment. Dropping it would leave the text in the box but out of the
|
||||
// send, which looks kept and is not.
|
||||
const cur = local.staged[id];
|
||||
stage(id, { type: "skip", skipped: true, ...(cur && cur.text ? { text: cur.text } : {}) });
|
||||
skipTimer = setTimeout(() => {
|
||||
skipTimer = null;
|
||||
local.skipFlash = null;
|
||||
@@ -3340,19 +3508,24 @@ function renderWaiting(main) {
|
||||
}
|
||||
pane.appendChild(title);
|
||||
pane.appendChild(el("p", null, doing));
|
||||
const ask = "If Plan2Code needs you, the question appears here on its own.";
|
||||
if (!docs().length) {
|
||||
pane.appendChild(el("p", null, "If Plan2Code needs you, the question appears here on its own."));
|
||||
pane.appendChild(el("p", null, ask));
|
||||
return;
|
||||
}
|
||||
// "Task" and the tasks tab's own name both open that tab, so the pointer is
|
||||
// one click from what it points at. A build posts it as `phase` ("Phase N
|
||||
// tasks"), a quick task as `tasks`; with neither the words stay plain.
|
||||
// tasks"), a quick task as `tasks`. A skill with no task list (Document,
|
||||
// Plan) has nothing live to follow, so it gets no pointer at all.
|
||||
const list =
|
||||
docs().find((d) => d.id === "phase") ||
|
||||
docs().find((d) => d.id === "tasks") ||
|
||||
docs().find((d) => /\btasks\b/i.test(d.title || ""));
|
||||
if (!list) {
|
||||
pane.appendChild(el("p", null, "The tabs above fill in as it goes. " + ask));
|
||||
return;
|
||||
}
|
||||
const jump = (word) => {
|
||||
if (!list) return el("strong", "waiting-jump", word);
|
||||
const b = el("button", "waiting-jump", word);
|
||||
b.type = "button";
|
||||
b.addEventListener("click", () => {
|
||||
@@ -3366,8 +3539,8 @@ function renderWaiting(main) {
|
||||
"The tabs above fill in as it goes. You can follow along with live ",
|
||||
jump("Task"),
|
||||
" updates in the ",
|
||||
jump((list && list.title) || "Phase tasks"),
|
||||
" tab. If Plan2Code needs you, the question appears here on its own."
|
||||
jump(list.title || "Phase tasks"),
|
||||
" tab. " + ask
|
||||
);
|
||||
pane.appendChild(p);
|
||||
}
|
||||
@@ -3505,8 +3678,8 @@ function renderSettled(card, item) {
|
||||
// would misreport which of the two was the answer.
|
||||
let prose = text;
|
||||
if (!prose && !lines.length) {
|
||||
const mine = (item.thread || []).filter((m) => m.who === "user");
|
||||
if (mine.length) prose = String(mine[mine.length - 1].text || "").trim();
|
||||
const mine = (item.thread || []).filter((m) => threadWho(m) === "user");
|
||||
if (mine.length) prose = threadText(mine[mine.length - 1]).trim();
|
||||
}
|
||||
|
||||
const nothing = !lines.length && !prose;
|
||||
@@ -4172,8 +4345,11 @@ function templateRow(item, input, entries, check) {
|
||||
save();
|
||||
paint();
|
||||
input.focus();
|
||||
const start = text.indexOf("[");
|
||||
const end = start < 0 ? -1 : text.indexOf("]", start);
|
||||
try {
|
||||
input.setSelectionRange(text.length, text.length);
|
||||
if (end > start) input.setSelectionRange(start, end + 1);
|
||||
else input.setSelectionRange(text.length, text.length);
|
||||
} catch {}
|
||||
};
|
||||
|
||||
@@ -4322,6 +4498,10 @@ function buildChecklist(card, item, staged) {
|
||||
const commitList = (change) => {
|
||||
const cur = local.staged[item.id];
|
||||
const next = { ...(cur || {}), type: "answer", kind: "checklist", ...change };
|
||||
// A tick or a state IS the answer, so it ends a skip staged earlier:
|
||||
// left in place, `skipped` would collapse the reply to "skip" while the
|
||||
// card showed ticked steps on their way.
|
||||
delete next.skipped;
|
||||
const empty = !(next.done && next.done.length) && !next.state && !next.text;
|
||||
stage(item.id, empty ? null : next);
|
||||
};
|
||||
@@ -4371,7 +4551,7 @@ function buildChecklist(card, item, staged) {
|
||||
function buildMenu(card, item, staged) {
|
||||
const list = el("ul", "options");
|
||||
const name = "menu-" + item.id;
|
||||
for (const o of item.options || []) {
|
||||
for (const [i, o] of (item.options || []).entries()) {
|
||||
const picked = staged && staged.k === o.k;
|
||||
const li = el("li", "option" + (picked ? " is-picked" : ""));
|
||||
const label = el("label");
|
||||
@@ -4379,7 +4559,13 @@ function buildMenu(card, item, staged) {
|
||||
const radio = el("input");
|
||||
radio.type = "radio";
|
||||
radio.name = name;
|
||||
// The same id buildChoice gives its radios: withFocus finds the focused
|
||||
// input by id after the render this change() sets off, and without one a
|
||||
// keyboard user arrowing through the menu lands on <body> every time.
|
||||
radio.id = optionId(item, o, i);
|
||||
radio.value = o.k;
|
||||
radio.checked = Boolean(picked);
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||
const body = el("div", "option-body");
|
||||
const head = el("div", "option-label");
|
||||
@@ -4678,6 +4864,42 @@ function renderOverview(main) {
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
// The helpers the agent reported, as it last posted them. Everything here is
|
||||
// the agent's text, so it goes in as text, never as markup.
|
||||
function renderSubagents(main) {
|
||||
const card = el("section", "card sa-card");
|
||||
card.appendChild(el("h2", null, "Subagents"));
|
||||
card.appendChild(el("p", "help", CHECKIN_LINE));
|
||||
const { alone, rows } = helperRows(S.helpers);
|
||||
if (alone) {
|
||||
card.appendChild(
|
||||
el("p", "sa-alone", "Working alone: your agent has no way to start helpers here, so it is doing this skill's work itself.")
|
||||
);
|
||||
main.appendChild(card);
|
||||
return;
|
||||
}
|
||||
const list = el("ul", "sa-list");
|
||||
for (const row of rows) {
|
||||
const item = el("li", "sa-row");
|
||||
const head = el("div", "sa-head");
|
||||
head.appendChild(el("strong", "sa-title", row.title));
|
||||
const pill = el("span", "pill sa-pill is-" + row.state);
|
||||
if (row.state === "running") {
|
||||
const spin = el("span", "spinner tiny");
|
||||
spin.setAttribute("aria-hidden", "true");
|
||||
pill.appendChild(spin);
|
||||
}
|
||||
pill.appendChild(document.createTextNode(row.stateLabel));
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
card.appendChild(list);
|
||||
main.appendChild(card);
|
||||
}
|
||||
|
||||
/* ---------------------------------------------------------------- ask */
|
||||
|
||||
// The frame's chat block, with `offline` worked out now rather than when the
|
||||
@@ -5276,20 +5498,30 @@ function renderAside() {
|
||||
)
|
||||
);
|
||||
}
|
||||
// A note that has been sent but not yet picked up: marked as waiting, so the
|
||||
// send is seen to have gone, until the agent replies. The server writes the
|
||||
// note into the thread as it arrives; a session from before that has only
|
||||
// `sentNote`, which gets a box of its own below.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
let waitingShown = false;
|
||||
for (const m of thread) {
|
||||
const box = el("div", "msg " + (m.who === "user" ? "you" : ""));
|
||||
const mine = threadWho(m) === "user";
|
||||
const pending = Boolean(waiting && mine && m.at && m.at === waiting.at);
|
||||
if (pending) waitingShown = true;
|
||||
const box = el("div", "msg" + (mine ? " you" : "") + (pending ? " pending" : ""));
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, m.who === "user" ? "You" : "Plan2Code"));
|
||||
if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
who.appendChild(el("span", null, mine ? "You" : "Plan2Code"));
|
||||
if (pending) who.appendChild(el("span", null, "Sent, waiting for Plan2Code"));
|
||||
else if (m.at) who.appendChild(el("span", null, shortTime(m.at)));
|
||||
box.appendChild(who);
|
||||
box.appendChild(md(m.text, "md"));
|
||||
const text = threadText(m);
|
||||
if (text) box.appendChild(md(text, "md"));
|
||||
const tray = mine ? sentAttachments(m) : null;
|
||||
if (tray) box.appendChild(tray);
|
||||
aside.appendChild(box);
|
||||
}
|
||||
|
||||
// A note that has been sent but not yet picked up: shown at once, so the
|
||||
// send is seen to have gone, and gone when the agent replies.
|
||||
const waiting = isOpen(item) && !finish() ? noteAwaiting(item) : null;
|
||||
if (waiting) {
|
||||
if (waiting && !waitingShown) {
|
||||
const box = el("div", "msg you pending");
|
||||
const who = el("div", "msg-who");
|
||||
who.appendChild(el("span", null, "You"));
|
||||
@@ -5589,7 +5821,10 @@ async function attachFiles(itemId, files) {
|
||||
const taken = wanted.slice(0, room);
|
||||
// One banner at a time, so every refusal goes into it, each by name.
|
||||
const said = refused.map((r) => (r.reason === "too-large" ? tooLargeText(r.name) : notAllowedText(r.name)));
|
||||
if (taken.length < wanted.length) said.push(chat ? "Up to 5 attachments per question." : "Up to 5 attachments per note.");
|
||||
if (taken.length < wanted.length)
|
||||
said.push(
|
||||
chat ? `Up to ${CHAT_MAX_ATTACHMENTS} attachments per question.` : `Up to ${MAX_ATTACHMENTS} attachments per note.`
|
||||
);
|
||||
if (said.length) banner(said.join(" "), refused.length ? "warn" : "info");
|
||||
await Promise.all(
|
||||
taken.map(async (file) => {
|
||||
@@ -5847,10 +6082,30 @@ const workspaceFolders = () => (wsFrame && Array.isArray(wsFrame.folders) ? wsFr
|
||||
// session opened before the server wrote `worktree` has nothing to show, so
|
||||
// the slot stays hidden. The footer renders on every tick, so the DOM is only
|
||||
// touched when the labels change, or when a resize clears the key.
|
||||
// The project's name: the workspace's original folder, or the session's
|
||||
// worktree folder before a frame carries the workspace.
|
||||
function projectName() {
|
||||
const folders = workspaceFolders();
|
||||
if (folders.length && folders[0].name) return folders[0].name;
|
||||
const path = (S && S.worktree) || "";
|
||||
return path ? path.split(/[\\/]/).filter(Boolean).pop() || path : "";
|
||||
}
|
||||
|
||||
// The browser tab's title, led by the project so tabs from different
|
||||
// projects are told apart. Called from the chrome and the footer, since the
|
||||
// workspace frame can arrive after either.
|
||||
function renderTabTitle() {
|
||||
if (!S) return;
|
||||
const name = projectName();
|
||||
document.title =
|
||||
(name ? name + " · " : "") + (S.title || "Session") + " · #" + String(S.sid || "").slice(-6) + " · Plan2Code";
|
||||
}
|
||||
|
||||
function renderWhere() {
|
||||
const b = $("footer-where");
|
||||
const folders = workspaceFolders();
|
||||
const path = S.worktree || "";
|
||||
renderTabTitle();
|
||||
const alert = Boolean(folders.length && ((wsFrame.missing || []).length || (wsFrame.issues || []).length));
|
||||
const labels = folders.length
|
||||
? Array.from({ length: FOOTER_TIERS }, (_, tier) => footerLabel({ folders, branch: S.branch }, tier))
|
||||
@@ -5863,7 +6118,16 @@ function renderWhere() {
|
||||
let label = labels[0];
|
||||
for (const text of labels) {
|
||||
label = text;
|
||||
b.textContent = text;
|
||||
// The project name takes the highlight color, so several consoles side by
|
||||
// side tell apart at a glance; the rest of the label stays quiet.
|
||||
const name = projectName();
|
||||
b.textContent = "";
|
||||
if (name && text.startsWith(name)) {
|
||||
b.appendChild(el("span", "where-project", name));
|
||||
b.appendChild(document.createTextNode(text.slice(name.length)));
|
||||
} else {
|
||||
b.textContent = text;
|
||||
}
|
||||
if (alert) {
|
||||
const dot = el("span", "where-alert");
|
||||
dot.setAttribute("aria-hidden", "true");
|
||||
@@ -6439,6 +6703,10 @@ async function goHome() {
|
||||
$("home-modal").close();
|
||||
} catch (err) {
|
||||
$("home-modal").close();
|
||||
// The server is holding an uncollected result: Send, Home and Stop all
|
||||
// need to read as busy until the frame or the ping says otherwise, same
|
||||
// as send() and sendAfterBuild() do on a 409.
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so that could not go yet. Try again in a moment."
|
||||
@@ -6499,6 +6767,7 @@ async function stopSession() {
|
||||
stoppingHidden = false;
|
||||
} catch (err) {
|
||||
$("stop-modal").close();
|
||||
if (err && err.pending) pendingResult = true;
|
||||
banner(
|
||||
err && err.pending
|
||||
? "Your last answers are still being picked up, so the stop could not go yet. Try again in a moment."
|
||||
@@ -6653,7 +6922,6 @@ function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
local.sent[id] = { at: Date.now(), summary: summaries[id] || "", value: values[id] || null };
|
||||
}
|
||||
local.staged = {};
|
||||
local.sentAt = Date.now();
|
||||
save();
|
||||
}
|
||||
|
||||
@@ -6706,7 +6974,7 @@ const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", d
|
||||
// something the agent never hears.
|
||||
function tokenFor(item, v) {
|
||||
const map = item.token || {};
|
||||
if (v.skipped) return "skip";
|
||||
if (v.skipped) return v.text ? `skip; ${v.text}` : "skip";
|
||||
const parts = [];
|
||||
if (v.k) parts.push(map[v.k] || v.k);
|
||||
if (Array.isArray(v.ks) && v.ks.length) parts.push(v.ks.map((k) => map[k] || k).join(", "));
|
||||
@@ -6938,14 +7206,14 @@ function renderAbout() {
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
const el = $("help-version");
|
||||
const slot = $("help-version");
|
||||
try {
|
||||
const res = await fetch("/version", { cache: "no-store" });
|
||||
const { version } = res.ok ? await res.json() : {};
|
||||
el.textContent = version ? "Plan2Code v" + version : "";
|
||||
el.hidden = !version;
|
||||
slot.replaceChildren(...(version ? [releasesLink("Plan2Code v" + version)] : []));
|
||||
slot.hidden = !version;
|
||||
} catch {
|
||||
el.hidden = true;
|
||||
slot.hidden = true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7053,6 +7321,7 @@ function openHelpOn(id) {
|
||||
}
|
||||
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
$("update-done").addEventListener("click", () => $("update-modal").close());
|
||||
$("home-cancel").addEventListener("click", () => $("home-modal").close());
|
||||
$("home-go").addEventListener("click", goHome);
|
||||
$("btn-stop").addEventListener("click", openStopConfirm);
|
||||
@@ -7083,6 +7352,7 @@ function lightDismiss(dlg) {
|
||||
});
|
||||
}
|
||||
lightDismiss($("looks-modal"));
|
||||
lightDismiss($("subagents-modal"));
|
||||
lightDismiss($("help-modal"));
|
||||
lightDismiss($("workspace-modal"));
|
||||
lightDismiss($("welcome-modal"));
|
||||
@@ -7132,6 +7402,7 @@ $("btn-looks").addEventListener("click", () => {
|
||||
});
|
||||
$("looks-done").addEventListener("click", () => $("looks-modal").close());
|
||||
$("looks-modal").addEventListener("close", () => {
|
||||
resetCleanup();
|
||||
if (isDashboard() && !needsRoleNudge(looks) && $("main").querySelector(".dash-nudge")) render();
|
||||
});
|
||||
$("looks-reset").addEventListener("click", () => {
|
||||
@@ -7278,7 +7549,119 @@ $("models-reset").addEventListener("click", () => {
|
||||
renderModels();
|
||||
});
|
||||
|
||||
// Cleanup: the server works out what in ~/.plan2code is not needed and
|
||||
// shows it first; Delete these sends back only the ids it was shown, and the
|
||||
// server re-checks every one before removing it.
|
||||
let cleanupFound = null;
|
||||
// Bumped by every scan, delete and reset: a response from an older one is
|
||||
// dropped, so a scan still in flight when Preferences closes cannot refill it.
|
||||
let cleanupGen = 0;
|
||||
const CLEANUP_SHOWN = 8;
|
||||
|
||||
function setCleanupStatus(text, isError) {
|
||||
const status = $("cleanup-status");
|
||||
status.textContent = text;
|
||||
status.classList.toggle("error", Boolean(isError));
|
||||
}
|
||||
|
||||
function cleanupLabel(item) {
|
||||
if (item.where === "session") return "Session " + item.name;
|
||||
const where = item.where === "root" ? "~/.plan2code/" : "~/.plan2code/console/";
|
||||
return where + item.name + (item.kind === "folder" ? "/" : "");
|
||||
}
|
||||
|
||||
function cleanupSummary(items, bytes) {
|
||||
const sessions = items.filter((i) => i.where === "session").length;
|
||||
const strays = items.length - sessions;
|
||||
const parts = [];
|
||||
if (sessions) parts.push(sessions + (sessions === 1 ? " old session" : " old sessions"));
|
||||
if (strays) parts.push(strays + (strays === 1 ? " stray file or folder" : " stray files and folders"));
|
||||
return parts.join(", ") + " · " + formatBytes(bytes);
|
||||
}
|
||||
|
||||
function resetCleanup() {
|
||||
cleanupGen++;
|
||||
cleanupFound = null;
|
||||
$("cleanup-list").replaceChildren();
|
||||
$("cleanup-delete").hidden = true;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
setCleanupStatus("", false);
|
||||
}
|
||||
|
||||
function renderCleanup() {
|
||||
const list = $("cleanup-list");
|
||||
list.replaceChildren();
|
||||
const items = (cleanupFound && cleanupFound.items) || [];
|
||||
$("cleanup-delete").hidden = !items.length;
|
||||
if (!items.length) return;
|
||||
const rows = (some) => some.map((item) => {
|
||||
const row = el("div", "cleanup-row");
|
||||
row.append(el("span", null, cleanupLabel(item)), el("span", "cleanup-size", formatBytes(item.bytes)));
|
||||
return row;
|
||||
});
|
||||
list.append(el("p", "cleanup-summary", cleanupSummary(items, cleanupFound.bytes)), ...rows(items.slice(0, CLEANUP_SHOWN)));
|
||||
if (items.length > CLEANUP_SHOWN) {
|
||||
const more = el("details", "cleanup-more");
|
||||
more.append(el("summary", null, (items.length - CLEANUP_SHOWN) + " more"), ...rows(items.slice(CLEANUP_SHOWN)));
|
||||
list.appendChild(more);
|
||||
}
|
||||
}
|
||||
|
||||
async function scanCleanup() {
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-scan").disabled = true;
|
||||
$("cleanup-delete").disabled = true;
|
||||
setCleanupStatus("Looking…", false);
|
||||
const { status, body } = await postJson("/cleanup", { scan: true });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-scan").disabled = false;
|
||||
$("cleanup-delete").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
return setCleanupStatus(status ? body.error || "Could not look." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
cleanupFound = { items: body.items || [], bytes: body.bytes || 0 };
|
||||
renderCleanup();
|
||||
// Left in the status line, not cleared: it is the live region, so this is
|
||||
// what a screen reader hears when the scan finishes.
|
||||
const found = cleanupFound.items.length;
|
||||
setCleanupStatus(found ? "Found " + found + (found === 1 ? " item." : " items.") : "Nothing to clean up.", false);
|
||||
}
|
||||
|
||||
async function deleteCleanup() {
|
||||
if (!cleanupFound || !cleanupFound.items.length) return;
|
||||
const gen = ++cleanupGen;
|
||||
$("cleanup-delete").disabled = true;
|
||||
$("cleanup-scan").disabled = true;
|
||||
setCleanupStatus("Deleting…", false);
|
||||
const { status, body } = await postJson("/cleanup", { delete: cleanupFound.items.map((i) => i.id) });
|
||||
if (gen !== cleanupGen) return;
|
||||
$("cleanup-delete").disabled = false;
|
||||
$("cleanup-scan").disabled = false;
|
||||
if (status !== 200 || !body.ok) {
|
||||
return setCleanupStatus(status ? body.error || "Could not delete." : "Plan2Code isn't reachable.", true);
|
||||
}
|
||||
const removed = (body.removed || []).length;
|
||||
const failed = (body.failed || []).length;
|
||||
cleanupFound = null;
|
||||
renderCleanup();
|
||||
const done = removed ? "Deleted " + removed + (removed === 1 ? " item" : " items") + " · " + formatBytes(body.bytes) + " freed." : "Nothing was deleted.";
|
||||
setCleanupStatus(failed ? done + " " + failed + " could not be removed." : done, Boolean(failed));
|
||||
}
|
||||
|
||||
$("cleanup-scan").addEventListener("click", scanCleanup);
|
||||
$("cleanup-delete").addEventListener("click", deleteCleanup);
|
||||
|
||||
$("btn-brief").addEventListener("click", openBrief);
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
$("subagents-instruction").value = defaultInstruction(S.workflow);
|
||||
});
|
||||
$("subagents-save").addEventListener("click", saveSubagents);
|
||||
$("subagents-cancel").addEventListener("click", () => $("subagents-modal").close());
|
||||
$("subagents-modal").addEventListener("close", () => $("btn-subagents").focus());
|
||||
$("brief-cancel").addEventListener("click", () => $("brief-modal").close());
|
||||
$("brief-go").addEventListener("click", sendBrief);
|
||||
for (const radio of document.querySelectorAll('input[name="brief-range"]')) {
|
||||
|
||||
@@ -19,6 +19,7 @@ export const HELP_TABS = Object.freeze([
|
||||
tab("dashboard", "The dashboard", true),
|
||||
tab("meter", "Session meter", false),
|
||||
tab("build", "Watching a build", false),
|
||||
tab("subagents", "Helpers (subagents)", false),
|
||||
tab("ask", "Ask a quick question", false),
|
||||
tab("finishing", "Stopping and finishing", false),
|
||||
tab("stuck", "When something looks stuck", true),
|
||||
@@ -39,6 +40,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (gone || adrift) return "stuck";
|
||||
if (workspace) return "workspace";
|
||||
if (v === "ask") return "ask";
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
|
||||
@@ -21,6 +21,7 @@
|
||||
<link rel="modulepreload" href="/starters.js" />
|
||||
<link rel="modulepreload" href="/workspace.js" />
|
||||
<link rel="modulepreload" href="/meter.js" />
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/vendor/marked.esm.js" />
|
||||
@@ -172,6 +173,18 @@
|
||||
<button type="button" class="btn ghost small brief-btn" id="btn-brief" hidden>
|
||||
Write a brief
|
||||
</button>
|
||||
<!-- Subagents: opted-in skills only. Lit while helpers are on; a click
|
||||
opens the Subagents dialog and never toggles them itself. -->
|
||||
<button type="button" class="btn ghost small subagents-btn" id="btn-subagents" aria-pressed="false" hidden>
|
||||
<!-- An orchestrator and its helpers: one larger node linked to three smaller ones. -->
|
||||
<svg viewBox="0 0 16 16" aria-hidden="true" focusable="false">
|
||||
<path class="sa-link" d="M6.9 6.6L10.9 3.9M7.4 8h3.5M6.9 9.4l4 2.7" />
|
||||
<circle cx="4.6" cy="8" r="2.6" class="sa-hub" />
|
||||
<circle cx="12.4" cy="3" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="8" r="1.5" class="sa-node" />
|
||||
<circle cx="12.4" cy="13" r="1.5" class="sa-node" />
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div class="views-group">
|
||||
<span class="views-arrow" aria-hidden="true">
|
||||
@@ -580,6 +593,13 @@
|
||||
<rect x="3" y="9" width="18" height="6" rx="3" />
|
||||
<path d="M6 12h7" />
|
||||
</symbol>
|
||||
<symbol id="hi-subagents" viewBox="0 0 24 24" fill="none">
|
||||
<circle cx="7" cy="12" r="3.5" />
|
||||
<circle cx="18" cy="5" r="2" />
|
||||
<circle cx="18" cy="12" r="2" />
|
||||
<circle cx="18" cy="19" r="2" />
|
||||
<path d="M10 10l6-4M10.5 12H16M10 14l6 4" />
|
||||
</symbol>
|
||||
<symbol id="hi-ask" viewBox="0 0 24 24" fill="none">
|
||||
<path d="M4 5h16v11H10l-4 4v-4H4z" />
|
||||
<path d="M8 9.5h8M8 12.5h5" />
|
||||
@@ -1291,6 +1311,14 @@
|
||||
come back, and you can change your role any time from the swatch
|
||||
button.
|
||||
</p>
|
||||
<h4>When an update is out</h4>
|
||||
<p>
|
||||
When a newer Plan2Code release is out, the dashboard shows
|
||||
<strong>UPDATE AVAILABLE</strong> at the top. Click it for the command
|
||||
to run in your terminal; × hides it until the next
|
||||
<code>/plan2code</code>. The version at the bottom of Help links to
|
||||
the Releases page.
|
||||
</p>
|
||||
<h4>The cards</h4>
|
||||
<p>They come in three groups.</p>
|
||||
<p><strong>First, the project</strong></p>
|
||||
@@ -1469,7 +1497,62 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 12: Ask a quick question -->
|
||||
<!-- Tab 12: Helpers (subagents) -->
|
||||
<section class="help-panel" data-tab="subagents">
|
||||
<h3>Helpers (subagents)</h3>
|
||||
<p>
|
||||
On a build, a review and Pathfinder, Plan2Code can hand independent
|
||||
pieces of work to helpers (subagents) while it keeps the conversation
|
||||
with you. The <strong>Subagents</strong> button in the top bar, after
|
||||
Stop session, is lit while helpers are on.
|
||||
</p>
|
||||
<h4>The switch</h4>
|
||||
<ul>
|
||||
<li>
|
||||
Clicking the button opens the <strong>Subagents</strong> dialog; it
|
||||
never switches helpers on or off by itself. Pick <strong>Use
|
||||
helpers</strong> or <strong>Work alone</strong>, edit the instruction
|
||||
Plan2Code follows (<strong>Reset to default</strong> puts the
|
||||
shipped one back), and say how many may run at once.
|
||||
</li>
|
||||
<li>
|
||||
It is off by default and saved for this project and this skill, so
|
||||
the next session of the same skill here starts the same way.
|
||||
</li>
|
||||
<li>
|
||||
The change reaches Plan2Code at its next check-in, as a setting,
|
||||
not as something you typed. How many helpers it can really start is
|
||||
up to your agent; some have no helpers at all.
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
With the first helper, a <strong>Subagents</strong> tab appears before
|
||||
Ask: one row each, with what it was asked, whether it is running, done
|
||||
or failed, and a one-line result at the end. The number on the tab is
|
||||
how many are still running.
|
||||
</li>
|
||||
<li>
|
||||
Helpers report through Plan2Code, so the rows change at its
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Working alone</strong> means your agent reported it has no
|
||||
way to start helpers here. If it starts one after all, the note
|
||||
goes away and the helper's row shows instead.
|
||||
</li>
|
||||
<li>
|
||||
Pathfinder always uses helpers for its research questions, whatever
|
||||
the switch says, and they show here too.
|
||||
</li>
|
||||
<li>The tab clears when you go back to the dashboard.</li>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Ask a quick question -->
|
||||
<section class="help-panel" data-tab="ask">
|
||||
<h3>Ask a quick question</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1560,7 +1643,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 13: Stopping and finishing -->
|
||||
<!-- Tab 14: Stopping and finishing -->
|
||||
<section class="help-panel" data-tab="finishing">
|
||||
<h3>Stopping and finishing</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1642,7 +1725,7 @@
|
||||
</p>
|
||||
</section>
|
||||
|
||||
<!-- Tab 14: When something looks stuck -->
|
||||
<!-- Tab 15: When something looks stuck -->
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1764,7 +1847,7 @@
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- Tab 15: Keyboard and preferences -->
|
||||
<!-- Tab 16: Keyboard and preferences -->
|
||||
<section class="help-panel" data-tab="prefs">
|
||||
<h3>Keyboard and preferences</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1845,6 +1928,15 @@
|
||||
joining the strip. Keep only the ones you want; ticking a box plays
|
||||
its sound.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Cleanup</strong>: <strong>Find files to clean up</strong>
|
||||
lists what Plan2Code doesn't need in your
|
||||
<code>~/.plan2code</code> folder: sessions nobody has opened for
|
||||
30 days, and files or folders that ended up there by mistake. It
|
||||
shows each one with its size, and <strong>Delete these</strong>
|
||||
removes exactly that list. Your preferences, saved folders, models,
|
||||
the launcher and the session you are in always stay.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Back to default</strong> puts everything back as it was, and
|
||||
sets Role back to Not set.
|
||||
@@ -1871,7 +1963,7 @@
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<!-- Tab 16: Privacy and where things are saved -->
|
||||
<!-- Tab 17: Privacy and where things are saved -->
|
||||
<section class="help-panel" data-tab="privacy">
|
||||
<h3>Privacy and where things are saved</h3>
|
||||
<p class="help-lead">
|
||||
@@ -1908,7 +2000,11 @@
|
||||
</li>
|
||||
<li>
|
||||
your role, theme, colors, card width and sounds, in
|
||||
<code>looks.json</code>.
|
||||
<code>looks.json</code>;
|
||||
</li>
|
||||
<li>
|
||||
your Subagents switch for each project and skill, in
|
||||
<code>subagents.json</code>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
@@ -1983,6 +2079,16 @@
|
||||
</div>
|
||||
<p class="help">Ticking one plays it. Play sounds switches them all off at once and keeps your picks for when you switch back on.</p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-cleanup">
|
||||
<legend>Cleanup</legend>
|
||||
<p class="help">Finds what Plan2Code doesn't need in your <code>~/.plan2code</code> folder: sessions nobody has opened for 30 days, and files or folders that ended up there by mistake. You see the list before anything is deleted. Your preferences, saved folders, models, the launcher and this session always stay.</p>
|
||||
<div class="cleanup-list" id="cleanup-list" aria-label="What would be deleted"></div>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small" id="cleanup-scan">Find files to clean up</button>
|
||||
<button type="button" class="btn small danger" id="cleanup-delete" hidden>Delete these</button>
|
||||
<span class="help" id="cleanup-status" role="status"></span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges looks-models">
|
||||
<legend>Models</legend>
|
||||
<div class="models-tabs" role="group" aria-label="Which agent">
|
||||
@@ -2012,6 +2118,46 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Subagents: the switch for this skill, filled from the frame's
|
||||
`subagents` by app.js and saved through POST /subagents. It borrows
|
||||
the User Preferences dialog's classes, so it needs no dialog styles of
|
||||
its own, only a themed number box. -->
|
||||
<dialog class="modal looks subagents" id="subagents-modal" aria-labelledby="subagents-title">
|
||||
<h2 id="subagents-title">Subagents</h2>
|
||||
<p class="modal-blurb">
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
<div class="models-actions">
|
||||
<button type="button" class="btn small ghost" id="subagents-default">Reset to default</button>
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn ghost" id="subagents-cancel">Cancel</button>
|
||||
<button type="button" class="btn primary" id="subagents-save">Save</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- The Workspace: the folder this session started in plus any added as
|
||||
context. The list is drawn by app.js from the frame's `workspace`;
|
||||
every change goes through the server's /workspace routes. -->
|
||||
@@ -2181,6 +2327,24 @@
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<!-- Opened from the dashboard's UPDATE AVAILABLE banner. The versions and
|
||||
the copy row are filled by app.js; the update itself runs in a
|
||||
terminal, never from this page. -->
|
||||
<dialog class="modal" id="update-modal" aria-labelledby="update-title">
|
||||
<h2 id="update-title">A new Plan2Code is available</h2>
|
||||
<p class="modal-blurb" id="update-versions"></p>
|
||||
<ol class="update-steps">
|
||||
<li>
|
||||
Run this in your terminal (not in this page or your agent):
|
||||
<div class="update-command" id="update-command"></div>
|
||||
</li>
|
||||
<li>When it finishes, close this console and start <code>plan2code</code> again.</li>
|
||||
</ol>
|
||||
<div class="modal-actions">
|
||||
<button type="button" class="btn primary" id="update-done">Close</button>
|
||||
</div>
|
||||
</dialog>
|
||||
|
||||
<footer class="footer">
|
||||
<div class="footer-summary" id="footer-summary" aria-live="polite">
|
||||
Nothing to send yet.
|
||||
|
||||
@@ -5,7 +5,10 @@
|
||||
// popover; this file owns the rules. No DOM access at module scope and no
|
||||
// imports: the page and `node --test` both import this file.
|
||||
|
||||
const NAME_CHAR = /[a-z0-9-]/;
|
||||
// Uppercase too: "@Repo" must still name @repo — names are forced lowercase
|
||||
// by the workspace rules, and a query typed with a capital otherwise matches
|
||||
// nothing and opens no suggestions at all.
|
||||
const NAME_CHAR = /[a-z0-9-]/i;
|
||||
const MAX_MATCHES = 6;
|
||||
|
||||
/**
|
||||
@@ -23,11 +26,13 @@ export function mentionAt(text, caret) {
|
||||
}
|
||||
|
||||
// Names starting with the query first, then names containing it, in the
|
||||
// order given, at most six.
|
||||
// order given, at most six. Case-folded: folder names are lowercase by rule,
|
||||
// and "@Repo" should still find @repo rather than claim nothing matches.
|
||||
export function matchNames(names, query) {
|
||||
const q = String(query || "");
|
||||
const prefix = names.filter((n) => n.startsWith(q));
|
||||
const inside = names.filter((n) => !n.startsWith(q) && n.includes(q));
|
||||
const q = String(query || "").toLowerCase();
|
||||
const fold = (n) => String(n).toLowerCase();
|
||||
const prefix = names.filter((n) => fold(n).startsWith(q));
|
||||
const inside = names.filter((n) => !fold(n).startsWith(q) && fold(n).includes(q));
|
||||
return [...prefix, ...inside].slice(0, MAX_MATCHES);
|
||||
}
|
||||
|
||||
|
||||
@@ -36,85 +36,271 @@ export function needsRoleNudge(looks) {
|
||||
return !Object.hasOwn(looks, "role");
|
||||
}
|
||||
|
||||
// The wording is approved (PLAN-DRAFT Appendix A); a change is a page change.
|
||||
// The wording was revised in v2.5.1 (Markdown sections); a change is a page change.
|
||||
const template = (id, label, lines) => Object.freeze({ id, label, text: lines.join("\n") });
|
||||
|
||||
export const TEMPLATES = Object.freeze({
|
||||
"engineering-spec": template("engineering-spec", "Engineering spec", [
|
||||
"Engineering spec for: [the feature or change, in a sentence]",
|
||||
"Who reads it: the engineers who will build and review it.",
|
||||
"What it should pin down: the behaviour, the parts of the code it touches, the interfaces between them, and how we'll know it works.",
|
||||
"What I already know: [constraints, links, earlier attempts]",
|
||||
"## Engineering spec",
|
||||
"[the feature or change, in a sentence]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineers who will build and review it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The behaviour, the parts of the code it touches, the interfaces between them, the simpler options we're turning down, and how we'll know it works.",
|
||||
"",
|
||||
"## Out of scope",
|
||||
"[what this deliberately won't do]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[constraints, links, earlier attempts]",
|
||||
]),
|
||||
"product-requirements": template("product-requirements", "Product requirements", [
|
||||
"Product requirements for: [the feature, in a sentence]",
|
||||
"Who it's for: [the users], and the product, design and engineering people deciding on it.",
|
||||
"What it should pin down: the problem, who has it, what success looks like, and what waits for later.",
|
||||
"What I already know: [customer asks, data, deadlines]",
|
||||
"## Product requirements",
|
||||
"[the feature, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"[the users], and the product, design and engineering people deciding on it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The problem, who has it, the evidence it's real, and how we'll measure success.",
|
||||
"",
|
||||
"## Not doing",
|
||||
"[what this release leaves out]",
|
||||
"",
|
||||
"## What I already know",
|
||||
"[customer asks, data, deadlines]",
|
||||
]),
|
||||
"design-decision": template("design-decision", "Design decision", [
|
||||
"A design decision to work out: [the choice we're facing, in a sentence]",
|
||||
"Who it's for: the engineers and architects who will live with it.",
|
||||
"What it should pin down: the options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"Constraints: [performance, compatibility, deadlines, team skills]",
|
||||
"## Design decision",
|
||||
"[the choice we're facing, in a sentence]",
|
||||
"",
|
||||
"## Who it's for",
|
||||
"The engineers and architects who will live with it.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"The options, the trade-offs of each, the one we pick and why, and what it costs us later.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[performance, compatibility, deadlines, team skills]",
|
||||
]),
|
||||
"test-strategy": template("test-strategy", "Test strategy", [
|
||||
"Test strategy for: [the feature or area]",
|
||||
"Who reads it: QA and the engineers writing the tests.",
|
||||
'What it should pin down: what\'s risky, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"What exists today: [current tests, known gaps]",
|
||||
"## Test strategy",
|
||||
"[the feature or area]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"QA and the engineers writing the tests.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
'What\'s riskiest, meaning what costs most if it breaks, what gets tested at which level (unit, integration, end to end, by hand), the test data needed, and what "done" means.',
|
||||
"",
|
||||
"## What exists today",
|
||||
"[current tests, known gaps]",
|
||||
]),
|
||||
"scoping-rollout": template("scoping-rollout", "Scoping & rollout", [
|
||||
"Scoping and rollout for: [the feature or project]",
|
||||
"Who reads it: the engineering manager, the product lead and the team.",
|
||||
"What it should pin down: what's in the first release and what waits, the build order, risks to the timeline, and how it reaches users (flags, stages, who goes first).",
|
||||
"Constraints: [dates, people, dependencies]",
|
||||
"## Scoping and rollout",
|
||||
"[the feature or project]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"The engineering manager, the product lead and the team.",
|
||||
"",
|
||||
"## What it should pin down",
|
||||
"What's in the first release and what waits, the build order, risks to the timeline, how it reaches users (flags, stages, who sees it first), and how we roll it back.",
|
||||
"",
|
||||
"## Constraints",
|
||||
"[dates, people, dependencies]",
|
||||
]),
|
||||
"brainstorm-notes": template("brainstorm-notes", "Brainstorm → curated notes", [
|
||||
"Brainstorm to turn into curated notes: [the topic or rough idea]",
|
||||
"Who reads the notes: [the team or people this goes to]",
|
||||
"What I want out of it: the ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"Starting thoughts: [anything already on your mind]",
|
||||
"## Brainstorm to curated notes",
|
||||
"[the topic or rough idea]",
|
||||
"",
|
||||
"## Who reads the notes",
|
||||
"[the team or people this goes to]",
|
||||
"",
|
||||
"## What I want out of it",
|
||||
"The ideas worth keeping, grouped, with the open questions, and the ones we dropped and why.",
|
||||
"",
|
||||
"## Starting thoughts",
|
||||
"[anything already on your mind]",
|
||||
]),
|
||||
"bug-investigation": template("bug-investigation", "Bug investigation", [
|
||||
"Bug to investigate: [what's going wrong, in a sentence]",
|
||||
"Steps to reproduce: [1. ... 2. ...]",
|
||||
"Expected: [what should happen]. Actual: [what happens instead]",
|
||||
"Where and since when: [environment, version, first seen]",
|
||||
"## Bug investigation",
|
||||
"[what's going wrong, in a sentence]",
|
||||
"",
|
||||
"## Steps to reproduce",
|
||||
"1. [first step]",
|
||||
"2. [next step]",
|
||||
"",
|
||||
"## Expected",
|
||||
"[what should happen]",
|
||||
"",
|
||||
"## Actual",
|
||||
"[what happens instead]",
|
||||
"",
|
||||
"## How often",
|
||||
"[every time, sometimes, once]",
|
||||
"",
|
||||
"## Error or logs",
|
||||
"[paste the exact text]",
|
||||
"",
|
||||
"## Where and since when",
|
||||
"[environment, version, first seen]",
|
||||
]),
|
||||
"small-change": template("small-change", "Small change", [
|
||||
"Small change: [what to change, in a sentence]",
|
||||
"Where: [the file, screen or command, if you know it]",
|
||||
"Done when: [how you'll tell it worked]",
|
||||
"## Small change",
|
||||
"[what to change, in a sentence]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the file, screen or command, if you know it]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not change]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the command to run or the thing to check]",
|
||||
]),
|
||||
"copy-tweak": template("copy-tweak", "Copy / content tweak", [
|
||||
"Change the wording of: [the screen, message, email or doc]",
|
||||
"Current text: [paste it]",
|
||||
"New text: [paste it, or describe the tone you want]",
|
||||
"Who reads it: [the people who see it]",
|
||||
"## Copy or content tweak",
|
||||
"[the screen, message, email or doc]",
|
||||
"",
|
||||
"## Current text",
|
||||
"[paste it]",
|
||||
"",
|
||||
"## New text",
|
||||
"[paste it, or describe the tone you want]",
|
||||
"",
|
||||
"## Who reads it",
|
||||
"[the people who see it]",
|
||||
]),
|
||||
"ui-polish": template("ui-polish", "UI polish", [
|
||||
"UI polish on: [the screen or component]",
|
||||
"What looks or feels off: [spacing, alignment, colour, states, small screens]",
|
||||
"What good looks like: [a reference, screenshot or description]",
|
||||
"Leave alone: [anything that must not move]",
|
||||
"## UI polish",
|
||||
"[the screen or component]",
|
||||
"",
|
||||
"## What looks or feels off",
|
||||
"[spacing, alignment, colour, states, small screens]",
|
||||
"",
|
||||
"## What good looks like",
|
||||
"[a reference, screenshot or description]",
|
||||
"",
|
||||
"## Leave alone",
|
||||
"[anything that must not move]",
|
||||
]),
|
||||
"visual-prototype": template("visual-prototype", "Visual prototype", [
|
||||
"A throwaway visual prototype of: [the screen or component]",
|
||||
"What to show: [the states or flows to click through]",
|
||||
"What I want to learn: [the question it should answer]",
|
||||
"Where it lives: a prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
"## Visual prototype",
|
||||
"[the screen or component to mock up]",
|
||||
"",
|
||||
"## What to show",
|
||||
"[the states or flows to click through]",
|
||||
"",
|
||||
"## What I want to learn",
|
||||
"[the question it should answer]",
|
||||
"",
|
||||
"## Where it lives",
|
||||
"A prototypes/ folder [or its own branch], never wired into the real code.",
|
||||
]),
|
||||
"add-a-test": template("add-a-test", "Add a test", [
|
||||
"Add a test for: [the function, behaviour or bug]",
|
||||
"Cases to cover: [the normal case, the edge cases, the bug it guards against]",
|
||||
"Where tests live: [the test file or folder, if you know it]",
|
||||
"## Add a test",
|
||||
"[the function, behaviour or bug]",
|
||||
"",
|
||||
"## Cases to cover",
|
||||
"- [the normal case]",
|
||||
"- [the edge cases]",
|
||||
"- [the failure or bug it guards against]",
|
||||
"",
|
||||
"## Where tests live",
|
||||
"[the test file or folder, if you know it]",
|
||||
]),
|
||||
"record-decision": template("record-decision", "Record a decision", [
|
||||
"Record a decision we've already made: [the decision, in a sentence]",
|
||||
"Why: [the reasons, and what we turned down]",
|
||||
"What it commits us to: [the consequences]",
|
||||
"Save it as an ADR in: docs/adr/ [or wherever this repo keeps them]",
|
||||
"## Record a decision",
|
||||
"[the decision we've already made, in a sentence]",
|
||||
"",
|
||||
"## Why",
|
||||
"[what forced the choice, and the options we turned down]",
|
||||
"",
|
||||
"## What it commits us to",
|
||||
"[the consequences]",
|
||||
"",
|
||||
"## Save it in",
|
||||
"docs/adr/ [or wherever this repo keeps them]",
|
||||
]),
|
||||
refactor: template("refactor", "Refactor", [
|
||||
"## Refactor",
|
||||
"[what to restructure, in a sentence]",
|
||||
"",
|
||||
"## Why now",
|
||||
"[what the current shape makes hard]",
|
||||
"",
|
||||
"## Behaviour that must not change",
|
||||
"[the public API, outputs or tests that must stay the same]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the tests that must still pass, and the shape it ends in]",
|
||||
]),
|
||||
"performance-problem": template("performance-problem", "Performance problem", [
|
||||
"## Performance problem",
|
||||
"[what's slow, in a sentence]",
|
||||
"",
|
||||
"## How it's measured today",
|
||||
"[the number, and how you got it]",
|
||||
"",
|
||||
"## Target",
|
||||
"[the number that counts as fixed]",
|
||||
"",
|
||||
"## Where",
|
||||
"[the endpoint, page, query or job]",
|
||||
]),
|
||||
"dependency-upgrade": template("dependency-upgrade", "Dependency upgrade", [
|
||||
"## Dependency upgrade",
|
||||
"[the package, from version to version]",
|
||||
"",
|
||||
"## Why",
|
||||
"[security fix, a feature we need, end of support]",
|
||||
"",
|
||||
"## Known breaking changes",
|
||||
'[release notes link, or "not checked yet"]',
|
||||
"",
|
||||
"## Done when",
|
||||
"[the build, tests or checks that must pass]",
|
||||
]),
|
||||
spike: template("spike", "Spike", [
|
||||
"## Spike",
|
||||
"[the question to answer, in a sentence]",
|
||||
"",
|
||||
"## Why it matters",
|
||||
"[the decision waiting on the answer]",
|
||||
"",
|
||||
"## Time box",
|
||||
"[how long before we stop and decide anyway]",
|
||||
"",
|
||||
"## Answered when",
|
||||
"[the evidence that would settle it]",
|
||||
]),
|
||||
integration: template("integration", "Integration", [
|
||||
"## Integration",
|
||||
"[the system we're connecting to, and why]",
|
||||
"",
|
||||
"## What flows",
|
||||
"[the data or events, and in which direction]",
|
||||
"",
|
||||
"## Their side",
|
||||
"[API docs, auth method, rate limits, test sandbox]",
|
||||
"",
|
||||
"## When it fails",
|
||||
"[what should happen if they're down or slow]",
|
||||
]),
|
||||
"data-migration": template("data-migration", "Data migration", [
|
||||
"## Data migration",
|
||||
"[what moves or changes shape]",
|
||||
"",
|
||||
"## Size and downtime",
|
||||
"[row counts, and whether users can stay on while it runs]",
|
||||
"",
|
||||
"## Rollback",
|
||||
"[how we undo it if it goes wrong]",
|
||||
"",
|
||||
"## Done when",
|
||||
"[the checks that prove nothing was lost]",
|
||||
]),
|
||||
});
|
||||
|
||||
@@ -123,28 +309,28 @@ const orders = (byRole) => Object.freeze(Object.fromEntries(Object.entries(byRol
|
||||
// One full order per role per skill. No "none" row: Not set reads Engineer's.
|
||||
export const TEMPLATE_ORDERS = Object.freeze({
|
||||
pathfinder: orders({
|
||||
engineer: ["engineering-spec", "design-decision", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "engineering-spec", "design-decision", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "design-decision", "brainstorm-notes"],
|
||||
engineer: ["engineering-spec", "design-decision", "spike", "integration", "test-strategy", "scoping-rollout", "product-requirements", "brainstorm-notes"],
|
||||
pm: ["product-requirements", "brainstorm-notes", "scoping-rollout", "spike", "engineering-spec", "design-decision", "integration", "test-strategy"],
|
||||
architect: ["design-decision", "engineering-spec", "integration", "spike", "scoping-rollout", "test-strategy", "product-requirements", "brainstorm-notes"],
|
||||
designer: ["brainstorm-notes", "product-requirements", "design-decision", "spike", "engineering-spec", "scoping-rollout", "integration", "test-strategy"],
|
||||
qa: ["test-strategy", "engineering-spec", "spike", "product-requirements", "integration", "scoping-rollout", "design-decision", "brainstorm-notes"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "spike", "test-strategy", "design-decision", "integration", "brainstorm-notes"],
|
||||
}),
|
||||
plan: orders({
|
||||
engineer: ["engineering-spec", "bug-investigation", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "test-strategy", "design-decision", "bug-investigation"],
|
||||
architect: ["design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "test-strategy", "bug-investigation"],
|
||||
qa: ["test-strategy", "bug-investigation", "engineering-spec", "product-requirements", "scoping-rollout", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "product-requirements", "test-strategy", "bug-investigation", "design-decision"],
|
||||
engineer: ["engineering-spec", "bug-investigation", "refactor", "performance-problem", "integration", "data-migration", "design-decision", "test-strategy", "scoping-rollout", "product-requirements"],
|
||||
pm: ["product-requirements", "scoping-rollout", "engineering-spec", "integration", "test-strategy", "design-decision", "performance-problem", "bug-investigation", "data-migration", "refactor"],
|
||||
architect: ["design-decision", "engineering-spec", "data-migration", "integration", "refactor", "scoping-rollout", "performance-problem", "test-strategy", "product-requirements", "bug-investigation"],
|
||||
designer: ["product-requirements", "design-decision", "engineering-spec", "scoping-rollout", "performance-problem", "test-strategy", "bug-investigation", "integration", "refactor", "data-migration"],
|
||||
qa: ["test-strategy", "bug-investigation", "performance-problem", "engineering-spec", "data-migration", "integration", "product-requirements", "scoping-rollout", "refactor", "design-decision"],
|
||||
em: ["scoping-rollout", "engineering-spec", "data-migration", "product-requirements", "test-strategy", "integration", "bug-investigation", "performance-problem", "refactor", "design-decision"],
|
||||
}),
|
||||
"quick-task": orders({
|
||||
engineer: ["small-change", "bug-investigation", "add-a-test", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "add-a-test", "record-decision"],
|
||||
architect: ["record-decision", "small-change", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "add-a-test", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "small-change", "ui-polish", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "add-a-test", "bug-investigation", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
engineer: ["small-change", "bug-investigation", "refactor", "add-a-test", "dependency-upgrade", "performance-problem", "ui-polish", "record-decision", "copy-tweak", "visual-prototype"],
|
||||
pm: ["copy-tweak", "small-change", "visual-prototype", "ui-polish", "bug-investigation", "performance-problem", "add-a-test", "record-decision", "dependency-upgrade", "refactor"],
|
||||
architect: ["record-decision", "refactor", "small-change", "dependency-upgrade", "performance-problem", "bug-investigation", "add-a-test", "visual-prototype", "ui-polish", "copy-tweak"],
|
||||
designer: ["ui-polish", "visual-prototype", "copy-tweak", "small-change", "bug-investigation", "performance-problem", "add-a-test", "refactor", "dependency-upgrade", "record-decision"],
|
||||
qa: ["add-a-test", "bug-investigation", "performance-problem", "small-change", "dependency-upgrade", "ui-polish", "refactor", "copy-tweak", "visual-prototype", "record-decision"],
|
||||
em: ["small-change", "record-decision", "dependency-upgrade", "add-a-test", "bug-investigation", "performance-problem", "refactor", "copy-tweak", "ui-polish", "visual-prototype"],
|
||||
}),
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Plan2Code Web Console - the Subagents switch's opt-in table, wording and checks.
|
||||
//
|
||||
// The source of truth for which workflows offer the switch, the instruction
|
||||
// each one ships with, the fixed frame every "on" block carries, the exact
|
||||
// lines the agent reads at a pickup (blockFor()), and the house rules for the
|
||||
// helpers an agent reports back (checkHelper()). No DOM access at module scope
|
||||
// and no imports: the server, console.mjs, the page and `node --test` all
|
||||
// import this file.
|
||||
|
||||
// The one place a skill opts in (FR-1). Wording is behaviour-level and names
|
||||
// no harness tool, so any agent can follow it or harmlessly ignore it.
|
||||
export const SUBAGENT_WORKFLOWS = Object.freeze({
|
||||
implement: Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"implement-review": Object.freeze({
|
||||
instruction:
|
||||
"Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.",
|
||||
}),
|
||||
"quick-task": Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
}),
|
||||
review: Object.freeze({
|
||||
instruction:
|
||||
"Split the review across helpers by area (for example correctness, tests and security), then merge and de-duplicate their findings yourself before you report.",
|
||||
}),
|
||||
pathfinder: Object.freeze({
|
||||
instruction:
|
||||
"Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
}),
|
||||
});
|
||||
|
||||
export function offered(workflow) {
|
||||
return typeof workflow === "string" && Object.prototype.hasOwnProperty.call(SUBAGENT_WORKFLOWS, workflow);
|
||||
}
|
||||
|
||||
export const MAX_MIN = 1;
|
||||
export const MAX_MAX = 20;
|
||||
export const DEFAULT_MAX = 3;
|
||||
export const INSTRUCTION_MAX_CHARS = 2000;
|
||||
export const HELPER_TITLE_MAX = 80;
|
||||
export const HELPER_ASK_MAX = 400;
|
||||
export const HELPER_RESULT_MAX = 200;
|
||||
export const HELPER_STATES = Object.freeze(["running", "done", "failed"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
export function defaultInstruction(workflow) {
|
||||
return offered(workflow) ? SUBAGENT_WORKFLOWS[workflow].instruction : "";
|
||||
}
|
||||
|
||||
// The person's own text when they wrote some, else the workflow's default.
|
||||
export function effectiveInstruction(setting) {
|
||||
const own = setting && typeof setting.instruction === "string" ? setting.instruction.trim() : "";
|
||||
return own || defaultInstruction(setting && setting.workflow);
|
||||
}
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
return { workflow, on: false, instruction: null, max: DEFAULT_MAX };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
export function cleanSetting(input) {
|
||||
if (!input || typeof input !== "object" || Array.isArray(input)) return { error: "bad" };
|
||||
if (typeof input.on !== "boolean") return { error: "bad" };
|
||||
let instruction = null;
|
||||
if (input.instruction !== null && input.instruction !== undefined) {
|
||||
if (typeof input.instruction !== "string") return { error: "bad" };
|
||||
const trimmed = input.instruction.trim();
|
||||
if (trimmed.length > INSTRUCTION_MAX_CHARS) return { error: "too-long" };
|
||||
instruction = trimmed || null;
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
|
||||
// The non-editable part of every "on" block (FR-8).
|
||||
export const FRAME_LINES = Object.freeze([
|
||||
"Hand independent work to helpers if your tools allow it; otherwise carry on alone.",
|
||||
"Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.",
|
||||
'If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.',
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// Only the first line of a block starts at column 0, so no line inside it can
|
||||
// be read as an entry of its own (NFR-5).
|
||||
export function onLines({ revision, replaces, max, instruction }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
.map((line) => line.trimEnd())
|
||||
.filter((line) => line.trim());
|
||||
return [
|
||||
`Subagents: on (${label}) — a console setting, not typed by the person.`,
|
||||
...[...FRAME_LINES, ...own, `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
export function offLine(revision) {
|
||||
return `Subagents: off (revision ${revision}) — don't start new helpers for the rest of this session.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the agent is owed at a pickup, given the session setting and the
|
||||
* cursor of what it was last told: `null`, or `{ field, lines, cursor }`
|
||||
* where `cursor` is what to write once the lines are printed. Never says
|
||||
* "off" to an agent that was not told "on" (FR-6). Pure: no clock, no I/O.
|
||||
*/
|
||||
export function blockFor(setting, told) {
|
||||
const last = told || { revision: 0, state: "none" };
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ helpers */
|
||||
|
||||
const isPlainObject = (v) => !!v && typeof v === "object" && !Array.isArray(v);
|
||||
const nonEmpty = (v) => typeof v === "string" && v.trim() !== "";
|
||||
|
||||
// The problems with one reported helper, [] when it is fine.
|
||||
export function checkHelper(entry) {
|
||||
if (!isPlainObject(entry)) return ["helper: each entry must be an object"];
|
||||
if (!nonEmpty(entry.id)) return ["helper: id must be a non-empty string"];
|
||||
const who = `helper "${entry.id}"`;
|
||||
if (entry.alone === true) return entry.id === "alone" ? [] : [`${who}: the working-alone entry must have id "alone"`];
|
||||
const problems = [];
|
||||
if (!nonEmpty(entry.title)) problems.push(`${who}: title must be a non-empty string`);
|
||||
else if (entry.title.length > HELPER_TITLE_MAX) problems.push(`${who}: title must be at most ${HELPER_TITLE_MAX} characters`);
|
||||
if (!nonEmpty(entry.ask)) problems.push(`${who}: ask must be a non-empty string`);
|
||||
else if (entry.ask.length > HELPER_ASK_MAX) problems.push(`${who}: ask must be at most ${HELPER_ASK_MAX} characters`);
|
||||
if (!HELPER_STATES.includes(entry.state)) problems.push(`${who}: state must be running, done or failed`);
|
||||
if (entry.result !== undefined) {
|
||||
if (typeof entry.result !== "string") problems.push(`${who}: result must be a string`);
|
||||
else if (entry.result.length > HELPER_RESULT_MAX) problems.push(`${who}: result must be at most ${HELPER_RESULT_MAX} characters`);
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
// The problems with a whole merged list.
|
||||
export function checkHelpers(list) {
|
||||
if (!Array.isArray(list)) return ["helpers must be an array"];
|
||||
const problems = [];
|
||||
const seen = new Set();
|
||||
let alone = 0;
|
||||
for (const entry of list) {
|
||||
if (isPlainObject(entry) && nonEmpty(entry.id)) {
|
||||
if (seen.has(entry.id)) problems.push(`helper "${entry.id}": duplicate id`);
|
||||
seen.add(entry.id);
|
||||
if (entry.alone === true && ++alone === 2) problems.push(`helper "${entry.id}": only one working-alone entry is allowed`);
|
||||
}
|
||||
problems.push(...checkHelper(entry));
|
||||
}
|
||||
return problems;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the page */
|
||||
|
||||
// The page's rules for the button, the modal and the tab, kept here so they
|
||||
// are tested without a browser. `frame` is the state frame's `subagents`
|
||||
// block; app.js only renders what these say.
|
||||
|
||||
export const CHECKIN_LINE = "Helpers report through Plan2Code, so their progress shows here at its check-ins, not live.";
|
||||
|
||||
const STATE_LABELS = Object.freeze({ running: "Running", done: "Done", failed: "Failed" });
|
||||
|
||||
// The switch shows only where the skill opts in AND the agent's console copy
|
||||
// said it can deliver it (FR-3).
|
||||
export function showSwitch(frame) {
|
||||
return Boolean(frame && frame.offered && frame.supported);
|
||||
}
|
||||
|
||||
// The button's tooltip and accessible name (FR-2).
|
||||
export function switchLabel(frame) {
|
||||
return frame && frame.on ? "Subagents: on" : "Subagents: off";
|
||||
}
|
||||
|
||||
// What the Subagents tab draws: the working-alone note, or one row per helper
|
||||
// in the order the agent reported them. A real helper supersedes the
|
||||
// working-alone marker, so the note only draws when no helper was ever
|
||||
// reported. A result shows once the helper ended.
|
||||
export function helperRows(helpers) {
|
||||
const list = Array.isArray(helpers) ? helpers.filter(isPlainObject) : [];
|
||||
const real = list.filter((h) => h.alone !== true);
|
||||
if (!real.length) return { alone: list.some((h) => h.alone === true), rows: [] };
|
||||
const rows = real.map(({ id, title, ask, state, result }) => ({
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
}));
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
// Never an empty tab. Independent of on / off, so Pathfinder's research
|
||||
// helpers show even with the switch off (FR-11, FR-12).
|
||||
export function showTab(frame, helpers) {
|
||||
return showSwitch(frame) && Array.isArray(helpers) && helpers.length > 0;
|
||||
}
|
||||
@@ -25,17 +25,21 @@ import {
|
||||
LOOKS_FILE,
|
||||
PUBLIC_DIR,
|
||||
SHIPPED_MODELS_FILE,
|
||||
SUBAGENTS_SETTING_FILE,
|
||||
UPDATE_CHECK_FILE,
|
||||
USER_MODELS_FILE,
|
||||
WORKSPACE_FILE,
|
||||
appendChat,
|
||||
appendEvent,
|
||||
chatForFrame,
|
||||
checkDocument,
|
||||
cleanupFindings,
|
||||
currentConversation,
|
||||
ensureDir,
|
||||
fileStamp,
|
||||
handleFile,
|
||||
initialWorkspace,
|
||||
latestOpenCaps,
|
||||
nowIso,
|
||||
parseArgs,
|
||||
pendingChatCount,
|
||||
@@ -44,21 +48,28 @@ import {
|
||||
readJson,
|
||||
readLedger,
|
||||
readOverview,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
rememberWorkspace,
|
||||
rememberedWorkspace,
|
||||
removeCleanup,
|
||||
remoteWarning,
|
||||
saveSubagentStoreEntry,
|
||||
specKey,
|
||||
subagentStoreEntry,
|
||||
typedCount,
|
||||
withStateLock,
|
||||
writeJsonAtomic,
|
||||
writeSubagentSetting,
|
||||
writeWorkspace,
|
||||
} from "./lib.mjs";
|
||||
import { DOC_TYPES, MAX_ATTACHMENTS, MAX_DOC_BYTES, docExt, workflowLabel, workflowTitle } from "./public/answers.js";
|
||||
import { CHAT_LIMIT, CHAT_MAX_CHARS, chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { defaultName, freeName, nameProblem } from "./public/workspace.js";
|
||||
import { checkForUpdate } from "./update-check.mjs";
|
||||
import { WORKSPACE_PICKER_PROMPT, pickFolder, pickerCommand } from "./picker.mjs";
|
||||
|
||||
const args = parseArgs(process.argv.slice(2));
|
||||
@@ -208,6 +219,7 @@ const SERVABLE = new Set([
|
||||
"starters.js",
|
||||
"workspace.js",
|
||||
"meter.js",
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"start-stop.mp3",
|
||||
@@ -597,6 +609,48 @@ function ensureConversation(state) {
|
||||
if (entry) appendEvent(DIR, { type: "chat-reset", reason: entry.reason });
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ subagents */
|
||||
|
||||
// subagents-setting.json has one writer, this server, and the agent hears of
|
||||
// it only through what console.mjs reads there; events.ndjson's latest `open`
|
||||
// says whether the agent's console copy can carry it. Both re-read only when
|
||||
// their file has moved.
|
||||
const SUBAGENTS_SETTING_PATH = path.join(DIR, SUBAGENTS_SETTING_FILE);
|
||||
const EVENTS_PATH = path.join(DIR, "events.ndjson");
|
||||
|
||||
let subagentSettingSeen = { stamp: null, setting: null };
|
||||
function subagentSettingNow() {
|
||||
const stamp = fileStamp(SUBAGENTS_SETTING_PATH);
|
||||
if (stamp !== subagentSettingSeen.stamp) subagentSettingSeen = { stamp, setting: readSubagentSetting(DIR) };
|
||||
return subagentSettingSeen.setting;
|
||||
}
|
||||
|
||||
let capsSeen = { stamp: null, caps: [] };
|
||||
function openCapsNow() {
|
||||
const stamp = fileStamp(EVENTS_PATH);
|
||||
if (stamp !== capsSeen.stamp) capsSeen = { stamp, caps: latestOpenCaps(DIR) };
|
||||
return capsSeen.caps;
|
||||
}
|
||||
|
||||
const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
|
||||
/**
|
||||
* Turn the per-project store into this session's setting, for the workflow
|
||||
* the session is in now. The only place that happens (FR-7): a session an
|
||||
* older server ran has no setting file, so nothing is ever injected into it.
|
||||
* A record that already matches is left alone, revision and all, so a
|
||||
* restart alone never re-tells the agent anything.
|
||||
*/
|
||||
function syncSubagentSetting(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(sessionWorktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const current = readSubagentSetting(DIR);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(DIR, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
}
|
||||
|
||||
// What the page needs to draw itself, in the shape of the SSE state frame.
|
||||
// `have` names that exact view, for the page to hand back when it opens its
|
||||
// stream (see /events).
|
||||
@@ -611,19 +665,33 @@ function stateFrame(state) {
|
||||
chat: { ...chatForFrame(chatEntries(), state), pickedUp: chatPickedUp(), offline: chatOfflineNow(state) },
|
||||
workspace: workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagentsView(state),
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
}
|
||||
|
||||
// The page shows the switch only when `offered && supported` (FR-3); the
|
||||
// frame says both and leaves combining them to the page. `instruction: null`
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function subagentsView(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = subagentSettingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: openCapsNow().includes("subagents"), on, instruction, max, revision };
|
||||
}
|
||||
|
||||
function haveKey() {
|
||||
const { pending, stop } = resultFlags();
|
||||
chatEntries();
|
||||
chatPickedUp();
|
||||
workspaceNow();
|
||||
ledgerEntries();
|
||||
subagentSettingNow();
|
||||
openCapsNow();
|
||||
return (
|
||||
`${STARTED}.${rev}.${pending ? 1 : 0}${stop ? 1 : 0}.${chatSeen.stamp || ""}.${cursorSeen.stamp || ""}` +
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}`
|
||||
`.${workspaceSeen.stamp || ""}.${ledgerSeen.stamp || ""}.${updateInfo ? updateInfo.latest : ""}` +
|
||||
`.${subagentSettingSeen.stamp || ""}.${capsSeen.stamp || ""}`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -648,6 +716,12 @@ function recordSubmitted(state, actions) {
|
||||
if (action.type === "comment") {
|
||||
const pick = (list) => (Array.isArray(list) ? list.map(({ path, name }) => ({ path, name })) : []);
|
||||
item.sentNote = { at, text: String(action.text || ""), images: pick(action.images), files: pick(action.files) };
|
||||
// The person's side of the Notes thread. Left to the agent it was never
|
||||
// written, so a question asked in a note vanished once it was picked up
|
||||
// and the reply under it answered nothing on the page.
|
||||
if (item.sentNote.text.trim() || item.sentNote.images.length || item.sentNote.files.length) {
|
||||
item.thread = [...(Array.isArray(item.thread) ? item.thread : []), { who: "user", ...item.sentNote }];
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const { i, type, ...rest } = action;
|
||||
@@ -933,6 +1007,38 @@ function pushState() {
|
||||
if (stateNow) broadcast("state", stateFrame(stateNow));
|
||||
}
|
||||
|
||||
/* --------------------------------------------------------- update check */
|
||||
|
||||
// The version this console was installed as: install.js writes version.json
|
||||
// beside console.mjs; a dev checkout falls back to the repo root's.
|
||||
function installedVersion() {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return version;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filled in once the boot-time check answers; until then, and whenever it
|
||||
// fails, the frame carries no `update` and the page shows no banner.
|
||||
let updateInfo = null;
|
||||
let updateLatest = null;
|
||||
|
||||
// Started at boot and never awaited: git may take up to its 10 s limit, and
|
||||
// nothing the person sees waits on it. The catch is not optional: a throw in
|
||||
// pushState() would otherwise be an unhandled rejection, which ends the server.
|
||||
function startUpdateCheck() {
|
||||
const installed = installedVersion();
|
||||
if (!installed) return;
|
||||
checkForUpdate({ installed, cacheFile: UPDATE_CHECK_FILE })
|
||||
.then((result) => {
|
||||
updateLatest = result?.latest ?? null;
|
||||
updateInfo = result?.updateAvailable ? { installed: result.installed, latest: result.latest } : null;
|
||||
if (updateInfo) pushState();
|
||||
})
|
||||
.catch(() => {});
|
||||
}
|
||||
|
||||
let agentSeenAt = Date.now();
|
||||
function agentLastSeen() {
|
||||
return new Date(agentSeenAt).toISOString();
|
||||
@@ -1039,10 +1145,8 @@ const server = http.createServer((req, res) => {
|
||||
}
|
||||
|
||||
if (pathname === "/version" && req.method === "GET") {
|
||||
for (const file of [path.join(HERE, "version.json"), path.join(HERE, "..", "..", "version.json")]) {
|
||||
const version = readJson(file, {}).version;
|
||||
if (typeof version === "string" && version) return json(res, 200, { version });
|
||||
}
|
||||
const version = installedVersion();
|
||||
if (version) return json(res, 200, { version, latest: updateLatest });
|
||||
return json(res, 404, { error: "no version" });
|
||||
}
|
||||
|
||||
@@ -1090,7 +1194,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/draft" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// Debounced client-side; this is just the durable mirror. Twenty minutes
|
||||
// of someone's structured answers must not die with a closed tab.
|
||||
try {
|
||||
@@ -1115,7 +1219,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/looks" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
// `set` carries only the keys one tab changed, merged onto what is on
|
||||
// disk, so a tab holding stale settings cannot undo another tab's change.
|
||||
const set = body && body.set !== undefined ? cleanLooks(body.set) : null;
|
||||
@@ -1131,6 +1235,39 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// The Subagents switch for the session's workflow. Saved per project folder
|
||||
// for the next session, and applied to this one with a bumped revision, which
|
||||
// is what console.mjs hands the agent at its next pickup. Never blocked by,
|
||||
// and never blocking, a card send.
|
||||
if (pathname === "/subagents" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const state = readState();
|
||||
if (!state || !offered(state.workflow)) return json(res, 400, { error: "not-offered" });
|
||||
const clean = cleanSetting(body);
|
||||
if (clean.error) return json(res, 400, { error: clean.error });
|
||||
const { on, instruction, max } = clean;
|
||||
const current = readSubagentSetting(DIR);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
// The store is per project, so another session may have moved it since
|
||||
// this one synced: it always takes the person's latest pick. Only a
|
||||
// real change to this session's setting bumps what the agent hears.
|
||||
const unchanged = Boolean(current && sameSetting(current, next));
|
||||
try {
|
||||
saveSubagentStoreEntry(sessionWorktree(), state.workflow, { on, instruction, max });
|
||||
if (!unchanged) writeSubagentSetting(DIR, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
}
|
||||
if (unchanged) return json(res, 200, { ok: true, setting: current });
|
||||
const setting = readSubagentSetting(DIR);
|
||||
appendEvent(DIR, { type: "subagents", on, revision: setting.revision });
|
||||
pushState();
|
||||
return json(res, 200, { ok: true, setting });
|
||||
});
|
||||
}
|
||||
|
||||
// The launcher's model menu: what ships (read-only here) and what the user added.
|
||||
if (pathname === "/models" && req.method === "GET") {
|
||||
const saved = readJson(USER_MODELS_FILE, null) || {};
|
||||
@@ -1141,7 +1278,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/models" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const { models, error } = cleanModels(body && body.models);
|
||||
if (error) return json(res, 400, { error });
|
||||
try {
|
||||
@@ -1154,6 +1291,24 @@ const server = http.createServer((req, res) => {
|
||||
});
|
||||
}
|
||||
|
||||
// User Preferences -> Cleanup. `{ scan: true }` lists what is not needed in
|
||||
// ~/.plan2code; `{ delete: [id] }` removes those of the ids a fresh scan
|
||||
// still finds. Never this session, never a path the page sent.
|
||||
if (pathname === "/cleanup" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (body && Array.isArray(body.delete)) {
|
||||
return removeCleanup(body.delete, { skipSid: SID })
|
||||
.then((done) => json(res, 200, { ok: true, ...done }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
}
|
||||
return cleanupFindings({ skipSid: SID })
|
||||
.then(({ items, bytes }) => json(res, 200, { ok: true, bytes, items: items.map(({ path: _p, ...item }) => item) }))
|
||||
.catch((e) => json(res, 500, { error: String(e.message) }));
|
||||
});
|
||||
}
|
||||
|
||||
if (pathname === "/upload" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
const contentType = String(req.headers["content-type"] || "");
|
||||
@@ -1260,7 +1415,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/submit" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, 400, { error: "body must be JSON" });
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
if (!body || !Array.isArray(body.actions) || body.actions.length === 0) {
|
||||
return json(res, 400, { error: "actions must be a non-empty array" });
|
||||
}
|
||||
@@ -1341,6 +1496,9 @@ const server = http.createServer((req, res) => {
|
||||
try {
|
||||
ensureConversation(written.state);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(written.state);
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
// Name the items that went. A page with OTHER answers staged should drop
|
||||
@@ -1361,6 +1519,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const state = readState() || {};
|
||||
const current = currentConversation(chatEntries()).conversation;
|
||||
@@ -1424,6 +1583,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/chat/decision" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
if (body.decision !== "approve" && body.decision !== "decline") return json(res, 400, { error: "bad" });
|
||||
if (body.text !== undefined && typeof body.text !== "string") return json(res, 400, { error: "bad" });
|
||||
@@ -1472,6 +1632,7 @@ const server = http.createServer((req, res) => {
|
||||
if (Object.hasOwn(workspaceRoutes, pathname) && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
let answer;
|
||||
try {
|
||||
@@ -1489,6 +1650,7 @@ const server = http.createServer((req, res) => {
|
||||
if (pathname === "/workspace/scope" && req.method === "POST") {
|
||||
if (!originOk(req, port)) return json(res, 403, { error: "bad origin" });
|
||||
return readBody(req, (err, body) => {
|
||||
if (err && err.tooBig) return json(res, 413, { error: "too large" });
|
||||
if (err || !body || typeof body !== "object" || Array.isArray(body)) return json(res, 400, { error: "bad" });
|
||||
const spec = typeof body.spec === "string" ? body.spec : "";
|
||||
if (spec && !/^specs\/[^/\\]+$/.test(specKey(spec))) return json(res, 400, { reason: "bad-spec" });
|
||||
@@ -1589,15 +1751,19 @@ function readBody(req, cb) {
|
||||
let tooBig = false;
|
||||
req.on("data", (c) => {
|
||||
size += c.length;
|
||||
// Drain past the cap rather than destroy, exactly like readRaw: a
|
||||
// destroyed request emits 'close', never 'end' or 'error', so cb would
|
||||
// never run and the page would see a reset instead of the 413 that names
|
||||
// the problem.
|
||||
if (size > MAX_BODY) {
|
||||
tooBig = true;
|
||||
req.destroy();
|
||||
chunks.length = 0;
|
||||
return;
|
||||
}
|
||||
chunks.push(c);
|
||||
});
|
||||
req.on("end", () => {
|
||||
if (tooBig) return cb(new Error("too large"));
|
||||
if (tooBig) return cb(Object.assign(new Error("too large"), { tooBig: true }));
|
||||
try {
|
||||
cb(null, JSON.parse(Buffer.concat(chunks).toString("utf8")));
|
||||
} catch (e) {
|
||||
@@ -1659,6 +1825,9 @@ function checkState() {
|
||||
try {
|
||||
ensureConversation(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(parsed);
|
||||
} catch {}
|
||||
try {
|
||||
followSpecDir(parsed);
|
||||
} catch {}
|
||||
@@ -1833,7 +2002,13 @@ function onListening(port) {
|
||||
try {
|
||||
bootWorkspace();
|
||||
} catch {}
|
||||
try {
|
||||
syncSubagentSetting(readState());
|
||||
} catch {}
|
||||
process.stdout.write(JSON.stringify({ type: "ready", url, port, sid: SID }) + "\n");
|
||||
try {
|
||||
startUpdateCheck();
|
||||
} catch {}
|
||||
try {
|
||||
process.send?.({ type: "listening", port });
|
||||
} catch {}
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
// Plan2Code Web Console - is a newer Plan2Code release out?
|
||||
//
|
||||
// `git ls-remote --tags` needs no API token and no rate-limited REST call,
|
||||
// rides on the person's own git and proxy setup, and the newest `vX.Y.Z`
|
||||
// release tag is "latest". The server
|
||||
// starts this at boot and never waits on it; the answer, failures included, is
|
||||
// cached for an hour so a burst of sessions asks GitHub once.
|
||||
//
|
||||
// Nothing here reads, stores or sends a credential: git authenticates itself,
|
||||
// with every prompt turned off so a missing login fails fast instead of
|
||||
// opening a window nobody asked for.
|
||||
//
|
||||
// Node built-ins only.
|
||||
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export const REPO_URL = "https://github.com/jparkerweb/plan2code.git";
|
||||
export const RELEASES_URL = "https://github.com/jparkerweb/plan2code/releases/";
|
||||
export const CACHE_MS = 60 * 60 * 1000;
|
||||
|
||||
const SEMVER = /^\d+\.\d+\.\d+$/;
|
||||
const TAG_REF = /refs\/tags\/v(\d+\.\d+\.\d+)$/;
|
||||
|
||||
/** -1, 0 or 1 comparing two plain X.Y.Z versions numerically; null unless both are X.Y.Z. */
|
||||
export function compareVersions(a, b) {
|
||||
if (typeof a !== "string" || typeof b !== "string" || !SEMVER.test(a) || !SEMVER.test(b)) return null;
|
||||
const x = a.split(".").map(Number);
|
||||
const y = b.split(".").map(Number);
|
||||
for (let i = 0; i < 3; i++) {
|
||||
if (x[i] !== y[i]) return x[i] < y[i] ? -1 : 1;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The highest `vX.Y.Z` tag in `git ls-remote --tags` output, without the `v`.
|
||||
* Peeled lines (`^{}`) never match, so an annotated tag counts once, and
|
||||
* pre-releases or other tag names are ignored. Null when nothing matches.
|
||||
*/
|
||||
export function latestTag(text) {
|
||||
if (typeof text !== "string") return null;
|
||||
let best = null;
|
||||
for (const line of text.split(/\r?\n/)) {
|
||||
const m = TAG_REF.exec(line.trim());
|
||||
if (m && (best === null || compareVersions(m[1], best) > 0)) best = m[1];
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function readCache(cacheFile, now) {
|
||||
try {
|
||||
const cached = JSON.parse(fs.readFileSync(cacheFile, "utf8"));
|
||||
if (!cached || typeof cached.checkedAt !== "number" || now - cached.checkedAt >= CACHE_MS) return undefined;
|
||||
return typeof cached.latest === "string" ? cached.latest : null;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function writeCache(cacheFile, data) {
|
||||
const tmp = cacheFile + "." + process.pid + ".tmp";
|
||||
try {
|
||||
fs.mkdirSync(path.dirname(cacheFile), { recursive: true });
|
||||
fs.writeFileSync(tmp, JSON.stringify(data, null, 2));
|
||||
fs.renameSync(tmp, cacheFile);
|
||||
} catch {
|
||||
try {
|
||||
fs.rmSync(tmp, { force: true });
|
||||
} catch {}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* `git ls-remote --tags` against the repo: resolves its stdout, or null when
|
||||
* git is missing, fails, or is still going after `timeoutMs`. No shell, no
|
||||
* window, no prompt.
|
||||
*/
|
||||
export function runLsRemote({ timeoutMs = 10000 } = {}) {
|
||||
return new Promise((resolve) => {
|
||||
let settled = false;
|
||||
const done = (value) => {
|
||||
if (settled) return;
|
||||
settled = true;
|
||||
clearTimeout(timer);
|
||||
resolve(value);
|
||||
};
|
||||
const env = { ...process.env, GIT_TERMINAL_PROMPT: "0", GCM_INTERACTIVE: "never" };
|
||||
if (!process.env.GIT_SSH_COMMAND) env.GIT_SSH_COMMAND = "ssh -o BatchMode=yes";
|
||||
let child;
|
||||
try {
|
||||
child = spawn("git", ["ls-remote", "--tags", REPO_URL], {
|
||||
shell: false,
|
||||
windowsHide: true,
|
||||
stdio: ["ignore", "pipe", "ignore"],
|
||||
env,
|
||||
});
|
||||
} catch {
|
||||
return resolve(null);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
try {
|
||||
child.kill();
|
||||
} catch {}
|
||||
done(null);
|
||||
}, timeoutMs);
|
||||
timer.unref?.();
|
||||
let out = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk) => {
|
||||
out += chunk;
|
||||
});
|
||||
child.on("error", () => done(null));
|
||||
child.on("close", (code) => done(code === 0 ? out : null));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `installed` is behind the newest release: `{ installed, latest,
|
||||
* updateAvailable }`, or null when either version is unknown. Reuses a cache
|
||||
* under an hour old, and caches a failed lookup as `latest: null` so it is
|
||||
* not retried until the hour is up. Never throws.
|
||||
*/
|
||||
export async function checkForUpdate({ installed, cacheFile, now = Date.now(), run = runLsRemote }) {
|
||||
try {
|
||||
let latest = readCache(cacheFile, now);
|
||||
if (latest === undefined) {
|
||||
latest = latestTag(await run());
|
||||
writeCache(cacheFile, { checkedAt: now, latest });
|
||||
}
|
||||
const order = compareVersions(installed, latest);
|
||||
if (latest === null || order === null) return null;
|
||||
return { installed, latest, updateAvailable: order < 0 };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "Plan2Code",
|
||||
"version": "2.4.1",
|
||||
"version": "2.5.1",
|
||||
"description": "A structured 4-step workflow methodology for AI-assisted software development",
|
||||
"keywords": [
|
||||
"ai",
|
||||
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-04",
|
||||
"releaseDate": "2026-10-07",
|
||||
"mode": "utility"
|
||||
}
|
||||
@@ -39,10 +39,10 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
| Scope | Trigger | Reviews |
|
||||
|-------|---------|---------|
|
||||
| **Focused** | User names files/functions, or conversation work detected | Specified files only |
|
||||
| **Branch** | "review my changes" or no context available | Branch changes vs main |
|
||||
| **Branch** | "review my changes", or picked when asked | Branch changes vs main |
|
||||
| **Full** | "full review" or names a subsystem | Entire codebase/subsystem |
|
||||
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Fallback = `branch`. Ambiguous? Ask.
|
||||
**Detection:** 1) User prompt wins. 2) Conversation context = `focused`. 3) Scope already decided by a host workflow (a build's review, `building.md`) = use it. 4) Standalone with nothing named = scan, then ask (Step 1). Never default to `branch` silently. Ambiguous? Ask.
|
||||
|
||||
**Thoroughness:** Scope controls WHAT is reviewed, not HOW DEEPLY. Every review is thorough.
|
||||
|
||||
@@ -52,7 +52,7 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
## Process
|
||||
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, use `ask_user_question` — never guess.
|
||||
**Pre-flight:** Check AGENTS.md — use conventions if found, note if missing. Determine review target from user prompt or conversation context. If neither provides clear signal, scan and use `ask_user_question` (Step 1) — never guess.
|
||||
|
||||
**Reference files:** Companion files loaded via Read directives. Fallback rules inline if unavailable.
|
||||
|
||||
@@ -62,7 +62,8 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
1. **User prompt** — use it.
|
||||
2. **Conversation context** — recent work? Those artifacts. Scope: `focused`.
|
||||
3. **Git fallback** — run `review-scope.mjs`. It compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
|
||||
3. **Standalone, nothing named** — do not assume a target. Do a quick scan (no file reading): `review-scope.mjs`, `specs.mjs list`, recent commits. Then ask what to review (`ask_user_question`; a `choice` on the console, scope questions up front), offering only options the scan supports, each with its size: the branch's changes vs base (files, ~lines, `commits`), uncommitted changes only (when any), a spec/plan under `specs/` (when any), a named subsystem or full codebase, or specific files/folders (free text via Other). Recommend the likeliest first. Nothing found (`empty: true`, no specs)? Ask for files or a subsystem. Use the answer as the scope, then continue.
|
||||
4. **Scan details** — `review-scope.mjs` compares the branch with its base (`main`, else `master`; `--base` overrides; `base` says which it used) and adds staged, unstaged and untracked changes: `files` (status, lines), `counts`, `commits`, `mix`, `batchByRisk`. `empty: true`? Ask user. Exit 3 `no-base` (no `main` or `master`, or no such `--base`)? Rerun with `--base <trunk>`, asking the user which branch is the trunk if unclear. Exit 3 `not-a-repo`? Ask user which files to review.
|
||||
|
||||
**Classify review type** from context (auto-detect; use `ask_user_question` only if ambiguous):
|
||||
|
||||
|
||||
@@ -64,6 +64,13 @@ progress bar is the first thing someone watching a build looks at. The session
|
||||
meter counts the build's tasks from `cleared` as it rises, so keep it current,
|
||||
and start every phase (a second one in the same run too) at `"cleared": 0`.
|
||||
|
||||
`"version": 1` is for the first phase of a session only. A doc's version
|
||||
never goes back (console.md → House rules, rule 9), so a later phase in the
|
||||
same session reposts `phase` and `phasefile` at one more than the version the
|
||||
page holds, with the new phase's title and content. The same goes for
|
||||
`report` at sign-off and `review` in a mid-session review: version 1 the
|
||||
first time, then up from wherever the page has it.
|
||||
|
||||
`phasefile` is the whole `phase-X.md`, verbatim from disk, as its own tab —
|
||||
the person can read the prerequisites and task specs while you build. Re-post
|
||||
it whenever the file changes, which is every task: the checkbox write that
|
||||
@@ -111,6 +118,12 @@ printed), never into the project or into `~/.plan2code/console/` directly:
|
||||
- Do not call `wait` while building. There is nothing to collect, and the page
|
||||
holds anything the person sends until you next look.
|
||||
|
||||
A build may receive a `Subagents:` standing instruction, on `open` output or a
|
||||
`chat` check between tasks. Follow console.md → Standing instructions for
|
||||
handing independent tasks to helpers and reporting them as `helpers`. Keep the
|
||||
per-task progress posts, the checkbox writes, the chat checks and the sign-off
|
||||
with you.
|
||||
|
||||
### Quick questions between tasks
|
||||
|
||||
The person can ask a Quick question on the Ask tab at any point in a build
|
||||
@@ -195,7 +208,8 @@ only ever be offered once nothing could come of it:
|
||||
`reply` carries `Approve this phase: approved`, which is the terminal's
|
||||
`approved`. If the note that came with an approval asks for a change, treat it
|
||||
as "describe any issues": do the change first and ask again. `changes` means
|
||||
exactly what it says: address it, bump the report's version, and reopen the
|
||||
exactly what it says: address it, bump the report's version (a later phase's
|
||||
report starts above the last one's, too), and reopen the
|
||||
item (`"status": "reopened"`) with a reply in its `thread`. `review` is the
|
||||
person asking for the code review before they approve anything — see "The
|
||||
review, mid-session" below.
|
||||
|
||||
@@ -170,7 +170,7 @@ so even a kill at the worst possible moment costs you a repeat, never an answer.
|
||||
|
||||
| Exit | Meaning | What you do |
|
||||
| --- | --- | --- |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace). | Handle the cards (if any), the chat (if any) and any `workspace` changes, then post once (below, Quick questions and Workspace). |
|
||||
| `0` | They pressed Send, or asked a Quick question. stdout is the result JSON, and may carry `workspace` (changes to the folder list, see Workspace) and `subagents` (the helpers switch, see Standing instructions). | Handle the cards (if any), the chat (if any), any `workspace` changes and any `subagents` block, then post once (below, Quick questions, Workspace and Standing instructions). |
|
||||
| `10` | Still working. stdout has a short progress summary; `pendingWorkspace` counts workspace changes waiting for the next send. | Relay ONE line: the `message` field itself, "Waiting on your answer in the web console", followed by the `terminalLine`. Then call `wait` again. |
|
||||
| `20` | The server is gone. | `open --resume <sid>`, give them the new link, then keep waiting. |
|
||||
| `30` | They pressed Cancel. | Stop. Ask what they want to do, in the terminal. |
|
||||
@@ -243,7 +243,7 @@ summarise it back.
|
||||
Then, in ONE `post`, do all of:
|
||||
|
||||
- mark each answered item `"status": "answered"` and record its `answer`
|
||||
- add your replies to any comment threads
|
||||
- reply to every note in that item's `thread` (shape below)
|
||||
- answer any Quick questions that came with it, in `chat.replies` (see Quick
|
||||
questions)
|
||||
- publish the next batch of questions
|
||||
@@ -251,6 +251,26 @@ Then, in ONE `post`, do all of:
|
||||
|
||||
One post is one atomic update, so the page never shows a half-changed state.
|
||||
|
||||
### Replying to a note
|
||||
|
||||
A `comment` is the person talking to you about that card, often asking
|
||||
something. It shows in the card's **Notes on this** panel, and so does your
|
||||
answer:
|
||||
|
||||
```jsonc
|
||||
{ "items": [{ "id": "p4", "thread": [
|
||||
{ "who": "agent", "text": "A proxy is the server some company networks route traffic through. **Markdown** is fine." }
|
||||
] }] }
|
||||
```
|
||||
|
||||
- Every entry is `{ "who": "agent", "text": "<markdown>" }`. `text`, not
|
||||
`md`: the page reads nothing else. An entry with no `text` is rejected.
|
||||
- The server writes their note into the thread as it arrives. Do not repeat
|
||||
it, and send only your new entries: `thread` appends.
|
||||
- Answer what they asked, in the thread, even when you also change a doc or
|
||||
re-ask the question. "I've updated the doc" alone leaves the question in the
|
||||
panel with no answer under it.
|
||||
|
||||
### Recording the answer
|
||||
|
||||
`answer` takes the same shape the item gave back: `{ "k": "A" }`, `{ "ks": ["A","C"] }`,
|
||||
@@ -627,6 +647,87 @@ for permission is not a failure; report only a read that failed after it.
|
||||
|
||||
---
|
||||
|
||||
## Standing instructions
|
||||
|
||||
On the skills that offer it (`implement`, `implement-review`, `quick-task`,
|
||||
`review`, `pathfinder`), the person can turn **helpers** (subagents) on or off
|
||||
from the top bar's Subagents button. Their pick is saved per project and per
|
||||
skill, off by default, and reaches you as a standing instruction, only when it
|
||||
changes.
|
||||
|
||||
### What arrives
|
||||
|
||||
A `subagents` field beside `reply`, and `Subagents:` lines last in `reply`,
|
||||
after the card lines, the `Quick question:` blocks and the `Workspace:` lines.
|
||||
It rides on `wait` exit `0`, `chat` exit `0` and `open` output. A setting
|
||||
change alone never ends a `wait` slice: it waits for the next send, or for
|
||||
your next `chat` check.
|
||||
|
||||
```
|
||||
Subagents: on (revision 2) — a console setting, not typed by the person.
|
||||
Hand independent work to helpers if your tools allow it; otherwise carry on alone.
|
||||
Report each helper on the page (console.md → Standing instructions); questions for the person stay with you.
|
||||
If your tools cannot start helpers at all, report one "working alone" entry for this skill run instead; a real helper report removes it.
|
||||
Hand independent tasks in a phase to helpers: tasks that touch different files and do not depend on each other. Keep tasks that share files, the phase's tests and the sign-off with you.
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
An edit while on arrives as `Subagents: on (revision 3, replaces revision 2) — …`
|
||||
with the whole block again; switching off arrives as one line:
|
||||
`Subagents: off (revision 4) — don't start new helpers for the rest of this session.`
|
||||
|
||||
It is a console setting, not something the person typed. It never answers a
|
||||
card, and it is never recorded under `specs/`.
|
||||
|
||||
### Obeying it
|
||||
|
||||
- **On:** hand independent work to helpers if your tools allow it, at most
|
||||
`max` at once, following the instruction lines. `max` is advisory: your
|
||||
harness's own limit still applies.
|
||||
- **A higher revision replaces a lower one.** Follow the latest block only.
|
||||
- **Off:** start no new helpers for the rest of the session. Let running ones
|
||||
finish and report them.
|
||||
- **Nothing arrives:** keep doing what the skill says.
|
||||
- **Scope is the skill run it arrived in.** After a dashboard launch, no block
|
||||
means the switch is off for this skill, even if an earlier skill in the same
|
||||
conversation was told "on": `open` starts the count again, and a launch with
|
||||
the switch off sends nothing.
|
||||
|
||||
### Reporting helpers
|
||||
|
||||
Post them, at your check-ins, so the page's Subagents tab can show them. The
|
||||
page never hears from a helper directly:
|
||||
|
||||
```jsonc
|
||||
{ "helpers": [
|
||||
{ "id": "h1", "title": "Read the store helpers", "ask": "Find every caller of readSubagentSetting.", "state": "running" },
|
||||
{ "id": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass." }
|
||||
] }
|
||||
```
|
||||
|
||||
- `id` (non-empty), `title` (at most 80 characters), `ask` (at most 400) and
|
||||
`state` (`running`, `done` or `failed`) are required; `result` (at most 200)
|
||||
is the one line you add once a helper ends.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
updates in place. `"helpers": null` clears the list. A dashboard hop clears it
|
||||
too; a resume into the same skill keeps it.
|
||||
- One post per change worth seeing, not a stream.
|
||||
- Questions for the person stay with you, never with a helper: most harnesses
|
||||
give helpers no way to ask, and an answer only reaches the agent holding the
|
||||
session.
|
||||
- **No way to start helpers at all?** Post one `{ "id": "alone", "alone": true }`
|
||||
entry for the skill run instead. The tab then says you are working alone.
|
||||
It is a claim about your tools, not about the moment — post it only when no
|
||||
helper mechanism exists. Reporting a real helper removes it, so an early
|
||||
`alone` can never hide a later helper.
|
||||
- **Pathfinder:** research questions always use helpers and are always
|
||||
reported, whatever the switch says. The switch governs recon, sketches and
|
||||
lookups beside the conversation.
|
||||
- Helpers add no session meter points. Post no `run` for them.
|
||||
|
||||
---
|
||||
|
||||
## Launches (dashboard only)
|
||||
|
||||
A `dashboard` session is not a conversation: the page draws a menu of every
|
||||
@@ -661,9 +762,17 @@ finish are dropped, so you start on a blank page and post your own. A skill
|
||||
run inline from another (a quick task's review) keeps the page it was
|
||||
handed. A
|
||||
fresh `open` would strand the page the person is watching on the dashboard's
|
||||
session while your questions went to a page nobody has open. Then run the
|
||||
skill normally: its Interface question was already answered by being
|
||||
launched, so start where its real work starts.
|
||||
session while your questions went to a page nobody has open.
|
||||
|
||||
> **Never hand this to a skill-invocation tool. Open its `SKILL.md` with your
|
||||
> own file-read tool and follow it from the top instead.** Every Plan2Code
|
||||
> skill below the dashboard ships `disable-model-invocation: true` on
|
||||
> purpose — it exists to be read and followed inline, not launched as a
|
||||
> sub-skill — and calling one through a skill-invocation tool errors out and
|
||||
> strands the hand-off mid-launch.
|
||||
|
||||
Its Interface step is already answered by having been launched, so start
|
||||
where its real work starts.
|
||||
|
||||
The menu itself is the page's own list — you never send it. The page knows
|
||||
the repo too: `open` scans `AGENTS.md` and `specs/` into `state.scan`
|
||||
@@ -735,7 +844,10 @@ commands follow the pipeline: the sign-off's is
|
||||
|
||||
### Review (`review`)
|
||||
|
||||
Scope questions up front, then the findings report as a doc (`id: "report"`),
|
||||
Scope questions up front — run standalone with nothing named, the first is
|
||||
a `choice`, "What should I review?", built from a quick scan (branch changes,
|
||||
uncommitted changes, specs, files you name; each option with its size),
|
||||
never an assumed target; a build's review skips it (`building.md`). Then the findings report as a doc (`id: "report"`),
|
||||
then the pick-what-gets-fixed menu as a `multi` or `choice` keyed by finding
|
||||
id, carrying `"doc": "report"` so the card links straight to the findings.
|
||||
Settle that item (`"status": "answered"` plus the `answer` they sent) in
|
||||
@@ -769,6 +881,8 @@ that is what the person is there to download. The finish carries no
|
||||
- Chart Step 8's research subagents must all report back before the
|
||||
finish (Finishing → Nothing of yours may still be running); the finish
|
||||
body then names what each one found.
|
||||
- Report every research subagent as a helper, whatever the Subagents switch
|
||||
says (Standing instructions → Reporting helpers).
|
||||
- At every session end, post `finish` (headline, `body`, and Form A's command as
|
||||
`command`) BEFORE `stop`. Someone who spent the session in the browser never
|
||||
sees the Trail Footer, and without this their last screen promises a question
|
||||
@@ -829,6 +943,12 @@ know:
|
||||
| 5, User Feedback | Optional items, `required: false`: the rating as a `choice` of 1 to 10 or a `text`, the three reasons as `text`. The submit-to-maintainer consent is a `confirm`. |
|
||||
| 6, Spec Cleanup | A `confirm` before moving anything, the archive paths in `consequences`, and a line that the spec's remembered workspace folders are forgotten too (`console.mjs forget --spec specs/<feature>` after the move). |
|
||||
|
||||
Post `activity` as each step starts, before its doc or question lands — reading
|
||||
the spec, running `specs.mjs status` or `archive --dry-run`, checking the
|
||||
implementation — the same way Review does. A step with no card of its own
|
||||
(2, 3) is otherwise a stretch of silence the page can only show as "Starting
|
||||
Finalize".
|
||||
|
||||
Pass `--spec specs/<feature>` to `open`, or post `specDir` once you know it.
|
||||
Stopping mid-finalize loses nothing
|
||||
— the specs are untouched until Step 3's summary write — so a stop's finish
|
||||
@@ -859,7 +979,7 @@ question or doc lands:
|
||||
`{"agent":{"status":"working","activity":"Reading the plan"}}`.
|
||||
|
||||
The patch merges: scalars replace, `null` deletes a key, `items` / `topics` / `docs`
|
||||
merge by `id` (an unknown id is added), and `thread` / `comments` append. Send only
|
||||
merge by `id` (an unknown id is added), and `thread` appends. Send only
|
||||
what changed. A whole-file rewrite would put the entire session back into your
|
||||
context on every turn.
|
||||
|
||||
@@ -1112,6 +1232,16 @@ A patch that breaks one of these is rejected with exit `3` and a message:
|
||||
(Session meter) and a non-empty `id`; a `folderIssue` needs non-empty
|
||||
`name` and `reason` strings, and `hint`, when present, is one too. Rules 4
|
||||
and 5 cover `reason` and `hint`.
|
||||
8. **`helpers` entries are well formed** (Standing instructions → Reporting
|
||||
helpers): an array of objects, each with a unique `id`, a `title`, an `ask`
|
||||
and a known `state` within their limits, plus at most one `alone` entry.
|
||||
Rules 4 and 5 cover `title`, `ask` and `result`.
|
||||
9. **A doc's `version` never goes back.** Sending a known doc a lower
|
||||
`version` than the page holds is refused: it is almost always a stale or
|
||||
copied payload. The same version again is fine, and a dashboard hop starts
|
||||
every doc fresh. Anything else reusing a doc id in the same session (a
|
||||
build's second phase, a second report or review) continues from the
|
||||
version the page holds.
|
||||
|
||||
These are workflow rules you already follow. The server just makes them checkable.
|
||||
|
||||
@@ -1133,7 +1263,9 @@ cannot see them, and the moment it says the session ended, the person is
|
||||
free to close that terminal and kill them mid-write. While you wait, post
|
||||
`{"agent":{"status":"working","activity":"Researching 3 questions (1 of 3 back)"}}`
|
||||
and update the count as each returns. Never write a `finish.body` that says
|
||||
work "is running in the background" or "will finish on its own".
|
||||
work "is running in the background" or "will finish on its own". Mark every
|
||||
reported helper `done` or `failed` before the finish, so the Subagents tab
|
||||
never ends on a row still running.
|
||||
|
||||
### 1. Post the finish
|
||||
|
||||
@@ -1239,7 +1371,7 @@ answers were submitted but never picked up.
|
||||
| You started subagents or background jobs | Wait for every one to report back before `finish`, posting `working` with a count meanwhile. A finish while they run tells the person it is safe to close the terminal, and that kills them. |
|
||||
| Any session end, not only the last one | Also post `finish`: an off-ramp that routes elsewhere, a checkpoint that saves and stops, a stop request. Anything that ends the session without it leaves the page promising a question that is not coming. |
|
||||
| Picking up a paused session | `open --resume <sid>` (or `open --session <sid>`) clears a paused `finish` itself, and the questions left open at the pause with it: the finish body already said what was still open, so re-ask whatever the new session needs in your own words rather than leaving the old asks on the page as duplicates. Settled items stay. For any other ending you are deliberately taking back, post `"finish": null` in your first patch. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` and `comments` **append**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same result arrives twice | Your harness killed `wait` after it handed the result over but before it recorded that. Handle it once. Most of a repeated patch is harmless, because items merge by id, but `thread` **appends**: leave out any thread entry you already sent, or the person sees your reply twice. |
|
||||
| The same chat arrives twice | Replies merge by `id`, so re-post the same reply if it is not on the page yet; do not answer the question a second time. |
|
||||
| `node` is missing, or older than 18 | One line, then the terminal. Do not try to install anything. |
|
||||
|
||||
|
||||
@@ -64,6 +64,8 @@ import {
|
||||
readChat,
|
||||
readJson,
|
||||
readLedger,
|
||||
readSubagentCursor,
|
||||
readSubagentSetting,
|
||||
readWorkspace,
|
||||
reapHandles,
|
||||
rememberedWorkspace,
|
||||
@@ -71,6 +73,7 @@ import {
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
repoRoots,
|
||||
resetSubagentCursor,
|
||||
scanProject,
|
||||
SESSION_MAX_AGE_MS,
|
||||
sessionDir,
|
||||
@@ -88,9 +91,11 @@ import {
|
||||
workspaceForAgent,
|
||||
writeCursor,
|
||||
writeJsonAtomic,
|
||||
writeSubagentCursor,
|
||||
writeWorkspaceCursor,
|
||||
} from "./lib.mjs";
|
||||
import { RUN_EVENTS, TASK_EVENTS, MAX_TASKS, isTaskCount, progressEntry } from "./public/meter.js";
|
||||
import { blockFor, offered } from "./public/subagents.js";
|
||||
import { changeLine } from "./public/workspace.js";
|
||||
|
||||
// Mirrors the server's absolute lifetime cap: a handle older than this cannot
|
||||
@@ -310,7 +315,11 @@ async function cmdOpen() {
|
||||
die(`could not write the session state: ${written ? written.error : "unknown"}`, 1);
|
||||
}
|
||||
state = written.state;
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried });
|
||||
appendEvent(dir, { type: "open", resumed: Boolean(args.resume || args.session), carried, caps: ["subagents"] });
|
||||
// A new agent conversation has been told nothing yet (FR-6).
|
||||
try {
|
||||
resetSubagentCursor(dir);
|
||||
} catch {}
|
||||
trace("open: state written");
|
||||
|
||||
// Dashboard launches are recorded too (they score nothing), so the folder
|
||||
@@ -337,9 +346,18 @@ async function cmdOpen() {
|
||||
removeScratch(HOME_DIR, sweptScratch).catch(() => {});
|
||||
};
|
||||
|
||||
// A standing instruction the new agent is owed, as `subagents` and a
|
||||
// `reply` holding only its lines; neither key when nothing is owed.
|
||||
const subagentsOwed = () => {
|
||||
awaitSubagentSync(dir, state.workflow);
|
||||
const [out, cursor] = withSubagents(dir, { reply: "" });
|
||||
return [out.subagents ? out : {}, cursor];
|
||||
};
|
||||
|
||||
// Reuse a live server if one is already serving this session.
|
||||
if (existing && (await reusable)) {
|
||||
if (!args["no-open"]) openBrowser(existing.url);
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -349,9 +367,11 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(existing.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...remoteWarning(),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
sweep();
|
||||
return;
|
||||
}
|
||||
@@ -384,6 +404,7 @@ async function cmdOpen() {
|
||||
const notes = [];
|
||||
if (remote.note) notes.push(remote.note);
|
||||
if (carried) notes.push("Answers are already waiting. Run `wait` to collect them.");
|
||||
const [owed, subCursor] = subagentsOwed();
|
||||
print({
|
||||
ok: true,
|
||||
sid,
|
||||
@@ -394,10 +415,12 @@ async function cmdOpen() {
|
||||
pendingResult: carried,
|
||||
terminalLine: terminalLine(handle.url),
|
||||
workspace,
|
||||
...owed,
|
||||
...swept,
|
||||
...(remote.remote ? { remote: remote.remote } : {}),
|
||||
...(notes.length ? { note: notes.join(" ") } : {}),
|
||||
});
|
||||
advanceSubagents(dir, subCursor);
|
||||
// After the print, never before it: the page and the link wait for nothing.
|
||||
sweep();
|
||||
}
|
||||
@@ -774,7 +797,7 @@ function serverGone(sid) {
|
||||
|
||||
// Quick questions and nothing else: an ordinary exit 0 with no card actions.
|
||||
function deliverChat(dir, sid, entries, url) {
|
||||
const [out, changes] = withWorkspace(dir, {
|
||||
const [withWs, changes] = withWorkspace(dir, {
|
||||
type: "chat",
|
||||
at: nowIso(),
|
||||
sid,
|
||||
@@ -782,9 +805,11 @@ function deliverChat(dir, sid, entries, url) {
|
||||
chat: entries,
|
||||
reply: chatReplyLines(entries),
|
||||
});
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print({ ...out, ...(url ? { terminalLine: terminalLine(url) } : {}) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -806,6 +831,52 @@ function advanceWorkspace(dir, changes) {
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// The server rewrites the session's setting for a new workflow only once its
|
||||
// watcher sees the state `open` just wrote, so a launch or hop that read the
|
||||
// file at once would find the old workflow's and owe the agent nothing until
|
||||
// its next pickup. Give the server a moment to catch up instead, never
|
||||
// writing the file ourselves (FR-7). A session with no setting file at all is
|
||||
// an older server, which never writes one: a short look, not the full wait.
|
||||
const SUBAGENT_SYNC_WAIT_MS = 1500;
|
||||
const SUBAGENT_SYNC_MISSING_MS = 250;
|
||||
function awaitSubagentSync(dir, workflow) {
|
||||
if (!offered(workflow)) return;
|
||||
const start = Date.now();
|
||||
for (;;) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (setting && setting.workflow === workflow) return;
|
||||
const budget = setting ? SUBAGENT_SYNC_WAIT_MS : SUBAGENT_SYNC_MISSING_MS;
|
||||
if (Date.now() - start >= budget) return;
|
||||
sleepSync(25);
|
||||
}
|
||||
}
|
||||
|
||||
// The Subagents switch the agent is owed, added to what it is about to read:
|
||||
// the setting as `subagents`, and its lines last in `reply`, after card lines,
|
||||
// Quick questions and Workspace lines (FR-9). Read from the session's own
|
||||
// setting file only, which only the server writes (FR-7). A setting for
|
||||
// another workflow is the server not having caught up with a hop yet: it
|
||||
// rides on the next pickup instead.
|
||||
function withSubagents(dir, out) {
|
||||
const setting = readSubagentSetting(dir);
|
||||
if (!setting) return [out, null];
|
||||
const workflow = (readJson(path.join(dir, "state.json")) || {}).workflow;
|
||||
if (setting.workflow !== workflow) return [out, null];
|
||||
const block = blockFor(setting, readSubagentCursor(dir));
|
||||
if (!block) return [out, null];
|
||||
const reply = [out.reply, ...block.lines].filter(Boolean).join("\n");
|
||||
return [{ ...out, subagents: block.field, reply }, block.cursor];
|
||||
}
|
||||
|
||||
// After the print, like advanceWorkspace(): a kill in between repeats the
|
||||
// block at the next pickup, never loses it.
|
||||
function advanceSubagents(dir, cursor) {
|
||||
if (!cursor) return;
|
||||
try {
|
||||
writeSubagentCursor(dir, cursor);
|
||||
} catch {}
|
||||
}
|
||||
|
||||
// Print first, then this, exactly as consume() stamps a result: a kill in
|
||||
// between can only hand the same chat over again, and collectChat() drops
|
||||
// anything that already has a reply.
|
||||
@@ -832,15 +903,17 @@ async function cmdChat() {
|
||||
}
|
||||
const entries = deliverableChat(collectChat(dir, readJson(path.join(dir, "state.json")) || {}));
|
||||
const changes = pendingWorkspaceChanges(dir);
|
||||
if (!entries.length && !changes.length) {
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
const [out, subCursor] = withSubagents(dir, { chat: entries, workspace: changes, reply });
|
||||
if (!entries.length && !changes.length && !subCursor) {
|
||||
print({ chat: [] });
|
||||
process.exitCode = 10;
|
||||
return;
|
||||
}
|
||||
const reply = [chatReplyLines(entries), ...changes.map(changeLine)].filter(Boolean).join("\n");
|
||||
print({ chat: entries, workspace: changes, reply, terminalLine: terminalLine(handle.url) });
|
||||
print({ ...out, terminalLine: terminalLine(handle.url) });
|
||||
advanceCursor(dir, entries);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = 0;
|
||||
}
|
||||
|
||||
@@ -865,7 +938,8 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
// never on result.json itself.
|
||||
const withChat = { ...collected, chat };
|
||||
if (chat.length) withChat.reply = [collected.reply, chatReplyLines(chat)].filter(Boolean).join("\n");
|
||||
const [out, changes] = withWorkspace(dir, withChat);
|
||||
const [withWs, changes] = withWorkspace(dir, withChat);
|
||||
const [out, subCursor] = withSubagents(dir, withWs);
|
||||
print(url ? { ...out, terminalLine: terminalLine(url) } : out);
|
||||
try {
|
||||
writeJsonAtomic(resultPath, collected);
|
||||
@@ -874,6 +948,7 @@ function consume(dir, resultPath, result, url, chat = []) {
|
||||
ledgerAnswers(dir, result);
|
||||
advanceCursor(dir, chat);
|
||||
advanceWorkspace(dir, changes);
|
||||
advanceSubagents(dir, subCursor);
|
||||
process.exitCode = result.type === "cancel" ? 30 : 0;
|
||||
}
|
||||
|
||||
@@ -986,12 +1061,18 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
path, description?, original? }], missing? }, the folders this
|
||||
console session reads as context, addressed as @name. The list is
|
||||
remembered per folder and spec in workspaces.json beside looks.json.
|
||||
May also print subagents: { state, revision, max, instruction } and
|
||||
a reply holding only its "Subagents: ..." lines, when a standing
|
||||
instruction (the page's Subagents switch) is owed to you.
|
||||
post --session <sid> --file <patch.json>
|
||||
Merge a patch into the session. Prints terminalLine while the
|
||||
server is live. Exit 3 = rejected; stderr says why. A patch may
|
||||
carry run: { event, id, tasks? } (session meter points) and folderIssue:
|
||||
{ name, reason, hint? } (a workspace folder you could not read);
|
||||
both go to the ledger, never into the state.
|
||||
both go to the ledger, never into the state. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(see console.md → Standing instructions).
|
||||
wait --session <sid> [--seconds <N>]
|
||||
A bounded wait slice, sized below your shell timeout. Exit 0 = the
|
||||
result is on stdout, 10 = still waiting ("Waiting on your answer
|
||||
@@ -1002,10 +1083,14 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
"workspace" (changes since you last heard, each once, with a
|
||||
"Workspace: ..." line in reply); exit 10 counts them as
|
||||
pendingWorkspace, and a change alone never ends a slice.
|
||||
Exit 0 may also carry "subagents" (a console setting, not typed
|
||||
by the person, with its "Subagents: ..." lines last in reply); a
|
||||
setting change alone never ends a slice either.
|
||||
chat --session <sid>
|
||||
Collect Quick questions and workspace changes now, never waiting,
|
||||
never touching card sends. Exit 0 = { chat, workspace, reply,
|
||||
terminalLine }, 10 = none, 20 = server gone.
|
||||
Collect Quick questions, workspace changes and a Subagents
|
||||
setting change now, never waiting, never touching card sends.
|
||||
Exit 0 = { chat, workspace, subagents?, reply, terminalLine },
|
||||
10 = none, 20 = server gone.
|
||||
terminalLine is "→ Look at the web console: <url>": end your terminal
|
||||
messages with it during a console session.
|
||||
keep --session <sid> --upload <path> --name <name> --spec specs/<idea> [--from <file>]
|
||||
|
||||
@@ -25,6 +25,7 @@ import { fileURLToPath } from "node:url";
|
||||
import { CHAT_LIMIT } from "./public/chat.js";
|
||||
import { DOC_TYPES } from "./public/answers.js";
|
||||
import { defaultName } from "./public/workspace.js";
|
||||
import { checkHelpers, cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
|
||||
export const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
export const PUBLIC_DIR = path.join(HERE, "public");
|
||||
@@ -48,6 +49,10 @@ export const USER_MODELS_FILE = path.join(PLAN2CODE_DIR, "models.json");
|
||||
|
||||
export const LOOKS_FILE = path.join(HOME_DIR, "looks.json");
|
||||
|
||||
// The newest Plan2Code release tag, as last asked of GitHub (update-check.mjs),
|
||||
// so every session within the hour reuses one lookup.
|
||||
export const UPDATE_CHECK_FILE = path.join(HOME_DIR, "update-check.json");
|
||||
|
||||
// The runtime dir has to follow PLAN2CODE_CONSOLE_HOME too. Without that, a
|
||||
// test run (or a second sandboxed instance) shares one handle directory with
|
||||
// the real thing, and `stop --all` reaches outside its own world and kills a
|
||||
@@ -487,9 +492,16 @@ export async function removeSessions(sessionsDir, sids) {
|
||||
}
|
||||
|
||||
// The console folder's own files that no sweep may ever remove: the person's
|
||||
// looks, the folders remembered per project and spec, and the pointer to
|
||||
// this console's directory.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set(["looks.json", "workspaces.json", "console-dir"]);
|
||||
// looks, the folders remembered per project and spec, the Subagents switch
|
||||
// saved per project and workflow, the pointer to this console's directory,
|
||||
// and the cached release check.
|
||||
export const PROTECTED_CONSOLE_FILES = new Set([
|
||||
"looks.json",
|
||||
"workspaces.json",
|
||||
"subagents.json",
|
||||
"console-dir",
|
||||
"update-check.json",
|
||||
]);
|
||||
|
||||
function isScratchName(name) {
|
||||
return (
|
||||
@@ -536,6 +548,148 @@ export async function removeScratch(consoleDir, names) {
|
||||
return removed;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------- cleanup */
|
||||
|
||||
// What User Preferences -> Cleanup never removes. The console folder keeps its
|
||||
// protected files, its sessions dir (old sessions go one by one, by age) and,
|
||||
// under PLAN2CODE_CONSOLE_HOME, its runtime dir; ~/.plan2code keeps the
|
||||
// console, the launcher (bin/, launcher.json) and the models the person added.
|
||||
const KEPT_CONSOLE_ENTRIES = new Set([...PROTECTED_CONSOLE_FILES, "sessions", "runtime"]);
|
||||
export const KEPT_PLAN2CODE_ENTRIES = new Set(["console", "bin", "launcher.json", "models.json"]);
|
||||
// A stray must sit untouched this long before Cleanup lists it. The same
|
||||
// folders hold files that live for milliseconds -- a held
|
||||
// `workspaces.json.lock`, a `<file>.<pid>.tmp` between its write and its
|
||||
// rename -- and removing one mid-write loses another session's change.
|
||||
export const STRAY_GRACE_MS = 60 * 60 * 1000;
|
||||
|
||||
// Bytes under `p`, never following a symlink: a link counts as itself.
|
||||
async function diskBytes(p) {
|
||||
let st;
|
||||
try {
|
||||
st = await fs.promises.lstat(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
if (!st.isDirectory()) return st.size;
|
||||
let entries;
|
||||
try {
|
||||
entries = await fs.promises.readdir(p);
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
let total = 0;
|
||||
for (const name of entries) total += await diskBytes(path.join(p, name));
|
||||
return total;
|
||||
}
|
||||
|
||||
// The newest mtime of anything under `p`, never following a symlink. A folder
|
||||
// counts by its files, since rewriting a file never touches its folder's
|
||||
// mtime; an empty folder counts by its own. Anything unreadable on the way
|
||||
// down answers Infinity, so it reads as just touched and stays.
|
||||
function newestMtime(p) {
|
||||
let st;
|
||||
try {
|
||||
st = fs.lstatSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!st.isDirectory()) return st.mtimeMs;
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(p);
|
||||
} catch {
|
||||
return Infinity;
|
||||
}
|
||||
if (!entries.length) return st.mtimeMs;
|
||||
let newest = 0;
|
||||
for (const name of entries) newest = Math.max(newest, newestMtime(path.join(p, name)));
|
||||
return newest;
|
||||
}
|
||||
|
||||
function entryKind(entry) {
|
||||
if (entry.isSymbolicLink()) return "link";
|
||||
return entry.isDirectory() ? "folder" : "file";
|
||||
}
|
||||
|
||||
function strayEntries(dir, kept, where, now) {
|
||||
let entries;
|
||||
try {
|
||||
entries = fs.readdirSync(dir, { withFileTypes: true });
|
||||
} catch {
|
||||
return [];
|
||||
}
|
||||
const settled = (p) => now - newestMtime(p) >= STRAY_GRACE_MS;
|
||||
return entries
|
||||
.filter((e) => !kept.has(e.name))
|
||||
.map((e) => ({ id: where + ":" + e.name, where, name: e.name, kind: entryKind(e), path: path.join(dir, e.name) }))
|
||||
.filter((e) => settled(e.path));
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything Cleanup would remove, worked out on the server and never taken
|
||||
* from a client: sessions untouched for `maxAgeMs` (never `skipSid`; the rule
|
||||
* `open` sweeps by, plus every file in the folder that old, so a resumed
|
||||
* session or a saved draft keeps it), anything at the top of the console folder that is
|
||||
* not kept, and -- only when the console runs from its default home inside
|
||||
* `plan2codeDir` -- anything at the top of `plan2codeDir` that is not kept. Strays
|
||||
* touched within `STRAY_GRACE_MS` are left for a later scan. A
|
||||
* console running from another home (tests, dev) never reaches ~/.plan2code.
|
||||
* Resolves to `{ items: [{ id, where, name, kind, bytes }], bytes }`.
|
||||
*/
|
||||
export async function cleanupFindings({
|
||||
consoleDir = HOME_DIR,
|
||||
plan2codeDir = PLAN2CODE_DIR,
|
||||
now = Date.now(),
|
||||
maxAgeMs = SESSION_MAX_AGE_MS,
|
||||
skipSid,
|
||||
} = {}) {
|
||||
const found = [];
|
||||
const sessionsDir = path.join(consoleDir, "sessions");
|
||||
for (const sid of staleSessions(sessionsDir, now, maxAgeMs, skipSid)) {
|
||||
if (now - newestMtime(path.join(sessionsDir, sid)) <= maxAgeMs) continue;
|
||||
found.push({ id: "session:" + sid, where: "session", name: sid, kind: "folder", path: path.join(sessionsDir, sid) });
|
||||
}
|
||||
found.push(...strayEntries(consoleDir, KEPT_CONSOLE_ENTRIES, "console", now));
|
||||
if (path.resolve(consoleDir) === path.resolve(plan2codeDir, "console")) {
|
||||
found.push(...strayEntries(plan2codeDir, KEPT_PLAN2CODE_ENTRIES, "root", now));
|
||||
}
|
||||
const items = [];
|
||||
let bytes = 0;
|
||||
for (const f of found) {
|
||||
const size = await diskBytes(f.path);
|
||||
bytes += size;
|
||||
items.push({ id: f.id, where: f.where, name: f.name, kind: f.kind, bytes: size, path: f.path });
|
||||
}
|
||||
return { items, bytes };
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove what Cleanup found, limited to `ids` the page was shown. The list is
|
||||
* worked out afresh first and only ids on it are touched, so a name from the
|
||||
* page is never a path, and anything that stopped qualifying since the scan
|
||||
* (a session touched again) stays. A link is unlinked, never followed.
|
||||
* Resolves to `{ removed: [id], bytes, failed: [id] }`.
|
||||
*/
|
||||
export async function removeCleanup(ids, opts = {}) {
|
||||
const wanted = new Set((Array.isArray(ids) ? ids : []).filter((id) => typeof id === "string"));
|
||||
const { items } = await cleanupFindings(opts);
|
||||
const removed = [];
|
||||
const failed = [];
|
||||
let bytes = 0;
|
||||
for (const item of items) {
|
||||
if (!wanted.has(item.id)) continue;
|
||||
try {
|
||||
if (item.kind === "link") await fs.promises.unlink(item.path);
|
||||
else await fs.promises.rm(item.path, { recursive: true, force: true });
|
||||
removed.push(item.id);
|
||||
bytes += item.bytes;
|
||||
} catch {
|
||||
failed.push(item.id);
|
||||
}
|
||||
}
|
||||
return { removed, bytes, failed };
|
||||
}
|
||||
|
||||
/**
|
||||
* A spec's overview.md, read-only, or null. `specDir` is relative to `root`;
|
||||
* the file's realpath must sit inside the root's, so `../`, an absolute path
|
||||
@@ -871,7 +1025,7 @@ export function handOff(child, pre) {
|
||||
|
||||
/* ----------------------------------------------------------- patch merge */
|
||||
|
||||
const APPEND_KEYS = new Set(["thread", "comments"]);
|
||||
const APPEND_KEYS = new Set(["thread"]);
|
||||
|
||||
function isPlainObject(v) {
|
||||
return v !== null && typeof v === "object" && !Array.isArray(v);
|
||||
@@ -896,7 +1050,7 @@ function mergeOne(target, patch, where) {
|
||||
}
|
||||
|
||||
// Merge a keyed collection: a known id merges one level, an unknown id appends.
|
||||
// Named fields are replaced whole; thread/comments append.
|
||||
// Named fields are replaced whole; thread appends.
|
||||
function mergeKeyed(current, patchList, idKey, defaults, where) {
|
||||
const out = Array.isArray(current) ? current.map((x) => ({ ...x })) : [];
|
||||
for (const entry of patchList) {
|
||||
@@ -955,11 +1109,60 @@ function dropStaleSubmissions(currentItems, before, patchList) {
|
||||
return merged;
|
||||
}
|
||||
|
||||
// A thread entry is `{ who, text }`, and the page reads nothing else. Models
|
||||
// borrow the shape of the replies and doc blocks they also write, so `from` /
|
||||
// `role` and `md` / `body` / `content` are lifted into place: left as they came,
|
||||
// each became a "Plan2Code" bubble with nothing in it. An entry with no words
|
||||
// at all is refused. The person's own notes are recorded by the server when
|
||||
// they send, so an agent that echoes one back is not shown it twice.
|
||||
const THREAD_TEXT_KEYS = ["text", "md", "body", "content"];
|
||||
|
||||
function normalizeThreads(patchList, currentItems) {
|
||||
return patchList.map((entry) => {
|
||||
if (!isPlainObject(entry) || entry.thread == null) return entry;
|
||||
if (!Array.isArray(entry.thread)) throw new Error(`item "${entry.id}" "thread" must be an array`);
|
||||
const prev = (currentItems || []).find((x) => x && x.id === entry.id);
|
||||
const said = new Set(
|
||||
((prev && prev.thread) || []).filter((m) => m && m.who === "user").map((m) => String(m.text || "").trim()),
|
||||
);
|
||||
const thread = [];
|
||||
for (const m of entry.thread) {
|
||||
if (!isPlainObject(m)) throw new Error(`item "${entry.id}" thread entries must be objects`);
|
||||
guard(m, "thread");
|
||||
const key = THREAD_TEXT_KEYS.find((k) => typeof m[k] === "string" && m[k].trim());
|
||||
if (!key) {
|
||||
throw new Error(
|
||||
`item "${entry.id}" thread entry has no "text". Write { "who": "agent", "text": "<markdown>" }; the page shows nothing else.`,
|
||||
);
|
||||
}
|
||||
const { from, role, md, body, content, ...rest } = m;
|
||||
const who = (m.who || from || role) === "user" ? "user" : "agent";
|
||||
const text = m[key];
|
||||
if (who === "user" && said.has(text.trim())) continue;
|
||||
thread.push({ ...rest, who, text });
|
||||
}
|
||||
return { ...entry, thread };
|
||||
});
|
||||
}
|
||||
|
||||
const DOC_DEFAULTS = { version: 1, stale: false, blocks: [] };
|
||||
|
||||
// Blocks merge by id like docs do, so a patch that only settles a block's
|
||||
// state keeps its text. Blocks left out of the patch stay as they are.
|
||||
function mergeDocs(current, patchList) {
|
||||
// A doc's version only moves forward. One going back is a stale or copied
|
||||
// payload (last phase's progress script, say), and the page would quietly
|
||||
// show the old content under the new run's name.
|
||||
for (const entry of patchList) {
|
||||
if (!isPlainObject(entry) || typeof entry.version !== "number") continue;
|
||||
const prev = (current || []).find((d) => d && d.id === entry.id);
|
||||
if (prev && typeof prev.version === "number" && entry.version < prev.version) {
|
||||
throw new Error(
|
||||
`doc "${entry.id}" is at version ${prev.version} on the page; this patch sends version ${entry.version}. ` +
|
||||
"Versions only go up: bump it, and check the payload is the current one."
|
||||
);
|
||||
}
|
||||
}
|
||||
const merged = mergeKeyed(current, patchList, "id", DOC_DEFAULTS, "docs");
|
||||
for (const entry of patchList) {
|
||||
if (!Array.isArray(entry.blocks)) continue;
|
||||
@@ -996,12 +1199,23 @@ export function applyPatch(state, patch) {
|
||||
break;
|
||||
case "items":
|
||||
if (!Array.isArray(v)) throw new Error('"items" must be an array');
|
||||
next.items = dropStaleSubmissions(next.items, state.items, v);
|
||||
next.items = dropStaleSubmissions(next.items, state.items, normalizeThreads(v, state.items));
|
||||
break;
|
||||
case "topics":
|
||||
if (!Array.isArray(v)) throw new Error('"topics" must be an array');
|
||||
next.topics = mergeKeyed(next.topics, v, "id", {}, "topics");
|
||||
break;
|
||||
case "helpers":
|
||||
// The agent's report of its helpers, for the page's Subagents tab.
|
||||
// Only `post` writes it; the server's /submit never touches it.
|
||||
if (!Array.isArray(v)) throw new Error('"helpers" must be an array');
|
||||
if (!v.every(isPlainObject)) throw new Error('"helpers" entries must be objects, each { id, title, ask, state }');
|
||||
next.helpers = mergeKeyed(next.helpers, v, "id", {}, "helpers");
|
||||
// A real helper report supersedes the working-alone marker, whether it
|
||||
// arrives after one or beside one.
|
||||
if (next.helpers.some((h) => isPlainObject(h) && h.alone !== true))
|
||||
next.helpers = next.helpers.filter((h) => !(isPlainObject(h) && h.alone === true));
|
||||
break;
|
||||
case "docs":
|
||||
if (!Array.isArray(v)) throw new Error('"docs" must be an array');
|
||||
next.docs = mergeDocs(next.docs, v);
|
||||
@@ -1048,15 +1262,11 @@ function stampTimes(before, next) {
|
||||
if (changed && !next.agent.since) next.agent = { ...next.agent, since: now };
|
||||
else if (!next.agent.since) next.agent = { ...next.agent, since: before.agent?.since || now };
|
||||
}
|
||||
for (const list of [next.items, next.docs]) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
for (const entry of list) {
|
||||
if (Array.isArray(next.items)) {
|
||||
for (const entry of next.items) {
|
||||
if (Array.isArray(entry.thread)) {
|
||||
for (const m of entry.thread) if (!m.at) m.at = now;
|
||||
}
|
||||
if (Array.isArray(entry.comments)) {
|
||||
for (const m of entry.comments) if (!m.at) m.at = now;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (Array.isArray(next.docs)) {
|
||||
@@ -1289,7 +1499,10 @@ export function validate(state) {
|
||||
// server's record of an answer someone pressed Send on; if their own words
|
||||
// happened to contain "TASK_COMPLETE" or "Risk 3", every later agent patch
|
||||
// would be rejected and the session would wedge with no way out.
|
||||
const authored = state.items.map(({ submitted, sentNote, ...rest }) => rest);
|
||||
const authored = state.items.map(({ submitted, sentNote, thread, ...rest }) => ({
|
||||
...rest,
|
||||
thread: Array.isArray(thread) ? thread.filter((m) => !m || m.who !== "user") : thread,
|
||||
}));
|
||||
const prose =
|
||||
JSON.stringify(authored) +
|
||||
JSON.stringify(state.docs || []) +
|
||||
@@ -1297,6 +1510,20 @@ export function validate(state) {
|
||||
JSON.stringify(state.menu || {});
|
||||
problems.push(...proseProblems(prose));
|
||||
|
||||
// The agent's report of its helpers: the shape the page draws from
|
||||
// (subagents.js), then the same prose scan as everything else it writes.
|
||||
if (state.helpers != null) {
|
||||
problems.push(...checkHelpers(state.helpers));
|
||||
for (const helper of Array.isArray(state.helpers) ? state.helpers : []) {
|
||||
if (!isPlainObject(helper)) continue;
|
||||
for (const field of ["title", "ask", "result"]) {
|
||||
if (typeof helper[field] === "string") {
|
||||
problems.push(...proseProblems(helper[field], `helper "${helper.id}" ${field}`));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -1326,7 +1553,8 @@ export function blankState({ sid, workflow, title, project, specDir }) {
|
||||
* A resume that passes through the dashboard (a finished skill going back to
|
||||
* it, or a launch from its menu) is a new skill taking the page over, so it
|
||||
* starts from a blank page: the last skill's questions, sections, docs,
|
||||
* headline and ending are its record on disk, not the next skill's opening.
|
||||
* helpers, headline and ending are its record on disk, not the next skill's
|
||||
* opening.
|
||||
* Only the session's identity carries across. `workspace.json`,
|
||||
* `ledger.ndjson` and the cursors live beside `state.json`, so the workspace
|
||||
* and the meter outlive every hop.
|
||||
@@ -1353,6 +1581,8 @@ export function switchWorkflow(state, { workflow, title, specDir }) {
|
||||
// workspace.json the server. Folders, version, change log, missing, remote.
|
||||
// ledger.ndjson console.mjs. Append-only meter events and folder issues.
|
||||
// workspace-cursor.json console.mjs. The last workspace version handed to the agent.
|
||||
// subagents-setting.json the server. The Subagents switch for this session, with its revision.
|
||||
// subagents-cursor.json console.mjs. The last Subagents revision and state handed to the agent.
|
||||
export const CHAT_FILE = "chat.ndjson";
|
||||
export const CHAT_CURSOR_FILE = "chat-cursor.json";
|
||||
export const WORKSPACE_FILE = "workspace.json";
|
||||
@@ -1808,6 +2038,98 @@ export function pendingWorkspaceChanges(dir) {
|
||||
return (readWorkspace(dir)?.changes || []).filter((c) => c.version > cursor);
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ the Subagents switch */
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
function readSubagentStore() {
|
||||
const saved = readJson(SUBAGENTS_FILE, null);
|
||||
return saved && typeof saved === "object" && !Array.isArray(saved) ? saved : {};
|
||||
}
|
||||
|
||||
// The saved `{ on, instruction, max }` for this folder and workflow, or the
|
||||
// default's when nothing (or something malformed) is saved.
|
||||
export function subagentStoreEntry(worktree, workflow) {
|
||||
const { on, instruction, max } = defaultSetting(workflow);
|
||||
const project = offered(workflow) ? readSubagentStore()[foldKey(worktree)] : null;
|
||||
const saved = project && typeof project === "object" ? cleanSetting(project[workflow]) : null;
|
||||
return saved && !saved.error ? saved : { on, instruction, max };
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this.
|
||||
export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
ensureDir(path.dirname(SUBAGENTS_FILE));
|
||||
withStateLock(
|
||||
path.dirname(SUBAGENTS_FILE),
|
||||
() => {
|
||||
const store = readSubagentStore();
|
||||
const key = foldKey(worktree);
|
||||
const project = store[key] && typeof store[key] === "object" ? store[key] : {};
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
);
|
||||
}
|
||||
|
||||
export const SUBAGENTS_SETTING_FILE = "subagents-setting.json";
|
||||
|
||||
const isCount = (n) => Number.isInteger(n) && n >= 0;
|
||||
|
||||
// This session's switch, `{ workflow, on, instruction, max, revision }`, or
|
||||
// null when there is none or it is malformed.
|
||||
export function readSubagentSetting(dir) {
|
||||
const s = readJson(path.join(dir, SUBAGENTS_SETTING_FILE), null);
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (typeof s.workflow !== "string" || typeof s.on !== "boolean" || !Number.isInteger(s.max) || !isCount(s.revision)) return null;
|
||||
return s;
|
||||
}
|
||||
|
||||
// Single-writer rule: only server.mjs may call this. The revision never goes
|
||||
// backwards within a session.
|
||||
export function writeSubagentSetting(dir, setting) {
|
||||
const previous = readSubagentSetting(dir);
|
||||
const revision = Math.max(previous ? previous.revision : 0, setting.revision);
|
||||
return writeJsonAtomic(path.join(dir, SUBAGENTS_SETTING_FILE), { ...setting, revision });
|
||||
}
|
||||
|
||||
export const SUBAGENTS_CURSOR_FILE = "subagents-cursor.json";
|
||||
const CURSOR_STATES = new Set(["none", "on", "off"]);
|
||||
|
||||
// What the agent was last told: `{ revision, state }`.
|
||||
export function readSubagentCursor(dir) {
|
||||
const saved = readJson(path.join(dir, SUBAGENTS_CURSOR_FILE), null);
|
||||
if (!saved || !isCount(saved.revision) || !CURSOR_STATES.has(saved.state)) return { revision: 0, state: "none" };
|
||||
return { revision: saved.revision, state: saved.state };
|
||||
}
|
||||
|
||||
// Single-writer rule: only console.mjs may call this. Never backwards, like
|
||||
// writeWorkspaceCursor(): a killed `wait` may repeat a change, never skip one.
|
||||
export function writeSubagentCursor(dir, cursor) {
|
||||
const old = readSubagentCursor(dir);
|
||||
const next = cursor.revision < old.revision ? old : { revision: cursor.revision, state: cursor.state };
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), next);
|
||||
}
|
||||
|
||||
// The one place the cursor may go back: `open`, which starts a fresh agent.
|
||||
export function resetSubagentCursor(dir) {
|
||||
writeJsonAtomic(path.join(dir, SUBAGENTS_CURSOR_FILE), { revision: 0, state: "none" });
|
||||
}
|
||||
|
||||
// The `caps` of the last `open` event: what the agent's console copy can do.
|
||||
export function latestOpenCaps(dir) {
|
||||
const opens = readJsonLines(path.join(dir, "events.ndjson")).filter((e) => e.type === "open");
|
||||
const last = opens[opens.length - 1];
|
||||
return last && Array.isArray(last.caps) ? last.caps : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag the case where the link cannot be opened by the person it is for.
|
||||
*
|
||||
|
||||
@@ -65,7 +65,7 @@ export function submittedAwaiting(item) {
|
||||
if (!s || typeof s !== "object") return null;
|
||||
if (item.answer && typeof item.answer === "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const replied = thread.some((m) => m && m.who === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
const replied = thread.some((m) => m && threadWho(m) === "agent" && (!s.at || !m.at || m.at >= s.at));
|
||||
return replied ? null : s;
|
||||
}
|
||||
|
||||
@@ -74,17 +74,33 @@ export function submittedAwaiting(item) {
|
||||
* agent has yet to say anything after it. The server records it as `sentNote`
|
||||
* on every send, so the page can show it in the Notes pane and in the Sent
|
||||
* box instead of letting it vanish into a send that shows no sign of arriving.
|
||||
* Any thread message from the send onwards, or none with a clock to compare,
|
||||
* means it has been picked up.
|
||||
* Any agent message from the send onwards, or one with no clock to compare,
|
||||
* means it has been picked up. The person's own entries never count: the
|
||||
* server writes their note into the thread as it arrives.
|
||||
*/
|
||||
export function noteAwaiting(item) {
|
||||
const n = item && item.sentNote;
|
||||
if (!n || typeof n !== "object") return null;
|
||||
const thread = Array.isArray(item.thread) ? item.thread : [];
|
||||
const picked = thread.some((m) => m && (!n.at || !m.at || m.at >= n.at));
|
||||
const picked = thread.some((m) => m && threadWho(m) === "agent" && (!n.at || !m.at || m.at >= n.at));
|
||||
return picked ? null : n;
|
||||
}
|
||||
|
||||
/**
|
||||
* Who said a thread entry and what they said. The contract is `{ who, text }`
|
||||
* and the server lifts anything else into it, but sessions written before that
|
||||
* hold `{ from, md }` replies, which would otherwise draw as empty bubbles.
|
||||
*/
|
||||
export function threadWho(m) {
|
||||
return m && (m.who || m.from || m.role) === "user" ? "user" : "agent";
|
||||
}
|
||||
|
||||
export function threadText(m) {
|
||||
if (!m) return "";
|
||||
for (const k of ["text", "md", "body", "content"]) if (typeof m[k] === "string" && m[k].trim()) return m[k];
|
||||
return "";
|
||||
}
|
||||
|
||||
/* -------------------------------------------------------------- labels */
|
||||
|
||||
export function optionLabel(item, k) {
|
||||
|
||||
@@ -23,6 +23,9 @@
|
||||
--warn-soft: #fbe7e3;
|
||||
--focus: #1f6feb;
|
||||
--shadow: 0 1px 2px rgba(29, 26, 23, 0.05), 0 8px 24px rgba(29, 26, 23, 0.06);
|
||||
/* A soft accent halo for the things that want noticing: the update banner
|
||||
and an enabled Send. Built from --accent, so a picked accent glows too. */
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 30%, transparent), 0 0 12px color-mix(in srgb, var(--accent) 35%, transparent);
|
||||
--sans: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
--serif: "Iowan Old Style", Charter, Georgia, Cambria, serif;
|
||||
--mono: ui-monospace, SFMono-Regular, "Cascadia Mono", Menlo, Consolas, monospace;
|
||||
@@ -61,6 +64,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -85,6 +89,7 @@
|
||||
--warn-soft: #34201d;
|
||||
--focus: #6aa3ff;
|
||||
--shadow: 0 1px 2px rgba(0, 0, 0, 0.4), 0 8px 24px rgba(0, 0, 0, 0.35);
|
||||
--glow: 0 0 0 1px color-mix(in srgb, var(--accent) 40%, transparent), 0 0 14px color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
}
|
||||
|
||||
* { box-sizing: border-box; }
|
||||
@@ -203,6 +208,26 @@ body {
|
||||
.stop-btn:hover:not(:disabled) { color: var(--warn); border-color: var(--warn); }
|
||||
.brief-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
|
||||
/* Subagents: an orchestrator and its helpers. Unlit is a hollow outline in
|
||||
the quiet ink; lit fills the nodes with the highlight color. */
|
||||
.subagents-btn { border-color: var(--rule-2); color: var(--ink-2); display: inline-flex; align-items: center; justify-content: center; }
|
||||
.btn.subagents-btn { padding: 0 6px; align-self: stretch; }
|
||||
.subagents-btn[hidden] { display: none; }
|
||||
.subagents-btn svg { width: 16px; height: 16px; display: block; }
|
||||
.subagents-btn .sa-link { fill: none; stroke: var(--ink-2); stroke-width: 1.2; stroke-linecap: round; }
|
||||
.subagents-btn .sa-hub { fill: none; stroke: var(--ink-2); stroke-width: 1.4; }
|
||||
.subagents-btn .sa-node { fill: none; stroke: var(--ink-2); stroke-width: 1.2; }
|
||||
.subagents-btn[aria-pressed="true"] .sa-hub,
|
||||
.subagents-btn[aria-pressed="true"] .sa-node { fill: var(--accent); stroke: var(--accent); }
|
||||
.subagents-btn[aria-pressed="true"] .sa-link { stroke: var(--accent); }
|
||||
.subagents-btn:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); }
|
||||
.subagents-btn:hover:not(:disabled) .sa-link,
|
||||
.subagents-btn:hover:not(:disabled) .sa-hub,
|
||||
.subagents-btn:hover:not(:disabled) .sa-node { stroke: var(--accent); }
|
||||
.subagents-btn:disabled .sa-link,
|
||||
.subagents-btn:disabled .sa-hub,
|
||||
.subagents-btn:disabled .sa-node { stroke: var(--ink-3); fill: none; }
|
||||
|
||||
.ident { display: flex; align-items: baseline; gap: 12px; min-width: 0; }
|
||||
|
||||
/* The session meter: a ring that fills with the points and a few words, in
|
||||
@@ -1097,10 +1122,11 @@ h1 {
|
||||
.ask-disabled-note.is-offline { color: var(--warn); background: var(--warn-soft); border: 1px solid var(--warn); }
|
||||
|
||||
/* Waiting on Plan2Code (an Ask answer, or answers sent from Questions):
|
||||
the tiny ring, left of the label. */
|
||||
.view-tab .tab-spin {
|
||||
the tiny ring, left of the label. The extra .spinner is for specificity:
|
||||
.spinner.tiny comes later and zeroes the margin otherwise. */
|
||||
.view-tab .spinner.tab-spin {
|
||||
display: inline-block;
|
||||
margin-right: 6px;
|
||||
margin-right: 7px;
|
||||
vertical-align: -1px;
|
||||
}
|
||||
|
||||
@@ -1424,6 +1450,30 @@ h1 {
|
||||
.pill.done { background: var(--ok-soft); color: var(--ok); }
|
||||
.pill.staged { background: var(--stage-soft); color: var(--stage); }
|
||||
|
||||
/* The Subagents tab: one row per reported helper, newest state in a pill. */
|
||||
.sa-card h2 { margin: 0 0 6px; }
|
||||
.sa-card > .help { margin: 0 0 16px; }
|
||||
.sa-alone { margin: 0; color: var(--ink-2); }
|
||||
.sa-list { list-style: none; margin: 0; padding: 0; display: grid; gap: 10px; }
|
||||
.sa-row { border: 1px solid var(--rule); border-radius: 8px; background: var(--panel-2); padding: 12px 14px; }
|
||||
.sa-head { display: flex; align-items: center; justify-content: space-between; gap: 10px; }
|
||||
.sa-title { min-width: 0; overflow-wrap: anywhere; }
|
||||
.sa-ask {
|
||||
margin: 4px 0 0; color: var(--ink-2); font-size: 13.5px;
|
||||
display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 2; line-clamp: 2; overflow: hidden;
|
||||
}
|
||||
.sa-result { margin: 8px 0 0; padding-top: 8px; border-top: 1px solid var(--rule); font-size: 13.5px; }
|
||||
.sa-pill { display: inline-flex; align-items: center; gap: 6px; flex: none; }
|
||||
.sa-pill.is-running { background: var(--accent-soft); color: var(--accent); border-color: var(--accent-line); }
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
border: 1px solid var(--rule-2); border-radius: 6px; padding: 4px 8px;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------ settled answer */
|
||||
|
||||
.answered {
|
||||
@@ -1657,11 +1707,13 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
.btn:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
.btn.primary { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
.btn.primary:hover:not(:disabled) { filter: brightness(1.08); background: var(--accent); }
|
||||
/* Send breathes while there is something to send: a soft accent ring that
|
||||
spreads and fades. Off under reduced motion, below. */
|
||||
/* Send glows and breathes while there is something to send: the steady
|
||||
--glow, plus a soft accent ring that spreads and fades. The ring is off
|
||||
under reduced motion, below; the glow stays. */
|
||||
#btn-send:not(:disabled) { box-shadow: var(--glow); }
|
||||
@keyframes send-pulse {
|
||||
0% { box-shadow: 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: 0 0 0 6px transparent; }
|
||||
0% { box-shadow: var(--glow), 0 0 0 0 var(--accent-line); }
|
||||
100% { box-shadow: var(--glow), 0 0 0 6px transparent; }
|
||||
}
|
||||
#btn-send.primary:not(:disabled) { animation: send-pulse 2.4s ease-out infinite; }
|
||||
.btn.ghost { background: transparent; border-color: transparent; color: var(--ink-2); }
|
||||
@@ -1963,6 +2015,8 @@ h4.md-h, h5.md-h, h6.md-h { font-size: 15px; }
|
||||
cursor: pointer;
|
||||
}
|
||||
.footer-where:hover { text-decoration: underline; }
|
||||
/* The project name, in the person's highlight color. */
|
||||
.where-project { color: var(--accent); font-weight: 600; }
|
||||
/* A folder is missing or the agent could not read one: the dialog says which. */
|
||||
.where-alert {
|
||||
display: inline-block; width: 7px; height: 7px; margin-left: 6px;
|
||||
@@ -2219,6 +2273,7 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.modal.help[open] { display: flex; }
|
||||
.modal.help .modal-actions { flex: none; margin-top: 16px; align-items: center; }
|
||||
.help-version { margin-right: auto; font-size: 12.5px; color: var(--ink-3); }
|
||||
.help-version a { color: inherit; }
|
||||
|
||||
.help-layout {
|
||||
display: grid;
|
||||
@@ -2668,6 +2723,74 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
border-left-width: 4px;
|
||||
color: var(--ink);
|
||||
}
|
||||
/* A newer release: the same slot, in the accent, with the label as the way
|
||||
into the update modal and a small × that hides it for this session. */
|
||||
.dash-nudge.update-banner {
|
||||
position: relative;
|
||||
padding-left: 40px;
|
||||
padding-right: 40px;
|
||||
border-left-width: 4px;
|
||||
border-left-color: var(--accent-line);
|
||||
color: var(--ink);
|
||||
box-shadow: var(--glow);
|
||||
}
|
||||
.update-banner-open {
|
||||
flex: 1 1 16em;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.02em;
|
||||
text-align: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-open:hover { text-decoration: underline; }
|
||||
/* Pinned to the right edge, out of the flow, so the label centres on the
|
||||
whole banner rather than on what the × leaves of it. */
|
||||
.update-banner-dismiss {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
right: 10px;
|
||||
transform: translateY(-50%);
|
||||
padding: 0 6px;
|
||||
border: 0;
|
||||
border-radius: var(--radius);
|
||||
background: none;
|
||||
color: inherit;
|
||||
font: inherit;
|
||||
font-size: 16px;
|
||||
line-height: 1;
|
||||
cursor: pointer;
|
||||
}
|
||||
.update-banner-dismiss:hover { background: var(--accent-line); }
|
||||
/* Wide enough that the update command sits on one line beside Copy; a
|
||||
narrow window still wraps it rather than overflowing. */
|
||||
#update-modal { max-width: 720px; }
|
||||
.update-steps { margin: 0 0 12px; padding-left: 1.4em; color: var(--ink); }
|
||||
.update-steps li { margin: 4px 0; }
|
||||
/* The hand-off copy row, in the modal's first step: the command and its Copy
|
||||
side by side. */
|
||||
.update-command {
|
||||
margin: 6px 0 4px;
|
||||
display: flex;
|
||||
align-items: stretch;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
.update-command code {
|
||||
flex: 1 1 260px;
|
||||
min-width: 0;
|
||||
font: 13px/1.5 var(--mono);
|
||||
color: var(--ink);
|
||||
background: var(--panel);
|
||||
border: 1px solid var(--rule-2);
|
||||
border-radius: 8px;
|
||||
padding: 10px 12px;
|
||||
white-space: pre-wrap;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
.dash-nudge-actions { display: flex; align-items: center; gap: 8px; margin-left: auto; }
|
||||
.dash-nudge-actions .btn.tiny { margin-bottom: 0; }
|
||||
.dash-working {
|
||||
@@ -3394,6 +3517,18 @@ a.icon-btn { box-sizing: border-box; text-decoration: none; }
|
||||
.models-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
|
||||
.models-actions .help.error { color: var(--danger, #d64545); }
|
||||
|
||||
/* User Preferences: Cleanup's list of what would go, shown before anything
|
||||
is deleted. */
|
||||
.cleanup-list { display: grid; gap: 4px; max-height: 200px; overflow: auto; font-size: 0.88em; }
|
||||
.cleanup-list:empty { display: none; }
|
||||
.cleanup-summary { margin: 0 0 2px; font-weight: 600; }
|
||||
.cleanup-row { display: flex; justify-content: space-between; gap: 12px; }
|
||||
.cleanup-row span:first-child { min-width: 0; overflow-wrap: anywhere; font-family: var(--mono); }
|
||||
.cleanup-size { flex: none; color: var(--ink-3); }
|
||||
.cleanup-more { display: grid; gap: 4px; }
|
||||
.cleanup-more summary { cursor: pointer; color: var(--ink-2); }
|
||||
#cleanup-delete[hidden] { display: none; }
|
||||
|
||||
/* A word the person has to type, bold and in their highlight color so it
|
||||
does not get lost in the status sentence. */
|
||||
.agent-key {
|
||||
|
||||
Loaded 100 of 242 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user