mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-19 05:11:18 -08:00
Compare commits
15
Commits
0de630603b
...
3e22d53bf5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3e22d53bf5 | ||
|
|
7a9f56a452 | ||
|
|
37f2735294 | ||
|
|
1d146cce6f | ||
|
|
5f91fb665f | ||
|
|
4d05b4f6f6 | ||
|
|
3155298fea | ||
|
|
a4644d533b | ||
|
|
b73a4cebe7 | ||
|
|
efc96e91c2 | ||
|
|
442904e6f2 | ||
|
|
c1f41e4a82 | ||
|
|
72043e20fc | ||
|
|
bdc4decbb4 | ||
|
|
cb6468577d |
No files matched your search
@@ -16,7 +16,8 @@ plan2code/
|
||||
│ │ ├── handoff.md # Clearing gate + PLAN-DRAFT handoff
|
||||
│ │ └── trail.md # Every-response map visual + pathed resume command
|
||||
│ ├── shared-references/ # Reference files shared across skills
|
||||
│ │ └── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review)
|
||||
│ │ ├── building-habits.md # Find the cause, test first, pin behaviour (quick-task, implement, implement-review)
|
||||
│ │ └── helper-strength.md # How strong a model and how much effort each helper gets (pathfinder, quick-task, implement, implement-review, review)
|
||||
│ ├── plan2code-review-references/ # Reference files for review skill
|
||||
│ │ ├── verification-protocol.md # Deep verification + confidence calibration
|
||||
│ │ ├── dimensions.md # 11 dimensions with detailed checklists
|
||||
@@ -192,6 +193,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `cmd-help.mjs` | the `help` command: the CLI's usage and the contract's topic files; the usage's workflow list and its build sessions come from `WORKFLOWS` and `isBuild()` in `skills.js` |
|
||||
| `cmd-open.mjs` | the `open` command: start or resume a session, its server and the browser; refuses a `--workflow` that `isWorkflow()` does not know (exit 2, naming the valid ones), and asks `startsClean()` (`public/hops.js`) whether a resume blanks the page |
|
||||
| `in-app.mjs` | the desktop app's signal to `open`: `inAppSignal()` reads `PLAN2CODE_IN_APP`, `PLAN2CODE_CONSOLE_SID`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_APP_TOKEN`; `announcePage()` POSTs the page to that window's loopback endpoint. Under the app `open` never starts a browser, resumes the app's session and announces the page; with the variables unset nothing here runs. Imported by `cmd-open.mjs` |
|
||||
| `open-link.mjs` | the desktop app's webview opens no new windows, so the page there sends links off the console (`linkLeavesPage()` in `public/app-bridge.js`: http or https on another origin, caught in `wireChrome()`) to `POST /open-link`. `linkToOpen()` takes http and https only (400 otherwise); `openLink()` starts the default browser with the link as one argument, never through a shell (`rundll32 url.dll,FileProtocolHandler` on Windows, `open` on macOS, `$BROWSER` or `xdg-open` elsewhere) and skips it under `PLAN2CODE_NO_BROWSER`. When that fails the page shows the link with a Copy button to paste into a browser |
|
||||
| `cmd-post-wait.mjs` | `post` and `wait`: publish a patch, then collect what the person sent |
|
||||
| `cmd-small.mjs` | the small commands: keep, forget, delete-spec, handoff, delete-handoff, status and stop; `handoff new` refuses an unknown `--workflow` the same way `open` does |
|
||||
| `files.mjs` | where the console's files live, how they are written safely, and the argument parser both command lines share |
|
||||
@@ -227,7 +229,7 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/screens/docs.js` | documents: tabs, blocks, print and download, and the brief button |
|
||||
| `public/screens/ending.js` | how a session ends: the finished screen, its offers, Stop and the way home |
|
||||
| `public/screens/git-host.js` | hosts the git board: tabs, panels and what each click sends |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js) |
|
||||
| `public/screens/help-dialog.js` | the Help dialog and the first-run Welcome (named so it is never confused with the pure help.js). Help reads right in both modes: a phrase that differs under the desktop app carries its app wording in `data-app` (swapped in by `renderAppWording()`), and a paragraph that differs is a `.for-browser` / `.for-app` sibling pair, switched by `:root.in-app` (set in `core.js` from `page.inApp`, rule in `help.css`). The older `render*Help()` functions patch a few ids the same way. `scripts/test-web-console-page-help.mjs` sweeps every topic's visible text in each mode for the other mode's wording |
|
||||
| `public/screens/looks.js` | User Preferences: looks, sounds and the launcher's model menus |
|
||||
| `public/screens/starting.js` | the launching, starting and waiting screens, with Planny's poses |
|
||||
| `public/screens/workspace.js` | the read-only Workspace of extra folders, and @mentions |
|
||||
@@ -253,7 +255,8 @@ Optional local browser UI shipped with **every** skill. Source lives in `src/web
|
||||
| `public/meter.js` | PURE, imports only `skills.js`: the session meter. `WEIGHTS` (the events that are not a skill's own launch, merged with each skill's `weight` from `skills.js`; 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, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `public/app-bridge.js` | The messages the page posts to the desktop app that frames it. `framed()` is true inside a frame; `tellApp(kind, extra)` posts `{ plan2code: kind }`, a named request with no free text: `looks` (the highlight's dark shades, from `applyLooks()`, for the app bar's buttons), `agent-continue` (the in-app **continue** button on the Not running line: the app types the keystrokes `continueKeys()` in `plan2code-app/ui/meter.js` names into the agent's terminal, `continue` and Enter, then under Claude Code its send-now chord ctrl+x ctrl+s, so a word queued behind a stuck turn is delivered) and `new-session` (the meter popover's New Session: the app presses its own bar button, confirm and all). Nothing outside a frame |
|
||||
| `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, strength }` or `{ error }`: `bad`, `too-long` past 2,000 characters, `max` outside 1-20, `strength` not one of `STRENGTHS`; `strength` is `balanced`, `thrifty`, `best` or `session`, missing reads as `balanced`, saved per project and skill in each `subagents.json` entry and sent as a `Helper strength:` line in the "on" block), `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, the `cmd-*.mjs` files, `patches.mjs`, `settings.mjs`, the page and the tests; in `SERVABLE` and preloaded |
|
||||
| `handoffs.mjs` | the handoff store, the only code that names, lists, marks, deletes and sweeps handoffs, all in `~/.plan2code/handoffs/` (`PLAN2CODE_HANDOFFS_DIR` for tests; `PLAN2CODE_NOW` pins its clock): `newHandoff()` claims `YYYY-MM-DD-HHmm-handoff` (`-2`, `-3` on a clash, the `.json` created exclusively) and writes only `<id>.json` (`{ v: 1, id, title, worktree, project, spec, workflow, skill, written, fromStop, usedAt }`), the agent writing `<id>.md`; `listHandoffs(worktree)` (unused, same worktree, `.md` present, newest first, title and Next task read off the document); `readHandoffMeta()`, `markHandoffUsed()`; `removeHandoff()` (`HANDOFF_ID` only, regular files, never a link, realpath inside the folder, throws on any refusal); `staleHandoffs()` / `removeHandoffs()` for the sweep |
|
||||
| `notepads.mjs` | the notebook store (the feature is named Notebook; its code, routes and storage folder keep the name `notepad`), the only code that names, reads, writes and removes notebooks, one per folder Plan2Code runs in, in `~/.plan2code/notepads/<folder-name>-<12 hex>/` (`PLAN2CODE_NOTEPADS_DIR` for tests), split into named tabs: `meta.json` (`{ v: 2, folder, created }`), `tabs.json` (`{ v: 1, order, last, tabs: { id: { name, created } } }`) and `tabs/<id>/note.md` with `tabs/<id>/images/`. `notepadKey()` (the folder's basename slug and the first 12 hex of `sha256(foldKey(folder))`), `listTabs()` / `defaultTabId()`, `readNotepad(folder, tab)` (never creates or writes anything; `{ tabs, last, tab }` with the tab's `text`, `savedAt` and `images` repeated at the top), the tab changes `createTab()` / `renameTab()` / `reorderTabs()` / `setLastTab()` / `deleteTab()` (index first, then the folder; names pass `normalizeTabName()`, `TAB_NAME_MAX` 40, any case compared by `nameKey()`, `NOTEPAD_MAX_TABS` 20), `saveNote(folder, tab, text)` (1 MB cap, atomic), `addImage()` / `addThumb()` / `removeImage()` (JPEG bytes only, 200 pictures per tab, UUID names), `imagePath()` (regular files whose realpath stays inside the folder), `staleNotepads(now, maxAgeMs)` (the real folders directly under it named like a key, never a link or a file, whose newest file is at least `maxAgeMs` old, as `{ key, folder, path }` with `folder` from `meta.json` or null), `removeNotepad(key)` (the key checked against `NOTEPAD_KEY_RE`, the path kept inside the notepads folder by `path.relative`, a link refused, then the whole folder removed; User Preferences, Cleanup is its only caller) and `NotepadError` (`code` and `status`, turned into `{ error }` by the `/notepad` routes). **Migration:** a notepad in the first shape (`note.md` and `images/` at the top) reads as one virtual tab, Notes (`LEGACY_TAB_ID`), and writes nothing; its first write moves the files into `tabs/<LEGACY_TAB_ID>/` and writes `tabs.json` last, every step safe to run again after a crash. A `tabs.json` that does not hold up is set aside as `tabs.json.corrupt` and rebuilt from the tab folders on the next write. Every write runs under a `notepad.lock` in the notepad's folder. The agent CLI never imports it: nothing in a notepad reaches the agent |
|
||||
| `public/notepad.js` | PURE, no imports: the Notebook's rules. `SAVE_DEBOUNCE_MS` 800, `RETRY_STEPS_MS` (1 s up to 30 s), `NOTE_MAX_BYTES` / `NOTEPAD_MAX_IMAGES` / `TAB_NAME_MAX` / `NOTEPAD_MAX_TABS` / `IMAGE_ID_RE` / `TAB_ID_RE` (kept equal to `notepads.mjs` by a test), `noteBytes()`, the save-state reducer `nextSave(state, event)` from `SAVE_START` (states `idle`, `pending`, `saving`, `saved`, `failed`, `too-long`; it returns the timer to arm), `saveStatus()` (the status line's words), `unsaved()` (what `beforeunload` asks on), `keepsText()` (unsaved or too long: a reopen never replaces the editor's text then), `tabSwitch()` (whether leaving a tab must save it first), `NOT_LOADED`, `EDITOR_NOT_LOADED`, `errorSentence()` (one sentence per `/notepad` refusal, else a lost connection), the tab rules `cleanTabName()`, `nameTaken()`, `tabNameProblem()`, `moveTab()`, `dropTab()` and the two-confirm delete `nextDelete()` / `DELETE_STAGES`, and `step()` (wrapping through the pictures) |
|
||||
|
||||
@@ -397,7 +397,11 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
- **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
|
||||
run at once (1 to 20; your agent's own limit still applies). Under Helpers,
|
||||
**Helper strength** sets how strong a model and how much effort helpers get:
|
||||
**Balanced** (the default), **Thrifty** (one step lighter; reviews never
|
||||
below standard), **Best** (strongest and high effort, except lookups) or
|
||||
**Match my session** (nothing set on helpers). **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**, on until switched off, in
|
||||
@@ -407,7 +411,10 @@ Pathfinder, the agent can hand independent pieces of work to helpers
|
||||
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.
|
||||
to start helpers here. Each row may carry one quiet line such as "Standard,
|
||||
medium effort" ("Session model" when the helper runs on yours). The rules
|
||||
live in `helper-strength.md` and apply in terminal sessions too. 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.
|
||||
|
||||
|
||||
@@ -42,7 +42,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 **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-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 (on by default for those skills until switched off, 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-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; 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 **git board** for the `git` workflow (three tabs, Changes, Branches and Sync, opening on the likely next step; branches, pull, push, commits and pull-request links, drawn from `state.git`; contract in `notes/git.md`), **Stop with a handoff** (handoffs live in `~/.plan2code/handoffs/`, owned by `handoffs.mjs`, swept after 30 days, and offered as dashboard chips to pick up in the same session), a private **Notebook** in the top bar (named tabs of Markdown and pictures, a live-preview CodeMirror editor, one notepad per folder in `~/.plan2code/notepads/`, owned by `notepads.mjs`, never shown to the agent, removed only through Cleanup once a month untouched), a built-in 18-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 (on by default for those skills until switched off, saved in `~/.plan2code/console/subagents.json`), and a Helper strength choice (Balanced, Thrifty, Best, Match my session; rules in `src/shared-references/helper-strength.md`, shipped in the five helper skills); 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-subagents.md`). Per-skill facts live in one list, `public/skills.js`, from which the meter, the resume command, Help's card list and the CLI's workflow list are derived; task files are read through `spec-files.mjs` (shared with the `specs.mjs` skill script), and the rule for which hops start the page clean is `startsClean()` in `public/hops.js`. The agent contract is read in pieces: `console.md` once per conversation, then a topic file (`console-*.md`, `notes/<workflow>.md`, `building*.md`) only when its moment comes; 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)
|
||||
|
||||
## Skill Scripts
|
||||
@@ -103,7 +103,8 @@ When you make a mistake, get corrected, or discover something about this codebas
|
||||
- Before deleting a test file that upstream split or removed, diff plan2code's copy against the rebranded upstream base and port the plan2code-only tests: v2.7.0's split of the web console suite would otherwise have dropped seven hardening tests (now in `scripts/test-web-console-hardening.mjs`).
|
||||
- Register a new skill in `install.js` `SOURCE_PROMPTS` before running its `scripts/test-script-<name>.mjs`: importing `scripts/skill-script-helpers.mjs` rebuilds `skills/` and prunes any skill folder `install.js` does not list, so the script under test vanishes.
|
||||
- When a `CHANGELOG.md` heading gets a version number, set the same number in `version.json` (with its `releaseDate`), the root `package.json` and README's `Version X.Y.Z` line in the same change, then run `npm run build:skills`. The changelog skill only touches `package.json`: v2.9.0 nearly shipped with `version.json` at 2.8.1, and README's line sat at 2.6.0 for three releases.
|
||||
- When `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone).
|
||||
- When `npm test` fails only timing-bound suites (the chat stress test, the page-cards redraw test "a redraw keeps the place of...", then a cascade in the session suite starting at "no submitted frame within 5s") while the machine is busy, rerun those files alone, and the `node --test` list with `--test-concurrency=4`, before suspecting the change: they failed that way on untouched code under load during the web console file split, and the redraw test did again in three phases of web-console-health. In web-console-notepad, four more failed only in full runs and passed alone: the Workspace page's @-mention test, the dashboard page's handoff chip test, the session suite's document route (`connect ETIMEDOUT`) and the notepad page's 200 KB typing test (why its budget there is 200 ms, not the 92 ms it takes alone). In helper-strength, the page-cards test "a card cut by the window fades at its bottom edge..." did the same.
|
||||
- Run `npm test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE` and `PLAN2CODE_EMBED_ORIGIN` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behaviour outside the app (the update banner, the terminal line, cookies, open's browser launch), which pass once unset.
|
||||
- Post a helper as `done` or `failed` in the same turn its completion notice arrives: its row stays `running` on the Subagents tab until a post says otherwise (a build once reached its sign-off with one row spinning). A `finish` is now refused while any helper is `running`.
|
||||
- Bring the Windows folder picker (`picker.mjs`, copied into `src/launcher/plan2code.js`) to the front with an Alt tap before `SetForegroundWindow`, never with `windowsHide`, the owner form's `TopMost`, `HWND_TOPMOST` or `AttachThreadInput`: measured on Windows 11, `SetWindowPos(HWND_TOPMOST)` returns true while the dialog stays non-topmost behind the browser, and only the Alt tap made it the foreground window. Check with `GetForegroundWindow` from a second process, since no test can see it.
|
||||
- Add any new file or folder Plan2Code writes at the top of `~/.plan2code/` to `KEPT_PLAN2CODE_ENTRIES` in `src/web-console/sessions.mjs` and to the Cleanup test in `scripts/test-web-console-server.mjs`: User Preferences → Cleanup offers every other entry there for deletion once it is an hour old, and the desktop app's `app/` and `app.json` were about to be listed.
|
||||
+28
-3
@@ -6,14 +6,39 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### ✨ Added
|
||||
|
||||
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **Restart** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
|
||||
- **desktop app**: a context meter in the bar reads how full the running agent's context window is: a real-ish number from Claude's own transcript or Codex's session log (labeled best-effort, since both formats are undocumented), a clearly labeled estimate for Devin or any agent with no documented signal, and a gentle nudge near 70% suggesting Restart, shown only for a real or best-effort reading.
|
||||
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Restart the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
|
||||
- **desktop app**: a cross-platform app (Rust, Tauri) that is the single window for working with an AI agent. It opens the Plan2Code dashboard as its main surface, runs Claude Code, Devin or Codex in a pseudo-terminal panel it owns, and adds a **New Session** button that replaces the agent with a fresh one on a brief the app builds from its own record of the session, with the in-progress work and recent activity carried over. Every console page (Ask, Workspace, Help, Preferences, Git, Notebook) opens inside the app, not a separate browser tab.
|
||||
- **desktop app**: **Update skills** in the bar brings the installed skills level with the app from the exact release the app ships, with live progress and a **Reconnect the console** offer once it finishes; an app older than the installed skills says so instead of trying to fix it by updating skills again.
|
||||
- **desktop app**: the window's own title (and so its taskbar entry) now reads **Plan2Code - <folder name>** once a project is open, instead of a plain **Plan2Code** every window shares; two or more windows on different projects read apart without opening each one to check.
|
||||
- **helpers**: a helper (subagent) no longer has to run on the session's own model and effort. A new shared reference, `helper-strength.md`, shipped in Pathfinder, Quick Task, Implement, Implement + Review and Review, matches each helper job to a strength (`light`, `standard`, `strongest` or `inherit`) and an effort (`low`, `medium` or `high`) from signals that can be checked, with floors, one-step escalation and a fallback order for tools that cannot set either, and never names a model or vendor. Review, Implement + Review and Pathfinder name the strength for the helpers they start, and the rules apply in terminal sessions too.
|
||||
- **web console**: the Subagents dialog has a **Helper strength** choice under Helpers: **Balanced** (the default), **Thrifty**, **Best** or **Match my session**, saved per project and skill and delivered to the agent as a `Helper strength:` line. Helper reports may say what each helper ran with (`strength`, `effort`), and the Subagents tab shows it as one quiet line, such as "Standard, medium effort".
|
||||
- `plan2code` opens the app automatically when a desktop is available; `plan2code --classic` (or no desktop, e.g. over SSH) keeps today's terminal-only flow unchanged, and the installer brings the app in alongside the skills and the command.
|
||||
|
||||
### 🔧 Changed
|
||||
|
||||
- **launcher**: `plan2code` no longer treats an SSH or service session on macOS or Windows as having a desktop, and asks before opening a folder that looks like it is not a project (no `.git`, `AGENTS.md` or `specs/`).
|
||||
- **desktop app**: the app's own bar no longer repeats the open page as a second "page: " label; the console's own bar, inside the window, already names it. The web console now knows when the agent driving it is the desktop app (the same signal that already routed `open` to the app's window) and, only there, drops advice that assumed a plain terminal: its session meter, the finished-step guide and the dashboard's red-session banner point at the app's own **New Session** button instead of a command to paste into a new conversation; its own "update available" banner, a copy-pasted shell command, never shows, since **Update skills** already covers it in one click with no shell involved; and a slash command still offered to continue a step says to paste it into the app's terminal panel, which runs the real agent CLI, rather than "a new conversation" that does not exist there. Running a plain terminal is unchanged.
|
||||
- **desktop app**: dropped the bar's own context-window meter and its restart nudge, front and back: a second, separately-tuned gauge beside the console's own Session meter (how much plan2code work this session has done) read as a duplicate of it, so there is now just the one, and it already points at New Session under the app (see above). The `agent_context` command, the Claude/Codex transcript readers behind it, and the context-nudge setting it read are removed from the Rust side too, not just unwired in the page. Every button that reconnects the console (after it stops, or after Update skills) is now labeled **Reconnect the console**, replacing the earlier mix of "Restart the console" and "Start it again" for the same action, and only one shows at a time.
|
||||
- **desktop app**: the launch card's permission-mode tick is now **on by default** (checks off), matching how `plan2code` has always started an agent from the plain terminal. It previously defaulted off, the opposite of the terminal's own long-standing default; untick it for an agent that keeps its normal approval prompts.
|
||||
- **web console**: Help's "When an update is out" line now knows when it is read inside the app too: there, it names **Update skills** in the bar instead of describing the dashboard's UPDATE AVAILABLE banner and a terminal command, since that banner never shows under the app and the command has no terminal to run in.
|
||||
- **desktop app**: the top bar's **Restart** button is now **New Session**, and every place the console names it under the app (the session meter, the dashboard's red-session banner, the finished-step guide, the Welcome tip, Help's Ask and Finishing topics, the handoff copy button's description) says so too; the meter's own advice under the app is a single **Start a New Session** button in the user's highlight colour. Its confirmation no longer claims "What it was doing is not saved" (not always true).
|
||||
- **desktop app**: with nothing saved yet, the terminal panel now starts docked right at a width that keeps the console's own side panels (such as Notes) from stacking under the main content, instead of the bottom dock it always opened with before; a saved choice from before is still kept exactly as it was.
|
||||
- **desktop app**: docked right and collapsed, the terminal panel's **Expand** label now reads top to bottom instead of running off the edge of the narrow strip.
|
||||
- **desktop app**: the agent no longer prints the console's web address in the terminal panel, since the page is already in the window beside it: `terminalLine` under the app points at the dashboard instead, and the agent contract says to give no link there.
|
||||
- **desktop app**: the console's "Not running... type **continue**" line makes **continue** a button under the app, which types `continue` and Enter (and, under Claude Code, its send-now chord) into the agent's terminal panel for you; the session meter's **Start a New Session** button presses the bar's own New Session (its confirmation included), replacing a "Press New Session at the top of the window" sentence now that the press works from there.
|
||||
- **desktop app**: **New Session** now starts the fresh agent on a new console session, so the session meter starts over at green. Before, the fresh agent joined the window's old session, and the meter stayed red after the very press it asks for. The brief of where you were is still written from the old session first, and the old console shuts itself down once the window moves on.
|
||||
- **web console**: the **Wrapping up** dialog after **Stop session** no longer closes itself when the stop lands: it turns into **Done**, with every step ticked, and stays up until you close it, so someone who stepped away comes back to an answer. Its "you can close the window/tab if you need to" line is gone.
|
||||
- **web console**: a plan's **Build order** card has a **Combine phases** button beside **No changes**. One click fills the box with a request to merge phases where possible while keeping each to a clear concern. It shows only in Plan and Revise plan, where the breakdown is phases.
|
||||
- **web console**: Help now reads right in the desktop app throughout, not just in the topics fixed before: what this page is and how long it runs, the troubleshooting table and its diagram, scroll memory, drafts, the session meter's red advice, Ask's "no agent" line and Privacy's link and address notes all name the app's window, its terminal panel, **New Session** and **Reconnect the console** instead of a browser tab, a link or a new conversation. The status line's approval hint says "the terminal panel" there too. In a browser, Help is unchanged.
|
||||
- **desktop app**: the top bar's buttons now look like the console's own: rounded, quiet until hovered, then in your highlight color from User Preferences (the app keeps it for the next launch), with **New Session** outlined in it as the likely next step.
|
||||
- **desktop app**: the New Session confirmation shows Planny, drawn like the console's own (outlined shell, star eye, smile), holding a steaming cup of coffee, and its buttons use the console's style: **New Session** in your highlight colour, **Cancel** a plain button. The same highlight applies to the panel's other one-button prompts, such as **Retry** and **Reconnect the console**.
|
||||
- **desktop app**: the top bar is rebuilt around two menus and one next step. The project shows as its folder name, with the full path and **Change project** in its menu; **New Session** always sits just left of the agent's menu, which carries a state dot, an amber **checks off** badge in place of the "Permission checks are off for ..." sentence, and **Change agent** once the agent has ended. The console's and the skills' messages share one slot at the right end that shows the most pressing step with its button (**Reconnect the console**, **Update skills**) and "+N more" for the rest, so the bar no longer overflows when several things go wrong at once. The repeated "Plan2Code" label, the full path, the "agent:" prefix and the long "Nothing starts until you press New Session" line are gone.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **desktop app**: under Claude Code, the console's **continue** button also sends Claude Code's send-now chord (ctrl+x ctrl+s), so a `continue` it held as a queued message behind a stuck turn is delivered in one press instead of waiting in the terminal.
|
||||
- **desktop app**: links that leave the console (**Open pull request**, links in documents, the feedback button) open in the default browser instead of doing nothing; when no browser can be started, the page shows the link with a **Copy** button to paste into one.
|
||||
- **web console**: answers sent and not picked up bring up the "not running, type **continue**" help after a minute of the agent's silence (three when it said it was working), instead of after its quiet allowance, which a build can set to half an hour.
|
||||
- **web console**: a failed Send says why: the lost-contact state and its reconnect help at once when the console is gone, the console's reason when it refuses the send, or that the console is still up and Send can be pressed again.
|
||||
|
||||
## v2.11.1
|
||||
|
||||
|
||||
@@ -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.11.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
Version 3.0.0 · MIT · 📖 [plan2code.jparkerweb.com](https://plan2code.jparkerweb.com)
|
||||
|
||||
---
|
||||
|
||||
@@ -92,12 +92,12 @@ which opens a folder picker first. Uninstalling (`U`) removes both.
|
||||
<summary>About the desktop app</summary>
|
||||
|
||||
The installer also offers the **Plan2Code desktop app**: one window with the dashboard and your agent's
|
||||
terminal side by side, docked bottom or right and collapsible. Every console page, not only the
|
||||
terminal side by side, docked right (or bottom) and collapsible. Every console page, not only the
|
||||
dashboard, opens inside it. A launch card asks which agent, model and effort to start on, with
|
||||
permission checks off as its own opt-in tick (off by default); a **Restart** button then replaces the
|
||||
agent with a fresh one on a brief built from the session, and a status strip below the top bar shows
|
||||
the agent, the page open and a context meter that nudges you toward Restart once Claude's or Codex's
|
||||
context is getting full. Once it is installed, `plan2code` opens the app instead of running the agent
|
||||
permission checks off as its own tick (on by default, matching the terminal flow; untick it to keep
|
||||
the agent's approval prompts). A **New Session** button in the top bar replaces the agent with a fresh
|
||||
one on a brief built from the session, and the console's own Session meter points at it when a
|
||||
session is getting long. Once it is installed, `plan2code` opens the app instead of running the agent
|
||||
in your terminal. `plan2code --classic` keeps the terminal flow, and so does a Linux machine with no
|
||||
display (over SSH, say) or any machine over an SSH session. `plan2code update` updates the skills, the
|
||||
command and the app together, and the bar offers the same **Update skills** when the app and the
|
||||
|
||||
+50
-19
@@ -1,9 +1,10 @@
|
||||
# The Plan2Code desktop app
|
||||
|
||||
One window for working with an AI agent. The app opens the Plan2Code dashboard as its main surface,
|
||||
runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **Restart**
|
||||
runs your agent (Claude Code, Devin or Codex) in a terminal panel it owns, and has a **New Session**
|
||||
button that replaces the agent with a fresh one on a brief the app builds from its own record of the
|
||||
session. It is an addition: `/plan2code` typed inside an agent works exactly as before, with or
|
||||
session. The fresh agent gets a console session of its own, so the Session meter starts over with it.
|
||||
It is an addition: `/plan2code` typed inside an agent works exactly as before, with or
|
||||
without the app.
|
||||
|
||||
## Get it
|
||||
@@ -31,6 +32,12 @@ Releases carry one file per system:
|
||||
|
||||
On any other system the installer says there is no build for it and carries on without the app.
|
||||
|
||||
Each of those is a plain executable, not an OS-level installer package (no `.msi`, no NSIS `.exe`
|
||||
setup, no `.dmg` with a drag-to-Applications step): the installer above places it directly, already
|
||||
verified. `plan2code-app`'s own `npm run build` can produce `.msi`/NSIS/`.dmg`/`.deb` bundles locally
|
||||
(Tauri's bundler is on), but the release workflow does not build or publish them; nothing today
|
||||
downloads or runs one.
|
||||
|
||||
You also need Node.js 18 or newer (the app checks at start and says what to install) and:
|
||||
|
||||
- **Windows:** the WebView2 runtime, which comes with Windows 11 and current Windows 10.
|
||||
@@ -59,18 +66,42 @@ The first time the app opens on a folder, a checklist confirms Node, the agent C
|
||||
folder and the skills version before anything else shows; a later launch skips straight past it.
|
||||
|
||||
A **launch card** then asks which agent (Claude, Devin or Codex), model and effort (Claude and Codex
|
||||
only) to start on. Permission checks off is its own tick, unchanged unless you choose it (Restart
|
||||
only) to start on. Permission checks off is its own tick, on by default (see below; New Session
|
||||
keeps whatever you picked); a CLI the app cannot find is named, with how to install it, instead of
|
||||
just being greyed out. The card is skipped when the launcher already passed an agent to start.
|
||||
|
||||
Once an agent is running, a slim top bar holds the project name, **Restart** and **Change project**,
|
||||
and a status strip beneath it shows the page the agent opened (not only the dashboard — every console
|
||||
page, including Ask, Workspace, Notebook, Help, Preferences and Git, opens inside the window), the
|
||||
agent's name and status, a context meter once one is readable, and the permission mode in use. The
|
||||
terminal panel has its own toolbar: dock it to the bottom or the right, collapse it to a thin strip,
|
||||
or maximize it; its size is remembered. An "agent may need you" badge appears on a collapsed or small
|
||||
panel once the agent has sat quiet for a while. **Change project** asks first if an agent is running,
|
||||
then stops it and the console before opening the new folder.
|
||||
The window's own title (and so its taskbar entry) reads **Plan2Code - <folder name>** once a
|
||||
project is open, so two or more windows on different projects read apart without opening each one
|
||||
to check.
|
||||
|
||||
A slim top bar reads, left to right: the project folder's name, a menu holding its full path and
|
||||
**Change project**; **New Session**, whenever an agent exists; the agent's own menu, with a dot for its
|
||||
state, an amber **checks off** badge while permission checks are off, and **Change agent** once it has
|
||||
ended; a short line (why the agent ended, a New Session's brief, or what went wrong); and, at the right
|
||||
end, the one next step for the console or the skills when there is one (**Reconnect the console**,
|
||||
**Update skills**), with "+N more" if anything else is waiting behind it. The console itself, opening inside the
|
||||
window (not only the dashboard — every console page, including Ask, Workspace, Notebook, Help,
|
||||
Preferences and Git), already shows which page is open and its own **Session** meter (how much plan2code
|
||||
work this session has done) in its own bar, so the app's bar does not repeat either. That Session meter
|
||||
is the one place for "is this session getting long" under the app, too: the app does not keep a second,
|
||||
separate context-window meter of its own, so there is only ever one gauge to read and only one place its
|
||||
threshold is tuned. The terminal panel has its own toolbar: dock it to the bottom or the right, collapse
|
||||
it to a thin strip, or maximize it; its size is remembered. An "agent may need you" badge appears on a
|
||||
collapsed or small panel once the agent has sat quiet for a while. **Change project** (in the project
|
||||
menu) asks first if an agent is running, then stops it and the console before opening the new folder.
|
||||
|
||||
If the console itself ever needs reconnecting (it stopped, or the skills were just updated), every path
|
||||
to that offers the same **Reconnect the console** button — never "Restart the console" in one place and
|
||||
"Start it again" in another for the same action — and only one shows at a time.
|
||||
|
||||
The console also knows when it is running inside the app (the agent it talks to carries that signal):
|
||||
its session meter, the "Before you close this" guide on a finished step, and the dashboard's red-session
|
||||
banner all point at the app's own **New Session** button instead of a command to paste into a new
|
||||
conversation, since New Session already does that in one click; and the console's own "update available"
|
||||
banner never shows, since the app's **Update skills** button (below) already covers it with no shell
|
||||
involved. A slash command still offered to continue a step (such as `/plan2code-4-finalize`) stays
|
||||
exactly as it would in a terminal: paste it into the app's own terminal panel, which runs the real
|
||||
agent CLI.
|
||||
|
||||
## Keep it up to date
|
||||
|
||||
@@ -93,15 +124,15 @@ anyway**.
|
||||
**Linux.** Nothing to allow. If the file is not executable, run
|
||||
`chmod +x ~/.plan2code/app/plan2code-app`.
|
||||
|
||||
## Permission checks are off, if you choose it
|
||||
## Permission checks are off by default, same as the terminal
|
||||
|
||||
The launch card's permission-mode tick is off by default: leave it off and the agent keeps its normal
|
||||
approval prompts. Turn it on and the agent starts with checks off instead
|
||||
(`--permission-mode bypassPermissions` in Claude Code, `--permission-mode bypass` in Devin,
|
||||
`--dangerously-bypass-approvals-and-sandbox` in Codex), reading, writing and running commands in your
|
||||
project folder without asking; the status strip says so while that agent runs. Restart keeps the same
|
||||
choice. Work in a folder you are happy for the agent to change, and keep it under version control,
|
||||
before turning checks off.
|
||||
The launch card's permission-mode tick is **on by default** (checks off), matching `plan2code` run the
|
||||
plain way: the agent starts with checks off (`--permission-mode bypassPermissions` in Claude Code,
|
||||
`--permission-mode bypass` in Devin, `--dangerously-bypass-approvals-and-sandbox` in Codex), reading,
|
||||
writing and running commands in your project folder without asking; the agent's amber **checks off** badge in
|
||||
the top bar says so while that agent runs. Untick it before pressing Start agent to keep the agent's normal approval prompts instead.
|
||||
New Session keeps the same choice. Work in a folder you are happy for the agent to change, and keep it under
|
||||
version control.
|
||||
|
||||
## Remove it
|
||||
|
||||
|
||||
+11
-2
@@ -161,7 +161,10 @@ const SOURCE_PROMPTS = [
|
||||
name: 'pathfinder',
|
||||
displayName: 'Pathfinder Mode',
|
||||
description: 'charting of a foggy idea as a map of decision questions, cleared one at a time',
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-quick-task.md',
|
||||
@@ -176,6 +179,7 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -219,6 +223,7 @@ const SOURCE_PROMPTS = [
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -234,6 +239,7 @@ const SOURCE_PROMPTS = [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'plan2code-3-implement.md', target: 'implement.md' },
|
||||
{ source: 'shared-references/building-habits.md', target: 'building-habits.md' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' },
|
||||
{ source: 'plan2code-review.md', target: 'review.md' },
|
||||
{ source: 'plan2code-review-references' }
|
||||
]
|
||||
@@ -246,7 +252,10 @@ const SOURCE_PROMPTS = [
|
||||
description: 'Comprehensive post-implementation review with spec compliance checking',
|
||||
isUtility: true,
|
||||
scripts: ['specs.mjs', 'commit-msg.mjs', 'review-scope.mjs'],
|
||||
additionalReferences: [{ source: 'web-console', target: 'web-console' }]
|
||||
additionalReferences: [
|
||||
{ source: 'web-console', target: 'web-console' },
|
||||
{ source: 'shared-references/helper-strength.md', target: 'helper-strength.md' }
|
||||
]
|
||||
},
|
||||
{
|
||||
source: 'plan2code-4-finalize.md',
|
||||
|
||||
+1
-1
@@ -8,7 +8,7 @@
|
||||
"scripts": {
|
||||
"prepare": "husky",
|
||||
"build:skills": "node install.js --build-skills",
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
"test": "node scripts/validate-char-count.js && node install.js --build-skills && node scripts/parse-check.mjs && node scripts/check-skill-table.mjs && node --test --test-concurrency=8 scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-speed.mjs scripts/test-web-console-qa.mjs scripts/test-web-console-concurrency.mjs scripts/test-web-console-workspace.mjs scripts/test-web-console-lifecycle.mjs scripts/test-web-console-chat-stress.mjs scripts/test-web-console-server.mjs scripts/test-web-console-session.mjs scripts/test-web-console-logic.mjs scripts/test-web-console-skills.mjs scripts/test-web-console-spec-states.mjs scripts/test-web-console-state.mjs scripts/test-web-console-shape.mjs scripts/test-script-pathfinder.mjs scripts/test-launcher.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-handoffs.mjs scripts/test-web-console-notepad.mjs scripts/test-script-xray.mjs scripts/test-script-finalize.mjs scripts/test-getting-started.mjs scripts/test-install-update.mjs scripts/test-browser-helper.mjs scripts/test-web-console-page-cards.mjs scripts/test-web-console-page-dashboard.mjs scripts/test-web-console-page-session.mjs scripts/test-web-console-page-ask.mjs scripts/test-web-console-page-workspace.mjs scripts/test-web-console-page-help.mjs scripts/test-web-console-page-prefs.mjs scripts/test-web-console-page-git.mjs scripts/test-web-console-page-notepad.mjs scripts/test-standalone-check.mjs scripts/test-check-versions.mjs scripts/test-app-meter.mjs"
|
||||
},
|
||||
"devDependencies": {
|
||||
"husky": "^9.0.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# plan2code-app
|
||||
|
||||
The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a Restart button. Built with Tauri 2 (Rust and a web view).
|
||||
The Plan2Code desktop app (v3.0): one window with the dashboard, a terminal panel for the agent, and a **New Session** button. Built with Tauri 2 (Rust and a web view).
|
||||
|
||||
The app is optional. The Node web console and the skills never depend on it, so running `/plan2code` inside an agent with no app works exactly as before.
|
||||
|
||||
|
||||
@@ -8,6 +8,12 @@ Work from the pre-release build: publish a GitHub pre-release so `release-app.ym
|
||||
then install from it. Tick each box per system and note anything that is a rough edge rather than a
|
||||
failure.
|
||||
|
||||
`npm run build` here runs `tauri build` with bundling on, so a local build also produces `.msi`/NSIS
|
||||
`.exe`/`.dmg`/`.deb` installer packages under `src-tauri/target/release/bundle/`. Ignore those: the
|
||||
release workflow builds with `--no-bundle` and attaches only the plain executable per system (see
|
||||
`.github/workflows/release-app.yml`); `install.js` is the only installer, and it places that plain
|
||||
file directly after checking it against the release's checksum list.
|
||||
|
||||
## Before you start
|
||||
|
||||
- [ ] `node scripts/check-versions.mjs --tag v<version>` passes (version.json, package.json,
|
||||
@@ -26,7 +32,7 @@ failure.
|
||||
the `plan2code` command are still installed
|
||||
- [ ] `plan2code` in a project asks for the agent and model, then opens the app on that folder
|
||||
- [ ] The agent and model picked in the launcher are the ones the app starts at once, with no
|
||||
launch card or checklist shown first, and Restart keeps them
|
||||
launch card or checklist shown first, and New Session keeps them
|
||||
- [ ] `plan2code --classic` runs the agent in the terminal with the app installed
|
||||
- [ ] Linux only: with `DISPLAY` and `WAYLAND_DISPLAY` unset, `plan2code` runs the terminal flow
|
||||
- [ ] The desktop shortcut opens the folder picker and then the app
|
||||
@@ -44,28 +50,37 @@ failure.
|
||||
|
||||
- [ ] The dashboard shows in the frame and the terminal panel is visible beneath it
|
||||
- [ ] Resizing the window keeps both usable; dragging the handle resizes the panel
|
||||
- [ ] The bar shows the project folder and the context meter; the permission note appears only
|
||||
while an agent started with checks off is running, never otherwise
|
||||
- [ ] The bar shows the project folder; the permission note appears only while an agent started
|
||||
with checks off is running, never otherwise
|
||||
- [ ] The OS window title (and so the taskbar entry) reads **Plan2Code - <folder name>**,
|
||||
not just **Plan2Code**; open a second window on a different folder and confirm they read
|
||||
apart in the taskbar without needing to restore either one
|
||||
- [ ] The first run (no `firstRunDone` saved yet) shows the checklist (Node, an agent CLI, the
|
||||
project folder, the skills version) before the launch card; a later launch goes straight to
|
||||
the launch card
|
||||
- [ ] The launch card offers agent, model, effort (Claude and Codex only) and permission mode
|
||||
(off is an explicit tick, never the default); a CLI it could not find is named, not just
|
||||
disabled
|
||||
(checks off is ticked by default, matching the plain `plan2code` launcher; untick it for
|
||||
an agent that keeps its normal approval prompts); a CLI it could not find is named, not
|
||||
just disabled
|
||||
- [ ] **Dock the terminal to the right**: the splitter becomes vertical, the toolbar stacks, and the
|
||||
dashboard keeps the rest of the width; dock it back to the bottom
|
||||
- [ ] **Collapse** the terminal to a thin strip (either dock) and **Expand** it back; its size from
|
||||
before collapsing is remembered
|
||||
- [ ] Docked right, collapsed: the **Expand** label reads top-to-bottom and fits inside the strip,
|
||||
not sideways text running off the edge
|
||||
- [ ] Collapse the terminal (or shrink it small), let the agent go quiet for a while mid-answer: the
|
||||
"agent may need you" badge appears on the strip; expanding it clears the badge
|
||||
- [ ] **Change project** in the top bar, with an agent running: it asks first, then the folder
|
||||
- [ ] The top bar's project and agent menus open under their name, close on a click elsewhere (the
|
||||
console frame and the terminal included) or Escape, and are not cut off by the bar
|
||||
- [ ] **Change project** in the top bar's project menu, with an agent running: it asks first, then the folder
|
||||
picker opens; cancelling the picker leaves the running agent and its project untouched
|
||||
- [ ] Change project, pick a different folder: the old agent and console stop, the new folder opens
|
||||
on the launch card (or the checklist, if its own first run has not passed yet)
|
||||
- [ ] Reload the window (or navigate away and back) while an agent is running: the terminal redraws
|
||||
from where it was, not blank, and the dashboard reconnects to the same session
|
||||
- [ ] When the app and the installed skills differ in version, the bar offers **Update skills**, and
|
||||
nothing updates until it is pressed
|
||||
- [ ] When the app and the installed skills differ in version, the bar's right end offers **Update
|
||||
skills**, and nothing updates until it is pressed; with the console stopped as well, Reconnect
|
||||
the console shows first and "+1 more" names the update
|
||||
|
||||
## The terminal panel, with each real agent (each system)
|
||||
|
||||
@@ -79,26 +94,21 @@ Do each of Claude Code, Devin and Codex for a few minutes:
|
||||
- [ ] A line with Unicode and emoji
|
||||
- [ ] Select text in the terminal: it copies on its own; Ctrl+Shift+C (Windows, Linux) or Cmd+C
|
||||
(macOS) copies the selection too; Ctrl+V / Cmd+V pastes
|
||||
- [ ] Exiting the agent: the bar says it ended and offers Restart
|
||||
- [ ] Exiting the agent: the agent menu reads "ended" with the reason beside it, and New Session stays
|
||||
just left of it
|
||||
|
||||
## Agent lifecycle
|
||||
|
||||
- [ ] Start, then **Restart**: it confirms once, then a fresh agent starts on the same agent, model,
|
||||
effort and permission mode, and the dashboard shows the pick-up chip with a brief that
|
||||
matches the session
|
||||
- [ ] An agent that ends by itself leaves the app asking nothing until Restart or **Change agent**
|
||||
is pressed; Change agent reopens the launch card with a real choice to make again
|
||||
- [ ] Start, then **New Session**: it confirms once, with Planny on a coffee break and no claim about unsaved
|
||||
work, then a fresh agent starts on the same agent, model, effort and permission mode, and the
|
||||
dashboard shows the pick-up chip with a brief that matches the session
|
||||
- [ ] An agent that ends by itself leaves the app asking nothing until New Session or **Change agent**
|
||||
(in the agent menu) is pressed; Change agent reopens the launch card with a real choice to make again
|
||||
- [ ] Closing the window while an agent runs asks first, and "no" keeps the window open
|
||||
- [ ] Cmd+Q on macOS asks the same
|
||||
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then Restart; check Task
|
||||
- [ ] Windows only: start a CLI installed through npm (a `.cmd` shim), then New Session; check Task
|
||||
Manager and confirm no leftover `node.exe` (or the CLI's own process) is left running
|
||||
|
||||
## Context meter
|
||||
|
||||
- [ ] Claude Code and Codex: the meter moves during a long session and the nudge appears once
|
||||
- [ ] Devin: the meter is labeled as an estimate
|
||||
- [ ] `~/.claude/settings.json` and your own status line are byte-identical before and after a session
|
||||
|
||||
## Standalone path
|
||||
|
||||
- [ ] `/plan2code` typed inside an agent with the app closed opens the dashboard exactly as before
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"$schema": "../gen/schemas/desktop-schema.json",
|
||||
"identifier": "default",
|
||||
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends",
|
||||
"description": "Permissions for the main window: its own commands need none, so only listening to the page events the app sends, plus setting the window's own title to the open project's name",
|
||||
"windows": ["main"],
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten"]
|
||||
"permissions": ["core:event:allow-listen", "core:event:allow-unlisten", "core:window:allow-set-title"]
|
||||
}
|
||||
@@ -228,6 +228,15 @@ impl AnnounceServer {
|
||||
self.current.lock().ok().and_then(|slot| slot.clone())
|
||||
}
|
||||
|
||||
/// Forget the page most recently announced, so the next agent's `open`
|
||||
/// starts a session of its own instead of joining that one. New Session
|
||||
/// does this: a fresh agent's session meter starts over with it.
|
||||
pub fn forget_current(&self) {
|
||||
if let Ok(mut slot) = self.current.lock() {
|
||||
*slot = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// What goes on the agent's process so its `console.mjs open` shows pages
|
||||
/// here. Every value belongs to this window. `embed_origin` is the origin of
|
||||
/// the app page, so a console the agent starts allows being framed by it.
|
||||
@@ -361,5 +370,8 @@ mod tests {
|
||||
assert!(ask(server.token()).contains(r#""sid":"s1""#));
|
||||
assert!(ask("wrong").starts_with("HTTP/1.1 403"));
|
||||
assert_eq!(server.current().unwrap().workflow, "plan");
|
||||
server.forget_current();
|
||||
assert!(ask(server.token()).ends_with("null"), "forgotten: the next open starts its own session");
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
}
|
||||
@@ -1,228 +0,0 @@
|
||||
//! Claude's context, read from its own transcript: the last `assistant` message's
|
||||
//! token usage, as a fraction of its context window. Claude Code writes one file
|
||||
//! per session under `~/.claude/projects/<cwd, every non-alphanumeric character
|
||||
//! replaced with `-`>/<session id>.jsonl` (relocatable via `CLAUDE_CONFIG_DIR`),
|
||||
//! and names it after the session's own id, so a project folder's newest file
|
||||
//! since the agent started is this run's transcript (Task 10.1's spike; the
|
||||
//! same approach `codex.rs` uses for Codex's log). The entry format is
|
||||
//! undocumented ("internal and may change between versions" per Claude's own
|
||||
//! docs), so a usable reading is `BestEffort`, never `Real`. An unreadable line
|
||||
//! is skipped, and a transcript with no usable line, or no transcript at all,
|
||||
//! is `Unknown`.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{ContextReader, ContextReading};
|
||||
|
||||
/// How much of a transcript's end is read; the newest usage is near the end.
|
||||
pub const TAIL_BYTES: u64 = 256 * 1024;
|
||||
|
||||
pub struct ClaudeReader {
|
||||
pub projects_dir: PathBuf,
|
||||
pub folder: PathBuf,
|
||||
/// Only a transcript written at or after this moment belongs to the running agent.
|
||||
pub since: SystemTime,
|
||||
/// The context window to read the usage against (`super::window_for`).
|
||||
pub window: u64,
|
||||
}
|
||||
|
||||
impl ContextReader for ClaudeReader {
|
||||
fn read(&self) -> ContextReading {
|
||||
match newest_transcript(&self.projects_dir.join(encode(&self.folder)), self.since) {
|
||||
Some(file) => reading_from_file(&file, self.window),
|
||||
None => ContextReading::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `folder` with every non-alphanumeric character replaced by `-`, the way
|
||||
/// Claude Code names a project's transcripts directory.
|
||||
fn encode(folder: &Path) -> String {
|
||||
folder.to_string_lossy().chars().map(|c| if c.is_ascii_alphanumeric() { c } else { '-' }).collect()
|
||||
}
|
||||
|
||||
/// The newest `*.jsonl` file directly under `dir` that was written at or after `since`.
|
||||
fn newest_transcript(dir: &Path, since: SystemTime) -> Option<PathBuf> {
|
||||
let entries = fs::read_dir(dir).ok()?;
|
||||
let mut newest: Option<(SystemTime, PathBuf)> = None;
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.extension().and_then(|e| e.to_str()) != Some("jsonl") {
|
||||
continue;
|
||||
}
|
||||
let Ok(modified) = entry.metadata().and_then(|m| m.modified()) else { continue };
|
||||
if modified < since {
|
||||
continue;
|
||||
}
|
||||
if newest.as_ref().is_none_or(|(best, _)| modified > *best) {
|
||||
newest = Some((modified, path));
|
||||
}
|
||||
}
|
||||
newest.map(|(_, path)| path)
|
||||
}
|
||||
|
||||
/// The percent of `window` the last usable `assistant` usage line in `text` used.
|
||||
pub fn reading_from_text(text: &str, window: u64) -> ContextReading {
|
||||
for line in text.lines().rev() {
|
||||
if let Some(percent) = percent_from_line(line, window) {
|
||||
return ContextReading::BestEffort { percent };
|
||||
}
|
||||
}
|
||||
ContextReading::Unknown
|
||||
}
|
||||
|
||||
fn percent_from_line(line: &str, window: u64) -> Option<u8> {
|
||||
if window == 0 {
|
||||
return None;
|
||||
}
|
||||
let value: Value = serde_json::from_str(line).ok()?;
|
||||
if value.get("type")?.as_str()? != "assistant" {
|
||||
return None;
|
||||
}
|
||||
let usage = value.get("message")?.get("usage")?;
|
||||
let input = usage.get("input_tokens")?.as_u64()?;
|
||||
let cache_read = usage.get("cache_read_input_tokens").and_then(Value::as_u64).unwrap_or(0);
|
||||
let cache_creation = usage.get("cache_creation_input_tokens").and_then(Value::as_u64).unwrap_or(0);
|
||||
let used = input.saturating_add(cache_read).saturating_add(cache_creation);
|
||||
Some((used.saturating_mul(100) / window).min(100) as u8)
|
||||
}
|
||||
|
||||
/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`.
|
||||
fn reading_from_file(file: &Path, window: u64) -> ContextReading {
|
||||
let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown };
|
||||
let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown };
|
||||
if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
if handle.read_to_end(&mut bytes).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
// The first line of a partial tail is cut short; it fails to parse and is skipped.
|
||||
reading_from_text(&String::from_utf8_lossy(&bytes), window)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
const GOOD: &str = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":724,"cache_read_input_tokens":205907}}}"#;
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-claude-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
fn epoch_plus(secs: u64) -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
fn write_transcript(dir: &Path, name: &str, body: &str, modified: SystemTime) -> PathBuf {
|
||||
fs::create_dir_all(dir).unwrap();
|
||||
let file = dir.join(format!("{name}.jsonl"));
|
||||
fs::write(&file, body).unwrap();
|
||||
File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_assistant_usage_gives_the_percent_of_the_window() {
|
||||
assert_eq!(reading_from_text(GOOD, 206_633), ContextReading::BestEffort { percent: 100 });
|
||||
assert_eq!(reading_from_text(GOOD, 1_000_000), ContextReading::BestEffort { percent: 20 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_normal_transcript_is_read_from_the_newest_assistant_line() {
|
||||
let early = r#"{"type":"assistant","message":{"usage":{"input_tokens":2,"cache_creation_input_tokens":0,"cache_read_input_tokens":99998}}}"#;
|
||||
let text = format!("{early}\n{GOOD}");
|
||||
assert_eq!(reading_from_text(&text, 206_633), ContextReading::BestEffort { percent: 100 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_partial_last_line_is_skipped_in_favour_of_the_line_before_it() {
|
||||
let text = format!("{GOOD}\n{{\"type\":\"assistant\",\"mess");
|
||||
assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_assistant_and_malformed_lines_are_skipped() {
|
||||
let text = format!("not json\n{{bad\n{{\"type\":\"user\",\"message\":{{}}}}\n{GOOD}");
|
||||
assert_eq!(reading_from_text(&text, 1_000_000), ContextReading::BestEffort { percent: 20 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_line_with_no_usable_usage_is_unknown() {
|
||||
assert_eq!(reading_from_text("", 1_000_000), ContextReading::Unknown);
|
||||
assert_eq!(reading_from_text(r#"{"type":"assistant","message":{}}"#, 1_000_000), ContextReading::Unknown);
|
||||
assert_eq!(reading_from_text(GOOD, 0), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_file_is_unknown() {
|
||||
let reader = ClaudeReader {
|
||||
projects_dir: temp_dir("missing").join("projects"),
|
||||
folder: PathBuf::from(r"C:\git\project"),
|
||||
since: epoch_plus(0),
|
||||
window: 200_000,
|
||||
};
|
||||
assert_eq!(reader.read(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_transcript_is_read_from_its_end() {
|
||||
let dir = temp_dir("long");
|
||||
let file = write_transcript(&dir, "long", &format!("{}\n{GOOD}", "x".repeat(TAIL_BYTES as usize + 100)), epoch_plus(0));
|
||||
assert_eq!(reading_from_file(&file, 206_633), ContextReading::BestEffort { percent: 100 });
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_transcript_for_this_folder_is_read() {
|
||||
let root = temp_dir("newest");
|
||||
let projects = root.join("projects");
|
||||
let dir = projects.join(encode(Path::new(r"C:\git\project")));
|
||||
write_transcript(&dir, "a-old", GOOD, epoch_plus(100));
|
||||
let newest = write_transcript(&dir, "b-new", &GOOD.replace("205907", "500000"), epoch_plus(200));
|
||||
let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 };
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
|
||||
let _ = fs::remove_dir_all(root);
|
||||
let _ = newest;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_file_is_read_from_the_new_one() {
|
||||
let root = temp_dir("rotated");
|
||||
let projects = root.join("projects");
|
||||
let dir = projects.join(encode(Path::new(r"C:\git\project")));
|
||||
write_transcript(&dir, "first", GOOD, epoch_plus(100));
|
||||
let reader = ClaudeReader { projects_dir: projects.clone(), folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(0), window: 1_000_000 };
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 20 });
|
||||
write_transcript(&dir, "second", &GOOD.replace("205907", "500000"), epoch_plus(200));
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_transcript_from_before_the_agent_started_is_ignored() {
|
||||
let root = temp_dir("since");
|
||||
let projects = root.join("projects");
|
||||
let dir = projects.join(encode(Path::new(r"C:\git\project")));
|
||||
write_transcript(&dir, "old", GOOD, epoch_plus(100));
|
||||
let reader = ClaudeReader { projects_dir: projects, folder: PathBuf::from(r"C:\git\project"), since: epoch_plus(200), window: 1_000_000 };
|
||||
assert_eq!(reader.read(), ContextReading::Unknown);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_cwd_is_encoded_the_way_claude_code_names_its_projects_folder() {
|
||||
assert_eq!(encode(Path::new(r"C:\git\plan2code")), "C--git-plan2code");
|
||||
}
|
||||
}
|
||||
@@ -1,315 +0,0 @@
|
||||
//! Codex's context, read from its session log. Codex writes each run to
|
||||
//! `sessions/YYYY/MM/DD/rollout-*.jsonl` under its home folder (`CODEX_HOME`,
|
||||
//! or `~/.codex`). The app reads the newest log for its project folder, from
|
||||
//! its end, and never writes there. The format is undocumented, so the reading
|
||||
//! is `BestEffort`: an unrecognised line is skipped, and a log with no usable
|
||||
//! line, or no log at all, is `Unknown`. Nothing here is an error.
|
||||
|
||||
use std::fs::{self, File};
|
||||
use std::io::{BufRead, BufReader, Read, Seek, SeekFrom};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde_json::Value;
|
||||
|
||||
use super::{ContextReader, ContextReading};
|
||||
|
||||
/// How much of a log's end is read. The newest token count is near the end,
|
||||
/// so a long log is never read whole.
|
||||
pub const TAIL_BYTES: u64 = 256 * 1024;
|
||||
|
||||
/// How deep the sessions folder is searched: year, month, day, file.
|
||||
const SEARCH_DEPTH: u32 = 4;
|
||||
|
||||
pub struct CodexReader {
|
||||
pub sessions_dir: PathBuf,
|
||||
pub folder: PathBuf,
|
||||
/// Only logs written at or after this moment belong to the running agent.
|
||||
pub since: SystemTime,
|
||||
}
|
||||
|
||||
impl ContextReader for CodexReader {
|
||||
fn read(&self) -> ContextReading {
|
||||
match newest_log(&self.sessions_dir, &self.folder, self.since) {
|
||||
Some(file) => reading_from_file(&file),
|
||||
None => ContextReading::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The percent of the model's window the newest request used, from the last
|
||||
/// usable `token_count` line in `text`.
|
||||
pub fn reading_from_text(text: &str) -> ContextReading {
|
||||
for line in text.lines().rev() {
|
||||
if let Some(percent) = percent_from_line(line) {
|
||||
return ContextReading::BestEffort { percent };
|
||||
}
|
||||
}
|
||||
ContextReading::Unknown
|
||||
}
|
||||
|
||||
fn percent_from_line(line: &str) -> Option<u8> {
|
||||
let value: Value = serde_json::from_str(line).ok()?;
|
||||
if value.get("type")?.as_str()? != "event_msg" {
|
||||
return None;
|
||||
}
|
||||
let payload = value.get("payload")?;
|
||||
if payload.get("type")?.as_str()? != "token_count" {
|
||||
return None;
|
||||
}
|
||||
let info = payload.get("info")?;
|
||||
let used = info.get("last_token_usage")?.get("input_tokens")?.as_u64()?;
|
||||
let window = info.get("model_context_window")?.as_u64()?;
|
||||
if window == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((used.saturating_mul(100) / window).min(100) as u8)
|
||||
}
|
||||
|
||||
/// Reads the end of `file`. A file that cannot be opened or read is `Unknown`.
|
||||
fn reading_from_file(file: &Path) -> ContextReading {
|
||||
let Ok(mut handle) = File::open(file) else { return ContextReading::Unknown };
|
||||
let Ok(len) = handle.metadata().map(|m| m.len()) else { return ContextReading::Unknown };
|
||||
if len > TAIL_BYTES && handle.seek(SeekFrom::Start(len - TAIL_BYTES)).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
if handle.read_to_end(&mut bytes).is_err() {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
// The first line of a partial tail is cut short; it fails to parse and is skipped.
|
||||
reading_from_text(&String::from_utf8_lossy(&bytes))
|
||||
}
|
||||
|
||||
/// The newest log under `sessions_dir` that was written since `since` and
|
||||
/// whose first line names `folder` as its working directory.
|
||||
pub fn newest_log(sessions_dir: &Path, folder: &Path, since: SystemTime) -> Option<PathBuf> {
|
||||
let mut logs = Vec::new();
|
||||
collect_logs(sessions_dir, SEARCH_DEPTH, since, &mut logs);
|
||||
let mut recent: Vec<(SystemTime, PathBuf)> = logs
|
||||
.into_iter()
|
||||
.filter_map(|file| {
|
||||
let modified = fs::metadata(&file).ok()?.modified().ok()?;
|
||||
(modified >= since).then_some((modified, file))
|
||||
})
|
||||
.collect();
|
||||
recent.sort_by(|a, b| b.0.cmp(&a.0));
|
||||
recent.into_iter().map(|(_, file)| file).find(|file| names_folder(file, folder))
|
||||
}
|
||||
|
||||
// A day folder not touched since `since` holds no log of this run (creating a
|
||||
// log updates its own folder, and only that one), so it is skipped: the walk
|
||||
// stays short however many old logs Codex has kept. Year and month folders are
|
||||
// always entered, as their own times say nothing about the logs below them.
|
||||
// `depth` is 2 while the entries of a month folder are listed.
|
||||
fn collect_logs(dir: &Path, depth: u32, since: SystemTime, out: &mut Vec<PathBuf>) {
|
||||
let Ok(entries) = fs::read_dir(dir) else { return };
|
||||
for entry in entries.flatten() {
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
let touched = fs::metadata(&path).and_then(|m| m.modified()).is_ok_and(|m| m >= since);
|
||||
if depth > 0 && (depth != 2 || touched) {
|
||||
collect_logs(&path, depth - 1, since, out);
|
||||
}
|
||||
} else if is_rollout(&path) {
|
||||
out.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn is_rollout(path: &Path) -> bool {
|
||||
path.file_name()
|
||||
.and_then(|name| name.to_str())
|
||||
.is_some_and(|name| name.starts_with("rollout-") && name.ends_with(".jsonl"))
|
||||
}
|
||||
|
||||
/// True when the log's first line is a `session_meta` for `folder`.
|
||||
fn names_folder(file: &Path, folder: &Path) -> bool {
|
||||
let Ok(handle) = File::open(file) else { return false };
|
||||
let mut first = String::new();
|
||||
if BufReader::new(handle).read_line(&mut first).is_err() {
|
||||
return false;
|
||||
}
|
||||
let Ok(value) = serde_json::from_str::<Value>(&first) else { return false };
|
||||
if value.get("type").and_then(Value::as_str) != Some("session_meta") {
|
||||
return false;
|
||||
}
|
||||
value
|
||||
.get("payload")
|
||||
.and_then(|payload| payload.get("cwd"))
|
||||
.and_then(Value::as_str)
|
||||
.is_some_and(|cwd| same_folder(cwd, folder))
|
||||
}
|
||||
|
||||
/// Compares two folder paths the way Windows does: case, slash style and a
|
||||
/// trailing separator do not count.
|
||||
fn same_folder(cwd: &str, folder: &Path) -> bool {
|
||||
let norm = |s: &str| {
|
||||
s.trim_start_matches(r"\\?\").trim_end_matches(['\\', '/']).replace('/', "\\").to_ascii_lowercase()
|
||||
};
|
||||
norm(cwd) == norm(&folder.to_string_lossy())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Duration;
|
||||
|
||||
const GOOD: &str = r#"{"type":"event_msg","payload":{"type":"token_count","info":{"last_token_usage":{"input_tokens":21839},"model_context_window":258400}}}"#;
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-codex-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
// A log whose first line names `cwd`, then `body` lines, dated `modified`.
|
||||
fn write_log(sessions: &Path, name: &str, cwd: &str, body: &str, modified: SystemTime) -> PathBuf {
|
||||
let day = sessions.join("2026").join("10").join("22");
|
||||
fs::create_dir_all(&day).unwrap();
|
||||
let file = day.join(format!("rollout-{name}.jsonl"));
|
||||
let meta = serde_json::json!({ "type": "session_meta", "payload": { "cwd": cwd } });
|
||||
fs::write(&file, format!("{meta}\n{body}")).unwrap();
|
||||
// `meta` is a JSON value, so its text is escaped for the log.
|
||||
fs::File::options().write(true).open(&file).unwrap().set_modified(modified).unwrap();
|
||||
file
|
||||
}
|
||||
|
||||
fn epoch_plus(secs: u64) -> SystemTime {
|
||||
SystemTime::UNIX_EPOCH + Duration::from_secs(secs)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_last_token_count_gives_the_percent_of_the_window() {
|
||||
assert_eq!(reading_from_text(GOOD), ContextReading::BestEffort { percent: 8 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unrecognised_and_malformed_lines_are_skipped() {
|
||||
let text = format!("not json\n{{bad\n{GOOD}\n{}", r#"{"type":"event_msg","payload":{"type":"other"}}"#);
|
||||
assert_eq!(reading_from_text(&text), ContextReading::BestEffort { percent: 8 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_with_no_usable_line_is_unknown() {
|
||||
assert_eq!(reading_from_text(""), ContextReading::Unknown);
|
||||
assert_eq!(reading_from_text("garbage\n{}"), ContextReading::Unknown);
|
||||
let zero_window = GOOD.replace("258400", "0");
|
||||
assert_eq!(reading_from_text(&zero_window), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_early_token_count_without_info_is_skipped() {
|
||||
let early = r#"{"type":"event_msg","payload":{"type":"token_count","info":null}}"#;
|
||||
assert_eq!(reading_from_text(&format!("{GOOD}\n{early}")), ContextReading::BestEffort { percent: 8 });
|
||||
assert_eq!(reading_from_text(early), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn only_a_session_meta_with_this_folder_names_it() {
|
||||
let root = temp_dir("names");
|
||||
let folder = Path::new(r"C:\git\project");
|
||||
let verbatim = serde_json::json!({ "type": "session_meta", "payload": { "cwd": r"\\?\C:\git\project" } });
|
||||
let cases = [
|
||||
("not json".to_string(), false),
|
||||
(r#"{"type":"other","payload":{"cwd":"x"}}"#.to_string(), false),
|
||||
(r#"{"type":"session_meta","payload":{}}"#.to_string(), false),
|
||||
(verbatim.to_string(), true),
|
||||
];
|
||||
for (i, (line, expected)) in cases.iter().enumerate() {
|
||||
let file = root.join(format!("rollout-{i}.jsonl"));
|
||||
fs::write(&file, format!("{line}\n{GOOD}\n")).unwrap();
|
||||
assert_eq!(names_folder(&file, folder), *expected, "{line}");
|
||||
}
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_log_is_read_from_its_end() {
|
||||
let dir = temp_dir("long");
|
||||
let file = dir.join("long.jsonl");
|
||||
fs::write(&file, format!("{}\n{GOOD}\n", "x".repeat(TAIL_BYTES as usize + 100))).unwrap();
|
||||
assert_eq!(reading_from_file(&file), ContextReading::BestEffort { percent: 8 });
|
||||
let _ = fs::remove_dir_all(dir);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_log_is_unknown() {
|
||||
assert_eq!(reading_from_file(Path::new("no-such-dir/rollout-x.jsonl")), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_missing_sessions_folder_is_unknown() {
|
||||
let reader = CodexReader {
|
||||
sessions_dir: temp_dir("none").join("sessions"),
|
||||
folder: PathBuf::from(r"C:\git\project"),
|
||||
since: epoch_plus(0),
|
||||
};
|
||||
assert_eq!(reader.read(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_newest_log_for_this_folder_is_read() {
|
||||
let root = temp_dir("newest");
|
||||
let sessions = root.join("sessions");
|
||||
write_log(&sessions, "a-old", r"C:\git\project", GOOD, epoch_plus(100));
|
||||
write_log(&sessions, "b-other", r"C:\git\elsewhere", GOOD, epoch_plus(300));
|
||||
let newest = write_log(&sessions, "c-new", r"c:\git\project\", &GOOD.replace("21839", "129200"), epoch_plus(200));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(0)), Some(newest));
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
// Sets a folder's modified time; Windows needs the backup-semantics flag to open one.
|
||||
fn set_dir_modified(dir: &Path, time: SystemTime) {
|
||||
let mut options = fs::OpenOptions::new();
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::OpenOptionsExt;
|
||||
options.write(true).custom_flags(0x0200_0000);
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
options.read(true);
|
||||
options.open(dir).unwrap().set_modified(time).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_year_and_month_folders_do_not_hide_todays_log() {
|
||||
let root = temp_dir("parents");
|
||||
let sessions = root.join("sessions");
|
||||
let log = write_log(&sessions, "today", r"C:\git\project", GOOD, epoch_plus(500));
|
||||
// Creating a log touches only its day folder: the parents keep their old times.
|
||||
set_dir_modified(&sessions.join("2026"), epoch_plus(10));
|
||||
set_dir_modified(&sessions.join("2026").join("10"), epoch_plus(20));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), Some(log));
|
||||
// A day folder untouched since the agent started is skipped.
|
||||
set_dir_modified(&sessions.join("2026").join("10").join("22"), epoch_plus(30));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(100)), None);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_log_from_before_the_agent_started_is_ignored() {
|
||||
let root = temp_dir("since");
|
||||
let sessions = root.join("sessions");
|
||||
write_log(&sessions, "old", r"C:\git\project", GOOD, epoch_plus(100));
|
||||
assert_eq!(newest_log(&sessions, Path::new(r"C:\git\project"), epoch_plus(200)), None);
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_rotated_log_is_read_from_the_new_file() {
|
||||
let root = temp_dir("rotated");
|
||||
let sessions = root.join("sessions");
|
||||
write_log(&sessions, "first", r"C:\git\project", GOOD, epoch_plus(100));
|
||||
let reader = CodexReader {
|
||||
sessions_dir: sessions.clone(),
|
||||
folder: PathBuf::from(r"C:\git\project"),
|
||||
since: epoch_plus(0),
|
||||
};
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 8 });
|
||||
write_log(&sessions, "second", r"C:\git\project", &GOOD.replace("21839", "129200"), epoch_plus(200));
|
||||
assert_eq!(reader.read(), ContextReading::BestEffort { percent: 50 });
|
||||
let _ = fs::remove_dir_all(root);
|
||||
}
|
||||
}
|
||||
@@ -1,313 +0,0 @@
|
||||
//! How full the agent's context is. A reader says one of four things: a real
|
||||
//! number (`Real`, documented by the agent and verified), a best-effort number
|
||||
//! (`BestEffort`, works today but undocumented), a labeled estimate (`Estimate`)
|
||||
//! or `Unknown`. Knows nothing about Tauri: the page asks for a reading and
|
||||
//! draws what it gets.
|
||||
|
||||
pub mod claude;
|
||||
pub mod codex;
|
||||
|
||||
use std::time::SystemTime;
|
||||
|
||||
use serde::Serialize;
|
||||
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
/// A rough token window used only by the estimate, and by `claude.rs` when no
|
||||
/// window comes with the signal it reads. The estimate is labeled as one
|
||||
/// everywhere it is shown, so the exact size does not have to be right.
|
||||
pub const ESTIMATE_TOKEN_WINDOW: u64 = 200_000;
|
||||
|
||||
/// The window for a model whose id names it a long-context one (Claude Code's
|
||||
/// `[1m]` model id suffix).
|
||||
pub const LONG_CONTEXT_TOKEN_WINDOW: u64 = 1_000_000;
|
||||
|
||||
/// The usual rule of thumb: about four characters of text per token.
|
||||
pub const BYTES_PER_TOKEN: u64 = 4;
|
||||
|
||||
/// The context window to read `kind`'s usage against, or `None` when no
|
||||
/// window is documented for it at all (Devin today), in which case a byte
|
||||
/// count is not even a meaningful guess. `model` is the id the person picked,
|
||||
/// if any; one naming a long-context model (Claude Code's `[1m]` suffix) gets
|
||||
/// the bigger window.
|
||||
pub fn window_for(kind: Option<AgentKind>, model: Option<&str>) -> Option<u64> {
|
||||
match kind {
|
||||
Some(AgentKind::Claude) | Some(AgentKind::Codex) => {
|
||||
let long_context = model.is_some_and(|m| m.to_ascii_lowercase().contains("[1m]"));
|
||||
Some(if long_context { LONG_CONTEXT_TOKEN_WINDOW } else { ESTIMATE_TOKEN_WINDOW })
|
||||
}
|
||||
Some(AgentKind::Devin) | None => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
|
||||
#[serde(tag = "kind", rename_all = "lowercase")]
|
||||
pub enum ContextReading {
|
||||
Real { percent: u8 },
|
||||
BestEffort { percent: u8 },
|
||||
Estimate { percent: u8 },
|
||||
Unknown,
|
||||
}
|
||||
|
||||
/// One agent's way of reading its context. The estimate is the fallback every
|
||||
/// agent has; a reader for an agent that documents its usage returns `Real`.
|
||||
pub trait ContextReader {
|
||||
fn read(&self) -> ContextReading;
|
||||
}
|
||||
|
||||
/// The percent of `window` that `bytes` of text fills, capped at 100 and
|
||||
/// rounded up: any text at all reads as at least 1 percent, never a flat 0
|
||||
/// while the agent is working.
|
||||
pub fn estimate_percent(bytes: u64, window: u64) -> u8 {
|
||||
let tokens = bytes / BYTES_PER_TOKEN;
|
||||
if tokens == 0 || window == 0 {
|
||||
return 0;
|
||||
}
|
||||
tokens.saturating_mul(100).div_ceil(window).min(100) as u8
|
||||
}
|
||||
|
||||
/// Where the output scan is inside a terminal control sequence.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
enum Escape {
|
||||
#[default]
|
||||
None,
|
||||
Esc,
|
||||
Intermediate,
|
||||
Csi,
|
||||
Osc,
|
||||
OscEnd,
|
||||
}
|
||||
|
||||
/// Counts the text an agent run has produced and been given. A new agent
|
||||
/// (a new `generation`) starts the count over, and nothing is counted while
|
||||
/// no agent runs.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Meter {
|
||||
generation: u64,
|
||||
seen: bool,
|
||||
running: bool,
|
||||
bytes: u64,
|
||||
escape: Escape,
|
||||
kind: Option<AgentKind>,
|
||||
// When the current agent run began: its own log must be written after this.
|
||||
since: Option<SystemTime>,
|
||||
}
|
||||
|
||||
impl Meter {
|
||||
/// Called on every agent state change: a new generation resets the count.
|
||||
pub fn observe(&mut self, generation: u64, running: bool) {
|
||||
if !self.seen || generation != self.generation {
|
||||
self.generation = generation;
|
||||
self.seen = true;
|
||||
self.bytes = 0;
|
||||
self.escape = Escape::None;
|
||||
self.since = Some(SystemTime::now());
|
||||
}
|
||||
self.running = running;
|
||||
}
|
||||
|
||||
pub fn set_kind(&mut self, kind: Option<AgentKind>) {
|
||||
self.kind = kind;
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> Option<AgentKind> {
|
||||
self.kind
|
||||
}
|
||||
|
||||
pub fn since(&self) -> Option<SystemTime> {
|
||||
self.since
|
||||
}
|
||||
|
||||
/// Output from the agent, or text typed to it, while it runs.
|
||||
/// Output from the agent. Terminal control sequences (colours, cursor
|
||||
/// moves, window titles) are not text the agent holds, so only the visible
|
||||
/// bytes count. A sequence cut across two chunks is still skipped whole.
|
||||
pub fn add_output(&mut self, chunk: &[u8]) {
|
||||
let mut visible = 0usize;
|
||||
for &byte in chunk {
|
||||
self.escape = match self.escape {
|
||||
Escape::None => match byte {
|
||||
0x1b => Escape::Esc,
|
||||
b'\n' | b'\t' => {
|
||||
visible += 1;
|
||||
Escape::None
|
||||
}
|
||||
0x20..=0x7e | 0x80..=0xff => {
|
||||
visible += 1;
|
||||
Escape::None
|
||||
}
|
||||
_ => Escape::None,
|
||||
},
|
||||
Escape::Esc => match byte {
|
||||
b'[' => Escape::Csi,
|
||||
// OSC, and the other strings that end the same way: DCS, SOS, PM, APC.
|
||||
b']' | b'P' | b'X' | b'^' | b'_' => Escape::Osc,
|
||||
// `ESC ( B` and the like: intermediate bytes, then one final byte.
|
||||
0x20..=0x2f => Escape::Intermediate,
|
||||
_ => Escape::None,
|
||||
},
|
||||
Escape::Intermediate => match byte {
|
||||
0x20..=0x2f => Escape::Intermediate,
|
||||
_ => Escape::None,
|
||||
},
|
||||
Escape::Csi => match byte {
|
||||
0x40..=0x7e => Escape::None,
|
||||
_ => Escape::Csi,
|
||||
},
|
||||
Escape::Osc => match byte {
|
||||
0x07 => Escape::None,
|
||||
0x1b => Escape::OscEnd,
|
||||
_ => Escape::Osc,
|
||||
},
|
||||
Escape::OscEnd => Escape::None,
|
||||
};
|
||||
}
|
||||
self.add(visible);
|
||||
}
|
||||
|
||||
/// Text typed to the agent, or any count of visible bytes.
|
||||
pub fn add(&mut self, bytes: usize) {
|
||||
if self.running {
|
||||
self.bytes = self.bytes.saturating_add(bytes as u64);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn reading(&self) -> ContextReading {
|
||||
if !self.seen || !self.running {
|
||||
return ContextReading::Unknown;
|
||||
}
|
||||
match window_for(self.kind, None) {
|
||||
Some(window) => ContextReading::Estimate { percent: estimate_percent(self.bytes, window) },
|
||||
None => ContextReading::Unknown,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ContextReader for Meter {
|
||||
fn read(&self) -> ContextReading {
|
||||
self.reading()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn no_text_is_zero_percent() {
|
||||
assert_eq!(estimate_percent(0, ESTIMATE_TOKEN_WINDOW), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn half_the_window_is_fifty_percent() {
|
||||
assert_eq!(estimate_percent(ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 2, ESTIMATE_TOKEN_WINDOW), 50);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn more_than_the_window_caps_at_one_hundred() {
|
||||
assert_eq!(estimate_percent(u64::MAX / 2, ESTIMATE_TOKEN_WINDOW), 100);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn any_text_at_all_rounds_up_instead_of_reading_zero() {
|
||||
assert_eq!(estimate_percent(BYTES_PER_TOKEN, ESTIMATE_TOKEN_WINDOW), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_long_context_model_gets_the_bigger_window() {
|
||||
assert_eq!(window_for(Some(AgentKind::Claude), Some("claude-sonnet-4-5-20250929[1m]")), Some(LONG_CONTEXT_TOKEN_WINDOW));
|
||||
assert_eq!(window_for(Some(AgentKind::Claude), Some("sonnet")), Some(ESTIMATE_TOKEN_WINDOW));
|
||||
assert_eq!(window_for(Some(AgentKind::Claude), None), Some(ESTIMATE_TOKEN_WINDOW));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_and_an_unknown_agent_have_no_basis_for_a_window() {
|
||||
assert_eq!(window_for(Some(AgentKind::Devin), None), None);
|
||||
assert_eq!(window_for(None, None), None);
|
||||
}
|
||||
|
||||
fn counted(chunks: &[&[u8]]) -> u64 {
|
||||
let mut meter = Meter::default();
|
||||
meter.observe(1, true);
|
||||
for chunk in chunks {
|
||||
meter.add_output(chunk);
|
||||
}
|
||||
meter.bytes
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plain_text_counts_and_control_sequences_do_not() {
|
||||
assert_eq!(counted(&[b"hello\n"]), 6);
|
||||
assert_eq!(counted(&[b"\x1b[31mred\x1b[0m"]), 3);
|
||||
assert_eq!(counted(&[b"\x1b[2K\x1b[1A\x1b[Gx"]), 1);
|
||||
assert_eq!(counted(&[b"\x1b]0;a title\x07ok"]), 2);
|
||||
assert_eq!(counted(&[b"\x1b]0;a title\x1b\\ok"]), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn charset_and_string_sequences_are_skipped() {
|
||||
assert_eq!(counted(&[b"\x1b(Bok"]), 2);
|
||||
assert_eq!(counted(&[b"\x1bPq#0;2;0;0;0\x1b\\ok"]), 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_sequence_split_across_chunks_is_still_skipped() {
|
||||
assert_eq!(counted(&[b"ab\x1b[3", b"1mcd"]), 4);
|
||||
assert_eq!(counted(&[b"\x1b", b"[0m", b"z"]), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nothing_running_is_unknown() {
|
||||
let mut meter = Meter::default();
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
meter.observe(1, false);
|
||||
meter.add(10_000);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_running_agent_is_an_estimate_of_what_it_has_seen() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Claude));
|
||||
meter.observe(1, true);
|
||||
meter.add((ESTIMATE_TOKEN_WINDOW * BYTES_PER_TOKEN / 4) as usize);
|
||||
assert_eq!(meter.reading(), ContextReading::Estimate { percent: 25 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_fresh_agent_starts_the_count_over() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Claude));
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
meter.observe(2, true);
|
||||
assert_eq!(meter.reading(), ContextReading::Estimate { percent: 0 });
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_stopped_agent_is_unknown_again() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Claude));
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
meter.observe(1, false);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_with_no_documented_window_is_unknown_not_a_guess() {
|
||||
let mut meter = Meter::default();
|
||||
meter.set_kind(Some(AgentKind::Devin));
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_kind_set_yet_is_unknown_not_a_guess() {
|
||||
let mut meter = Meter::default();
|
||||
meter.observe(1, true);
|
||||
meter.add(400_000);
|
||||
assert_eq!(meter.reading(), ContextReading::Unknown);
|
||||
}
|
||||
}
|
||||
@@ -5,7 +5,6 @@ pub mod agents;
|
||||
pub mod announce;
|
||||
pub mod brief;
|
||||
pub mod console_supervisor;
|
||||
pub mod context;
|
||||
pub mod handoff;
|
||||
pub mod node_check;
|
||||
pub mod project;
|
||||
|
||||
@@ -4,12 +4,9 @@
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use plan2code_app_lib::announce::AnnounceServer;
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, Sink};
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, BeforeFresh, Sink};
|
||||
use plan2code_app_lib::agents::{self, AgentKind, PermissionMode};
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, ConsoleSupervisor};
|
||||
use plan2code_app_lib::context::claude::ClaudeReader;
|
||||
use plan2code_app_lib::context::codex::CodexReader;
|
||||
use plan2code_app_lib::context::{self, ContextReader, ContextReading, Meter};
|
||||
use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::restart_brief;
|
||||
@@ -32,10 +29,8 @@ struct AppState {
|
||||
agent: Mutex<Option<Arc<AgentManager>>>,
|
||||
// Where the agent's output and state changes go: the page's latest channel.
|
||||
page: PageChannel,
|
||||
// How much text the running agent has produced and been given, for the meter.
|
||||
context: Arc<Mutex<Meter>>,
|
||||
// This window's endpoint for pages the agent's `console.mjs open` wants shown here.
|
||||
announce: Mutex<Option<AnnounceServer>>,
|
||||
announce: Arc<Mutex<Option<AnnounceServer>>>,
|
||||
// The Node version `main()` found before opening the window (Task 1.7 exits
|
||||
// cleanly on anything else, so this is always a passing version once the
|
||||
// window exists), and which binary that was, with `resolved_path`'s PATH
|
||||
@@ -83,19 +78,8 @@ fn windows_build() -> Option<u32> {
|
||||
|
||||
// Sends the agent's output as raw bytes and its state changes as JSON, on the
|
||||
// page's latest channel. Nothing is sent while no page has registered one.
|
||||
// The meter sees every output and state change too, page or no page.
|
||||
fn page_sink(page: PageChannel, meter: Arc<Mutex<Meter>>) -> Sink {
|
||||
fn page_sink(page: PageChannel) -> Sink {
|
||||
Arc::new(move |event| {
|
||||
if let Ok(mut meter) = meter.lock() {
|
||||
match &event {
|
||||
AgentEvent::Output(bytes) => meter.add_output(bytes),
|
||||
AgentEvent::State(snapshot) => {
|
||||
let running = snapshot.state == AgentState::Running;
|
||||
meter.observe(snapshot.generation, running);
|
||||
meter.set_kind(snapshot.kind);
|
||||
}
|
||||
}
|
||||
}
|
||||
let Ok(guard) = page.lock() else { return };
|
||||
let Some(channel) = guard.as_ref() else { return };
|
||||
let body = match event {
|
||||
@@ -125,18 +109,34 @@ fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||
return Ok(Arc::clone(agent));
|
||||
}
|
||||
}
|
||||
let sink = page_sink(Arc::clone(&state.page), Arc::clone(&state.context));
|
||||
let sink = page_sink(Arc::clone(&state.page));
|
||||
let agent = Arc::new(AgentManager::new(dir, sink));
|
||||
// A Restart leaves the brief for the dashboard, from the console that is running now.
|
||||
let console = Arc::clone(&state.console);
|
||||
agent.set_before_fresh(Arc::new(move || {
|
||||
let sid = console.lock().ok()?.as_ref()?.session().sid.clone();
|
||||
restart_brief::note_for_restart(&sid)
|
||||
}));
|
||||
agent.set_before_fresh(before_fresh_hook(state));
|
||||
*guard = Some(Arc::clone(&agent));
|
||||
Ok(agent)
|
||||
}
|
||||
|
||||
// What New Session does before the fresh agent starts. It leaves the brief for
|
||||
// the dashboard, from the console session running now, then forgets that
|
||||
// session, so the fresh agent's `open` starts one of its own: a session that
|
||||
// joined the old one would carry its meter along, still red after the very
|
||||
// press the red meter asks for. The old console is left to shut itself down
|
||||
// once the frame moves on to the new page.
|
||||
fn before_fresh_hook(state: &AppState) -> BeforeFresh {
|
||||
let console = Arc::clone(&state.console);
|
||||
let announce = Arc::clone(&state.announce);
|
||||
Arc::new(move || {
|
||||
let sid = console.lock().ok().and_then(|guard| guard.as_ref().map(|sup| sup.session().sid.clone()));
|
||||
let note = sid.and_then(|sid| restart_brief::note_for_restart(&sid));
|
||||
if let Ok(guard) = announce.lock() {
|
||||
if let Some(server) = guard.as_ref() {
|
||||
server.forget_current();
|
||||
}
|
||||
}
|
||||
note
|
||||
})
|
||||
}
|
||||
|
||||
fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
||||
state.agent.lock().ok().and_then(|guard| guard.clone())
|
||||
}
|
||||
@@ -201,9 +201,6 @@ fn agent_start(
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_input(state: State<'_, AppState>, data: String) -> Result<(), String> {
|
||||
if let Ok(mut meter) = state.context.lock() {
|
||||
meter.add(data.len());
|
||||
}
|
||||
match current_agent(&state) {
|
||||
Some(agent) => agent.input(data.as_bytes()),
|
||||
None => Ok(()),
|
||||
@@ -223,14 +220,6 @@ fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
|
||||
current_agent(&state).ok_or("no agent has been started")?.restart()
|
||||
}
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
match current_agent(&state) {
|
||||
Some(agent) => serde_json::to_value(agent.snapshot()).unwrap_or_default(),
|
||||
None => idle_snapshot_json(),
|
||||
}
|
||||
}
|
||||
|
||||
fn idle_snapshot_json() -> serde_json::Value {
|
||||
serde_json::json!({ "state": "idle", "kind": null, "mode": null, "generation": 0 })
|
||||
}
|
||||
@@ -239,7 +228,7 @@ fn idle_snapshot_json() -> serde_json::Value {
|
||||
/// agent survived it) registers its output channel here instead of through
|
||||
/// `agent_start`, which would try to start a second agent. Replays the
|
||||
/// current generation's recent output on it at once, so the terminal does
|
||||
/// not come up blank, and returns the same shape `agent_state` does.
|
||||
/// not come up blank.
|
||||
#[tauri::command]
|
||||
fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseBody>) -> Result<serde_json::Value, String> {
|
||||
let agent = current_agent(&state);
|
||||
@@ -256,65 +245,6 @@ fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseB
|
||||
})
|
||||
}
|
||||
|
||||
// The bar's meter, polled at most every two seconds: how full the running
|
||||
// agent's context looks, labeled by how it was read.
|
||||
#[tauri::command]
|
||||
fn agent_context(state: State<'_, AppState>) -> serde_json::Value {
|
||||
let (estimate, kind, since) = match state.context.lock() {
|
||||
Ok(meter) => (meter.read(), meter.kind(), meter.since()),
|
||||
Err(_) => (ContextReading::Unknown, None, None),
|
||||
};
|
||||
let agent = current_agent(&state);
|
||||
let model = agent.as_ref().and_then(|agent| agent.model_and_effort().0);
|
||||
// Claude's own transcript, or Codex's own log, is read when there is one;
|
||||
// an unknown reading from either falls back to the labeled estimate.
|
||||
// Nothing is read while no agent runs.
|
||||
let reading = match (estimate, kind, agent, since) {
|
||||
(ContextReading::Unknown, _, _, _) => ContextReading::Unknown,
|
||||
(_, Some(AgentKind::Claude), Some(agent), Some(since)) => {
|
||||
// `window_for` always has a window for Claude; the fallback here only
|
||||
// guards against a future change to that rule.
|
||||
let window = context::window_for(kind, model.as_deref()).unwrap_or(context::ESTIMATE_TOKEN_WINDOW);
|
||||
let claude = ClaudeReader { projects_dir: claude_projects_dir(), folder: agent.folder().clone(), since, window };
|
||||
match claude.read() {
|
||||
ContextReading::Unknown => estimate,
|
||||
read => read,
|
||||
}
|
||||
}
|
||||
(_, Some(AgentKind::Codex), Some(agent), Some(since)) => {
|
||||
let codex = CodexReader {
|
||||
sessions_dir: codex_sessions_dir(),
|
||||
folder: agent.folder().clone(),
|
||||
since,
|
||||
};
|
||||
match codex.read() {
|
||||
ContextReading::Unknown => estimate,
|
||||
read => read,
|
||||
}
|
||||
}
|
||||
_ => estimate,
|
||||
};
|
||||
serde_json::to_value(reading).unwrap_or_default()
|
||||
}
|
||||
|
||||
// Claude Code's transcripts folder: `CLAUDE_CONFIG_DIR` when it is set, else `~/.claude`.
|
||||
fn claude_projects_dir() -> std::path::PathBuf {
|
||||
let home = std::env::var_os("CLAUDE_CONFIG_DIR")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::home_dir().map(|home| home.join(".claude")))
|
||||
.unwrap_or_default();
|
||||
home.join("projects")
|
||||
}
|
||||
|
||||
// Codex's sessions folder: `CODEX_HOME` when it is set, else `~/.codex`.
|
||||
fn codex_sessions_dir() -> std::path::PathBuf {
|
||||
let home = std::env::var_os("CODEX_HOME")
|
||||
.map(std::path::PathBuf::from)
|
||||
.or_else(|| std::env::home_dir().map(|home| home.join(".codex")))
|
||||
.unwrap_or_default();
|
||||
home.join("sessions")
|
||||
}
|
||||
|
||||
// Asks before quitting while an agent runs; "no" keeps the app open.
|
||||
fn confirm_quit(app: &tauri::AppHandle) {
|
||||
let app = app.clone();
|
||||
@@ -363,9 +293,6 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
.agent
|
||||
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)))
|
||||
.or_else(project::remembered_agent);
|
||||
let nudge = settings_file
|
||||
.as_ref()
|
||||
.map_or(settings::DEFAULT_NUDGE_PERCENT, |file| settings::load_nudge_percent(file));
|
||||
let term_panel = settings_file.as_ref().map_or(
|
||||
settings::TermPanelSettings {
|
||||
dock: settings::DEFAULT_TERM_DOCK.to_string(),
|
||||
@@ -380,7 +307,6 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
"projectDirSource": project.as_ref().map(|p| p.source),
|
||||
"lastAgent": last_agent.map(|kind| kind.id()),
|
||||
"launchModel": state.launch.model,
|
||||
"contextNudgePercent": nudge,
|
||||
// Task 1.7 already exits before the window opens on a missing or too-old
|
||||
// Node, so this is always a pass; the checklist's Node row just names it.
|
||||
"nodeVersion": state.node_version,
|
||||
@@ -579,9 +505,7 @@ fn main() {
|
||||
agent_input,
|
||||
agent_resize,
|
||||
agent_restart,
|
||||
agent_state,
|
||||
agent_reattach,
|
||||
agent_context,
|
||||
app_state,
|
||||
save_term_panel,
|
||||
save_first_run_done,
|
||||
@@ -691,6 +615,32 @@ mod tests {
|
||||
assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_session_forgets_the_windows_session_so_the_fresh_agent_starts_its_own() {
|
||||
let state = state_for("project-a");
|
||||
let server = AnnounceServer::start(Arc::new(|_| {})).unwrap();
|
||||
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
|
||||
*state.announce.lock().unwrap() = Some(server);
|
||||
let body = r#"{"url":"http://127.0.0.1:5000/s/abc/","sid":"s1","workflow":"plan"}"#;
|
||||
let mut stream = std::net::TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
let token = state.announce.lock().unwrap().as_ref().unwrap().token().to_string();
|
||||
use std::io::{Read, Write};
|
||||
write!(
|
||||
stream,
|
||||
"POST /page HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\ncontent-length: {}\r\nConnection: close\r\n\r\n{body}",
|
||||
body.len()
|
||||
)
|
||||
.unwrap();
|
||||
let mut answer = String::new();
|
||||
stream.read_to_string(&mut answer).unwrap();
|
||||
assert!(answer.starts_with("HTTP/1.1 204"), "the page was announced: {answer}");
|
||||
assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current().map(|n| n.sid), Some("s1".to_string()));
|
||||
|
||||
// No console supervised here, so no brief to write: only the forgetting.
|
||||
assert_eq!(before_fresh_hook(&state)(), None);
|
||||
assert_eq!(state.announce.lock().unwrap().as_ref().unwrap().current(), None, "the fresh agent's open must not join s1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_same_folder_reuses_the_same_manager() {
|
||||
let state = state_for("project-a");
|
||||
|
||||
@@ -19,20 +19,23 @@ pub const READY_NOTE: &str = "Brief ready on the dashboard";
|
||||
/// has not picked it up, so unused briefs do not pile up as chips.
|
||||
static LAST_BRIEF: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
/// The skill named on a handoff record for a workflow `brief::skill_for_workflow`
|
||||
/// does not map, such as `dashboard`: the console's own name for that pseudo-skill.
|
||||
const UNMAPPED_SKILL: &str = "plan2code";
|
||||
|
||||
/// Write the brief for session `sid` as a handoff. A workflow with no mapped
|
||||
/// skill (a dashboard, or one not yet known) still gets a short, honest chip
|
||||
/// rather than nothing. Returns the handoff's id, or `None` when there is
|
||||
/// truly nothing to write (the session names no worktree is an error, not a
|
||||
/// `None`, since that is a broken session rather than an empty one).
|
||||
/// Write the brief for session `sid` as a handoff. Returns the handoff's id,
|
||||
/// or `None` when there is nothing worth picking up: a workflow with no mapped
|
||||
/// skill (the dashboard, or one not yet known), whose only next step would be
|
||||
/// "Open the dashboard" where the fresh agent lands anyway, and a session that
|
||||
/// finished, whose finished screen already named what comes next, and one
|
||||
/// that has posted nothing yet (no spec, progress, activity or questions),
|
||||
/// whose brief would only repeat the skill's name. A session
|
||||
/// that names no worktree is an error, not a `None`, since that is a broken
|
||||
/// session rather than an empty one.
|
||||
pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTime<Local>) -> Result<Option<String>, String> {
|
||||
let session = session_reader::load(console_home, sid).map_err(|e| e.to_string())?;
|
||||
let state = &session.state;
|
||||
let workflow = text(state, "workflow").unwrap_or("");
|
||||
let skill = brief::skill_for_workflow(workflow);
|
||||
let Some(skill) = brief::skill_for_workflow(workflow) else { return Ok(None) };
|
||||
if finished(state) || empty(state) {
|
||||
return Ok(None);
|
||||
}
|
||||
let worktree = text(state, "worktree").ok_or("the session names no worktree")?;
|
||||
let project = text(state, "project").unwrap_or(worktree);
|
||||
let spec = text(state, "specDir").filter(|s| valid_spec(s));
|
||||
@@ -40,14 +43,11 @@ pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTi
|
||||
let git = brief::git_summary(Path::new(worktree));
|
||||
let events = session_reader::read_ndjson(&session.dir.join("events.ndjson"));
|
||||
let body = brief::build_brief(state, spec_dir.as_deref(), git.as_ref(), &events);
|
||||
let title = match skill {
|
||||
Some(skill) => match spec {
|
||||
Some(spec) => format!("Restart of {skill} on {spec}"),
|
||||
None => format!("Restart of {skill}"),
|
||||
},
|
||||
None => format!("Restart while on {workflow}"),
|
||||
let title = match spec {
|
||||
Some(spec) => format!("Restart of {skill} on {spec}"),
|
||||
None => format!("Restart of {skill}"),
|
||||
};
|
||||
let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill: skill.unwrap_or(UNMAPPED_SKILL) };
|
||||
let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill };
|
||||
handoff::write(handoffs, when, &record, &body).map(Some)
|
||||
}
|
||||
|
||||
@@ -73,6 +73,22 @@ fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> {
|
||||
state.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
}
|
||||
|
||||
/// The session posted a `finish` that is not a pause. A pause's headline starts
|
||||
/// with "Paused" (the page's `finishPaused`) and keeps a place worth picking up.
|
||||
fn finished(state: &Value) -> bool {
|
||||
let Some(finish) = state.get("finish").filter(|f| f.is_object()) else { return false };
|
||||
let headline = finish.get("headline").and_then(Value::as_str).unwrap_or("").trim_start();
|
||||
!headline.get(..6).is_some_and(|word| word.eq_ignore_ascii_case("paused"))
|
||||
}
|
||||
|
||||
/// Nothing a fresh agent could pick up beyond the skill's name.
|
||||
fn empty(state: &Value) -> bool {
|
||||
let stage = state.get("headline").and_then(|h| text(h, "stage"));
|
||||
let activity = state.get("agent").and_then(|a| text(a, "activity")).filter(|a| !a.trim().is_empty());
|
||||
let items = state.get("items").and_then(Value::as_array).is_some_and(|items| !items.is_empty());
|
||||
text(state, "specDir").is_none() && stage.is_none() && activity.is_none() && !items
|
||||
}
|
||||
|
||||
fn valid_spec(spec: &str) -> bool {
|
||||
spec.strip_prefix("specs/").is_some_and(|name| !name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\']))
|
||||
}
|
||||
@@ -135,16 +151,34 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_dashboard_session_still_leaves_a_chip() {
|
||||
fn a_dashboard_session_leaves_nothing() {
|
||||
let (home, _, handoffs) = session("dashboard", "dashboard", None);
|
||||
let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff");
|
||||
let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap();
|
||||
assert_eq!(record["title"], "Restart while on dashboard");
|
||||
assert_eq!(record["skill"], "plan2code");
|
||||
assert_eq!(record["workflow"], "dashboard");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("- Workflow: `dashboard`"));
|
||||
assert!(doc.contains("## Next task\n\nOpen the dashboard"));
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
assert!(!handoffs.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_skill_that_has_posted_nothing_leaves_nothing() {
|
||||
let (home, _, handoffs) = session("blank", "quick-task", None);
|
||||
let file = home.join("sessions").join("s1").join("state.json");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||||
state["headline"] = Value::Null;
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_finished_session_leaves_nothing_but_a_paused_one_does() {
|
||||
let (home, _, handoffs) = session("finished", "implement", Some("specs/feature"));
|
||||
let file = home.join("sessions").join("s1").join("state.json");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(&file).unwrap()).unwrap();
|
||||
state["finish"] = serde_json::json!({ "headline": "Phase 5 is built", "dashboard": true });
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert_eq!(leave_brief(&home, &handoffs, "s1", when()).unwrap(), None);
|
||||
|
||||
state["finish"] = serde_json::json!({ "headline": "Paused at Phase 5" });
|
||||
fs::write(&file, state.to_string()).unwrap();
|
||||
assert!(leave_brief(&home, &handoffs, "s1", when()).unwrap().is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -7,16 +7,11 @@ use std::path::{Path, PathBuf};
|
||||
use crate::agents::AgentKind;
|
||||
|
||||
const LAST_AGENT_KEY: &str = "lastAgent";
|
||||
const NUDGE_KEY: &str = "CONTEXT_NUDGE_PERCENT";
|
||||
const TERM_DOCK_KEY: &str = "termDock";
|
||||
const TERM_FRACTION_KEY: &str = "termFraction";
|
||||
const TERM_COLLAPSED_KEY: &str = "termCollapsed";
|
||||
const FIRST_RUN_DONE_KEY: &str = "firstRunDone";
|
||||
|
||||
/// The context percent at which the bar suggests a Restart, when the file
|
||||
/// names no other.
|
||||
pub const DEFAULT_NUDGE_PERCENT: u8 = 70;
|
||||
|
||||
/// The terminal pane's remembered shape: which edge it docks to, how much of
|
||||
/// the window it takes (a fraction, not collapsed or maximized), and whether
|
||||
/// it was left collapsed.
|
||||
@@ -48,16 +43,6 @@ pub fn load_last_agent(file: &Path) -> Option<AgentKind> {
|
||||
AgentKind::from_id(read(file).get(LAST_AGENT_KEY)?.as_str()?)
|
||||
}
|
||||
|
||||
/// The context percent that triggers the Restart suggestion. A value outside
|
||||
/// 1 to 100, or one that is not a number, means the default.
|
||||
pub fn load_nudge_percent(file: &Path) -> u8 {
|
||||
read(file)
|
||||
.get(NUDGE_KEY)
|
||||
.and_then(|value| value.as_u64())
|
||||
.filter(|percent| (1..=100).contains(percent))
|
||||
.map_or(DEFAULT_NUDGE_PERCENT, |percent| percent as u8)
|
||||
}
|
||||
|
||||
/// Save the pick, keeping any other key the file holds.
|
||||
pub fn save_last_agent(file: &Path, kind: AgentKind) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
@@ -150,35 +135,6 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nudge_defaults_to_seventy() {
|
||||
assert_eq!(load_nudge_percent(&temp_file("nudge-missing")), 70);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_nudge_reads_a_named_percent() {
|
||||
let file = temp_file("nudge-set");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, r#"{"CONTEXT_NUDGE_PERCENT": 85}"#).unwrap();
|
||||
assert_eq!(load_nudge_percent(&file), 85);
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nudge_outside_one_to_one_hundred_or_not_a_number_is_the_default() {
|
||||
for text in [
|
||||
r#"{"CONTEXT_NUDGE_PERCENT": 0}"#,
|
||||
r#"{"CONTEXT_NUDGE_PERCENT": 150}"#,
|
||||
r#"{"CONTEXT_NUDGE_PERCENT": "high"}"#,
|
||||
] {
|
||||
let file = temp_file("nudge-bad");
|
||||
std::fs::create_dir_all(file.parent().unwrap()).unwrap();
|
||||
std::fs::write(&file, text).unwrap();
|
||||
assert_eq!(load_nudge_percent(&file), 70, "{text}");
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_agent_is_ignored() {
|
||||
let file = temp_file("unknown");
|
||||
|
||||
+274
-149
@@ -2,16 +2,27 @@
|
||||
// agent's terminal panel docked at the bottom with a drag handle.
|
||||
|
||||
import { mountTerminal } from './terminal.js';
|
||||
import { nudgeDue } from './meter.js';
|
||||
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor } from './meter.js';
|
||||
|
||||
const { invoke, Channel } = window.__TAURI__.core;
|
||||
|
||||
const projectDirEl = document.getElementById('project-dir');
|
||||
const projectMenuBtn = document.getElementById('project-menu-button');
|
||||
const projectNameEl = document.getElementById('project-name');
|
||||
const projectPathEl = document.getElementById('project-path');
|
||||
const projectMenu = document.getElementById('project-menu');
|
||||
const agentMenuBtn = document.getElementById('agent-menu-button');
|
||||
const agentMenu = document.getElementById('agent-menu');
|
||||
const agentMenuHeadEl = document.getElementById('agent-menu-head');
|
||||
const agentDotEl = document.getElementById('agent-dot');
|
||||
const agentNameEl = document.getElementById('agent-name');
|
||||
const agentEndedEl = document.getElementById('agent-ended');
|
||||
const agentBypassEl = document.getElementById('agent-bypass');
|
||||
const agentNoneEl = document.getElementById('agent-none');
|
||||
const agentStatusEl = document.getElementById('agent-status');
|
||||
const restartBtn = document.getElementById('agent-restart');
|
||||
const changeAgentBtn = document.getElementById('change-agent');
|
||||
const changeProjectBtn = document.getElementById('change-project');
|
||||
const barRowEl = document.getElementById('bar-row');
|
||||
const launchCard = document.getElementById('launch-card');
|
||||
const launchAgentEl = document.getElementById('launch-agent');
|
||||
const launchMissingEl = document.getElementById('launch-missing');
|
||||
@@ -24,18 +35,13 @@ const launchStartBtn = document.getElementById('launch-start');
|
||||
const firstRunEl = document.getElementById('first-run');
|
||||
const firstRunListEl = document.getElementById('first-run-list');
|
||||
const firstRunStartBtn = document.getElementById('first-run-start');
|
||||
const meterSlot = document.getElementById('bar-slot-meter');
|
||||
const nudgeEl = document.getElementById('context-nudge');
|
||||
const nudgeRestartBtn = document.getElementById('context-restart');
|
||||
const versionEl = document.getElementById('version-update');
|
||||
const versionTextEl = document.getElementById('version-update-text');
|
||||
const versionBtn = document.getElementById('version-update-button');
|
||||
const versionRestartBtn = document.getElementById('version-update-restart');
|
||||
const consoleStatusEl = document.getElementById('console-status');
|
||||
const permissionsNoteEl = document.getElementById('permissions-note');
|
||||
const consoleAgainBtn = document.getElementById('console-again');
|
||||
const nextStepEl = document.getElementById('next-step');
|
||||
const nextStepTextEl = document.getElementById('next-step-text');
|
||||
const nextStepBtn = document.getElementById('next-step-button');
|
||||
const nextStepMoreEl = document.getElementById('next-step-more');
|
||||
const frame = document.getElementById('console-frame');
|
||||
const stateBox = document.getElementById('dashboard-state');
|
||||
const statePlannyEl = document.getElementById('dashboard-state-planny');
|
||||
const stateText = document.getElementById('dashboard-state-text');
|
||||
const stateButton = document.getElementById('dashboard-state-button');
|
||||
const stateCancelEl = document.getElementById('dashboard-state-cancel');
|
||||
@@ -46,10 +52,8 @@ const termDockBtn = document.getElementById('term-dock');
|
||||
const termMaximizeBtn = document.getElementById('term-maximize');
|
||||
const termCollapseBtn = document.getElementById('term-collapse');
|
||||
const termBadgeEl = document.getElementById('term-badge');
|
||||
const currentPageEl = document.getElementById('current-page');
|
||||
|
||||
const STATUS_POLL_MS = 5000;
|
||||
const METER_POLL_MS = 2000;
|
||||
const BADGE_POLL_MS = 2000;
|
||||
const MIN_PANE = 0.10;
|
||||
const MAX_PANE = 0.60;
|
||||
@@ -71,12 +75,6 @@ const EFFORT_OPTIONS = {
|
||||
let agent = { state: 'idle', kind: null, generation: 0 };
|
||||
const agentActive = () => agent.state === 'running';
|
||||
|
||||
// The context percent that triggers the Restart suggestion, from the app's
|
||||
// settings (main() reads it), and the agent run the suggestion was shown for:
|
||||
// it appears once per run, not again after it is dismissed by a Restart.
|
||||
let nudgePercent = 70;
|
||||
let nudgeShownFor = null;
|
||||
|
||||
const terminal = await mountTerminal(document.getElementById('term'), {
|
||||
onInput: (data) => {
|
||||
if (agentActive()) invoke('agent_input', { data });
|
||||
@@ -114,7 +112,7 @@ function applyAgentState(next, { skipReset } = {}) {
|
||||
const label = AGENT_LABELS[agent.kind] || '';
|
||||
const active = agentActive();
|
||||
|
||||
agentNameEl.textContent = active ? label : '';
|
||||
const ended = agent.state === 'ended';
|
||||
if (active) {
|
||||
// Only ever auto-*hides* the card (the agent just started); it must
|
||||
// never auto-*show* it on 'ended' or 'idle' — that is Change agent's
|
||||
@@ -122,39 +120,118 @@ function applyAgentState(next, { skipReset } = {}) {
|
||||
launchCard.hidden = true;
|
||||
hideFirstRun();
|
||||
}
|
||||
// One rule throughout: Restart while running or ended (it keeps the
|
||||
// previous agent, model, effort and mode); Change agent only once ended,
|
||||
// when there is a real choice to make again.
|
||||
restartBtn.hidden = !(active || agent.state === 'ended');
|
||||
changeAgentBtn.hidden = agent.state !== 'ended';
|
||||
// Checked mode needs no banner; bypass always gets one, naming the agent it
|
||||
// applies to, for exactly as long as that agent runs.
|
||||
// One rule throughout: New Session and the agent menu while running or
|
||||
// ended (New Session keeps the previous agent, model, effort and mode);
|
||||
// Change agent, in that menu, only once ended, when there is a real choice
|
||||
// to make again.
|
||||
restartBtn.hidden = !(active || ended);
|
||||
changeAgentBtn.hidden = !ended;
|
||||
// Checked mode needs no marker; bypass always gets the "checks off" badge
|
||||
// on the agent, for exactly as long as that agent runs.
|
||||
const bypassActive = active && agent.mode === 'bypass';
|
||||
permissionsNoteEl.hidden = !bypassActive;
|
||||
permissionsNoteEl.textContent = bypassActive ? `Permission checks are off for ${label || 'the running agent'}` : '';
|
||||
restartBtn.title = agent.state === 'ended' ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window';
|
||||
if (freshScreen || agent.state !== 'running') nudgeEl.hidden = true;
|
||||
if (!agentActive()) renderMeter({ kind: 'unknown' });
|
||||
agentMenuBtn.hidden = !(active || ended);
|
||||
agentNoneEl.hidden = active || ended;
|
||||
agentNameEl.textContent = active || ended ? label || 'The agent' : '';
|
||||
agentDotEl.className = `agent-dot${active ? (bypassActive ? ' is-warn' : ' is-ok') : ''}`;
|
||||
agentEndedEl.hidden = !ended;
|
||||
agentBypassEl.hidden = !bypassActive;
|
||||
renderAgentMenuHead(label || 'The agent', { active, ended, bypassActive });
|
||||
if (agentMenu.hidden === false && agentMenuBtn.hidden) closeBarMenus();
|
||||
restartBtn.title = ended ? 'Start a fresh agent on the same brief' : 'Replace the agent with a fresh one, on a fresh context window';
|
||||
// The agent is back (a fresh generation, running): the restart message stays
|
||||
// on screen (restarting() below) until its dashboard page is announced.
|
||||
if (restarting && freshScreen && agent.state === 'running') {
|
||||
terminal.write('\r\n\r\n[Fresh agent started. Waiting for the dashboard...]\r\n\r\n');
|
||||
}
|
||||
|
||||
if (agent.state === 'ended') {
|
||||
agentStatusEl.textContent = `${label || 'The agent'} ended: ${agent.reason}. Nothing starts until you press Restart.`;
|
||||
if (ended) {
|
||||
// The why sits beside the agent's menu; the menu says the rest.
|
||||
setAgentStatus(agent.reason);
|
||||
// A failed Restart clears the screen too, so it says so again.
|
||||
if (!wasEnded || freshScreen) {
|
||||
terminal.write(`\r\n[${label || 'The agent'} ended: ${agent.reason}. Press Restart in the bar to start a fresh one.]\r\n`);
|
||||
terminal.write(`\r\n[${label || 'The agent'} ended: ${agent.reason}. Press New Session in the bar to start a fresh one.]\r\n`);
|
||||
}
|
||||
} else {
|
||||
// After a Restart the bar says what it left for the dashboard, if anything.
|
||||
agentStatusEl.textContent = agent.briefNote || '';
|
||||
setAgentStatus(agent.briefNote || '');
|
||||
}
|
||||
agentStatusEl.title = agentStatusEl.textContent;
|
||||
updateBadge();
|
||||
}
|
||||
|
||||
// The short line after the agent's menu: an ended agent's reason or a
|
||||
// Restart's brief note (quiet), or something that went wrong (in red).
|
||||
function setAgentStatus(text, { error = false } = {}) {
|
||||
agentStatusEl.textContent = text;
|
||||
agentStatusEl.title = text;
|
||||
agentStatusEl.classList.toggle('is-error', error && Boolean(text));
|
||||
}
|
||||
|
||||
// The agent menu's first lines: what the agent is doing and, while it runs,
|
||||
// which permission mode it started with.
|
||||
function renderAgentMenuHead(label, { active, ended, bypassActive }) {
|
||||
const name = document.createElement('b');
|
||||
name.textContent = label;
|
||||
if (active) {
|
||||
const mode = document.createElement('span');
|
||||
if (bypassActive) {
|
||||
mode.className = 'is-warn';
|
||||
mode.textContent = 'off';
|
||||
} else {
|
||||
mode.textContent = 'on';
|
||||
}
|
||||
agentMenuHeadEl.replaceChildren(name, ' is running', document.createElement('br'), 'Permission checks are ', mode);
|
||||
if (bypassActive) agentMenuHeadEl.append(': it runs commands and changes files without asking');
|
||||
} else if (ended) {
|
||||
agentMenuHeadEl.replaceChildren(name, ` ended: ${agent.reason}`, document.createElement('br'), 'Nothing starts until you press New Session.');
|
||||
} else {
|
||||
agentMenuHeadEl.replaceChildren();
|
||||
}
|
||||
}
|
||||
|
||||
// The bar's two menus (project, agent). They hang outside the scrolling bar
|
||||
// row, fixed under their trigger, so the row's overflow never clips them.
|
||||
// Clicking anywhere else (the console frame and the terminal too), Escape,
|
||||
// a resize or a scroll of the row all close them.
|
||||
let openBarMenu = null;
|
||||
|
||||
function closeBarMenus() {
|
||||
for (const [button, menu] of [[projectMenuBtn, projectMenu], [agentMenuBtn, agentMenu]]) {
|
||||
menu.hidden = true;
|
||||
button.setAttribute('aria-expanded', 'false');
|
||||
}
|
||||
openBarMenu = null;
|
||||
}
|
||||
|
||||
function toggleBarMenu(button, menu) {
|
||||
const wasOpen = openBarMenu === menu;
|
||||
closeBarMenus();
|
||||
if (wasOpen) return;
|
||||
menu.hidden = false;
|
||||
const at = button.getBoundingClientRect();
|
||||
const left = Math.max(8, Math.min(at.left, window.innerWidth - menu.offsetWidth - 8));
|
||||
menu.style.left = `${left}px`;
|
||||
menu.style.top = `${at.bottom + 4}px`;
|
||||
button.setAttribute('aria-expanded', 'true');
|
||||
openBarMenu = menu;
|
||||
}
|
||||
|
||||
projectMenuBtn.onclick = () => toggleBarMenu(projectMenuBtn, projectMenu);
|
||||
agentMenuBtn.onclick = () => toggleBarMenu(agentMenuBtn, agentMenu);
|
||||
document.addEventListener('pointerdown', (event) => {
|
||||
if (!openBarMenu) return;
|
||||
if (openBarMenu.contains(event.target) || projectMenuBtn.contains(event.target) || agentMenuBtn.contains(event.target)) return;
|
||||
closeBarMenus();
|
||||
});
|
||||
document.addEventListener('keydown', (event) => {
|
||||
if (event.key !== 'Escape' || !openBarMenu) return;
|
||||
const trigger = openBarMenu === projectMenu ? projectMenuBtn : agentMenuBtn;
|
||||
closeBarMenus();
|
||||
trigger.focus();
|
||||
});
|
||||
window.addEventListener('blur', closeBarMenus);
|
||||
window.addEventListener('resize', closeBarMenus);
|
||||
barRowEl.addEventListener('scroll', closeBarMenus);
|
||||
|
||||
// True from a confirmed Restart until the fresh agent's dashboard page is
|
||||
// announced (showAnnounced below): the frame stays blanked with a message the
|
||||
// whole time, since the restarted agent must boot and run the skill again
|
||||
@@ -167,17 +244,17 @@ function confirmRestart(onYes) {
|
||||
return;
|
||||
}
|
||||
showState(
|
||||
'Restart the agent on a fresh context window? What it was doing is not saved.',
|
||||
'Restart',
|
||||
'Restart the agent on a fresh context window?',
|
||||
'New Session',
|
||||
() => {
|
||||
restarting = true;
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
currentPageEl.textContent = '';
|
||||
showState('The agent is restarting on a fresh context window. Please wait for the dashboard to load.');
|
||||
onYes();
|
||||
},
|
||||
() => (frameReady ? hideState() : showState('No dashboard has loaded yet.'))
|
||||
() => (frameReady ? hideState() : showState('No dashboard has loaded yet.')),
|
||||
{ tired: true }
|
||||
);
|
||||
}
|
||||
|
||||
@@ -322,14 +399,14 @@ async function startAgent(event) {
|
||||
const model = launchModelEl.value.trim() || null;
|
||||
const effort = (EFFORT_OPTIONS[kind] || []).length > 0 ? launchEffortEl.value || null : null;
|
||||
const mode = launchBypassEl.checked ? 'bypass' : 'checked';
|
||||
agentStatusEl.textContent = '';
|
||||
setAgentStatus('');
|
||||
showState('Waiting for the agent to open the dashboard');
|
||||
const { cols, rows } = terminal.size();
|
||||
try {
|
||||
await invoke('agent_start', { kind, model, effort, mode, cols, rows });
|
||||
terminal.focus();
|
||||
} catch (error) {
|
||||
agentStatusEl.textContent = `Could not start the agent: ${error}`;
|
||||
setAgentStatus(`Could not start the agent: ${error}`, { error: true });
|
||||
showLaunchCard();
|
||||
}
|
||||
}
|
||||
@@ -339,15 +416,17 @@ async function agentAction(command) {
|
||||
await invoke(command);
|
||||
terminal.focus();
|
||||
} catch (error) {
|
||||
agentStatusEl.textContent = String(error);
|
||||
setAgentStatus(String(error), { error: true });
|
||||
}
|
||||
}
|
||||
|
||||
launchCard.addEventListener('submit', startAgent);
|
||||
restartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
|
||||
nudgeRestartBtn.onclick = () => confirmRestart(() => agentAction('agent_restart'));
|
||||
// Only ever enabled once the agent has ended: nothing active to lose, so no confirm.
|
||||
changeAgentBtn.onclick = () => showLaunchCard();
|
||||
changeAgentBtn.onclick = () => {
|
||||
closeBarMenus();
|
||||
showLaunchCard();
|
||||
};
|
||||
|
||||
// The pane's shape: which edge it docks to, its share of the window when it
|
||||
// is neither collapsed nor maximized (dragging and the settings file both
|
||||
@@ -455,14 +534,69 @@ function loadFrame(url) {
|
||||
frame.src = url;
|
||||
}
|
||||
|
||||
// What the console page may ask of this window. Each is a named request with
|
||||
// no free text, so the page can never type anything but "continue".
|
||||
window.addEventListener('message', (event) => {
|
||||
if (event.source !== frame.contentWindow) return;
|
||||
if (!event.data || event.data.plan2code !== 'console-ready') return;
|
||||
frameReady = true;
|
||||
clearTimeout(helloTimer);
|
||||
hideState();
|
||||
const kind = event.data && event.data.plan2code;
|
||||
if (kind === 'console-ready') {
|
||||
frameReady = true;
|
||||
clearTimeout(helloTimer);
|
||||
hideState();
|
||||
} else if (kind === 'agent-continue') {
|
||||
typeContinue();
|
||||
} else if (kind === 'new-session') {
|
||||
// The bar's own button, so the press is confirmed exactly the same way.
|
||||
if (!restartBtn.hidden) restartBtn.click();
|
||||
} else if (kind === 'looks') {
|
||||
applyAccent(event.data.accent, { save: true });
|
||||
}
|
||||
});
|
||||
|
||||
// Its "Not running... type continue" line, pressed: the keystrokes
|
||||
// continueKeys names, each on its own a moment after the last, so an agent
|
||||
// that treats one burst of input as a paste still reads the Enter as a submit.
|
||||
const ENTER_AFTER_MS = 120;
|
||||
|
||||
function typeContinue() {
|
||||
if (!agentActive()) return;
|
||||
continueKeys(agent.kind)
|
||||
.reduce(
|
||||
(typed, data, i) =>
|
||||
typed
|
||||
.then(() => (i ? new Promise((resolve) => setTimeout(resolve, ENTER_AFTER_MS)) : null))
|
||||
.then(() => invoke('agent_input', { data })),
|
||||
Promise.resolve()
|
||||
)
|
||||
.catch((error) => {
|
||||
setAgentStatus(`Could not type continue: ${error}`, { error: true });
|
||||
});
|
||||
}
|
||||
|
||||
// The person's highlight color, as the console page last sent it (its dark
|
||||
// shades: fill, soft, ink, line), so the bar's buttons light in it too. Kept
|
||||
// here for the next launch, which paints the bar before any page has loaded.
|
||||
const ACCENT_KEY = 'p2c-app:accent';
|
||||
const ACCENT_VARS = ['--accent', '--accent-soft', '--accent-ink', '--accent-line'];
|
||||
|
||||
function applyAccent(shades, { save = false } = {}) {
|
||||
if (!Array.isArray(shades) || shades.length !== ACCENT_VARS.length) return;
|
||||
if (!shades.every((c) => typeof c === 'string' && /^#[0-9a-f]{6}$/i.test(c))) return;
|
||||
ACCENT_VARS.forEach((name, i) => document.documentElement.style.setProperty(name, shades[i]));
|
||||
if (!save) return;
|
||||
try {
|
||||
localStorage.setItem(ACCENT_KEY, JSON.stringify(shades));
|
||||
} catch {
|
||||
// Not remembered is fine: the stylesheet's default shows until a page loads.
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
applyAccent(JSON.parse(localStorage.getItem(ACCENT_KEY)));
|
||||
} catch {
|
||||
// Nothing saved, or storage is blocked: the stylesheet's default stands.
|
||||
}
|
||||
|
||||
// No hello in time: ask the console why, and say so with a way forward.
|
||||
async function onNoHello() {
|
||||
if (frameReady || !consoleKnown || restarting) return;
|
||||
@@ -473,7 +607,7 @@ async function onNoHello() {
|
||||
// The status check itself failed; treat it as a console that is not answering.
|
||||
}
|
||||
if (!status || status.state !== 'running') {
|
||||
showState('The console stopped, so the page could not show.', 'Restart the console', reconnectConsole);
|
||||
showState('The console stopped, so the page could not show.', 'Reconnect the console', reconnectConsole);
|
||||
} else {
|
||||
showState('The console is running but its page did not show in this window.', 'Reload the page', () => {
|
||||
showState('Reloading the page');
|
||||
@@ -482,9 +616,13 @@ async function onNoHello() {
|
||||
}
|
||||
}
|
||||
|
||||
function showState(text, buttonLabel, onButton, onCancel) {
|
||||
function showState(text, buttonLabel, onButton, onCancel, { tired = false } = {}) {
|
||||
hideLaunchCard();
|
||||
hideFirstRun();
|
||||
// statePlannyEl is an <svg>: unlike HTMLElement, it does not reflect the
|
||||
// `.hidden` property to the attribute, so toggling the property alone left
|
||||
// `hidden` in the markup forever. The attribute itself always works.
|
||||
statePlannyEl.toggleAttribute('hidden', !tired);
|
||||
stateText.textContent = text;
|
||||
stateButton.hidden = !buttonLabel;
|
||||
stateButton.textContent = buttonLabel || '';
|
||||
@@ -512,10 +650,7 @@ async function reconnectConsole() {
|
||||
} catch (error) {
|
||||
showState(`The console could not be reached: ${error}`, 'Retry', reconnectConsole);
|
||||
// An old console cannot be framed: the fix is the skills update, so offer it.
|
||||
if (String(error).includes('too old')) {
|
||||
versionTextEl.textContent = 'The installed console is too old for the app';
|
||||
versionEl.hidden = false;
|
||||
}
|
||||
if (String(error).includes('too old')) setVersionState({ kind: 'too-old' });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -545,113 +680,55 @@ async function pollConsole() {
|
||||
}
|
||||
}
|
||||
|
||||
// The meter: a bar and a percent for a real or best-effort reading, a dashed
|
||||
// bar with "about N%" and an "estimate" tag for an estimate, "unknown" when
|
||||
// nothing is available. Built with DOM calls, never innerHTML.
|
||||
function renderMeter(reading) {
|
||||
meterSlot.replaceChildren();
|
||||
// Left empty, not even an "unknown" label: #bar-slot-meter:empty hides it,
|
||||
// so the bar carries nothing until the reading means something.
|
||||
if (reading.kind === 'unknown') return;
|
||||
const label = document.createElement('span');
|
||||
const track = document.createElement('span');
|
||||
track.className = `meter-track ${reading.kind}`;
|
||||
const fill = document.createElement('span');
|
||||
fill.className = 'meter-fill';
|
||||
fill.style.width = `${reading.percent}%`;
|
||||
track.append(fill);
|
||||
label.textContent = reading.kind === 'estimate' ? `about ${reading.percent}%` : `${reading.percent}%`;
|
||||
meterSlot.append(track, label);
|
||||
if (reading.kind === 'estimate') {
|
||||
const tag = document.createElement('span');
|
||||
tag.className = 'meter-tag';
|
||||
tag.textContent = 'estimate';
|
||||
meterSlot.append(tag);
|
||||
meterSlot.title = 'Estimated from the text so far: the agent does not report its context size';
|
||||
} else if (reading.kind === 'besteffort') {
|
||||
meterSlot.title = 'Read from the agent\'s session log: undocumented, so it may stop working after an update';
|
||||
} else {
|
||||
meterSlot.title = 'How full the agent context is, as the agent reports it';
|
||||
}
|
||||
}
|
||||
|
||||
// Every two seconds while an agent runs: draw the meter and, once per run,
|
||||
// suggest a Restart when the context reaches the nudge percent.
|
||||
async function pollMeter() {
|
||||
if (!agentActive()) return;
|
||||
try {
|
||||
// The reading may land after a Restart: only a reading for the same run counts.
|
||||
const { generation, state } = agent;
|
||||
const reading = await invoke('agent_context');
|
||||
if (agent.generation !== generation || agent.state !== state) return;
|
||||
renderMeter(reading);
|
||||
if (nudgeDue(reading, nudgePercent) && state === 'running' && nudgeShownFor !== generation) {
|
||||
nudgeShownFor = generation;
|
||||
nudgeEl.hidden = false;
|
||||
}
|
||||
} catch {
|
||||
// A failed read is not a reading: look again on the next tick.
|
||||
}
|
||||
}
|
||||
|
||||
// Once, at start: when the app and the installed skills are on different versions the bar
|
||||
// says so and offers Update skills. Nothing runs until that button is pressed.
|
||||
async function checkVersions() {
|
||||
try {
|
||||
const status = await invoke('version_status');
|
||||
if (!status.mismatch) return;
|
||||
if (status.skills_ahead) {
|
||||
// The skills are ahead of this app: another Update skills run cannot help.
|
||||
versionTextEl.textContent = `The installed skills are v${status.skills}, newer than this app (v${status.app}). Get the new app.`;
|
||||
versionBtn.hidden = true;
|
||||
} else {
|
||||
versionTextEl.textContent = `Skills are v${status.skills}, this app is v${status.app}`;
|
||||
versionBtn.hidden = false;
|
||||
}
|
||||
versionEl.hidden = false;
|
||||
// Skills ahead of this app: another Update skills run cannot help, so
|
||||
// that state offers no button.
|
||||
setVersionState({ kind: status.skills_ahead ? 'ahead' : 'mismatch', skills: status.skills, app: status.app });
|
||||
} catch {
|
||||
// No version to compare is no reason to nag.
|
||||
}
|
||||
}
|
||||
|
||||
versionBtn.onclick = async () => {
|
||||
versionBtn.disabled = true;
|
||||
versionRestartBtn.hidden = true;
|
||||
versionTextEl.textContent = 'Updating Plan2Code...';
|
||||
async function updateSkills() {
|
||||
setVersionState({ kind: 'updating', line: 'Updating Plan2Code...' });
|
||||
const progress = new Channel();
|
||||
progress.onmessage = (line) => {
|
||||
if (line) versionTextEl.textContent = line;
|
||||
if (line && versionState && versionState.kind === 'updating') setVersionState({ kind: 'updating', line });
|
||||
};
|
||||
try {
|
||||
const outcome = await invoke('update_skills', { progress });
|
||||
versionTextEl.textContent = outcome.status.mismatch
|
||||
? `Updated, but the mismatch remains (skills v${outcome.status.skills}, app v${outcome.status.app}).`
|
||||
: 'Updated. Restart the console to use the new version.';
|
||||
versionBtn.hidden = true;
|
||||
versionRestartBtn.hidden = outcome.status.mismatch;
|
||||
setVersionState(
|
||||
outcome.status.mismatch
|
||||
? { kind: 'remains', skills: outcome.status.skills, app: outcome.status.app }
|
||||
: { kind: 'updated' }
|
||||
);
|
||||
} catch (error) {
|
||||
versionTextEl.textContent = String(error);
|
||||
versionBtn.disabled = false;
|
||||
setVersionState({ kind: 'failed', error: String(error) });
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
versionRestartBtn.onclick = async () => {
|
||||
versionRestartBtn.disabled = true;
|
||||
// After an update: stop the old console first, so the new skills are really
|
||||
// picked up, then bring a fresh one back on the same session.
|
||||
async function restartConsole() {
|
||||
try {
|
||||
await invoke('console_stop');
|
||||
} catch {
|
||||
// Nothing to stop is fine: reconnectConsole starts a fresh one either way.
|
||||
}
|
||||
versionEl.hidden = true;
|
||||
setVersionState(null);
|
||||
await reconnectConsole();
|
||||
};
|
||||
|
||||
// A page the agent's `console.mjs open` asked this window to show.
|
||||
const pageLabel = (workflow) => (workflow || '').replace(/-/g, ' ').replace(/^./, (c) => c.toUpperCase());
|
||||
}
|
||||
|
||||
// A page the agent's `console.mjs open` asked this window to show. Which page
|
||||
// it is shows inside the frame itself (the console's own badge and title),
|
||||
// not repeated here.
|
||||
function showAnnounced(notice) {
|
||||
restarting = false;
|
||||
currentPageEl.textContent = pageLabel(notice.workflow);
|
||||
if (!consoleKnown) {
|
||||
consoleKnown = true;
|
||||
if (!pollTimer) pollTimer = setInterval(pollConsole, STATUS_POLL_MS);
|
||||
@@ -665,21 +742,62 @@ function showAnnounced(notice) {
|
||||
|
||||
window.__TAURI__.event.listen('console-page', (event) => showAnnounced(event.payload));
|
||||
|
||||
// The right end of the bar: whether the console stopped answering and where
|
||||
// the skills stand against this app, drawn as one next step (meter.js
|
||||
// barNextSteps decides which, and its button), with the rest as "+N more".
|
||||
let consoleDead = false;
|
||||
let versionState = null;
|
||||
const NEXT_STEP_ACTIONS = { reconnect: reconnectConsole, 'restart-console': restartConsole, update: updateSkills };
|
||||
let nextStepAction = null;
|
||||
|
||||
function renderNextStep() {
|
||||
const steps = barNextSteps({ consoleDead, version: versionState });
|
||||
nextStepEl.hidden = steps.length === 0;
|
||||
const [first, ...rest] = steps;
|
||||
nextStepTextEl.textContent = first ? first.text : '';
|
||||
nextStepTextEl.title = first ? first.title : '';
|
||||
nextStepTextEl.className = first ? `is-${first.tone}${first.busy ? ' is-busy' : ''}` : '';
|
||||
nextStepAction = first && first.action ? NEXT_STEP_ACTIONS[first.action] : null;
|
||||
nextStepBtn.hidden = !nextStepAction;
|
||||
nextStepBtn.disabled = false;
|
||||
nextStepBtn.textContent = first && first.label ? first.label : '';
|
||||
nextStepMoreEl.hidden = rest.length === 0;
|
||||
nextStepMoreEl.textContent = `+${rest.length} more`;
|
||||
nextStepMoreEl.title = rest.map((step) => step.title).join('\n');
|
||||
}
|
||||
|
||||
function setVersionState(next) {
|
||||
versionState = next;
|
||||
renderNextStep();
|
||||
}
|
||||
|
||||
function markConsoleAlive() {
|
||||
consoleStatusEl.textContent = '';
|
||||
consoleAgainBtn.hidden = true;
|
||||
consoleDead = false;
|
||||
renderNextStep();
|
||||
}
|
||||
|
||||
function markConsoleDead() {
|
||||
consoleStatusEl.textContent = 'The console stopped.';
|
||||
consoleAgainBtn.hidden = false;
|
||||
consoleDead = true;
|
||||
renderNextStep();
|
||||
}
|
||||
|
||||
consoleAgainBtn.onclick = () => reconnectConsole();
|
||||
nextStepBtn.onclick = () => {
|
||||
if (!nextStepAction) return;
|
||||
// Pressed once per step: whatever it starts draws the next state itself.
|
||||
nextStepBtn.disabled = true;
|
||||
nextStepAction();
|
||||
};
|
||||
|
||||
function setProjectDir(dir) {
|
||||
projectDirEl.textContent = dir;
|
||||
projectDirEl.title = dir;
|
||||
// The bar names the folder; its menu holds the full path.
|
||||
projectNameEl.textContent = folderName(dir);
|
||||
projectMenuBtn.title = dir;
|
||||
projectPathEl.textContent = dir;
|
||||
projectMenuBtn.hidden = !dir;
|
||||
// So two or more windows read apart in the taskbar without opening each
|
||||
// one: a setTitle that fails (an old Tauri runtime, say) just leaves the
|
||||
// static "Plan2Code" title from tauri.conf.json, never breaks the start.
|
||||
window.__TAURI__.window.getCurrentWindow().setTitle(windowTitleFor(dir)).catch(() => {});
|
||||
}
|
||||
|
||||
// The state `main()` read at startup: `pickFolder()` and the first-run
|
||||
@@ -731,7 +849,6 @@ async function doChangeProject() {
|
||||
restarting = false;
|
||||
currentUrl = null;
|
||||
frameReady = false;
|
||||
currentPageEl.textContent = '';
|
||||
afterProjectKnown();
|
||||
} catch (error) {
|
||||
showState(`Could not switch project: ${error}`, 'Try again', doChangeProject);
|
||||
@@ -751,7 +868,10 @@ function changeProject() {
|
||||
doChangeProject();
|
||||
}
|
||||
|
||||
changeProjectBtn.onclick = changeProject;
|
||||
changeProjectBtn.onclick = () => {
|
||||
closeBarMenus();
|
||||
changeProject();
|
||||
};
|
||||
|
||||
// The launcher passed `--agent`: start it at once, on its model, with the
|
||||
// same bypass flags the terminal launcher itself always runs that agent with
|
||||
@@ -759,7 +879,7 @@ changeProjectBtn.onclick = changeProject;
|
||||
async function autoStartAgent(state) {
|
||||
launchAgentEl.value = state.autoStart;
|
||||
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
|
||||
agentStatusEl.textContent = '';
|
||||
setAgentStatus('');
|
||||
showState('Starting the agent...');
|
||||
const { cols, rows } = terminal.size();
|
||||
try {
|
||||
@@ -773,7 +893,7 @@ async function autoStartAgent(state) {
|
||||
});
|
||||
terminal.focus();
|
||||
} catch (error) {
|
||||
agentStatusEl.textContent = `Could not start the agent: ${error}`;
|
||||
setAgentStatus(`Could not start the agent: ${error}`, { error: true });
|
||||
showLaunchCard();
|
||||
}
|
||||
}
|
||||
@@ -811,16 +931,21 @@ async function main() {
|
||||
appState = state;
|
||||
if (AGENT_LABELS[state.lastAgent]) launchAgentEl.value = state.lastAgent;
|
||||
if (typeof state.launchModel === 'string' && state.launchModel) launchModelEl.value = state.launchModel;
|
||||
if (Number.isInteger(state.contextNudgePercent)) nudgePercent = state.contextNudgePercent;
|
||||
if (state.termPanel) {
|
||||
paneDock = state.termPanel.dock === 'right' ? 'right' : 'bottom';
|
||||
paneFraction = state.termPanel.fraction;
|
||||
paneCollapsed = Boolean(state.termPanel.collapsed);
|
||||
} else {
|
||||
// Nothing saved yet: start docked right, wide enough to keep the
|
||||
// console's own side-by-side panels from stacking, where the window
|
||||
// allows it.
|
||||
paneDock = 'right';
|
||||
paneFraction = defaultRightFraction(window.innerWidth, { minFraction: MIN_PANE, maxFraction: MAX_PANE });
|
||||
savePaneSettings();
|
||||
}
|
||||
applyPaneLayout();
|
||||
await loadAgentAvailability();
|
||||
refreshLaunchCard();
|
||||
setInterval(pollMeter, METER_POLL_MS);
|
||||
setInterval(updateBadge, BADGE_POLL_MS);
|
||||
checkVersions();
|
||||
|
||||
|
||||
+160
-47
@@ -10,30 +10,75 @@
|
||||
html, body { margin: 0; height: 100%; font-family: system-ui, sans-serif; background: #1e1e1e; color: #ddd; }
|
||||
body { display: flex; flex-direction: column; overflow: hidden; }
|
||||
|
||||
/* The console's dark tokens and its default highlight (Ocean). app.js sets
|
||||
the four accent ones to the person's own highlight once the console page
|
||||
says which it is, and keeps them for the next launch. */
|
||||
:root {
|
||||
--panel: #201d1a; --panel-2: #262220; --ink: #f0ece5; --ink-2: #b6afa3; --ink-3: #8b8376; --rule-2: #46403a;
|
||||
--accent: #619fe5; --accent-soft: #1a2533; --accent-ink: #0c1117; --accent-line: #3d5978;
|
||||
}
|
||||
|
||||
#bar { flex: none; border-bottom: 1px solid #444; }
|
||||
/* The console's top bar buttons (.btn small ghost), sized to this bar:
|
||||
quiet until hovered, then in the highlight color. New Session is the
|
||||
one that is often the next step, so it wears the highlight outline at
|
||||
rest, like the console's standby buttons. */
|
||||
#bar button {
|
||||
appearance: none; font: inherit; font-size: 12px; font-weight: 600; line-height: 1.2;
|
||||
padding: 4px 10px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink-2);
|
||||
transition: background 0.12s, border-color 0.12s, color 0.12s;
|
||||
}
|
||||
#bar button:hover:not(:disabled) { color: var(--accent); border-color: var(--accent-line); background: var(--panel-2); }
|
||||
#bar button:disabled { opacity: 0.45; cursor: not-allowed; }
|
||||
#bar button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
#bar #agent-restart { background: transparent; border-color: var(--accent-line); color: var(--accent); }
|
||||
#bar #agent-restart:hover:not(:disabled) { background: var(--accent-soft); border-color: var(--accent); }
|
||||
#bar-row { height: 34px; flex: none; display: flex; align-items: center; gap: 10px; padding: 0 10px; font-size: 12px; white-space: nowrap; overflow-x: auto; overflow-y: hidden; }
|
||||
#bar-sep { flex: none; align-self: stretch; width: 1px; margin: 8px 0; background: #3a3a3a; }
|
||||
#title { font-weight: 600; font-size: 13px; }
|
||||
#project-dir { color: #9ab; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 220px; }
|
||||
#current-page { color: #8c8; }
|
||||
#current-page:not(:empty)::before { content: "page: "; color: #666; }
|
||||
#agent-name { color: #9ab; }
|
||||
#agent-name:not(:empty)::before { content: "agent: "; color: #666; }
|
||||
#console-status, #agent-status { color: #d7ba7d; overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 260px; }
|
||||
#agent-restart[hidden], #change-agent[hidden] { display: none; }
|
||||
.bar-slot { flex: none; }
|
||||
#permissions-note { color: #888; }
|
||||
#context-nudge { display: flex; align-items: center; gap: 6px; color: #d7ba7d; }
|
||||
#context-nudge[hidden] { display: none; }
|
||||
#version-update { display: flex; align-items: center; gap: 6px; color: #d7ba7d; }
|
||||
#version-update[hidden], #version-update-button[hidden] { display: none; }
|
||||
#bar-slot-meter { display: flex; align-items: center; gap: 6px; color: #9ab; }
|
||||
#bar-slot-meter:empty { display: none; }
|
||||
.meter-track { display: inline-block; width: 64px; height: 8px; border: 1px solid #666; border-radius: 2px; overflow: hidden; background: #2a2a2a; }
|
||||
.meter-track.estimate { border-style: dashed; }
|
||||
.meter-fill { display: block; height: 100%; background: #6a9955; }
|
||||
.meter-track.estimate .meter-fill { background: repeating-linear-gradient(45deg, #6a9955 0 4px, transparent 4px 8px); }
|
||||
.meter-tag { color: #d7ba7d; font-style: italic; }
|
||||
#bar [hidden] { display: none !important; }
|
||||
/* The project and agent menus' triggers: plain text until hovered, a
|
||||
caret saying there is more behind them. */
|
||||
#bar .bar-menu { display: inline-flex; align-items: center; gap: 6px; flex: none; border-color: transparent; background: transparent; color: var(--ink); padding: 4px 8px; }
|
||||
#bar .bar-menu:hover:not(:disabled), #bar .bar-menu[aria-expanded="true"] { background: var(--panel-2); border-color: transparent; color: var(--ink); }
|
||||
.bar-caret { color: var(--ink-3); font-size: 10px; }
|
||||
#project-name { max-width: 220px; overflow: hidden; text-overflow: ellipsis; }
|
||||
.agent-dot { flex: none; width: 8px; height: 8px; border-radius: 50%; background: #666; }
|
||||
.agent-dot.is-ok { background: #6a9955; }
|
||||
.agent-dot.is-warn { background: #d7ba7d; }
|
||||
#agent-ended { color: var(--ink-3); font-weight: 400; }
|
||||
#agent-bypass { flex: none; font-size: 11px; font-weight: 600; line-height: 1.3; padding: 0 7px; border-radius: 999px; border: 1px solid #d7ba7d; color: #d7ba7d; }
|
||||
#agent-none { color: var(--ink-3); }
|
||||
#agent-status { color: var(--ink-3); overflow: hidden; text-overflow: ellipsis; min-width: 0; max-width: 320px; }
|
||||
#agent-status.is-error { color: #f48771; }
|
||||
#bar-grow { flex: 1; min-width: 0; }
|
||||
/* The one next step for the console or the skills, at the right end. */
|
||||
#next-step { display: flex; align-items: center; gap: 8px; flex: none; }
|
||||
#next-step-text { overflow: hidden; text-overflow: ellipsis; max-width: 320px; }
|
||||
#next-step-text.is-ok { color: #6a9955; }
|
||||
#next-step-text.is-warn { color: #d7ba7d; }
|
||||
#next-step-text.is-err { color: #f48771; }
|
||||
#next-step-text.is-busy::before {
|
||||
content: ""; display: inline-block; width: 8px; height: 8px; margin-right: 6px; vertical-align: -1px;
|
||||
border: 2px solid currentColor; border-right-color: transparent; border-radius: 50%; animation: bar-spin 0.8s linear infinite;
|
||||
}
|
||||
@keyframes bar-spin { to { transform: rotate(360deg); } }
|
||||
#bar #next-step-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
#bar #next-step-button:hover:not(:disabled) { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); filter: brightness(1.12); }
|
||||
#next-step-more { color: var(--ink-3); font-size: 11px; border-bottom: 1px dotted var(--ink-3); cursor: help; }
|
||||
/* The menus sit outside the scrolling row (fixed, placed under their
|
||||
trigger by app.js), so the row's overflow never clips them. */
|
||||
.bar-dropdown {
|
||||
position: fixed; z-index: 20; min-width: 240px; max-width: 380px; padding: 6px; box-sizing: border-box;
|
||||
font-size: 12px; background: var(--panel); border: 1px solid var(--rule-2); border-radius: 8px; box-shadow: 0 10px 28px rgba(0, 0, 0, 0.45);
|
||||
}
|
||||
.bar-dropdown-head { margin: 0; padding: 4px 8px 8px; color: var(--ink-3); line-height: 1.45; overflow-wrap: anywhere; }
|
||||
.bar-dropdown-head b { color: var(--ink); font-weight: 600; }
|
||||
.bar-dropdown-head .is-warn { color: #d7ba7d; }
|
||||
#bar .bar-dropdown button {
|
||||
display: block; width: 100%; text-align: left; font-weight: 400; padding: 6px 8px; border: 0; border-radius: 6px;
|
||||
background: transparent; color: var(--ink);
|
||||
}
|
||||
#bar .bar-dropdown button:hover:not(:disabled), #bar .bar-dropdown button:focus-visible { background: var(--panel-2); color: var(--accent); }
|
||||
|
||||
#workspace { flex: 1; min-height: 0; display: flex; flex-direction: column; }
|
||||
#workspace.dock-right { flex-direction: row; }
|
||||
@@ -43,6 +88,49 @@
|
||||
#dashboard-state { position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 12px; background: #1e1e1e; text-align: center; padding: 16px; box-sizing: border-box; }
|
||||
#dashboard-state[hidden] { display: none; }
|
||||
#dashboard-state-text { margin: 0; max-width: 60ch; overflow-wrap: anywhere; color: #bbb; }
|
||||
#dashboard-state-planny[hidden] { display: none; }
|
||||
/* Drawn and coloured like the console's own Planny (styles/planny.css):
|
||||
an outlined shell, the star eye, a lip of a smile, round hands. */
|
||||
#dashboard-state-planny { width: 104px; height: auto; overflow: visible; }
|
||||
#dashboard-state-planny :is(.ps-shell, .ps-smile, .ps-arm path, .ps-mug, .ps-handle) {
|
||||
fill: none; stroke: var(--ink-2); stroke-width: 1.3; stroke-linecap: round; stroke-linejoin: round;
|
||||
}
|
||||
#dashboard-state-planny .ps-shell { fill: var(--panel-2); }
|
||||
#dashboard-state-planny .ps-smile { stroke-width: 0.9; }
|
||||
#dashboard-state-planny .ps-arm path { stroke-width: 1.2; }
|
||||
#dashboard-state-planny :is(.ps-arm circle, .ps-foot) { fill: var(--ink-2); stroke: none; }
|
||||
#dashboard-state-planny .ps-eye { fill: var(--ink); }
|
||||
#dashboard-state-planny .ps-mug { fill: var(--panel-2); stroke-width: 1; }
|
||||
#dashboard-state-planny .ps-handle { stroke-width: 0.9; }
|
||||
#dashboard-state-planny .ps-coffee { fill: #9a6b47; }
|
||||
#dashboard-state-planny .ps-steam path {
|
||||
fill: none; stroke: var(--ink-3); stroke-width: 0.7; stroke-linecap: round;
|
||||
animation: ps-steam 2.4s ease-in-out infinite; opacity: 0;
|
||||
}
|
||||
#dashboard-state-planny .ps-steam path:nth-child(2) { animation-delay: 0.8s; }
|
||||
#dashboard-state-planny .ps-steam path:nth-child(3) { animation-delay: 1.6s; }
|
||||
@keyframes ps-steam {
|
||||
0% { opacity: 0; transform: translateY(1px); }
|
||||
35% { opacity: 0.9; }
|
||||
100% { opacity: 0; transform: translateY(-2.4px); }
|
||||
}
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
#dashboard-state-planny .ps-steam path { animation: none; opacity: 0.8; }
|
||||
}
|
||||
/* The console's buttons (.btn, with .primary for the way forward): the
|
||||
one action wears the highlight, Cancel is a plain button. */
|
||||
#dashboard-state-actions { display: flex; gap: 10px; flex-wrap: wrap; justify-content: center; }
|
||||
#dashboard-state-actions button {
|
||||
appearance: none; font: inherit; font-size: 13.5px; font-weight: 600; line-height: 1.2;
|
||||
padding: 7px 13px; border-radius: 8px; cursor: pointer;
|
||||
border: 1px solid var(--rule-2); background: var(--panel); color: var(--ink);
|
||||
transition: filter 0.12s, background 0.12s;
|
||||
}
|
||||
#dashboard-state-actions button:hover { background: var(--panel-2); }
|
||||
#dashboard-state-actions button:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
|
||||
#dashboard-state-actions #dashboard-state-button { background: var(--accent); border-color: var(--accent); color: var(--accent-ink); }
|
||||
#dashboard-state-actions #dashboard-state-button:hover { background: var(--accent); filter: brightness(1.08); }
|
||||
#dashboard-state-actions button[hidden] { display: none; }
|
||||
|
||||
#launch-card {
|
||||
position: absolute; inset: 0; z-index: 1; display: flex; flex-direction: column;
|
||||
@@ -120,6 +208,13 @@
|
||||
#term-toolbar button:hover { background: #333; }
|
||||
#term-toolbar button[aria-pressed="true"] { color: #fff; border-color: #888; }
|
||||
#term-panel.collapsed #term-dock, #term-panel.collapsed #term-maximize { display: none; }
|
||||
/* Docked right and collapsed, the panel is a 28px-wide strip: "Expand"
|
||||
does not fit sideways, so it reads top-to-bottom instead, rotated the
|
||||
same way a reader would turn the panel to read it. */
|
||||
#workspace.dock-right #term-panel.collapsed #term-toolbar { padding: 6px 2px; align-items: center; }
|
||||
#workspace.dock-right #term-panel.collapsed #term-collapse {
|
||||
writing-mode: vertical-rl; text-orientation: mixed; padding: 6px 2px;
|
||||
}
|
||||
#term-badge { color: #d7ba7d; font-size: 14px; line-height: 1; }
|
||||
#term-badge[hidden] { display: none; }
|
||||
#term { flex: 1; min-height: 0; min-width: 0; padding: 4px; }
|
||||
@@ -128,38 +223,56 @@
|
||||
<body>
|
||||
<header id="bar">
|
||||
<div id="bar-row">
|
||||
<span id="title">Plan2Code</span>
|
||||
<span id="project-dir"></span>
|
||||
<span id="bar-slot-restart" class="bar-slot"><button id="agent-restart" hidden>Restart</button></span>
|
||||
<span id="bar-slot-change-agent" class="bar-slot"><button id="change-agent" hidden>Change agent</button></span>
|
||||
<span id="bar-slot-change-project" class="bar-slot"><button id="change-project">Change project</button></span>
|
||||
<span id="bar-sep" aria-hidden="true"></span>
|
||||
<span id="current-page" title="The page the agent opened"></span>
|
||||
<span id="agent-name"></span>
|
||||
<button id="project-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="project-menu" hidden><span id="project-name"></span><span class="bar-caret" aria-hidden="true">▾</span></button>
|
||||
<!-- Whenever an agent exists, running or ended, just left of its menu. -->
|
||||
<button id="agent-restart" hidden>New Session</button>
|
||||
<button id="agent-menu-button" class="bar-menu" aria-haspopup="menu" aria-expanded="false" aria-controls="agent-menu" hidden><span id="agent-dot" class="agent-dot" aria-hidden="true"></span><span id="agent-name"></span><span id="agent-ended" hidden>ended</span><span id="agent-bypass" title="Permission checks are off: the agent runs commands and changes files without asking" hidden>checks off</span><span class="bar-caret" aria-hidden="true">▾</span></button>
|
||||
<span id="agent-none">No agent</span>
|
||||
<span id="agent-status" role="status"></span>
|
||||
<span id="console-status"></span>
|
||||
<button id="console-again" hidden>Start it again</button>
|
||||
<span id="context-nudge" class="bar-slot" hidden>
|
||||
<span>Context is getting full: consider Restart</span>
|
||||
<button id="context-restart">Restart</button>
|
||||
<span id="bar-grow"></span>
|
||||
<!-- The console's or the skills' one next step (meter.js barNextSteps), when there is one. -->
|
||||
<span id="next-step" role="status" hidden>
|
||||
<span id="next-step-text"></span>
|
||||
<button id="next-step-button" hidden></button>
|
||||
<span id="next-step-more" hidden></span>
|
||||
</span>
|
||||
<!-- Shown only when the app and the installed skills are on different versions. -->
|
||||
<span id="version-update" class="bar-slot" hidden>
|
||||
<span id="version-update-text"></span>
|
||||
<button id="version-update-button">Update skills</button>
|
||||
<button id="version-update-restart" hidden>Restart the console</button>
|
||||
</span>
|
||||
<span id="bar-slot-meter" class="bar-slot"></span>
|
||||
<!-- Shown only while an agent is running, naming the real mode it started with. -->
|
||||
<span id="permissions-note" hidden></span>
|
||||
</div>
|
||||
<div id="project-menu" class="bar-dropdown" role="menu" aria-label="Project" hidden>
|
||||
<p class="bar-dropdown-head">Project<br><b id="project-path"></b></p>
|
||||
<button id="change-project" role="menuitem">Change project...</button>
|
||||
</div>
|
||||
<div id="agent-menu" class="bar-dropdown" role="menu" aria-label="Agent" hidden>
|
||||
<p id="agent-menu-head" class="bar-dropdown-head"></p>
|
||||
<button id="change-agent" role="menuitem" hidden>Change agent...</button>
|
||||
</div>
|
||||
</header>
|
||||
<div id="workspace">
|
||||
<main id="dashboard">
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard"></iframe>
|
||||
<div id="dashboard-state" hidden>
|
||||
<!-- Planny on a coffee break: shown only before a New Session press,
|
||||
the one state here that is a question rather than a status. The
|
||||
console's own Planny (shell, star eye, smile, feet, resting left
|
||||
arm) with the right arm reaching out to a steaming mug. -->
|
||||
<svg id="dashboard-state-planny" viewBox="0 7 29 23" aria-hidden="true" focusable="false" hidden>
|
||||
<rect class="ps-foot" x="5.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="ps-foot" x="12.7" y="27.1" width="3.6" height="1.7" rx="0.85" />
|
||||
<rect class="ps-shell" x="3" y="7" width="16" height="20" rx="3.2" />
|
||||
<path class="ps-eye" d="M11 10.95 L11.79 12.91 L13.9 13.06 L12.28 14.42 L12.79 16.47 L11 15.35 L9.21 16.47 L9.72 14.42 L8.1 13.06 L10.21 12.91 Z" />
|
||||
<path class="ps-smile" d="M8.3 18.4 Q11 21 13.7 18.4" />
|
||||
<g class="ps-arm"><path d="M3 18 L1.3 21" /><circle cx="1.3" cy="21" r="0.85" /></g>
|
||||
<g class="ps-steam">
|
||||
<path d="M23 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
<path d="M24.4 17.1 q0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
<path d="M25.8 17.3 q-0.6 -0.9 0 -1.8 t0 -1.8" />
|
||||
</g>
|
||||
<g class="ps-arm"><path d="M19 18 L21.6 20.6" /><circle cx="21.6" cy="20.6" r="0.85" /></g>
|
||||
<path class="ps-handle" d="M26.7 19.6 h0.3 a1.15 1.15 0 0 1 0 2.3 h-0.3" />
|
||||
<rect class="ps-mug" x="22.4" y="18.4" width="4.3" height="4.6" rx="0.8" />
|
||||
<rect class="ps-coffee" x="23" y="19" width="3.1" height="0.8" rx="0.35" />
|
||||
</svg>
|
||||
<p id="dashboard-state-text"></p>
|
||||
<span>
|
||||
<span id="dashboard-state-actions">
|
||||
<button id="dashboard-state-button" hidden></button>
|
||||
<button id="dashboard-state-cancel" hidden>Cancel</button>
|
||||
</span>
|
||||
@@ -185,10 +298,10 @@
|
||||
<select id="launch-effort"></select>
|
||||
</div>
|
||||
<label id="launch-bypass-row">
|
||||
<input id="launch-bypass" type="checkbox">
|
||||
<input id="launch-bypass" type="checkbox" checked>
|
||||
Turn permission checks off for this agent
|
||||
</label>
|
||||
<p id="launch-bypass-warning" hidden>Permission checks will be off: the agent can run commands and change files without asking first.</p>
|
||||
<p id="launch-bypass-warning">Permission checks will be off: the agent can run commands and change files without asking first.</p>
|
||||
<button id="launch-start" type="submit">Start agent</button>
|
||||
</form>
|
||||
</main>
|
||||
|
||||
+121
-11
@@ -1,15 +1,125 @@
|
||||
// The context meter's pure decisions, kept out of app.js so they can be
|
||||
// imported and tested without a DOM or `window.__TAURI__` (app.js touches
|
||||
// both at module scope, the same reason the web console keeps its own pure
|
||||
// logic in answers.js rather than app.js).
|
||||
// The bar's pure decisions, kept out of app.js so they can be imported and
|
||||
// tested without a DOM or `window.__TAURI__` (app.js touches both at module
|
||||
// scope, the same reason the web console keeps its own pure logic in
|
||||
// answers.js rather than app.js).
|
||||
|
||||
// The button label for each next-step action. Both ways of reconnecting the
|
||||
// console read the same, wherever they come from.
|
||||
export const NEXT_STEP_LABELS = {
|
||||
reconnect: 'Reconnect the console',
|
||||
'restart-console': 'Reconnect the console',
|
||||
update: 'Update skills',
|
||||
};
|
||||
|
||||
/**
|
||||
* Whether `reading` (what the `agent_context` command returns) should fire
|
||||
* the Restart nudge at `nudgePercent`. Only a real or best-effort number
|
||||
* counts, per the context policy (pathfinder Question 11): an estimate is
|
||||
* not precise enough for "about 70%" to mean the window really is close to
|
||||
* full, so an estimate-only agent gets the meter but never the nudge.
|
||||
* What the console page's **continue** button types into the agent's
|
||||
* terminal, one write each: the word, then Enter. Claude Code holds typed
|
||||
* text as a queued message while its turn is busy, and the button only shows
|
||||
* once the agent stopped checking in with the console, so by then the turn is
|
||||
* stuck and the queued word would never send by itself: for it, the send-now
|
||||
* chord (ctrl+x ctrl+s) follows.
|
||||
*/
|
||||
export function nudgeDue(reading, nudgePercent) {
|
||||
return (reading.kind === 'real' || reading.kind === 'besteffort') && reading.percent >= nudgePercent;
|
||||
export function continueKeys(kind) {
|
||||
const keys = ['continue', '\r'];
|
||||
if (kind === 'claude') keys.push('\x18\x13');
|
||||
return keys;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the right end of the bar offers, most pressing first: the bar shows
|
||||
* the first step (short text plus its one button) and counts the rest as
|
||||
* "+N more". `consoleDead` is whether the console stopped answering;
|
||||
* `version` is the skills/app version state, or null when they agree:
|
||||
* `{ kind: 'mismatch' | 'ahead' | 'remains', skills, app }`,
|
||||
* `{ kind: 'updating', line }`, `{ kind: 'updated' }`, `{ kind: 'too-old' }`
|
||||
* or `{ kind: 'failed', error }`.
|
||||
*
|
||||
* Only one control for "reconnect the console" is ever offered: after an
|
||||
* update, its Reconnect (which stops the old console first, so the new skills
|
||||
* are really picked up) covers a console that has also stopped.
|
||||
*/
|
||||
export function barNextSteps({ consoleDead = false, version = null } = {}) {
|
||||
const v = version || {};
|
||||
const steps = [];
|
||||
if (v.kind === 'updated') {
|
||||
steps.push({ id: 'updated', text: 'Skills updated', title: 'Updated. Reconnect the console to use the new version.', tone: 'ok', action: 'restart-console' });
|
||||
} else if (consoleDead) {
|
||||
steps.push({ id: 'console-dead', text: 'Console stopped', title: 'The console stopped, so the dashboard cannot show.', tone: 'err', action: 'reconnect' });
|
||||
}
|
||||
switch (v.kind) {
|
||||
case 'too-old':
|
||||
steps.push({ id: 'too-old', text: 'Console too old for this app', title: 'The installed console is too old for the app. Update skills to fix it.', tone: 'warn', action: 'update' });
|
||||
break;
|
||||
case 'mismatch':
|
||||
steps.push({ id: 'mismatch', text: `Skills v${v.skills}, app v${v.app}`, title: `The installed skills are v${v.skills}, this app is v${v.app}.`, tone: 'warn', action: 'update' });
|
||||
break;
|
||||
case 'updating': {
|
||||
const line = v.line || 'Updating Plan2Code...';
|
||||
steps.push({ id: 'updating', text: line, title: line, tone: 'warn', busy: true, action: null });
|
||||
break;
|
||||
}
|
||||
case 'remains':
|
||||
steps.push({ id: 'remains', text: `Still mismatched: skills v${v.skills}, app v${v.app}`, title: `Updated, but the mismatch remains (skills v${v.skills}, app v${v.app}).`, tone: 'warn', action: null });
|
||||
break;
|
||||
case 'failed':
|
||||
steps.push({ id: 'failed', text: 'Update failed', title: String(v.error || 'The update did not finish.'), tone: 'err', action: 'update' });
|
||||
break;
|
||||
case 'ahead':
|
||||
steps.push({ id: 'ahead', text: `Skills v${v.skills} are newer than this app`, title: `The installed skills are v${v.skills}, newer than this app (v${v.app}). Get the new app.`, tone: 'warn', action: null });
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
return steps.map((step) => ({ ...step, label: step.action ? NEXT_STEP_LABELS[step.action] : null }));
|
||||
}
|
||||
|
||||
// Below this many px of its own width, the console's "Notes on this" aside
|
||||
// stacks under the main column instead of sitting beside it
|
||||
// (src/web-console/public/styles/responsive.css's 1080px breakpoint).
|
||||
export const CONSOLE_ASIDE_BREAKPOINT_PX = 1080;
|
||||
// A roomy default width for the terminal docked at the side, before the
|
||||
// console's own width is taken into account.
|
||||
const IDEAL_RIGHT_PANE_PX = 440;
|
||||
|
||||
/**
|
||||
* The terminal panel's width, as a share of the window, for a first run with
|
||||
* nothing saved yet: docked right, at whatever width keeps the console's own
|
||||
* aside panel from stacking, down to `minFraction` when the window is too
|
||||
* narrow for both (its own minimum still wins over squeezing the console).
|
||||
*/
|
||||
export function defaultRightFraction(windowWidth, { minFraction, maxFraction, idealPanePx = IDEAL_RIGHT_PANE_PX, consoleMinPx = CONSOLE_ASIDE_BREAKPOINT_PX } = {}) {
|
||||
const roomForConsole = Math.max(0, windowWidth - consoleMinPx);
|
||||
const panePx = Math.min(idealPanePx, roomForConsole);
|
||||
const fraction = windowWidth > 0 ? panePx / windowWidth : minFraction;
|
||||
return Math.min(maxFraction, Math.max(minFraction, fraction));
|
||||
}
|
||||
|
||||
/**
|
||||
* The OS window title for a project folder: its own name (the repo's, most
|
||||
* of the time) after "Plan2Code - ", so two or more windows read apart in a
|
||||
* taskbar without opening each to see which project is which. Trailing
|
||||
* slashes and a drive root (`C:\`, `/`) leave nothing to show, so that falls
|
||||
* back to the plain title rather than a trailing "Plan2Code - ".
|
||||
*/
|
||||
export function windowTitleFor(dir) {
|
||||
const name = lastSegment(dir);
|
||||
return name ? `Plan2Code - ${name}` : "Plan2Code";
|
||||
}
|
||||
|
||||
/**
|
||||
* A project folder's own name, for the bar's project menu: the same last
|
||||
* segment the window title uses, or the whole path when there is none (a
|
||||
* root such as `/`), so the menu never shows an empty name.
|
||||
*/
|
||||
export function folderName(dir) {
|
||||
return lastSegment(dir) || String(dir || "").trim();
|
||||
}
|
||||
|
||||
function lastSegment(dir) {
|
||||
return String(dir || "")
|
||||
.trim()
|
||||
.replace(/[\\/]+$/, "")
|
||||
.split(/[\\/]/)
|
||||
.filter(Boolean)
|
||||
.pop();
|
||||
}
|
||||
Generated
+2613
File diff suppressed because it is too large.
Load diff
@@ -46,10 +46,10 @@ export function tempProject(files = {}) {
|
||||
// test still cleans up, and a page error fails the test. `clock: true` gives
|
||||
// the page Playwright's fake clock before it loads (s.page.clock), so a test
|
||||
// can jump past the page's silence limits instead of sitting through them.
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false }) {
|
||||
export async function openSession(browser, { t, workflow, payload: first, project, open = [], clock = false, env, init } = {}) {
|
||||
fs.rmSync(REMEMBERED, { force: true });
|
||||
const cwd = project || tempProject();
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd }).json;
|
||||
const opened = cli(["open", "--workflow", workflow, "--no-open", ...open], { cwd, env }).json;
|
||||
const s = {
|
||||
sid: opened.sid,
|
||||
session: opened.session,
|
||||
@@ -95,7 +95,16 @@ export async function openSession(browser, { t, workflow, payload: first, projec
|
||||
if (first) s.post(first);
|
||||
s.context = await browser.newContext({ viewport: { width: 1280, height: 800 } });
|
||||
if (clock) await s.context.clock.install();
|
||||
// A script run before the page's own, such as a stand-in for the app's frame.
|
||||
if (init) await s.context.addInitScript(init);
|
||||
s.page = await s.context.newPage();
|
||||
// Playwright's own default (30s) assumes a dedicated machine: the whole
|
||||
// suite runs dozens of these pages at once, and a host under that load can
|
||||
// leave one of them waiting past 30s for its turn at the CPU to paint a
|
||||
// dropdown or settle a click, with nothing wrong in the page itself. Twice
|
||||
// the default still catches a genuinely broken page, just gives a busy host
|
||||
// room to breathe.
|
||||
s.page.setDefaultTimeout(60000);
|
||||
s.page.on("pageerror", (e) => s.errors.push(e.message));
|
||||
await s.page.goto(s.url, { waitUntil: "domcontentloaded" });
|
||||
await drawn(s.page);
|
||||
@@ -105,7 +114,7 @@ export async function openSession(browser, { t, workflow, payload: first, projec
|
||||
// The page has adopted a state frame: app.js has replaced the boot pane the
|
||||
// markup ships with.
|
||||
export async function drawn(page) {
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 15000 });
|
||||
await page.waitForFunction(() => !document.querySelector("#main .boot-pane"), null, { timeout: 30000 });
|
||||
}
|
||||
|
||||
// Presses Send on the page and collects the send the way an agent's `wait`
|
||||
|
||||
+221
-13
@@ -1,26 +1,234 @@
|
||||
// Tests for plan2code-app/ui/meter.js. Run with: node --test scripts/test-app-meter.mjs
|
||||
// Tests for plan2code-app/ui/meter.js and the app bar's own shape. Run with:
|
||||
// node --test scripts/test-app-meter.mjs
|
||||
//
|
||||
// app.js itself cannot be imported here (it touches `document` and
|
||||
// `window.__TAURI__` at module scope), which is why the nudge decision lives
|
||||
// in its own pure module.
|
||||
// `window.__TAURI__` at module scope), which is why the bar's pure decisions
|
||||
// live in their own module and the rest is checked as plain text, the same
|
||||
// way the web console's own "shape" tests work.
|
||||
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { nudgeDue } from "../plan2code-app/ui/meter.js";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { fileURLToPath, pathToFileURL } from "node:url";
|
||||
import { barNextSteps, continueKeys, defaultRightFraction, folderName, windowTitleFor, CONSOLE_ASIDE_BREAKPOINT_PX, NEXT_STEP_LABELS } from "../plan2code-app/ui/meter.js";
|
||||
import { findBrowser, launchBrowser } from "./browser.mjs";
|
||||
|
||||
test("meter: a real reading at or past the threshold nudges", () => {
|
||||
assert.equal(nudgeDue({ kind: "real", percent: 70 }, 70), true);
|
||||
assert.equal(nudgeDue({ kind: "real", percent: 69 }, 70), false);
|
||||
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
||||
const INDEX_HTML_PATH = path.join(HERE, "../plan2code-app/ui/index.html");
|
||||
const APP_JS = fs.readFileSync(path.join(HERE, "../plan2code-app/ui/app.js"), "utf8");
|
||||
const INDEX_HTML = fs.readFileSync(INDEX_HTML_PATH, "utf8");
|
||||
|
||||
test("barNextSteps offers nothing while the console runs and the versions agree", () => {
|
||||
assert.deepEqual(barNextSteps(), []);
|
||||
assert.deepEqual(barNextSteps({ consoleDead: false, version: null }), []);
|
||||
});
|
||||
|
||||
test("meter: a best-effort reading nudges the same as a real one", () => {
|
||||
assert.equal(nudgeDue({ kind: "besteffort", percent: 80 }, 70), true);
|
||||
test("barNextSteps puts the most pressing step first: a done update, then a stopped console, then the skills", () => {
|
||||
const ids = (input) => barNextSteps(input).map((step) => step.id);
|
||||
assert.deepEqual(ids({ consoleDead: true }), ["console-dead"]);
|
||||
assert.deepEqual(ids({ version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } }), ["mismatch"]);
|
||||
assert.deepEqual(ids({ consoleDead: true, version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } }), ["console-dead", "mismatch"]);
|
||||
assert.deepEqual(ids({ consoleDead: true, version: { kind: "too-old" } }), ["console-dead", "too-old"]);
|
||||
assert.deepEqual(ids({ version: { kind: "updated" } }), ["updated"]);
|
||||
});
|
||||
|
||||
test("meter: an estimate never nudges, however high its percent", () => {
|
||||
assert.equal(nudgeDue({ kind: "estimate", percent: 99 }, 70), false);
|
||||
test("only one control for reconnecting the console is ever offered: after an update, its Reconnect covers a stopped console too", () => {
|
||||
const steps = barNextSteps({ consoleDead: true, version: { kind: "updated" } });
|
||||
assert.deepEqual(steps.map((step) => step.action), ["restart-console"], "the plain reconnect steps aside for the one that stops the old console first");
|
||||
});
|
||||
|
||||
test("meter: unknown never nudges", () => {
|
||||
assert.equal(nudgeDue({ kind: "unknown" }, 70), false);
|
||||
test("each version state reads and acts as the old version bar did", () => {
|
||||
const [mismatch] = barNextSteps({ version: { kind: "mismatch", skills: "3.0.0", app: "3.1.0" } });
|
||||
assert.equal(mismatch.text, "Skills v3.0.0, app v3.1.0");
|
||||
assert.equal(mismatch.label, "Update skills");
|
||||
const [ahead] = barNextSteps({ version: { kind: "ahead", skills: "3.2.0", app: "3.1.0" } });
|
||||
assert.equal(ahead.action, null, "another Update skills run cannot help when the skills are ahead");
|
||||
assert.match(ahead.title, /newer than this app \(v3\.1\.0\)\. Get the new app\./);
|
||||
const [updating] = barNextSteps({ version: { kind: "updating", line: "Installing skills (4 of 9)" } });
|
||||
assert.deepEqual([updating.text, updating.busy, updating.action], ["Installing skills (4 of 9)", true, null], "no button while it runs");
|
||||
const [remains] = barNextSteps({ version: { kind: "remains", skills: "3.0.0", app: "3.1.0" } });
|
||||
assert.equal(remains.action, null);
|
||||
assert.equal(remains.title, "Updated, but the mismatch remains (skills v3.0.0, app v3.1.0).");
|
||||
const [failed] = barNextSteps({ version: { kind: "failed", error: "npm exited with code 1" } });
|
||||
assert.deepEqual([failed.tone, failed.title, failed.label], ["err", "npm exited with code 1", "Update skills"], "a failed update can be tried again");
|
||||
const [tooOld] = barNextSteps({ version: { kind: "too-old" } });
|
||||
assert.equal(tooOld.label, "Update skills", "an old console is fixed by the skills update");
|
||||
});
|
||||
|
||||
test("every control that reconnects the console carries the same label, never 'Restart the console' or 'Start it again'", () => {
|
||||
assert.equal(NEXT_STEP_LABELS.reconnect, "Reconnect the console");
|
||||
assert.equal(NEXT_STEP_LABELS["restart-console"], "Reconnect the console");
|
||||
assert.doesNotMatch(APP_JS, /'Restart the console'|"Start it again"/, "no stale label text left in app.js");
|
||||
});
|
||||
|
||||
test("app.js draws the bar's right end through barNextSteps, not a hand-rolled copy of its order", () => {
|
||||
assert.match(APP_JS, /const steps = barNextSteps\(\{ consoleDead, version: versionState \}\);/);
|
||||
for (const gone of ["console-again", "version-update", "permissions-note", "console-status", "project-dir"]) {
|
||||
assert.ok(!INDEX_HTML.includes(`id="${gone}"`), `index.html still has #${gone}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Claude Code holds typed text as a queued message while its turn is busy,
|
||||
// and the continue button only shows once the agent stopped checking in, so
|
||||
// by then the turn is stuck and the queued word would never send by itself.
|
||||
test("continueKeys types continue and Enter, and under Claude Code also its send-now chord (ctrl+x ctrl+s)", () => {
|
||||
assert.deepEqual(continueKeys("claude"), ["continue", "\r", "\x18\x13"]);
|
||||
for (const kind of ["devin", "codex", null, undefined, "something-new"]) {
|
||||
assert.deepEqual(continueKeys(kind), ["continue", "\r"], `${kind} gets the plain word and Enter`);
|
||||
}
|
||||
});
|
||||
|
||||
test("app.js types the continue button's keystrokes through continueKeys, for the running agent's kind", () => {
|
||||
const typeContinue = APP_JS.slice(APP_JS.indexOf("function typeContinue"), APP_JS.indexOf("function typeContinue") + 800);
|
||||
assert.match(typeContinue, /continueKeys\(agent\.kind\)/, "the keystrokes come from continueKeys");
|
||||
assert.doesNotMatch(typeContinue, /data: 'continue'/, "no hand-typed word left beside it");
|
||||
});
|
||||
|
||||
test("the bar reads project menu, New Session, agent menu, with both menus outside the scrolling row", () => {
|
||||
const row = INDEX_HTML.slice(INDEX_HTML.indexOf('<div id="bar-row">'), INDEX_HTML.indexOf('<div id="project-menu"'));
|
||||
const at = (id) => row.indexOf(`id="${id}"`);
|
||||
assert.ok(at("project-menu-button") >= 0 && at("agent-restart") > at("project-menu-button"), "New Session follows the project menu");
|
||||
assert.ok(at("agent-menu-button") > at("agent-restart"), "New Session sits just left of the agent menu");
|
||||
assert.ok(!row.includes('id="project-menu"') && !row.includes('id="agent-menu"'), "the menus are not inside #bar-row, whose overflow would clip them");
|
||||
assert.match(INDEX_HTML, /<div id="agent-menu"[\s\S]*?<button id="change-agent" role="menuitem" hidden>/, "Change agent lives in the agent menu");
|
||||
assert.match(INDEX_HTML, /<div id="project-menu"[\s\S]*?<button id="change-project" role="menuitem">/, "Change project lives in the project menu");
|
||||
});
|
||||
|
||||
test("folderName shows the project folder's own name, or the whole path when it has none", () => {
|
||||
assert.equal(folderName("C:\\git\\azw3-to-pdf"), "azw3-to-pdf");
|
||||
assert.equal(folderName("/home/me/plan2code/"), "plan2code");
|
||||
assert.equal(folderName("/"), "/");
|
||||
assert.equal(folderName(""), "");
|
||||
});
|
||||
|
||||
test("the context-window meter is gone for good: no stray element, poll, or backend call left wired up", () => {
|
||||
for (const needle of ["bar-slot-meter", "context-group", "context-nudge", "context-restart", "Agent context"]) {
|
||||
assert.ok(!INDEX_HTML.includes(needle), `index.html still has ${needle}`);
|
||||
}
|
||||
for (const needle of ["agent_context", "pollMeter", "nudgeDue", "renderMeter", "nudgePercent"]) {
|
||||
assert.ok(!APP_JS.includes(needle), `app.js still has ${needle}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("the launch card's permission-mode tick starts checked (off), matching the plain terminal launcher's own always-off default", () => {
|
||||
assert.match(
|
||||
INDEX_HTML,
|
||||
/<input id="launch-bypass" type="checkbox" checked>/,
|
||||
"the checkbox markup itself must carry `checked`, not something app.js sets later"
|
||||
);
|
||||
// The warning sentence starts visible along with it: no `hidden` attribute on this element.
|
||||
assert.match(INDEX_HTML, /<p id="launch-bypass-warning">Permission checks will be off/);
|
||||
// Nothing in app.js resets it back to unchecked on every card show.
|
||||
assert.doesNotMatch(APP_JS, /launchBypassEl\.checked\s*=\s*false/, "no reset back to unchecked anywhere");
|
||||
});
|
||||
|
||||
test("windowTitleFor names the project folder after Plan2Code, so two or more windows read apart in a taskbar", () => {
|
||||
assert.equal(windowTitleFor("C:\\git\\azw3-to-pdf"), "Plan2Code - azw3-to-pdf");
|
||||
assert.equal(windowTitleFor("/home/me/projects/plan2code"), "Plan2Code - plan2code");
|
||||
assert.equal(windowTitleFor("C:\\git\\azw3-to-pdf\\"), "Plan2Code - azw3-to-pdf", "a trailing slash does not leave an empty last segment");
|
||||
assert.equal(windowTitleFor("/"), "Plan2Code", "a root with nothing after it has no folder name to show");
|
||||
assert.equal(windowTitleFor(""), "Plan2Code");
|
||||
assert.equal(windowTitleFor(null), "Plan2Code");
|
||||
assert.equal(windowTitleFor(undefined), "Plan2Code");
|
||||
});
|
||||
|
||||
test("setProjectDir sets the OS window title through windowTitleFor, with a real permission to do so", () => {
|
||||
assert.match(APP_JS, /window\.__TAURI__\.window\.getCurrentWindow\(\)\.setTitle\(windowTitleFor\(dir\)\)/, "setProjectDir is the one place every project-dir change flows through");
|
||||
const caps = JSON.parse(fs.readFileSync(path.join(HERE, "../plan2code-app/src-tauri/capabilities/default.json"), "utf8"));
|
||||
assert.ok(caps.permissions.includes("core:window:allow-set-title"), "the capability to call setTitle must be granted, or the call is silently refused at runtime");
|
||||
});
|
||||
|
||||
test("app.js never sets statePlannyEl.hidden directly: SVGElement does not reflect that property to the attribute", () => {
|
||||
assert.doesNotMatch(APP_JS, /statePlannyEl\.hidden\s*=/, "must use toggleAttribute, not the .hidden property, on an <svg>");
|
||||
assert.match(APP_JS, /statePlannyEl\.toggleAttribute\('hidden', !tired\)/);
|
||||
});
|
||||
|
||||
test("the Restart confirmation no longer claims unsaved work, and offers New Session with the tired Planny", () => {
|
||||
const confirmRestart = APP_JS.slice(APP_JS.indexOf("function confirmRestart"), APP_JS.indexOf("function confirmRestart") + 600);
|
||||
assert.doesNotMatch(confirmRestart, /not saved/, "not always true, so it is gone from this dialog specifically");
|
||||
assert.match(confirmRestart, /'Restart the agent on a fresh context window\?',\s*\n\s*'New Session',/);
|
||||
assert.match(confirmRestart, /\{ tired: true \}/, "the confirm dialog asks for the tired Planny");
|
||||
assert.match(INDEX_HTML, /<svg id="dashboard-state-planny"[^>]*hidden>/, "the tired Planny starts hidden in the markup");
|
||||
});
|
||||
|
||||
test("defaultRightFraction gives the terminal a roomy width when the window has space for it, down to the floor when it does not", () => {
|
||||
const opts = { minFraction: 0.1, maxFraction: 0.6 };
|
||||
// Plenty of room: the ideal 440px pane, well inside both the console's own
|
||||
// 1080px minimum and the 0.6 ceiling.
|
||||
assert.equal(defaultRightFraction(1920, opts), 440 / 1920);
|
||||
// Just enough room for the console at 1080px and nothing more for the pane
|
||||
// than that leaves: the pane shrinks to fit, never pushing the console under.
|
||||
assert.equal(defaultRightFraction(1200, opts), 120 / 1200);
|
||||
// No room at all for the console's own 1080px minimum: the pane's floor
|
||||
// wins rather than vanishing to 0 or going negative.
|
||||
assert.equal(defaultRightFraction(1000, opts), 0.1);
|
||||
// The ceiling still applies even with abundant width.
|
||||
assert.equal(defaultRightFraction(3000, { minFraction: 0.1, maxFraction: 0.1 }), 0.1);
|
||||
assert.equal(CONSOLE_ASIDE_BREAKPOINT_PX, 1080, "matches responsive.css's own breakpoint");
|
||||
});
|
||||
|
||||
test("with nothing saved yet, app.js starts the terminal docked right via defaultRightFraction, not the bottom default", () => {
|
||||
assert.match(APP_JS, /paneDock = 'right';\s*\n\s*paneFraction = defaultRightFraction\(/, "the no-saved-state branch sets dock right");
|
||||
assert.match(APP_JS, /\} else \{[\s\S]{0,200}paneDock = 'right'/, "this only runs when state.termPanel is absent, never overriding a saved choice");
|
||||
});
|
||||
|
||||
// Docked right and collapsed, the terminal panel is a 28px-wide strip: the
|
||||
// Expand/Collapse button's text used to run horizontally off the edge of it
|
||||
// (visible, unreadable). It now reads top-to-bottom instead.
|
||||
test("docked right and collapsed, the terminal panel's Expand button fits the strip instead of overflowing it", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 1000, height: 600 } });
|
||||
page.on("pageerror", () => {}); // app.js calls into __TAURI__, absent here; the markup and CSS still load fine
|
||||
await page.goto(pathToFileURL(INDEX_HTML_PATH).href);
|
||||
await page.evaluate(() => {
|
||||
document.getElementById("workspace").classList.add("dock-right");
|
||||
document.getElementById("term-panel").classList.add("collapsed");
|
||||
document.getElementById("term-collapse").textContent = "Expand";
|
||||
});
|
||||
const fit = await page.evaluate(() => {
|
||||
const el = document.getElementById("term-collapse");
|
||||
return {
|
||||
writingMode: getComputedStyle(el).writingMode,
|
||||
overflowsWidth: el.scrollWidth > el.clientWidth,
|
||||
overflowsPanel: el.getBoundingClientRect().right > document.getElementById("term-panel").getBoundingClientRect().right,
|
||||
};
|
||||
});
|
||||
assert.equal(fit.writingMode, "vertical-rl", "the label is set to run top-to-bottom, not sideways");
|
||||
assert.equal(fit.overflowsWidth, false, "the label text does not overflow its own box");
|
||||
assert.equal(fit.overflowsPanel, false, "the button does not spill past the collapsed panel's edge");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("toggling the tired Planny <svg>'s hidden attribute the way app.js does actually shows and hides it", async (t) => {
|
||||
if (!findBrowser()) return t.skip("no Chrome or Edge installed");
|
||||
const browser = await launchBrowser();
|
||||
try {
|
||||
const page = await browser.newPage({ viewport: { width: 700, height: 500 } });
|
||||
page.on("pageerror", () => {});
|
||||
await page.goto(pathToFileURL(INDEX_HTML_PATH).href);
|
||||
// Setting the .hidden *property* on an <svg> does not reflect to the
|
||||
// attribute the way it does on an HTMLElement; app.js uses
|
||||
// toggleAttribute for exactly this reason. This exercises that real path.
|
||||
const shown = await page.evaluate(() => {
|
||||
document.getElementById("dashboard-state").hidden = false; // a plain div: the .hidden property works fine here
|
||||
const el = document.getElementById("dashboard-state-planny");
|
||||
el.toggleAttribute("hidden", false);
|
||||
return { display: getComputedStyle(el).display, rect: el.getBoundingClientRect() };
|
||||
});
|
||||
assert.notEqual(shown.display, "none", "toggleAttribute(false) makes it visible");
|
||||
assert.ok(shown.rect.width > 0 && shown.rect.height > 0, "it actually takes up space, not just display != none");
|
||||
const hiddenAgain = await page.evaluate(() => {
|
||||
const el = document.getElementById("dashboard-state-planny");
|
||||
el.toggleAttribute("hidden", true);
|
||||
return getComputedStyle(el).display;
|
||||
});
|
||||
assert.equal(hiddenAgain, "none", "toggleAttribute(true) hides it again");
|
||||
} finally {
|
||||
await browser.close();
|
||||
}
|
||||
});
|
||||
@@ -52,9 +52,14 @@ test("stress: 200 posts interleaved with 200 chat messages lose no message from
|
||||
const c = spawn(process.execPath, [CONSOLE_CLI, "post", "--session", s.sid, "--file", patchFile], {
|
||||
env: ENV,
|
||||
cwd: ROOT,
|
||||
stdio: "ignore",
|
||||
stdio: ["ignore", "ignore", "pipe"],
|
||||
});
|
||||
let err = "";
|
||||
c.stderr.on("data", (d) => (err += d));
|
||||
c.on("exit", (code) => {
|
||||
if (code !== 0) process.stderr.write(`[repro] exit ${code}: ${err}\n`);
|
||||
resolve(code);
|
||||
});
|
||||
c.on("exit", (code) => resolve(code));
|
||||
});
|
||||
try {
|
||||
for (let block = 0; block < 20; block++) {
|
||||
|
||||
@@ -291,8 +291,9 @@ test("open from a linked worktree seeds the workspace with the worktree, not the
|
||||
} finally {
|
||||
if (sidOpened) cliIn(wt, ["stop", "--session", sidOpened]);
|
||||
// A stopped server can take a while to let go of its working directory on
|
||||
// Windows, and longer while other test files load the machine.
|
||||
fs.rmSync(base, { recursive: true, force: true, maxRetries: 20, retryDelay: 250 });
|
||||
// Windows, and longer while other test files load the machine: under a
|
||||
// full-suite run this needed more than the 5s a 20x250ms retry gave it.
|
||||
fs.rmSync(base, { recursive: true, force: true, maxRetries: 40, retryDelay: 250 });
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1999,7 +1999,7 @@ test("subagents: only the five opted-in workflows offer the switch", () => {
|
||||
assert.equal(defaultInstruction(w), "");
|
||||
}
|
||||
assert.equal(Object.keys(SUBAGENT_WORKFLOWS).length, 5);
|
||||
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3 });
|
||||
assert.deepEqual(defaultSetting("review"), { workflow: "review", on: true, instruction: null, max: 3, strength: "balanced" });
|
||||
assert.equal(defaultSetting("plan").on, false, "a skill without the switch is never on");
|
||||
assert.equal(effectiveInstruction({ workflow: "review", instruction: " " }), defaultInstruction("review"));
|
||||
assert.equal(effectiveInstruction({ workflow: "review", instruction: " Mine " }), "Mine");
|
||||
@@ -2015,7 +2015,7 @@ test("subagents: blockFor walks every switch transition, and never says off to a
|
||||
const on = blockFor(setting(true, 2), none);
|
||||
assert.equal(on.lines[0], "Subagents: on (revision 2) — a console setting, not typed by the person.");
|
||||
assert.ok(!on.lines[0].includes("replaces"));
|
||||
assert.deepEqual(on.field, { state: "on", revision: 2, max: 3, instruction: defaultInstruction("implement") });
|
||||
assert.deepEqual(on.field, { state: "on", revision: 2, max: 3, instruction: defaultInstruction("implement"), strength: "balanced" });
|
||||
assert.deepEqual(on.cursor, { revision: 2, state: "on" });
|
||||
assert.equal(on.lines[on.lines.length - 1], " At most 3 helpers at once.");
|
||||
for (const frame of FRAME_LINES) assert.ok(on.lines.includes(" " + frame), frame);
|
||||
@@ -2025,7 +2025,7 @@ test("subagents: blockFor walks every switch transition, and never says off to a
|
||||
assert.ok(edit.lines.includes(" First line") && edit.lines.includes(" Second line"), "the instruction's own lines are indented");
|
||||
assert.ok(!edit.lines.some((line) => !line.trim()), "blank instruction lines are dropped");
|
||||
const nested = blockFor(setting(true, 2, { instruction: "- a\r\n - b\n \n" }), none);
|
||||
assert.deepEqual(nested.lines.slice(-3, -1), [" - a", " - b"], "the person's own indentation survives, CRLF and blank lines do not");
|
||||
assert.deepEqual(nested.lines.slice(-4, -2), [" - a", " - b"], "the person's own indentation survives, CRLF and blank lines do not");
|
||||
assert.equal(edit.field.max, 7);
|
||||
for (const line of edit.lines.slice(1)) assert.match(line, /^ {2}\S/, "only the first line starts at column 0");
|
||||
|
||||
@@ -2053,9 +2053,26 @@ test("subagents: the injected wording names no harness tool", () => {
|
||||
}
|
||||
});
|
||||
|
||||
// Guards NFR-1: the strength guidance and the wording the console injects speak
|
||||
// in strength words only, never a model or vendor name, so they stay right on
|
||||
// every harness and every model line-up.
|
||||
const MODEL_NAMES = /\b(haiku|sonnet|opus|fable|gpt|o\d|codex|gemini|flash|pro|claude|anthropic|openai|google|swe-\d)\b/i;
|
||||
|
||||
test("subagents: the strength guidance and the injected wording name no model or vendor", () => {
|
||||
const texts = [
|
||||
fs.readFileSync(path.join(ROOT, "src", "shared-references", "helper-strength.md"), "utf8"),
|
||||
...FRAME_LINES,
|
||||
...Object.keys(SUBAGENT_WORKFLOWS).map(defaultInstruction),
|
||||
];
|
||||
for (const text of texts) assert.doesNotMatch(text, MODEL_NAMES);
|
||||
assert.match("Start it on Sonnet at high effort.", MODEL_NAMES, "the check catches a model name");
|
||||
});
|
||||
|
||||
test("subagents: cleanSetting accepts a good setting and names the field that fails", () => {
|
||||
assert.deepEqual(cleanSetting({ on: true, instruction: null, max: 3 }), { on: true, instruction: null, max: 3 });
|
||||
assert.deepEqual(cleanSetting({ on: false, instruction: " Do it ", max: 20 }), { on: false, instruction: "Do it", max: 20 });
|
||||
assert.deepEqual(cleanSetting({ on: true, instruction: null, max: 3 }), { on: true, instruction: null, max: 3, strength: "balanced" });
|
||||
assert.deepEqual(cleanSetting({ on: false, instruction: " Do it ", max: 20, strength: "best" }), { on: false, instruction: "Do it", max: 20, strength: "best" });
|
||||
assert.equal(cleanSetting({ on: true, instruction: null, max: 3, strength: null }).strength, "balanced", "a null strength is the default");
|
||||
for (const strength of ["fast", "Balanced", 1, ""]) assert.deepEqual(cleanSetting({ on: true, instruction: null, max: 3, strength }), { error: "strength" }, String(strength));
|
||||
assert.equal(cleanSetting({ on: true, instruction: "", max: 1 }).instruction, null, "an empty instruction is the default");
|
||||
for (const max of [0, 21, 2.5, "3"]) assert.deepEqual(cleanSetting({ on: true, instruction: null, max }), { error: "max" }, String(max));
|
||||
assert.deepEqual(cleanSetting({ on: true, instruction: "x".repeat(2001), max: 3 }), { error: "too-long" });
|
||||
@@ -2129,6 +2146,28 @@ test("subagents: helperRows labels each state, shows a result only once a helper
|
||||
assert.equal(rows[2].result, "Timed out");
|
||||
});
|
||||
|
||||
test("subagents: helperRows turns a reported strength and effort into one line, and leaves it out when neither was reported", () => {
|
||||
const line = (extra) => helperRows([{ id: "h1", title: "One", ask: "a", state: "running", ...extra }]).rows[0];
|
||||
const cases = [
|
||||
[{ strength: "standard", effort: "medium" }, "Standard, medium effort"],
|
||||
[{ strength: "light" }, "Light"],
|
||||
[{ strength: "strongest", effort: "high" }, "Strongest, high effort"],
|
||||
[{ strength: "inherit", effort: "high" }, "Session model, high effort"],
|
||||
[{ strength: "inherit" }, "Session model"],
|
||||
[{ effort: "low" }, "Low effort"],
|
||||
];
|
||||
for (const [extra, want] of cases) {
|
||||
const row = line(extra);
|
||||
assert.equal(row.strengthLine, want, JSON.stringify(extra));
|
||||
assert.equal(row.strength, extra.strength);
|
||||
assert.equal(row.effort, extra.effort);
|
||||
}
|
||||
for (const extra of [{}, { strength: "huge", effort: "max" }]) {
|
||||
const row = line(extra);
|
||||
for (const key of ["strengthLine", "strength", "effort"]) assert.equal(key in row, false, `${JSON.stringify(extra)}: no ${key}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("page: the Subagents button sits right after Write a brief, and its dialog is in the page with no inline styles or scripts", () => {
|
||||
const html = fs.readFileSync(path.join(ROOT, "src", "web-console", "public", "index.html"), "utf8");
|
||||
const row = html.match(/<div class="row-left">([\s\S]*?)<\/div>\s*<div class="views-group">/);
|
||||
@@ -2153,7 +2192,7 @@ test("subagents: the store round-trips per project and workflow under the consol
|
||||
const script = `
|
||||
const lib = await import(${JSON.stringify(new URL("../src/web-console/settings.mjs", import.meta.url).href)});
|
||||
const project = ${JSON.stringify(project)};
|
||||
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5 });
|
||||
lib.saveSubagentStoreEntry(project, "implement", { on: true, instruction: "Mine", max: 5, strength: "best" });
|
||||
const flipped = project.replace(/My Repo$/, "MY REPO");
|
||||
console.log(JSON.stringify({
|
||||
file: lib.SUBAGENTS_FILE,
|
||||
@@ -2169,11 +2208,11 @@ test("subagents: the store round-trips per project and workflow under the consol
|
||||
assert.equal(res.status, 0, res.stderr);
|
||||
const out = JSON.parse(res.stdout);
|
||||
assert.equal(out.file, path.join(home, "subagents.json"), "the store follows PLAN2CODE_CONSOLE_HOME");
|
||||
assert.deepEqual(out.saved, { on: true, instruction: "Mine", max: 5 });
|
||||
assert.deepEqual(out.saved, { on: true, instruction: "Mine", max: 5, strength: "best" });
|
||||
if (process.platform === "win32" || process.platform === "darwin") {
|
||||
assert.deepEqual(out.otherCase, out.saved, "a different-case path reads the same entry");
|
||||
}
|
||||
assert.deepEqual(out.unsaved, { on: true, instruction: null, max: 3 }, "nothing saved means on");
|
||||
assert.deepEqual(out.unsaved, { on: true, instruction: null, max: 3, strength: "balanced" }, "nothing saved means on, at balanced");
|
||||
assert.ok(!fs.existsSync(path.join(home, "subagents.json.lock")), "the lock is released");
|
||||
} finally {
|
||||
fs.rmSync(home, { recursive: true, force: true });
|
||||
|
||||
@@ -211,3 +211,64 @@ test("posting helpers adds a Subagents tab that lists each with its state and re
|
||||
assert.match(await textOf(done), /All 9 pass\./);
|
||||
assert.match(await textOf(running), /Find the callers of applyPatch/);
|
||||
});
|
||||
|
||||
// What a person sees break: the strength they saved not shown when the dialog
|
||||
// opens again, a help line that ignores their pick, or Save dropping it.
|
||||
test("the Subagents dialog shows the saved strength, explains the picked one, goes inert under Work alone and saves it", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 2" } },
|
||||
});
|
||||
const modal = s.page.locator("#subagents-modal");
|
||||
const radio = (value) => modal.locator(`input[name="subagents-strength"][value="${value}"]`);
|
||||
const help = modal.locator("#subagents-strength-help");
|
||||
const open = async () => {
|
||||
await s.page.locator("#btn-subagents").click();
|
||||
await modal.waitFor();
|
||||
};
|
||||
|
||||
await open();
|
||||
assert.equal(await radio("balanced").isChecked(), true, "an unsaved strength opens as Balanced");
|
||||
assert.match(await textOf(help), /light for lookups/);
|
||||
await radio("thrifty").check();
|
||||
assert.match(await textOf(help), /One step lighter everywhere/);
|
||||
await modal.locator('input[name="subagents-on"][value="off"]').check();
|
||||
for (const value of ["balanced", "thrifty", "best", "session"]) assert.equal(await radio(value).isDisabled(), true, `${value} is inert under Work alone`);
|
||||
await modal.locator('input[name="subagents-on"][value="on"]').check();
|
||||
assert.equal(await radio("thrifty").isEnabled(), true);
|
||||
|
||||
const posted = s.page.waitForRequest((r) => r.url().endsWith("/subagents") && r.method() === "POST");
|
||||
await modal.getByRole("button", { name: "Save", exact: true }).click();
|
||||
assert.equal(JSON.parse((await posted).postData()).strength, "thrifty");
|
||||
await modal.waitFor({ state: "hidden" });
|
||||
|
||||
// The next frame carries the saved strength; the dialog opens on it.
|
||||
await s.page.waitForFunction(async () => (await (await fetch("/state")).json()).subagents.strength === "thrifty");
|
||||
await open();
|
||||
assert.equal(await radio("thrifty").isChecked(), true, "the saved strength is checked");
|
||||
assert.match(await textOf(help), /One step lighter everywhere/);
|
||||
});
|
||||
|
||||
// What a person sees break: the strength a helper ran with missing from the
|
||||
// tab, or a stray line under a helper that reported none.
|
||||
test("the Subagents tab shows a reported helper's strength line and none for a helper without one", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 2" } },
|
||||
});
|
||||
s.post({
|
||||
helpers: [
|
||||
reportedHelper("h1", { title: "Read the store helpers", strength: "standard", effort: "medium" }),
|
||||
reportedHelper("h2", { title: "Check the tests" }),
|
||||
],
|
||||
});
|
||||
const tab = s.page.locator("nav").getByRole("button", { name: /^Subagents/ });
|
||||
await tab.waitFor();
|
||||
await tab.click();
|
||||
const rows = s.page.locator("#main .sa-card .sa-row");
|
||||
await rows.first().waitFor();
|
||||
assert.equal(await textOf(rows.filter({ hasText: "Read the store helpers" }).locator(".sa-strength")), "Standard, medium effort");
|
||||
assert.equal(await rows.filter({ hasText: "Check the tests" }).locator(".sa-strength").count(), 0);
|
||||
});
|
||||
@@ -395,6 +395,23 @@ test("Skip this one and a comment box's quick answer are the same small accent b
|
||||
assert.equal(colour, await accentOf(s.page), "in the accent");
|
||||
});
|
||||
|
||||
// What a person sees break: Combine phases is missing from a plan's breakdown,
|
||||
// fills nothing, or shows on a list that is not phases.
|
||||
test("a plan's breakdown offers Combine phases beside No changes, and other workflows do not", async (t) => {
|
||||
const rows = [{ id: "a", title: "Read the data", body: "x" }];
|
||||
let s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
let card = await ask(s, { id: "l1", kind: "list", title: "Build order", body: "Reorder.", rows });
|
||||
const quicks = card.locator(".quick-answer");
|
||||
assert.deepEqual(await quicks.allTextContents(), ["No changes", "Combine phases"]);
|
||||
await card.getByRole("button", { name: "Combine phases" }).click();
|
||||
const got = await sendAndCollect(s);
|
||||
assert.match(answerTo(got, "l1").text, /^Combine phases where possible/);
|
||||
|
||||
s = await openSession(await suite.browser(), { t, workflow: "quick-task" });
|
||||
card = await ask(s, { id: "l2", kind: "list", title: "Steps", body: "Reorder.", rows });
|
||||
assert.deepEqual(await card.locator(".quick-answer").allTextContents(), ["No changes"]);
|
||||
});
|
||||
|
||||
// What a person sees break: a safe yes looks like any button, or a risky yes
|
||||
// stops warning.
|
||||
test("a confirm's safe yes and a recap's yes are outlined in the accent, and a dangerous yes stays red", async (t) => {
|
||||
|
||||
@@ -181,7 +181,7 @@ test("a fixed bug's Delete asks once with no name to type, while any other spec
|
||||
// The fixed bug: a visible Delete, its own warning, and one press sends it.
|
||||
const del = main.getByRole("button", { name: "Delete the spec old-bug" });
|
||||
assert.equal(await textOf(del), "Delete", "a fixed bug's Delete is a labelled button");
|
||||
await del.click();
|
||||
await del.click({ force: true });
|
||||
await dialog.waitFor();
|
||||
assert.match(await textOf(s.page.locator("#delete-warn")), /The bug is fixed, so this only clears the write-up/);
|
||||
assert.equal(await textOf(go), "Delete it");
|
||||
@@ -257,9 +257,9 @@ function handoffProject(t) {
|
||||
return { project, made };
|
||||
}
|
||||
|
||||
async function openHandoffMenu(t) {
|
||||
async function openHandoffMenu(t, env) {
|
||||
const { project, made } = handoffProject(t);
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project, env });
|
||||
const main = await toTheMenu(s);
|
||||
const chip = chipFor(main, "Lunch vote");
|
||||
await chip.waitFor();
|
||||
@@ -320,6 +320,20 @@ test("Read it all opens the handoff's text, and Copy puts a prompt naming its fi
|
||||
assert.ok(text.includes(made.id), `the prompt names the handoff's file: ${text}`);
|
||||
});
|
||||
|
||||
// Under the app, "a new conversation" is this console's own wording for what
|
||||
// New Session does, so the handoff's copy button says "another session"
|
||||
// instead, still naming the same clipboard prompt.
|
||||
test("under the app, a handoff's copy button says Copy for another session, and still works", async (t) => {
|
||||
const { s, main, chip } = await openHandoffMenu(t, { PLAN2CODE_IN_APP: "1" });
|
||||
await s.context.grantPermissions(["clipboard-read", "clipboard-write"], { origin: new URL(s.url).origin });
|
||||
await chip.click();
|
||||
assert.equal(await main.getByRole("button", { name: "Copy for a new conversation" }).count(), 0, "no classic-mode wording under the app");
|
||||
const copy = main.getByRole("button", { name: "Copy for another session" });
|
||||
await copy.click();
|
||||
await main.getByRole("button", { name: "Copied" }).waitFor();
|
||||
await copy.waitFor();
|
||||
});
|
||||
|
||||
// What a person would see break: Delete asks for a name, or sends a spec
|
||||
// delete instead of the handoff's.
|
||||
test("a handoff's Delete asks once in its own dialog and sends a delete naming the handoff", async (t) => {
|
||||
@@ -366,6 +380,39 @@ test("the update banner shows on the dashboard only, and its dismiss hides it",
|
||||
await banner.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
// Under the desktop app (PLAN2CODE_IN_APP=1) the app's own top bar already
|
||||
// nags about a skills/app mismatch and updates in one click, so this banner
|
||||
// (a copy-pasted shell command) must never show there, newer release or not.
|
||||
test("under the app, the update banner never shows", async (t) => {
|
||||
aNewerReleaseExists(t);
|
||||
const dash = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "dashboard",
|
||||
payload: MENU,
|
||||
project: tempProject(DRAFT_PROJECT),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
const main = await toTheMenu(dash);
|
||||
await main.getByText("One spec on disk, with a plan drafted.").waitFor();
|
||||
assert.equal(await main.getByText("UPDATE AVAILABLE").count(), 0, "no banner under the app");
|
||||
});
|
||||
|
||||
// Same reasoning for the dashboard's own red-meter banner: under the app it
|
||||
// must point at New Session, never at starting a new console session.
|
||||
test("under the app, the dashboard's red-meter banner points at New Session", async (t) => {
|
||||
const dash = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "dashboard",
|
||||
payload: MENU,
|
||||
project: tempProject(DRAFT_PROJECT),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
const main = await toTheMenu(dash);
|
||||
dash.post({ run: { event: "implement-phase", id: "phase-1", tasks: 30 } });
|
||||
await main.getByText("Press New Session at the top of the window to start the agent fresh.").waitFor();
|
||||
assert.equal(await main.getByText("Starting a new console session").count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// What a person would see break: two dashboard tabs of one session, on
|
||||
// different picks, keep taking the workspace's folders back from each other.
|
||||
test("two dashboard tabs on different picks leave the workspace scope with the last pick and ask for it no more", async (t) => {
|
||||
|
||||
@@ -12,9 +12,17 @@ import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, tempProject, textOf, drawn } from "./page-test-helpers.mjs";
|
||||
import { HOME } from "./web-console-test-helpers.mjs";
|
||||
import { HOME, cli, until } from "./web-console-test-helpers.mjs";
|
||||
import { HELP_TABS } from "../src/web-console/public/help.js";
|
||||
import { CATALOG_GROUPS, SKILL_CATALOG } from "../src/web-console/public/answers.js";
|
||||
import { GONE_AFTER_MS } from "../src/web-console/public/screens/core.js";
|
||||
|
||||
// The agent's side of `stop`, leaving the browser context open (s.stop()
|
||||
// closes it, which would hide what the page does next).
|
||||
async function stopServer(s) {
|
||||
cli(["stop", "--session", s.sid], { cwd: s.project });
|
||||
assert.ok(await until(async () => !(await s.answers()), 5000), "the server still answers after stop");
|
||||
}
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
@@ -290,3 +298,252 @@ test("the update banner opens a modal with the exact update commands, and its di
|
||||
await toTheDashboard(s);
|
||||
assert.equal(await main.getByRole("button", { name: /UPDATE AVAILABLE/ }).count(), 0, "the banner came back after a reload");
|
||||
});
|
||||
|
||||
// Under the app the dashboard's own UPDATE AVAILABLE banner never shows (a
|
||||
// separate test already covers that), so Help's own line about it must not
|
||||
// send an in-app reader to a terminal command for a banner they can never see.
|
||||
test("under the app, Help's update line points at Update skills, not the dashboard banner's terminal command", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "dashboard",
|
||||
payload: { agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await toTheDashboard(s);
|
||||
await openHelp(s);
|
||||
await tabButton(s, "dashboard").click();
|
||||
const text = s.page.locator("#help-update-text");
|
||||
await text.getByText("Update skills", { exact: false }).waitFor();
|
||||
assert.equal(await text.locator("code").count(), 0, "no terminal command under the app");
|
||||
assert.equal(await text.getByText("UPDATE AVAILABLE", { exact: false }).count(), 0, "no mention of a banner that never shows there");
|
||||
});
|
||||
|
||||
// Under the app, when the console server itself is gone, the live "About"
|
||||
// line must not send the reader hunting for a link in a terminal: the app's
|
||||
// own bar already notices and offers to reconnect it.
|
||||
test("under the app, Help's live line about a gone console names the app's bar, not a terminal link", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
clock: true,
|
||||
});
|
||||
await stopServer(s);
|
||||
for (let i = 0; i < 20 && !(await s.page.locator("#planny.is-gone").count()); i++) {
|
||||
await s.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
await openHelp(s);
|
||||
// Help opens on "stuck" while gone (helpTabFor); the live line itself lives
|
||||
// on "about", built the same regardless of which tab is first shown.
|
||||
await tabButton(s, "about").click();
|
||||
const live = s.page.locator("#about-live");
|
||||
await live.getByText("The app's own bar notices and offers to reconnect it", { exact: false }).waitFor();
|
||||
assert.equal(await live.getByText("link from the terminal", { exact: false }).count(), 0, "no terminal-link wording under the app");
|
||||
});
|
||||
|
||||
// Help's own "Running the next command" explainer (the Finishing topic) said
|
||||
// "paste into the terminal... in a new conversation": wrong under the app,
|
||||
// where it's the one terminal panel, not a separate conversation.
|
||||
test("under the app, Help's Finishing topic says to paste into the terminal panel, not a new conversation", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await openHelp(s);
|
||||
await tabButton(s, "finishing").click();
|
||||
const text = s.page.locator("#help-finishing-command-text");
|
||||
await text.getByText("terminal panel below", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("new conversation", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// The same topic's "Back to the dashboard" and "Continue here" explainers
|
||||
// also described classic-only behavior the screens themselves no longer show
|
||||
// under the app: a command to copy, and a new conversation to start fresh in.
|
||||
test("under the app, Help's dashboard and Continue here explainers point at the app's own controls", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await openHelp(s);
|
||||
await tabButton(s, "finishing").click();
|
||||
const dash = s.page.locator("#help-finishing-dashboard-text");
|
||||
await dash.getByText("the app's own bar notices and offers to reconnect it", { exact: false }).waitFor();
|
||||
assert.equal(await dash.locator("code").count(), 0, "no /plan2code command under the app");
|
||||
const cont = s.page.locator("#help-finishing-continue-text");
|
||||
await cont.getByText("press New Session at the top of the window", { exact: false }).waitFor();
|
||||
assert.equal(await cont.getByText("new conversation", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// The Welcome dialog's own onboarding tip gave the same classic-only advice.
|
||||
test("under the app, the Welcome dialog's refresh tip names New Session, not a new conversation", async (t) => {
|
||||
savedLooks(t, null);
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "dashboard",
|
||||
payload: { agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await toTheDashboard(s);
|
||||
const welcome = s.page.locator("#welcome-modal");
|
||||
await welcome.waitFor();
|
||||
const text = s.page.locator("#welcome-refresh-text");
|
||||
await text.getByText("press New Session at the top of the window", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("new conversation", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// The Troubleshooting tab's own "getting a new link" recovery flow is
|
||||
// classic-only (it ends in a command that prints a fresh browser link);
|
||||
// under the app, Reconnect the console in the bar already does this.
|
||||
test("under the app, Help's Troubleshooting topic names Reconnect the console, not a new link to print", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await openHelp(s);
|
||||
await tabButton(s, "stuck").click();
|
||||
const ref = s.page.locator("#help-stuck-not-connected-ref");
|
||||
await ref.getByText("the app's own bar notices and offers to reconnect it", { exact: false }).waitFor();
|
||||
await s.page.locator("#help-stuck-reconnect-title").getByText("Reconnecting").waitFor();
|
||||
const text = s.page.locator("#help-stuck-reconnect-text");
|
||||
await text.getByText("Reconnect the console", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("in the terminal", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
assert.equal(await s.page.locator("#help-stuck-reconnect-command").isVisible(), false, "no command to copy under the app");
|
||||
// The "What you might see" symptom table has its own, separate "Not
|
||||
// connected" row making the same classic-only claim.
|
||||
const tableRow = s.page.locator("#help-stuck-table-reconnect-text");
|
||||
await tableRow.getByText("Reconnect the console", { exact: false }).waitFor();
|
||||
assert.equal(await tableRow.getByText("new link", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// The Ask tab's "carry away" prompt is meant to start a genuinely fresh task:
|
||||
// under the app that means New Session first, then the terminal panel, not
|
||||
// "a new conversation" that does not exist there.
|
||||
test("under the app, Help's Ask topic says to press New Session and paste into the terminal panel, not a new conversation", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await openHelp(s);
|
||||
await tabButton(s, "ask").click();
|
||||
const text = s.page.locator("#help-ask-prompt-text");
|
||||
await text.getByText("Press New Session for a clean context, then paste it into the terminal panel", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("new conversation", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// "Stopping early" also pointed to a terminal command "in a new conversation":
|
||||
// matches ending.js's own renderStopping, which already says the terminal panel.
|
||||
test("under the app, Help's Stopping early topic says to paste into the terminal panel, not a new conversation", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await openHelp(s);
|
||||
await tabButton(s, "finishing").click();
|
||||
const text = s.page.locator("#help-finishing-stop-text");
|
||||
await text.getByText("to paste into the terminal panel", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("new conversation", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// The Planny-poses catalog's own "Done" entry also said "close the tab":
|
||||
// there is no tab under the app, only the one window.
|
||||
test("under the app, Planny's Done pose says to close the window, not the tab", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await openHelp(s);
|
||||
await tabButton(s, "planny").click();
|
||||
const text = s.page.locator("#help-planny-done-text");
|
||||
await text.getByText("close the window", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("close the tab", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// Help's own description of the handoff Copy button named "a new conversation",
|
||||
// the console's own wording for what New Session does under the app.
|
||||
test("under the app, Help's dashboard topic calls the handoff copy button Copy for another session", async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "dashboard",
|
||||
payload: { agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
await toTheDashboard(s);
|
||||
await openHelp(s);
|
||||
await tabButton(s, "dashboard").click();
|
||||
const text = s.page.locator("#help-handoff-copy-text");
|
||||
await text.getByText("Copy for another session", { exact: false }).waitFor();
|
||||
assert.equal(await text.getByText("Copy for a new conversation", { exact: false }).count(), 0, "no classic-mode wording under the app");
|
||||
});
|
||||
|
||||
// Every Help topic, as the reader sees it in each mode: the visible text of
|
||||
// each panel in turn. A browser tab's wording never shows under the app, and
|
||||
// the app's never shows in a browser, wherever in Help it sits.
|
||||
async function visibleHelpText(s) {
|
||||
await openHelp(s);
|
||||
const texts = {};
|
||||
for (const t of HELP_TABS) {
|
||||
await tabButton(s, t.id).click();
|
||||
texts[t.id] = await s.page.locator("#help-panel-" + t.id).innerText();
|
||||
}
|
||||
return texts;
|
||||
}
|
||||
|
||||
const BROWSER_ONLY = [/browser tab/i, /this tab\b/i, /close the tab/i, /closed tab/i, /in your browser/i, /your terminal/i, /in a new conversation/i, /new link/i, /same link/i, /address bar/i, /terminal you started/i];
|
||||
const APP_ONLY = [/terminal panel/i, /app's window/i, /app's own bar/i, /New Session/];
|
||||
|
||||
for (const inApp of [true, false]) {
|
||||
test(`every Help topic reads right ${inApp ? "under the app" : "in a browser"}`, async (t) => {
|
||||
savedLooks(t, { welcomeSeen: true });
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
project: tempProject(),
|
||||
...(inApp ? { env: { PLAN2CODE_IN_APP: "1" } } : {}),
|
||||
});
|
||||
const texts = await visibleHelpText(s);
|
||||
const hits = [];
|
||||
for (const [tab, text] of Object.entries(texts)) {
|
||||
for (const re of inApp ? BROWSER_ONLY : APP_ONLY) {
|
||||
const hit = text.match(re);
|
||||
if (hit) hits.push(`${tab}: ...${text.slice(Math.max(0, hit.index - 50), hit.index + 50).replace(/\s+/g, " ")}...`);
|
||||
}
|
||||
}
|
||||
assert.deepEqual(hits, [], "wording from the other mode");
|
||||
// And each mode's own wording is really there, so the sweep is reading the panels.
|
||||
const all = Object.values(texts).join(" ");
|
||||
assert.match(all, inApp ? /terminal panel/ : /your terminal/);
|
||||
});
|
||||
}
|
||||
@@ -760,6 +760,9 @@ test("text typed into a tab that is then deleted is never saved, and a tab delet
|
||||
deleteTab(s.project, elsewhere);
|
||||
await tabNamed(s, "Elsewhere").click();
|
||||
await s.page.waitForFunction((want) => document.getElementById("notepad-status").textContent.includes(want), errorSentence("no-such-tab"));
|
||||
// The status line updates first; the bar itself waits on a second, separate
|
||||
// fetch (readNote(null), after the first one 404s) that lands after it.
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
assert.deepEqual(await tabNames(s), ["Notes"]);
|
||||
});
|
||||
|
||||
|
||||
@@ -161,6 +161,140 @@ test("Continue here is hidden once the session meter is red, and the command and
|
||||
assert.equal(await closeGuide(s).count(), 1, "the fresh-session advice stays");
|
||||
});
|
||||
|
||||
// Under the desktop app (PLAN2CODE_IN_APP=1) the fresh-session advice in the
|
||||
// meter's popover and the dashboard's red banner must point at the app's own
|
||||
// New Session, never a command to copy into a terminal that is not there:
|
||||
// the popover's is a button filled with the user's highlight colour.
|
||||
test("under the app, the meter popover and the dashboard's red banner point at New Session, not a command", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 1" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
s.post({ run: { event: "implement-phase", id: "phase-1", tasks: 30 } });
|
||||
const pill = s.page.locator("#meter-pill[data-level='red']");
|
||||
await pill.waitFor();
|
||||
await pill.click();
|
||||
const fresh = s.page.locator("#meter-fresh");
|
||||
const press = fresh.getByRole("button", { name: "Start a New Session" });
|
||||
await press.waitFor();
|
||||
assert.equal(await fresh.locator(".meter-fresh-text").count(), 0, "the button is the whole note, no sentence around it");
|
||||
// The page's highlight, resolved the same way the button's fill is.
|
||||
const [fill, highlight] = await press.evaluate((n) => {
|
||||
const probe = document.createElement("i");
|
||||
probe.style.color = "var(--accent)";
|
||||
n.append(probe);
|
||||
const colour = getComputedStyle(probe).color;
|
||||
probe.remove();
|
||||
return [getComputedStyle(n).backgroundColor, colour];
|
||||
});
|
||||
assert.equal(fill, highlight, "filled with the user's highlight colour");
|
||||
assert.equal(await fresh.locator("code").count(), 0, "no command to copy under the app");
|
||||
});
|
||||
|
||||
// The desktop app's frame, as the page sees it: a parent that keeps every
|
||||
// message posted to it, for the test to read back.
|
||||
const FAKE_APP_FRAME = () => {
|
||||
window.__toApp = [];
|
||||
Object.defineProperty(window, "parent", { configurable: true, get: () => ({ postMessage: (m) => window.__toApp.push(m) }) });
|
||||
};
|
||||
const toApp = (s, kind) => s.page.evaluate((k) => window.__toApp.filter((m) => m.plan2code === k), kind);
|
||||
|
||||
test("under the app, the meter popover's Start a New Session button asks the app for its New Session", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 1" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
init: FAKE_APP_FRAME,
|
||||
});
|
||||
s.post({ run: { event: "implement-phase", id: "phase-1", tasks: 30 } });
|
||||
const pill = s.page.locator("#meter-pill[data-level='red']");
|
||||
await pill.waitFor();
|
||||
await pill.click();
|
||||
await s.page.locator("#meter-fresh").getByRole("button", { name: "Start a New Session" }).click();
|
||||
await until(async () => (await toApp(s, "new-session")).length === 1, 5000);
|
||||
assert.deepEqual(await toApp(s, "new-session"), [{ plan2code: "new-session" }], "a named request, nothing else in it");
|
||||
});
|
||||
|
||||
test("under the app, the not running line's continue is a button that asks the app to type it, and the page hands the app its highlight", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
clock: true,
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
init: FAKE_APP_FRAME,
|
||||
});
|
||||
const looks = await toApp(s, "looks");
|
||||
assert.ok(looks.length >= 1, "the page told the app its highlight");
|
||||
assert.deepEqual(looks.at(-1).accent, ["#619fe5", "#1a2533", "#0c1117", "#3d5978"], "the default highlight, in its dark shades");
|
||||
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running right now\./);
|
||||
const press = s.page.locator("#agent-text .agent-key-btn");
|
||||
assert.equal(await press.textContent(), "continue");
|
||||
await press.click();
|
||||
await until(async () => (await toApp(s, "agent-continue")).length === 1, 5000);
|
||||
assert.ok(await press.isDisabled(), "held off, so a double press does not type it twice");
|
||||
});
|
||||
|
||||
// The app's webview opens no new windows, so a link off the page asks the
|
||||
// console to open it in the default browser instead, and says where to paste
|
||||
// it when that fails.
|
||||
const FEEDBACK_URL = "https://github.com/jparkerweb/plan2code/issues/new/choose";
|
||||
|
||||
test("under the app, a link off the page goes to the default browser through the console, not a new window", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
|
||||
const asked = [];
|
||||
await s.page.route("**/open-link", async (route) => {
|
||||
asked.push(route.request().postDataJSON());
|
||||
await route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify({ ok: true, url: FEEDBACK_URL }) });
|
||||
});
|
||||
let popups = 0;
|
||||
s.page.context().on("page", () => popups++);
|
||||
await s.page.locator("#btn-feedback").click();
|
||||
await until(async () => asked.length === 1, 5000);
|
||||
assert.deepEqual(asked, [{ url: FEEDBACK_URL }]);
|
||||
await new Promise((r) => setTimeout(r, 300));
|
||||
assert.equal(popups, 0, "no window opened inside the app");
|
||||
});
|
||||
|
||||
test("under the app, a link the console cannot open is shown to paste into a browser", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
|
||||
await s.page.route("**/open-link", (route) => route.fulfill({ status: 500, contentType: "application/json", body: "{}" }));
|
||||
await s.page.locator("#btn-feedback").click();
|
||||
await s.page.waitForFunction((u) => document.getElementById("banner").textContent.includes(u), FEEDBACK_URL, { timeout: 5000 });
|
||||
assert.match(await s.page.locator("#banner").innerText(), /paste it into your browser/i);
|
||||
});
|
||||
|
||||
test("outside the app, a link off the page opens as a plain link, with no detour through the console", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
let asked = 0;
|
||||
await s.page.route("**/open-link", (route) => {
|
||||
asked++;
|
||||
return route.fulfill({ status: 200, contentType: "application/json", body: "{}" });
|
||||
});
|
||||
const popup = s.page.context().waitForEvent("page", { timeout: 5000 });
|
||||
await s.page.locator("#btn-feedback").click();
|
||||
await (await popup).close();
|
||||
assert.equal(asked, 0);
|
||||
});
|
||||
|
||||
test("outside the app, the not running line's continue stays a word to type", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
clock: true,
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: "A short name." }], agent: { status: "waiting" } },
|
||||
});
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running right now\./);
|
||||
assert.equal(await s.page.locator("#agent-text .agent-key-btn").count(), 0);
|
||||
assert.equal(await s.page.locator("#agent-text strong.agent-key").textContent(), "continue");
|
||||
});
|
||||
|
||||
test("Stop session, confirmed, sends __stop with no handoff", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
@@ -207,6 +341,28 @@ test("Stop with a handoff sends __stop with handoff, and the paused finish and s
|
||||
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code-1-plan --web$/ }).count(), "the resume command is gone");
|
||||
});
|
||||
|
||||
// Someone who presses Stop and steps away comes back to an answer: the
|
||||
// wrapping-up dialog turns into Done once the stop lands and stays up until
|
||||
// it is closed, rather than quietly going away.
|
||||
test("the wrapping-up dialog says Done when the stop lands, and stays until closed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.click("#btn-stop");
|
||||
await s.page.locator("#stop-go").click();
|
||||
const dlg = s.page.locator("#stopping-modal");
|
||||
await dlg.waitFor();
|
||||
assert.equal(await s.page.locator("#stopping-title").textContent(), "Wrapping up");
|
||||
assert.doesNotMatch(await dlg.innerText(), /close the (window|tab)/i, "no advice to close the page mid-stop");
|
||||
|
||||
collect(s);
|
||||
s.post({ settle: true, finish: { headline: "Paused at the naming question", body: "Your place is saved.", command: "/plan2code-1-plan" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Paused at the naming question" }).waitFor();
|
||||
await s.page.locator("#stopping-title").getByText("Done", { exact: true }).waitFor();
|
||||
assert.equal(await s.page.locator("#stop-steps li.is-done").count(), 3, "every step ticked");
|
||||
assert.ok(await holds(async () => dlg.isVisible(), 2000), "Done stays up on its own");
|
||||
await s.page.locator("#stopping-hide").getByText("Close", { exact: true }).click();
|
||||
await dlg.waitFor({ state: "hidden" });
|
||||
});
|
||||
|
||||
test("a page that loses its server goes offline, and after a resume it shows the session again with the unsent answer still typed", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
const field = () => itemCard(s.page, "q1").locator("textarea, input[type=text]").first();
|
||||
@@ -300,6 +456,83 @@ test("the quiet, not running and not connected lines offer What to check, openin
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
|
||||
});
|
||||
|
||||
// An agent sitting in `wait` pings every five seconds and collects a send at
|
||||
// once, so answers still uncollected after a minute of its silence mean
|
||||
// nothing is listening: the wake-up help shows then, not after three minutes.
|
||||
test("answers a waiting agent never collects bring up the saved-and-waiting line after a minute of silence, not before", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", clock: true, payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
|
||||
await s.page.clock.fastForward(30_000);
|
||||
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
|
||||
await s.page.clock.fastForward(40_000);
|
||||
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the line carries What to check");
|
||||
});
|
||||
|
||||
// An agent that asked and carried on working collects at its next `wait`, so
|
||||
// a minute is no proof against it; three minutes of silence is, whatever
|
||||
// longer quiet allowance it gave itself before it went.
|
||||
test("answers a working agent has not collected bring up the saved-and-waiting line after three minutes, not its long quiet allowance", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", clock: true, payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await lineSays(s, /^Sent\. Waiting for Plan2Code\./);
|
||||
// Its last word before it went quiet: working, with half an hour to spare.
|
||||
s.post({ agent: { status: "working", activity: "Task 1 of 3: the reader", quietMinutes: 30 } });
|
||||
await lineSays(s, /Task 1 of 3: the reader/);
|
||||
await s.page.clock.fastForward(70_000);
|
||||
await lineSays(s, /Task 1 of 3: the reader/);
|
||||
await s.page.clock.fastForward(130_000);
|
||||
await lineSays(s, /^Plan2Code is not running\. Your answers are saved and waiting for it\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the line carries What to check");
|
||||
});
|
||||
|
||||
// A failed Send says why at once, rather than one line for every cause and
|
||||
// the real state only showing once the page's own timers catch up.
|
||||
test("a Send that finds the server gone says so at once, with the reconnect help", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await stopServer(s);
|
||||
await s.page.click("#btn-send");
|
||||
await s.page.waitForFunction(() => document.getElementById("planny").classList.contains("is-gone"), null, { timeout: 3000 });
|
||||
assert.match(await s.page.locator("#banner").innerText(), LOST_CONTACT);
|
||||
assert.match(await textOf(statusLine(s)), /^Not connected\. Your answers are saved\./);
|
||||
assert.equal(await whatToCheck(s).count(), 1, "the not connected line carries What to check");
|
||||
});
|
||||
|
||||
test("a Send the server refuses shows the server's reason", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.route("**/submit", (route) =>
|
||||
route.fulfill({ status: 500, contentType: "application/json", body: JSON.stringify({ error: "the disk is full" }) })
|
||||
);
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await s.page.waitForFunction(() => /the disk is full/.test(document.getElementById("banner").textContent), null, { timeout: 3000 });
|
||||
assert.match(await s.page.locator("#banner").innerText(), /Nothing was lost/);
|
||||
});
|
||||
|
||||
test("a Send the server refuses as too large says to remove an attachment, not to try the same send again", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.route("**/submit", (route) =>
|
||||
route.fulfill({ status: 413, contentType: "application/json", body: JSON.stringify({ error: "too large" }) })
|
||||
);
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await s.page.waitForFunction(() => /remove an attachment/.test(document.getElementById("banner").textContent), null, { timeout: 3000 });
|
||||
assert.doesNotMatch(await s.page.locator("#banner").innerText(), /try Send again/);
|
||||
});
|
||||
|
||||
test("a Send lost on the way, with the server still up, says the console is there and to send again", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan", payload: PLAN_QUESTION });
|
||||
await s.page.route("**/submit", (route) => route.abort());
|
||||
await itemCard(s.page, "q1").locator("textarea, input[type=text]").first().fill("audit-export");
|
||||
await s.page.click("#btn-send");
|
||||
await s.page.waitForFunction(() => /console is still up/.test(document.getElementById("banner").textContent), null, { timeout: 3000 });
|
||||
assert.equal(await s.page.locator("#planny").evaluate((n) => n.classList.contains("is-gone")), false, "not called gone");
|
||||
});
|
||||
|
||||
test("an answered finish offer comes back unanswered on a later finish, once the first finish has gone", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
const finishWith = (headline) => s.post({ finish: { headline, command: "/plan2code-3-implement specs/audit-export/overview.md", dashboard: true } });
|
||||
@@ -531,6 +764,71 @@ test("every finished shape shows Before you close this with its three rows, and
|
||||
assert.equal(await s.page.locator("#btn-home").isVisible(), false, "a finished screen carries its own way back");
|
||||
});
|
||||
|
||||
// Under the app the same three rows point at the app's own controls instead:
|
||||
// New Session for "Start fresh", the top bar's dashboard button for "Carry
|
||||
// on", and no stray command to copy into a shell that is not there.
|
||||
test("under the app, Before you close this points at New Session, and never at a \"new conversation\" that does not exist there", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 1" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
const main = s.page.locator("#main");
|
||||
s.post({ finish: { headline: "A skill next", command: "/plan2code-4-finalize" } });
|
||||
await main.getByRole("heading", { name: "A skill next" }).waitFor();
|
||||
const guide = closeGuide(s);
|
||||
const text = await textOf(guide);
|
||||
assert.ok(text.includes("Press New Session at the top of the window to start the agent fresh."), "Start fresh points at New Session");
|
||||
assert.ok(text.includes("Paste the command above into the terminal panel, or start from the dashboard with /plan2code."), "Carry on names the terminal panel");
|
||||
assert.ok(!text.includes("new session") && !text.includes("new conversation"), "no classic-mode wording under the app");
|
||||
// The extra "To start something else..." paragraph a classic finish also
|
||||
// shows is left out here: the row above already says it once.
|
||||
assert.equal(await main.getByText("To start something else, run").count(), 0, "no second mention of the same command");
|
||||
|
||||
// Nothing left to run: the all-done shape still offers the command (the
|
||||
// app's terminal panel is a real terminal the agent runs in, so pasting it
|
||||
// there works), worded for the one panel rather than a new conversation.
|
||||
s.post({ finish: { headline: "AGENTS.md is updated" } });
|
||||
await main.getByText(/paste .* into the terminal panel below/).waitFor();
|
||||
assert.ok(await main.locator("code").filter({ hasText: /^\/plan2code --web$/ }).count(), "the command is still offered");
|
||||
|
||||
// The live dashboard button's own note, under it, also points at New
|
||||
// Session instead of typing `/clear` by hand.
|
||||
s.post({ finish: { headline: "A skill next, with a live dashboard offer", command: "/plan2code-4-finalize", dashboard: true } });
|
||||
await main.getByRole("button", { name: "Back to the dashboard" }).waitFor();
|
||||
assert.ok(await main.getByText("press New Session at the top of the window for a clean start instead").count(), "the dashboard note points at New Session");
|
||||
assert.equal(await main.getByText("type `/clear`", { exact: false }).count(), 0, "no hand-typed /clear under the app");
|
||||
});
|
||||
|
||||
// Once the console server itself is gone (not just finished), the review and
|
||||
// dashboard offers' own "new conversation" fallback text must say the same:
|
||||
// paste into the terminal panel, under the app, and never claim a command is
|
||||
// needed to reconnect, since the app's own bar already does that on its own.
|
||||
test("under the app, a gone session's review and dashboard fallbacks name the terminal panel, and reconnect needs no command", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "quick-task",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 1" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
clock: true,
|
||||
});
|
||||
s.post({ finish: OFFERS });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Quick task done" }).waitFor();
|
||||
await s.page.locator("#main").getByRole("button", { name: "Review it now" }).click();
|
||||
collect(s);
|
||||
await stopServer(s);
|
||||
for (let i = 0; i < 20 && !(await s.page.locator("#planny.is-gone").count()); i++) {
|
||||
await s.page.clock.fastForward(GONE_AFTER_MS);
|
||||
await new Promise((r) => setTimeout(r, 250));
|
||||
}
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByText(/paste this into the terminal panel/i).first().waitFor();
|
||||
assert.equal(await main.getByText(/new conversation/i).count(), 0, "no classic-mode wording under the app");
|
||||
await main.getByText("Plan2Code will try to reconnect the console on its own; if it cannot, the app's bar offers Reconnect the console.").waitFor();
|
||||
assert.equal(await main.getByText(/run this in a new conversation/i).count(), 0, "no stray reconnect command under the app");
|
||||
});
|
||||
|
||||
// What a person sees break: the triangle leaving answers behind, or sending a
|
||||
// finish-style stop instead of the way home.
|
||||
test("the top bar's back triangle asks first, then sends __dashboard with the typed answers and the home reply", async (t) => {
|
||||
@@ -607,3 +905,18 @@ test("Back to default in Preferences returns the theme to follow the system and
|
||||
await s.page.waitForFunction(() => !document.documentElement.hasAttribute("data-theme"));
|
||||
assert.equal(await s.page.locator('input[name="looks-theme"][value="system"]').isChecked(), true, "the system choice is ticked again");
|
||||
});
|
||||
|
||||
// Planny's own spoken line said "close this tab": under the app there is no
|
||||
// tab, only the one window.
|
||||
test("under the app, Planny's finished line says to close the window, not the tab", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "implement",
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 1" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
});
|
||||
s.post({ finish: { headline: "All done", dashboard: true } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "All done" }).waitFor();
|
||||
const line = await lineSays(s, /close this window/);
|
||||
assert.doesNotMatch(line, /close this tab/, "no classic-mode wording under the app");
|
||||
});
|
||||
@@ -256,6 +256,10 @@ test("a working agent's line falls back to its headline note", () => {
|
||||
|
||||
test("the terminal line is the exact text every command hands back", () => {
|
||||
assert.equal(terminalLine("http://127.0.0.1:1/s/abc/"), "→ Look at the web console: http://127.0.0.1:1/s/abc/");
|
||||
// Under the desktop app the page is beside the terminal: no address to print.
|
||||
const inApp = terminalLine("http://127.0.0.1:1/s/abc/", { PLAN2CODE_IN_APP: "1" });
|
||||
assert.equal(inApp.includes("127.0.0.1"), false, "no address under the app");
|
||||
assert.equal(terminalLine("http://127.0.0.1:1/s/abc/", {}), "→ Look at the web console: http://127.0.0.1:1/s/abc/");
|
||||
});
|
||||
|
||||
test("repoRoots reads the branch off disk: named, detached, a linked worktree's own, and none", () => {
|
||||
@@ -849,3 +853,36 @@ test("the built skills tree serves the same /app.css as the source console", asy
|
||||
execFileSync(process.execPath, [path.join(built, "console.mjs"), "stop", "--session", json.sid], { env: ENV, cwd: ROOT });
|
||||
}
|
||||
});
|
||||
|
||||
// The desktop app's webview opens no new windows, so a link the page shows
|
||||
// there goes through /open-link, which hands it to the default browser. Only
|
||||
// http and https: anything else would be the page asking the machine to run
|
||||
// whatever a link names.
|
||||
test("/open-link takes an http or https link and refuses every other kind", async () => {
|
||||
const res = cli(["open", "--workflow", "git", "--no-open"]);
|
||||
const m = res.json.url.match(/^(http:\/\/127\.0\.0\.1:\d+)\/s\/([^/]+)\//);
|
||||
const cookie = cookieFor(m[1], m[2]);
|
||||
const open = (url) =>
|
||||
fetch(`${m[1]}/open-link`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie, origin: m[1], connection: "close" },
|
||||
body: JSON.stringify({ url }),
|
||||
});
|
||||
try {
|
||||
const ok = await open("https://github.com/jparkerweb/plan2code/compare/main...feature?expand=1");
|
||||
assert.equal(ok.status, 200);
|
||||
assert.deepEqual(await ok.json(), { ok: true, url: "https://github.com/jparkerweb/plan2code/compare/main...feature?expand=1" });
|
||||
for (const bad of ["javascript:alert(1)", "file:///C:/Windows/System32/calc.exe", "ms-settings:", "not a link", "", 42]) {
|
||||
const no = await open(bad);
|
||||
assert.equal(no.status, 400, `${JSON.stringify(bad)} was not refused`);
|
||||
}
|
||||
const foreign = await fetch(`${m[1]}/open-link`, {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json", cookie, origin: "https://evil.example", connection: "close" },
|
||||
body: JSON.stringify({ url: "https://example.com/" }),
|
||||
});
|
||||
assert.notEqual(foreign.status, 200, "another site's page cannot open links through the console");
|
||||
} finally {
|
||||
cli(["stop", "--session", res.json.sid]);
|
||||
}
|
||||
});
|
||||
@@ -188,7 +188,7 @@ const ROUTE_ORDER = [
|
||||
"/looks", "/looks", "/subagents", "/pr-host", "/models", "/models", "/cleanup", "/upload",
|
||||
"/notepad", "/notepad/text", "/notepad/image", "/notepad/thumb", "/notepad/image/delete", "/notepad/tab",
|
||||
"/notepad/tab/rename", "/notepad/tab/delete", "/notepad/tab/order", "/notepad/tab/last", "/notepad/images/",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/chat", "/chat/decision", "/workspace",
|
||||
"/attachments/", "/shots/", "/uploads/", "/submit", "/open-link", "/chat", "/chat/decision", "/workspace",
|
||||
"WORKSPACE_EDITS", "/workspace/scope", "/workspace/browse", "/cancel", "/ping", "/bye",
|
||||
];
|
||||
|
||||
@@ -236,9 +236,19 @@ function appJsReaders(dir) {
|
||||
.filter((f) => f.endsWith(".mjs") && f !== "test-web-console-shape.mjs" && !MAY_NAME_APP_JS.has(f))
|
||||
.filter((f) => {
|
||||
const text = fs.readFileSync(path.join(dir, f), "utf8");
|
||||
// A bare readFileSync/readFile only counts against the web console's
|
||||
// own public/app.js, named somewhere in the same statement: otherwise
|
||||
// this would also catch a test reading some other app.js entirely,
|
||||
// such as plan2code-app/ui/app.js (the desktop app's, a different file
|
||||
// with its own shape rules in its own test). publicSource() implies
|
||||
// the public dir by its own name, so any app.js it is handed counts.
|
||||
const oneStatement = text
|
||||
.split(";")
|
||||
.some((statement) => /\b(readFileSync|readFile|publicSource)\s*\(/.test(statement) && /["'/]app\.js["']/.test(statement));
|
||||
.some(
|
||||
(statement) =>
|
||||
/["'/]app\.js["']/.test(statement) &&
|
||||
(/\bpublicSource\s*\(/.test(statement) || (/\b(readFileSync|readFile)\s*\(/.test(statement) && /\bpublic\b/.test(statement)))
|
||||
);
|
||||
const handedToAHelper = /\w\(\s*["'](?:(?:src\/web-console\/)?public\/)?app\.js["']\s*\)/.test(text);
|
||||
const publicPath = /["']public["']\s*,\s*["']app\.js["']|\bpublic\/app\.js/.test(text) && /\breadFile(Sync)?\b/.test(text);
|
||||
return oneStatement || handedToAHelper || publicPath;
|
||||
|
||||
@@ -25,6 +25,7 @@ import fs from "node:fs";
|
||||
import os from "node:os";
|
||||
import path from "node:path";
|
||||
import { createRequire } from "node:module";
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { ROOT, cli, poseTemplate } from "./web-console-test-helpers.mjs";
|
||||
import { SUBAGENT_WORKFLOWS } from "../src/web-console/public/subagents.js";
|
||||
import { TEMPLATE_WORKFLOWS } from "../src/web-console/public/starters.js";
|
||||
@@ -380,3 +381,19 @@ test("Implement's card launches Implement + Review when Review is ticked", () =>
|
||||
const quick = SKILL_CATALOG.find((e) => e.skill === "plan2code-quick-task");
|
||||
assert.equal(launchVariant(quick, true), quick, "a card with no Review box is unchanged");
|
||||
});
|
||||
|
||||
test("helper-strength.md ships in the five skills that start helpers, and in no other", () => {
|
||||
// npm test has just built skills/; a direct run builds it so the check never reads a stale tree.
|
||||
if (process.env.npm_lifecycle_event !== "test") {
|
||||
execFileSync(process.execPath, [path.join(ROOT, "install.js"), "--build-skills"], { stdio: "ignore" });
|
||||
}
|
||||
const built = path.join(ROOT, "skills");
|
||||
const having = fs.readdirSync(built).filter((dir) => fs.existsSync(path.join(built, dir, "references", "helper-strength.md")));
|
||||
assert.deepEqual(having.sort(), [
|
||||
"plan2code-0-pathfinder",
|
||||
"plan2code-3-implement",
|
||||
"plan2code-3-implement-review",
|
||||
"plan2code-quick-task",
|
||||
"plan2code-review",
|
||||
]);
|
||||
});
|
||||
@@ -43,6 +43,7 @@ test("state: the rest of the shared state starts as app.js always started it", (
|
||||
wsFrame: null,
|
||||
meterFrame: null,
|
||||
updateFrame: null,
|
||||
inApp: false,
|
||||
subagentsFrame: null,
|
||||
overview: { key: null, text: null },
|
||||
wake: null,
|
||||
|
||||
@@ -8,7 +8,7 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { defaultInstruction, offered } from "../src/web-console/public/subagents.js";
|
||||
import { defaultInstruction, offered, onLines, STRENGTH_LINES, STRENGTHS } from "../src/web-console/public/subagents.js";
|
||||
import { readSubagentCursor } from "../src/web-console/settings.mjs";
|
||||
import {
|
||||
ROOT,
|
||||
@@ -64,13 +64,13 @@ test("subagents: a change reaches the next pickup once, last in reply, edits nam
|
||||
assert.equal(on.status, 200);
|
||||
assert.equal(on.body.ok, true);
|
||||
const rev = on.body.setting.revision;
|
||||
assert.deepEqual(on.body.setting, { workflow: "implement", on: true, instruction: null, max: 3, revision: rev });
|
||||
assert.deepEqual(on.body.setting, { workflow: "implement", on: true, instruction: null, max: 3, strength: "balanced", revision: rev });
|
||||
|
||||
assert.equal((await ask(s, "Which files does the first task touch?")).status, 200);
|
||||
assert.equal((await addFolder(s, { path: extra })).status, 200);
|
||||
const first = await submitAndWait(s);
|
||||
assert.equal(first.status, 0);
|
||||
assert.deepEqual(first.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement") });
|
||||
assert.deepEqual(first.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement"), strength: "balanced" });
|
||||
const reply = first.json.reply;
|
||||
const at = (re) => reply.search(re);
|
||||
assert.ok(at(/^Export format: a$/m) === 0, reply);
|
||||
@@ -149,7 +149,7 @@ test("subagents: a resume re-states an on setting once, says nothing when off, a
|
||||
const rev = (await setSubagents(s, ON3)).body.setting.revision;
|
||||
const resumed = cli(["open", "--resume", s.sid, "--no-open"]);
|
||||
assert.equal(resumed.json.ok, true);
|
||||
assert.deepEqual(resumed.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement") });
|
||||
assert.deepEqual(resumed.json.subagents, { state: "on", revision: rev, max: 3, instruction: defaultInstruction("implement"), strength: "balanced" });
|
||||
assert.equal(subagentLines(resumed.json.reply)[0], `Subagents: on (revision ${rev}) — a console setting, not typed by the person.`);
|
||||
assert.ok(resumed.json.reply.split("\n").every((l, i) => i === 0 || l.startsWith(" ")), "only the block's lines");
|
||||
assert.equal("subagents" in (await submitAndWait(s)).json, false, "the next pickup carries nothing");
|
||||
@@ -254,6 +254,7 @@ test("subagents: a workflow without the switch refuses it, bad bodies name the f
|
||||
assert.deepEqual(await setSubagents(s, { ...ON3, max: 21 }), { status: 400, body: { error: "max" } });
|
||||
assert.deepEqual(await setSubagents(s, { ...ON3, instruction: "x".repeat(2001) }), { status: 400, body: { error: "too-long" } });
|
||||
assert.deepEqual(await setSubagents(s, { ...ON3, on: "yes" }), { status: 400, body: { error: "bad" } });
|
||||
assert.deepEqual(await setSubagents(s, { ...ON3, strength: "fast" }), { status: 400, body: { error: "strength" } });
|
||||
|
||||
assert.equal((await frameSubagents(s)).supported, true, "this copy's open carries caps");
|
||||
fs.appendFileSync(path.join(s.session, "events.ndjson"), JSON.stringify({ at: new Date().toISOString(), type: "open", resumed: true }) + "\n");
|
||||
@@ -272,6 +273,60 @@ test("subagents: a workflow without the switch refuses it, bad bodies name the f
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: a strength-only change reaches the agent once, with its profile line", async () => {
|
||||
const s = subagentsSession();
|
||||
try {
|
||||
const before = (await frameSubagents(s)).revision;
|
||||
const thrifty = await setSubagents(s, { ...ON3, strength: "thrifty" });
|
||||
assert.equal(thrifty.status, 200);
|
||||
assert.equal(thrifty.body.setting.revision, before + 1, "a strength alone is a change");
|
||||
assert.equal(thrifty.body.setting.strength, "thrifty");
|
||||
const picked = await submitAndWait(s);
|
||||
assert.equal(picked.json.subagents.strength, "thrifty");
|
||||
assert.ok(picked.json.reply.endsWith(["", STRENGTH_LINES.thrifty, "At most 3 helpers at once."].join("\n ")), picked.json.reply);
|
||||
assert.equal((await frameSubagents(s)).strength, "thrifty");
|
||||
|
||||
const again = await setSubagents(s, { ...ON3, strength: "thrifty" });
|
||||
assert.equal(again.body.setting.revision, before + 1, "the same strength again bumps nothing");
|
||||
assert.equal("subagents" in (await submitAndWait(s)).json, false);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: a setting saved before strength existed reads as balanced and bumps nothing", async () => {
|
||||
const s = subagentsSession();
|
||||
try {
|
||||
assert.equal((await setSubagents(s, { ...ON3, max: 4 })).status, 200);
|
||||
const strip = (file, entries) => {
|
||||
const saved = JSON.parse(fs.readFileSync(file, "utf8"));
|
||||
for (const entry of entries(saved)) delete entry.strength;
|
||||
fs.writeFileSync(file, JSON.stringify(saved));
|
||||
};
|
||||
strip(SUBAGENTS_STORE, (store) => Object.values(store).flatMap((project) => Object.values(project)));
|
||||
strip(path.join(s.session, "subagents-setting.json"), (setting) => [setting]);
|
||||
const rev = JSON.parse(fs.readFileSync(path.join(s.session, "subagents-setting.json"), "utf8")).revision;
|
||||
|
||||
cli(["stop", "--session", s.sid]);
|
||||
const resumed = sessionUrl(cli(["open", "--resume", s.sid, "--no-open"]).json.url);
|
||||
const frame = (await (await fetch(`${resumed.base}/state`, { headers: { cookie: resumed.cookie, connection: "close" } })).json()).subagents;
|
||||
assert.deepEqual([frame.max, frame.strength, frame.revision], [4, "balanced", rev], "an upgrade alone bumps nothing");
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
test("subagents: every strength renders its own profile line, and a missing one is balanced", () => {
|
||||
const base = { revision: 1, max: 3, instruction: "Split by file." };
|
||||
for (const strength of STRENGTHS) {
|
||||
const lines = onLines({ ...base, strength });
|
||||
assert.equal(lines[lines.length - 2], " " + STRENGTH_LINES[strength], strength);
|
||||
assert.equal(lines.filter((l) => l.includes("Helper strength:")).length, 1, strength);
|
||||
}
|
||||
assert.equal(new Set(STRENGTHS.map((k) => STRENGTH_LINES[k])).size, STRENGTHS.length, "four different lines");
|
||||
assert.equal(onLines(base).at(-2), " " + STRENGTH_LINES.balanced);
|
||||
});
|
||||
|
||||
/* ------------------------------------------ subagents: helper reports */
|
||||
|
||||
|
||||
@@ -334,6 +389,30 @@ test("helpers: every malformed report exits 3 naming the helper, and nothing is
|
||||
}
|
||||
});
|
||||
|
||||
test("helpers: a reported strength and effort are kept, other values exit 3 naming the helper, and both stay optional", () => {
|
||||
const s = consoleSession(["--workflow", "implement"]);
|
||||
try {
|
||||
const ran = reportedHelper("h1", { strength: "standard", effort: "medium" });
|
||||
assert.equal(postPatch(s, { helpers: [ran] }).status, 0);
|
||||
assert.deepEqual(readState(s.session).helpers, [ran], "strength and effort are kept as reported");
|
||||
const statePath = path.join(s.session, "state.json");
|
||||
const before = fs.readFileSync(statePath, "utf8");
|
||||
for (const [name, extra, re] of [
|
||||
["unknown strength", { strength: "huge" }, /helper "h2": strength must be light, standard, strongest or inherit/],
|
||||
["unknown effort", { effort: "max" }, /helper "h2": effort must be low, medium or high/],
|
||||
]) {
|
||||
const res = postPatch(s, { helpers: [reportedHelper("h2", extra)] }, { expectFail: true });
|
||||
assert.equal(res.status, 3, name);
|
||||
assert.match(res.stderr, re, name);
|
||||
assert.equal(fs.readFileSync(statePath, "utf8"), before, `${name}: nothing written`);
|
||||
}
|
||||
assert.equal(postPatch(s, { helpers: [reportedHelper("h3")] }).status, 0, "a helper without the fields still posts");
|
||||
assert.deepEqual(readState(s.session).helpers.map((h) => h.id), ["h1", "h3"]);
|
||||
} finally {
|
||||
cli(["stop", "--session", s.sid]);
|
||||
}
|
||||
});
|
||||
|
||||
test("docs: a doc's version never goes back; the same version again is fine, and a hop starts every doc fresh", () => {
|
||||
const s = consoleSession(["--workflow", "implement"]);
|
||||
try {
|
||||
|
||||
@@ -26,7 +26,26 @@ import { readChat } from "../src/web-console/inbox.mjs";
|
||||
export const ROOT = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
|
||||
export const CONSOLE_CLI = path.join(ROOT, "src", "web-console", "console.mjs");
|
||||
|
||||
export const HOME = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
|
||||
// Canonicalised the same way server.mjs canonicalises a session dir (DIR,
|
||||
// server.mjs): on a machine whose %TEMP% itself resolves through an 8.3
|
||||
// short name (seen in the wild on Windows), a server started later writes
|
||||
// `state.worktree` in its realpath'd form, while anything in a test that
|
||||
// builds a path under HOME without this would use the short one. Two
|
||||
// spellings of the same folder hash to two different keys wherever a test
|
||||
// writes through a path-keyed store (notepads.mjs, workspace.mjs,
|
||||
// settings.mjs) ahead of the server itself touching that path, so the
|
||||
// server's own later read finds nothing there. Resolving it once, here,
|
||||
// keeps every path this file hands out consistent with what the server
|
||||
// will compute.
|
||||
const rawHome = fs.mkdtempSync(path.join(os.tmpdir(), "p2c-console-test-"));
|
||||
export const HOME = (() => {
|
||||
for (const real of [fs.realpathSync.native, fs.realpathSync]) {
|
||||
try {
|
||||
return real(rawHome);
|
||||
} catch {}
|
||||
}
|
||||
return rawHome;
|
||||
})();
|
||||
export const MODELS_DIR = path.join(HOME, "plan2code");
|
||||
// Handoffs are written outside every repo, under ~/.plan2code/handoffs, so
|
||||
// each test file gets its own throwaway folder for them too.
|
||||
|
||||
@@ -58,6 +58,8 @@ The only type an agent resolves alone, and the only type that may run several at
|
||||
|
||||
One subagent per research question. Do not read the docs yourself in the main session — the point is that the main session's context stays clean for the decision work.
|
||||
|
||||
Start each research subagent at standard strength and medium effort per `helper-strength.md` (its fallback order applies; a re-fired subagent from `refire` goes one strength up).
|
||||
|
||||
The subagent's brief must carry, verbatim:
|
||||
|
||||
1. The absolute path of the question file it owns.
|
||||
|
||||
@@ -54,7 +54,7 @@ Run Review Mode with this explicit scope:
|
||||
- Use overview.md and the active phase file for spec-compliance context; they do not broaden scope to other phases.
|
||||
- Read related callers, dependencies, and project files when needed to verify a finding, but do not turn them into unrelated review targets.
|
||||
- Review all changed files completely and apply the full focused-review depth required by Review Mode.
|
||||
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
|
||||
- Review Mode's helper rule applies: a fresh helper runs the analysis when available, at the strength `helper-strength.md` gives for the phase's review (standard and high, or strongest and high when the phase touches security, auth or data), this session verifies every finding, and the Stage 4 report carries the Reviewed by line. The helper's brief carries the phase's `phase-X.md` and its change set only, never Stage 1's work notes.
|
||||
|
||||
Override Review Mode's completion and session-end behavior:
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Reviewer Brief
|
||||
> Part of plan2code-review: filled in by the main session at Step 3 (Analyze) and handed, whole, to ONE fresh helper.
|
||||
|
||||
Fill every `{{...}}` field, drop the lines that do not apply, and send the filled text as the helper's entire instructions. Never add the builder's conversation, reasoning, work notes or self-review: the helper's value is that it did not see them.
|
||||
Fill every `{{...}}` field, drop the lines that do not apply, and send the filled text as the helper's entire instructions. Never add the builder's conversation, reasoning, work notes or self-review: the helper's value is that it did not see them. Start the helper at the strength and effort `helper-strength.md` gives for review analysis, following its fallback order.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -93,7 +93,7 @@ Three levels -- auto-detected, always respect explicit user override:
|
||||
|
||||
### Step 3: Analyze
|
||||
|
||||
**Who reviews:** when your tool can start a helper (subagent) and helpers are not switched off for this skill run, fill references/reviewer-brief.md and hand the analysis to ONE fresh helper; do not analyze in parallel. The brief carries the review-depth references, the dimensions and the finding format: send only the filled brief. With no helper, or one that fails or returns nothing usable, run this step in this session.
|
||||
**Who reviews:** when your tool can start a helper (subagent) and helpers are not switched off for this skill run, fill references/reviewer-brief.md and hand the analysis to ONE fresh helper; do not analyze in parallel. The brief carries the review-depth references, the dimensions and the finding format: send only the filled brief. Start the helper at the strength and effort references/helper-strength.md gives for review analysis (standard and high for a focused scope; strongest and high for branch or full scope, or changes touching security, auth or data), following its fallback order. With no helper, or one that fails or returns nothing usable, run this step in this session.
|
||||
|
||||
**Load review depth (conditional on scope):**
|
||||
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
# Helper Strength
|
||||
> Shared by the skills that start helpers (subagents): Pathfinder, Quick Task, Implement, Implement + Review and Review. Read it when you first start a helper in a session. Never invoked as a skill.
|
||||
|
||||
## The words
|
||||
|
||||
- **Strength:** `light`, `standard`, `strongest` or `inherit`.
|
||||
- `light`: your tool's fastest, cheapest model class.
|
||||
- `strongest`: its most capable model class.
|
||||
- `standard`: the one between them, often your tool's default.
|
||||
- `inherit`: the helper runs with the session's own model.
|
||||
- **Effort:** `low`, `medium` or `high`, where your tool lets you set how hard a model thinks.
|
||||
|
||||
Never write a model or vendor name in a brief, a report or a file, and never invent a model id: map the word to whatever your tool offers.
|
||||
|
||||
## Picking a strength
|
||||
|
||||
| Helper's job | Strength | Effort |
|
||||
|---|---|---|
|
||||
| Lookups, reading code, checking docs, recon | light | low |
|
||||
| Build task in 1 or 2 files, with the change spelled out in the task | light | medium |
|
||||
| Build task across several files, integration work, debugging | standard | medium |
|
||||
| Build task needing a design decision the spec leaves open | strongest (or keep it yourself) | high |
|
||||
| Pathfinder research question, sketch | standard | medium |
|
||||
| Review analysis, focused scope | standard | high |
|
||||
| Review analysis, branch or full scope, or touching security, auth or data | strongest | high |
|
||||
|
||||
Decide from these signals: how many files the job touches, whether the task spells out the change, whether a design decision is still open, and the review's scope and risk. Never decide from how hard the task feels.
|
||||
|
||||
## Floor and escalation
|
||||
|
||||
- A review helper never runs below `standard`.
|
||||
- A retry, after a helper fails or after its work fails the phase's tests, goes one strength up and at least `medium` effort. Never retry at the same strength.
|
||||
- When a `strongest` helper fails, its task comes back to you.
|
||||
|
||||
## Setting it
|
||||
|
||||
In this order:
|
||||
|
||||
1. Your tool accepts a model or effort setting when it starts a helper: set the closest match.
|
||||
2. It lets you choose a helper profile or agent type instead: pick the one that matches.
|
||||
3. Neither: start the helper without one, and it inherits.
|
||||
|
||||
Set it explicitly wherever you can. A helper left unset usually inherits the session's most capable and most expensive model.
|
||||
|
||||
## The person's choice (web console)
|
||||
|
||||
On the web console the person picks a profile in the Subagents dialog. A `Helper strength:` line in a `Subagents:` block replaces the Balanced default:
|
||||
|
||||
| Choice | Effect |
|
||||
|---|---|
|
||||
| Balanced (default) | The table as written |
|
||||
| Thrifty | One step lighter in strength and effort; reviews never below standard |
|
||||
| Best | Strongest and high effort for everything except lookups, which stay light |
|
||||
| Match my session | No model or effort set on any helper, whatever the skill files say |
|
||||
|
||||
## Reporting
|
||||
|
||||
On the web console, report each helper's `strength` and `effort` as it actually ran (`console-subagents.md`, Reporting helpers). Report `inherit` when you could not set it. When `console-subagents.md` does not list those two fields yet, your console is older than this file: leave them out, since it ignores them.
|
||||
@@ -51,7 +51,7 @@ 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
|
||||
May also print subagents: { state, revision, max, instruction, strength } 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 | -> [--wait <N>]
|
||||
@@ -66,9 +66,9 @@ port, and the filesystem as transport; this CLI is the whole agent surface.
|
||||
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. A patch may also
|
||||
carry helpers: [{ id, title, ask, state, result? }] or one
|
||||
{ id: "alone", alone: true }, merged by id, for the Subagents tab
|
||||
(help subagents).
|
||||
carry helpers: [{ id, title, ask, state, result?, strength?,
|
||||
effort? }] or one { id: "alone", alone: true }, merged by id, for
|
||||
the Subagents tab (help subagents).
|
||||
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
|
||||
|
||||
@@ -22,11 +22,21 @@ 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-subagents.md); 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.
|
||||
Match each helper's strength and effort to its job, as helper-strength.md says; when your tools cannot set them, start the helper without them.
|
||||
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. Pick each helper's strength and effort from helper-strength.md's table: light for a 1-2 file task the task file spells out, standard for multi-file or debugging work.
|
||||
Helper strength: balanced (the table in helper-strength.md as written).
|
||||
At most 3 helpers at once.
|
||||
```
|
||||
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…" }`.
|
||||
beside `"subagents": { "state": "on", "revision": 2, "max": 3, "instruction": "…", "strength": "balanced" }`.
|
||||
The `Helper strength:` line carries the person's profile, and replaces the
|
||||
Balanced default when they pick another:
|
||||
|
||||
- `balanced`: the table in `helper-strength.md` as written (the default).
|
||||
- `thrifty`: one step lighter in strength and effort; reviews never below standard.
|
||||
- `best`: strongest and high effort for every helper except lookups, which stay light.
|
||||
- `session`: set no model or effort on any helper.
|
||||
|
||||
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.`
|
||||
@@ -39,6 +49,9 @@ card, and it is never recorded under `specs/`.
|
||||
- **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.
|
||||
- **Strength:** start each helper at the strength and effort
|
||||
`helper-strength.md` (in the skill's `references/`) gives for its job,
|
||||
following its fallback order. Read it when you first start a helper.
|
||||
- **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.
|
||||
@@ -56,13 +69,16 @@ 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": "h2", "title": "Check the tests", "ask": "Run the subagents tests and report failures.", "state": "done", "result": "All 9 pass.", "strength": "light", "effort": "low" }
|
||||
] }
|
||||
```
|
||||
|
||||
- `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. Anything else is exit `3`, and
|
||||
is the one line you add once a helper ends. `strength` (`light`,
|
||||
`standard`, `strongest` or `inherit`) and `effort` (`low`, `medium` or
|
||||
`high`) are optional: report what the helper actually ran with, and
|
||||
`inherit` when its strength could not be set. Anything else is exit `3`, and
|
||||
the house rules on completion markers and metric-like words cover `title`,
|
||||
`ask` and `result`.
|
||||
- Merged by `id`: post a helper again with its new `state` and `result` and it
|
||||
|
||||
@@ -80,7 +80,9 @@ terminal — that path loses nothing, and they can switch either way at any time
|
||||
first so the page says what you are doing.
|
||||
4. Tell the person, in one line, the link and how many questions are waiting.
|
||||
While the session is open, end every terminal message with the latest
|
||||
`terminalLine`, verbatim.
|
||||
`terminalLine`, verbatim. When `open` printed `"inApp":true` the page is
|
||||
already in the desktop app's window: never print the link (here, after a
|
||||
resume or anywhere else), only the count; `terminalLine` leaves it out too.
|
||||
|
||||
Keep `sid`: every later command takes `--session <sid>`.
|
||||
|
||||
|
||||
@@ -192,7 +192,11 @@ export function appendEvent(dir, event) {
|
||||
// past the stale age, so a writer always gets in eventually.
|
||||
export const STATE_LOCK_FILE = "state.json.lock";
|
||||
const LOCK_STALE_MS = 5000;
|
||||
const LOCK_WAIT_MS = 7000;
|
||||
// A pile-up of many writers (a burst of concurrent `post`s) queues behind
|
||||
// each other's hold, milliseconds long apiece; 7s left too little headroom
|
||||
// for that queue to drain under real machine load, throwing "busy" on a
|
||||
// writer that was never going to be denied, just slow to get its turn.
|
||||
const LOCK_WAIT_MS = 20000;
|
||||
|
||||
function lockStale(lock) {
|
||||
try {
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Plan2Code Web Console - hands an http or https link to the person's default browser, for the page inside the desktop app; defines only.
|
||||
//
|
||||
// The app's webview opens no new windows, so a link the page shows there (Open
|
||||
// pull request, a link in a doc, the feedback button) would do nothing. The
|
||||
// page posts it to /open-link instead, and this opens it. Never through a
|
||||
// shell: the link is the page's to name, so it travels as one argument to a
|
||||
// program that only opens links.
|
||||
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
/** The link to open, normalised, or null when it is not a plain http or https link. */
|
||||
export function linkToOpen(raw) {
|
||||
if (typeof raw !== "string" || raw.length > 4096) return null;
|
||||
let url;
|
||||
try {
|
||||
url = new URL(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
return url.protocol === "http:" || url.protocol === "https:" ? url.href : null;
|
||||
}
|
||||
|
||||
/** Opens `href` (from linkToOpen) in the default browser; false when it could not start one. */
|
||||
export function openLink(href) {
|
||||
// Tests, and a person who turned the console's own browser launches off.
|
||||
if (process.env.NO_BROWSER || process.env.PLAN2CODE_NO_BROWSER) return true;
|
||||
const [cmd, args] =
|
||||
process.platform === "win32"
|
||||
? ["rundll32.exe", ["url.dll,FileProtocolHandler", href]]
|
||||
: process.platform === "darwin"
|
||||
? ["open", [href]]
|
||||
: [process.env.BROWSER || "xdg-open", [href]];
|
||||
try {
|
||||
const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true });
|
||||
child.on("error", () => {});
|
||||
child.unref();
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -319,6 +319,9 @@ export function finishPaused(fin) {
|
||||
// read as one sentence.
|
||||
export const ALL_DONE_LEAD = "All done, nothing left to run.";
|
||||
export const ALL_DONE_REST = "To start something else, run `/plan2code` in a new conversation to open the dashboard.";
|
||||
// The same line for the desktop app: there is no separate "new conversation"
|
||||
// to paste this into, only the one terminal panel the agent already runs in.
|
||||
export const ALL_DONE_REST_IN_APP = "To start something else, paste `/plan2code` into the terminal panel below to open the dashboard.";
|
||||
export const DASHBOARD_COMMAND = "/plan2code";
|
||||
|
||||
/**
|
||||
@@ -440,6 +443,10 @@ export const CHANGELOG_REPLY = "Update the CHANGELOG before I commit: open Chang
|
||||
// conversation, which carries a long skill's context into the next one.
|
||||
export const DASHBOARD_NOTE =
|
||||
"This picks up in the same conversation. That's fine after a quick or small skill; after a long one, type `/clear` in your terminal and run `/plan2code` for a clean start.";
|
||||
// Under the app, a clean start is New Session, not typing `/clear` by hand:
|
||||
// it also leaves the dashboard a handoff brief of where this step left off.
|
||||
export const DASHBOARD_NOTE_IN_APP =
|
||||
"This picks up in the same conversation. That's fine after a quick or small skill; after a long one, press New Session at the top of the window for a clean start instead.";
|
||||
|
||||
/**
|
||||
* Whether a finish offers the way back to the dashboard. The agent opts in
|
||||
@@ -1016,6 +1023,8 @@ export function nextOpenAfter(openIds, staged, sent, currentId) {
|
||||
export const APPROVAL_TIP =
|
||||
"Your agent may pause for approvals in the terminal. A hands-off mode (e.g. `auto` mode in Claude Code, `smart` mode in Devin) can help avoid that, but additional attention may still be required.";
|
||||
export const APPROVAL_HINT = "Still working, or waiting on an approval in your terminal?";
|
||||
// The same line under the desktop app, where the terminal is the window's own panel.
|
||||
export const APPROVAL_HINT_IN_APP = "Still working, or waiting on an approval in the terminal panel?";
|
||||
export const APPROVAL_HINT_MS = 30_000;
|
||||
// When a working agent's silence turns into "has not checked in".
|
||||
export const STALE_MS = 2 * 60 * 1000;
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
// Plan2Code Web Console - the few messages this page sends the desktop app that frames it, and which links it must open another way there; defines only.
|
||||
//
|
||||
// Each one is a named request with no free text in it, so the app decides what
|
||||
// it does: a page can ask for "continue" to be typed, never for anything else.
|
||||
|
||||
/** True inside a frame: the desktop app's window, the only place that frames this page. */
|
||||
export function framed() {
|
||||
return Boolean(window.parent) && window.parent !== window;
|
||||
}
|
||||
|
||||
/**
|
||||
* True for a link that leaves the console for the web: http or https on
|
||||
* another origin. Inside the app those open through /open-link, since the
|
||||
* app's window opens no new ones; the console's own files stay put.
|
||||
*/
|
||||
export function linkLeavesPage(href, origin) {
|
||||
let url;
|
||||
try {
|
||||
url = new URL(href, origin);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
return (url.protocol === "http:" || url.protocol === "https:") && url.origin !== origin;
|
||||
}
|
||||
|
||||
/** Post `message` to the frame's parent, as `{ plan2code: kind, ...extra }`; nothing outside a frame. */
|
||||
export function tellApp(kind, extra = {}) {
|
||||
if (!framed()) return;
|
||||
try {
|
||||
window.parent.postMessage({ ...extra, plan2code: kind }, "*");
|
||||
} catch {
|
||||
/* no parent to tell */
|
||||
}
|
||||
}
|
||||
@@ -48,6 +48,7 @@
|
||||
<link rel="modulepreload" href="/subagents.js" />
|
||||
<link rel="modulepreload" href="/mentions.js" />
|
||||
<link rel="modulepreload" href="/favicon.js" />
|
||||
<link rel="modulepreload" href="/app-bridge.js" />
|
||||
<link rel="modulepreload" href="/git-board.js" />
|
||||
<link rel="modulepreload" href="/git-board-view.js" />
|
||||
<link rel="modulepreload" href="/pr-url.js" />
|
||||
@@ -825,12 +826,12 @@
|
||||
<rect class="hd-box" x="304" y="42" width="100" height="64" rx="8" />
|
||||
<rect class="hd-box" x="448" y="42" width="100" height="64" rx="8" />
|
||||
<text class="hd-label" x="66" y="70" text-anchor="middle">You</text>
|
||||
<text class="hd-label small" x="66" y="88" text-anchor="middle">in your browser</text>
|
||||
<text class="hd-label small" x="66" y="88" text-anchor="middle" data-app="in the app">in your browser</text>
|
||||
<text class="hd-label" x="210" y="79" text-anchor="middle">This page</text>
|
||||
<text class="hd-label" x="354" y="70" text-anchor="middle">Small program</text>
|
||||
<text class="hd-label small" x="354" y="88" text-anchor="middle">on 127.0.0.1</text>
|
||||
<text class="hd-label" x="498" y="70" text-anchor="middle">Plan2Code</text>
|
||||
<text class="hd-label small" x="498" y="88" text-anchor="middle">in your terminal</text>
|
||||
<text class="hd-label small" x="498" y="88" text-anchor="middle" data-app="in its terminal panel">in your terminal</text>
|
||||
<path class="hd-line" d="M120 74 H156" marker-start="url(#hd-about-arrow)" marker-end="url(#hd-about-arrow)" />
|
||||
<path class="hd-line" d="M264 74 H300" marker-start="url(#hd-about-arrow)" marker-end="url(#hd-about-arrow)" />
|
||||
<path class="hd-line" d="M408 74 H444" marker-start="url(#hd-about-arrow)" marker-end="url(#hd-about-arrow)" />
|
||||
@@ -840,18 +841,24 @@
|
||||
</figure>
|
||||
<p>
|
||||
A small program running on your own machine, started for you by
|
||||
Plan2Code in your terminal. Nothing here goes over the internet, and
|
||||
<span data-app="Plan2Code in the terminal panel">Plan2Code in your terminal</span>. Nothing here goes over the internet, and
|
||||
there is no account and nothing to install.
|
||||
</p>
|
||||
<h4>On this machine only</h4>
|
||||
<p>
|
||||
<p class="for-browser">
|
||||
The address starts with <strong>127.0.0.1</strong>, which always means
|
||||
"this computer". Nothing you type leaves your machine, and a colleague
|
||||
cannot open your link from theirs. To work through a session together,
|
||||
share your screen.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
The app loads this page from <strong>127.0.0.1</strong>, which always
|
||||
means "this computer". Nothing you type leaves your machine, and the
|
||||
page's address stays inside the app, so there is no link to pass
|
||||
around. To work through a session together, share your screen.
|
||||
</p>
|
||||
<h4>How long it runs</h4>
|
||||
<p>
|
||||
<p class="for-browser">
|
||||
<strong>It stays up while this tab is open.</strong> Close the tab and
|
||||
it shuts itself down <span data-fact="closedTabMinutes">2</span> minutes
|
||||
later. It also stops after <span data-fact="idleMinutes">30</span>
|
||||
@@ -859,19 +866,35 @@
|
||||
<span data-fact="maxLifeHours">4</span> hours regardless. Reopening the same link brings everything back: nothing you
|
||||
typed is kept in the browser alone.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
<strong>It stays up while the app's window shows it.</strong> Close the
|
||||
window and it shuts itself down <span data-fact="closedTabMinutes">2</span>
|
||||
minutes later. It also stops after <span data-fact="idleMinutes">30</span>
|
||||
minutes without hearing from anyone, and after
|
||||
<span data-fact="maxLifeHours">4</span> hours regardless. When it
|
||||
stops, the app's own bar notices and brings it back on the same
|
||||
session, or offers <strong>Reconnect the console</strong>: nothing you
|
||||
typed is kept in the window alone.
|
||||
</p>
|
||||
<h4>Two halves, both running</h4>
|
||||
<p>
|
||||
<p class="for-browser">
|
||||
<strong>The terminal is the other half.</strong> This page collects your
|
||||
answers; Plan2Code, in the terminal you started it from, is what reads
|
||||
them and writes the files. Both have to be running for a question to
|
||||
reach you or an answer to reach it.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
<strong>The terminal panel is the other half.</strong> This page collects
|
||||
your answers; Plan2Code, the agent running in the app's terminal panel,
|
||||
is what reads them and writes the files. Both have to be running for a
|
||||
question to reach you or an answer to reach it.
|
||||
</p>
|
||||
<p id="about-live" class="about-live"></p>
|
||||
<p>
|
||||
<strong>If it stops.</strong> Press Send anyway. Answers are written to
|
||||
disk the moment they leave this page and are held until something
|
||||
collects them, so starting Plan2Code again picks them up where you
|
||||
left off. Nothing is lost by closing this tab either.
|
||||
left off. <span data-app="Nothing is lost by closing the window either.">Nothing is lost by closing this tab either.</span>
|
||||
</p>
|
||||
</section>
|
||||
|
||||
@@ -879,7 +902,7 @@
|
||||
<section class="help-panel" data-tab="stuck">
|
||||
<h3>When something looks stuck</h3>
|
||||
<p class="help-lead">
|
||||
This page and Plan2Code in your terminal are two programs, and either
|
||||
This page and <span data-app="Plan2Code in the terminal panel">Plan2Code in your terminal</span> are two programs, and either
|
||||
can stop without the other. Nothing you have typed is lost either way.
|
||||
</p>
|
||||
<div class="help-callout" role="note">
|
||||
@@ -891,7 +914,7 @@
|
||||
<div>
|
||||
<strong class="help-callout-label">Check this first</strong>
|
||||
<p>
|
||||
If nothing seems to be happening, look at your terminal. Plan2Code
|
||||
If nothing seems to be happening, <span data-app="look at the terminal panel (collapsed, it shows a dot once the agent has gone quiet)">look at your terminal</span>. Plan2Code
|
||||
often stops there to ask your permission, and this page cannot see it.
|
||||
</p>
|
||||
</div>
|
||||
@@ -901,7 +924,7 @@
|
||||
<li class="help-row">
|
||||
<dl>
|
||||
<dt>You see</dt><dd>The line beside Planny stays quiet for half a minute or more while it is working.</dd>
|
||||
<dt>Likely cause</dt><dd>A permission prompt is waiting in your terminal.</dd>
|
||||
<dt>Likely cause</dt><dd data-app="A permission prompt is waiting in the terminal panel.">A permission prompt is waiting in your terminal.</dd>
|
||||
<dt>Do this</dt><dd>Switch to the terminal and answer it.</dd>
|
||||
</dl>
|
||||
</li>
|
||||
@@ -909,14 +932,14 @@
|
||||
<dl>
|
||||
<dt>You see</dt><dd><strong>Not running</strong> (Planny grey and still).</dd>
|
||||
<dt>Likely cause</dt><dd>Plan2Code has not checked in for a few minutes.</dd>
|
||||
<dt>Do this</dt><dd>Look at the terminal. If it is idle, type <code>continue</code> there.</dd>
|
||||
<dt>Do this</dt><dd class="for-browser">Look at the terminal. If it is idle, type <code>continue</code> there.</dd><dd class="for-app">Look at the terminal panel. If it is idle, press <strong>continue</strong> in the line beside Planny, which types it there for you.</dd>
|
||||
</dl>
|
||||
</li>
|
||||
<li class="help-row">
|
||||
<dl>
|
||||
<dt>You see</dt><dd><strong>Not connected</strong> (Planny faded, his star shut).</dd>
|
||||
<dt>Likely cause</dt><dd>The program behind this page shut itself down.</dd>
|
||||
<dt>Do this</dt><dd>Ask Plan2Code to resume the session (or run the command again), and use the new link.</dd>
|
||||
<dt>Do this</dt><dd id="help-stuck-table-reconnect-text">Ask Plan2Code to resume the session (or run the command again), and use the new link.</dd>
|
||||
</dl>
|
||||
</li>
|
||||
<li class="help-row">
|
||||
@@ -947,8 +970,8 @@
|
||||
<text class="hd-label" x="110" y="46" text-anchor="middle">Says Not</text>
|
||||
<text class="hd-label" x="110" y="63" text-anchor="middle">connected?</text>
|
||||
<rect class="hd-box" x="260" y="26" width="284" height="48" rx="8" />
|
||||
<text class="hd-label" x="402" y="46" text-anchor="middle">Run the command again,</text>
|
||||
<text class="hd-label" x="402" y="63" text-anchor="middle">use the new link</text>
|
||||
<text class="hd-label" x="402" y="46" text-anchor="middle" data-app="Press Reconnect the console">Run the command again,</text>
|
||||
<text class="hd-label" x="402" y="63" text-anchor="middle" data-app="in the app's own bar">use the new link</text>
|
||||
<path class="hd-line" d="M202 50 H256" marker-end="url(#hd-stuck-arrow)" />
|
||||
<text class="hd-label small" x="228" y="43" text-anchor="middle">yes</text>
|
||||
<path class="hd-line" d="M110 86 V112" marker-end="url(#hd-stuck-arrow)" />
|
||||
@@ -984,7 +1007,7 @@
|
||||
<strong>Not connected</strong> (Planny faded, arms hanging, his star shut in red):
|
||||
this page cannot reach its own program, after
|
||||
<span data-fact="goneSeconds">8</span> seconds without contact.
|
||||
Usually it has shut itself down; see "Getting a new link" below.
|
||||
Usually it has shut itself down; <span id="help-stuck-not-connected-ref">see "Getting a new link" below</span>.
|
||||
</li>
|
||||
</ul>
|
||||
<p>"Reading Planny" shows every mood side by side.</p>
|
||||
@@ -993,8 +1016,8 @@
|
||||
Plan2Code sometimes stops in the terminal to ask your permission
|
||||
before it runs a command or changes a file, and this page cannot see
|
||||
that. After about 30 seconds of silence while it is working, the line
|
||||
beside Planny asks "Still working, or waiting on an approval in your
|
||||
terminal?" Have a look at the terminal: answering there sets it going
|
||||
beside Planny asks <span data-app=""Still working, or waiting on an approval in the terminal panel?"">"Still working, or waiting on an approval in your
|
||||
terminal?"</span> Have a look at the terminal: answering there sets it going
|
||||
again.
|
||||
</p>
|
||||
<p>
|
||||
@@ -1016,13 +1039,17 @@
|
||||
What you send is written to disk and held until something collects it,
|
||||
so starting Plan2Code again picks it up where you left off.
|
||||
</p>
|
||||
<h4>Getting a new link</h4>
|
||||
<h4 id="help-stuck-reconnect-title">Getting a new link</h4>
|
||||
<p>The program behind this page shuts itself down:</p>
|
||||
<ul>
|
||||
<li>
|
||||
<li class="for-browser">
|
||||
<span data-fact="closedTabMinutes">2</span> minutes after the last tab
|
||||
showing it closes,
|
||||
</li>
|
||||
<li class="for-app">
|
||||
<span data-fact="closedTabMinutes">2</span> minutes after the app's
|
||||
window closes,
|
||||
</li>
|
||||
<li>
|
||||
after <span data-fact="idleMinutes">30</span> minutes without hearing
|
||||
from anyone, or
|
||||
@@ -1032,12 +1059,12 @@
|
||||
happening.
|
||||
</li>
|
||||
</ul>
|
||||
<p>
|
||||
<p id="help-stuck-reconnect-text">
|
||||
To get it back, ask Plan2Code in the terminal to resume the session,
|
||||
or run the step's command again, and use the new link it gives you.
|
||||
Everything you typed, sent or not, is still there.
|
||||
</p>
|
||||
<div class="handoff-command" data-copy>
|
||||
<div class="handoff-command" data-copy id="help-stuck-reconnect-command">
|
||||
<code class="handoff-code">resume the session and print the web console address here</code>
|
||||
</div>
|
||||
</section>
|
||||
@@ -1119,10 +1146,14 @@
|
||||
beside it opens <strong>User Preferences</strong>: your role first,
|
||||
then your colors, theme, card width and sounds.
|
||||
</li>
|
||||
<li>
|
||||
<li class="for-browser">
|
||||
The <strong>megaphone</strong> button at the far right opens GitHub in a
|
||||
new tab, where you can report a bug or suggest an idea.
|
||||
</li>
|
||||
<li class="for-app">
|
||||
The <strong>megaphone</strong> button at the far right opens Plan2Code's
|
||||
GitHub issues, where you can report a bug or suggest an idea.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Stop session</strong> ends the session and saves your place.
|
||||
See "Stopping and finishing".
|
||||
@@ -1146,8 +1177,8 @@
|
||||
<strong>Overview</strong> when the session is working on a spec, then
|
||||
one tab per document Plan2Code has written, and <strong>Ask</strong>,
|
||||
always last.
|
||||
Each tab remembers where you scrolled for as long as this browser tab
|
||||
stays open.
|
||||
<span data-app="Each tab remembers where you scrolled for as long as the app's window stays open.">Each tab remembers where you scrolled for as long as this browser tab
|
||||
stays open.</span>
|
||||
</p>
|
||||
<h4>Moving between questions</h4>
|
||||
<p>
|
||||
@@ -1342,8 +1373,8 @@
|
||||
<p>
|
||||
Star turning, arms pumping, feet walking on the spot. Plan2Code has your answers and is thinking, or is
|
||||
busy building. The line beside him says what it is doing. After about
|
||||
30 seconds of silence it asks "Still working, or waiting on an approval
|
||||
in your terminal?", because the terminal may have stopped to ask your
|
||||
30 seconds of silence it asks <span data-app=""Still working, or waiting on an approval in the terminal panel?"">"Still working, or waiting on an approval
|
||||
in your terminal?"</span>, because the terminal may have stopped to ask your
|
||||
permission for something, and this page cannot see that.
|
||||
</p>
|
||||
<h4>All caught up</h4>
|
||||
@@ -1352,7 +1383,7 @@
|
||||
answered and Plan2Code has nothing new yet.
|
||||
</p>
|
||||
<h4>Done</h4>
|
||||
<p>A green star and both arms up. The session is finished. You can close the tab.</p>
|
||||
<p id="help-planny-done-text">A green star and both arms up. The session is finished. You can close the tab.</p>
|
||||
<h4>Not running</h4>
|
||||
<p>
|
||||
Grey, still, arms down out of sight. This page is fine, but Plan2Code has not checked in
|
||||
@@ -1488,10 +1519,14 @@
|
||||
Everything you pick or type is a draft that Plan2Code cannot see
|
||||
yet, and every bit of it can be undone.
|
||||
</li>
|
||||
<li>
|
||||
<li class="for-browser">
|
||||
Drafts survive a closed tab and a reload: open the same link again and
|
||||
your half-typed answers are still there.
|
||||
</li>
|
||||
<li class="for-app">
|
||||
Drafts survive a closed window and a reload: when the app shows this
|
||||
session again, your half-typed answers are still there.
|
||||
</li>
|
||||
<li>
|
||||
The footer says what is ready to go, and the Send button pulses gently
|
||||
while there is something to send.
|
||||
@@ -1560,7 +1595,7 @@
|
||||
images and documents counted together.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Images</strong> are shrunk in your browser to a JPEG at most
|
||||
<strong>Images</strong> are shrunk <span data-app="on this machine">in your browser</span> to a JPEG at most
|
||||
<span data-fact="imageEdge">2000</span> px on the long edge, and must
|
||||
be under <span data-fact="maxUploadMb">4</span> MB after shrinking.
|
||||
</li>
|
||||
@@ -1709,7 +1744,7 @@
|
||||
button.
|
||||
</p>
|
||||
<h4>When an update is out</h4>
|
||||
<p>
|
||||
<p id="help-update-text">
|
||||
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, <code>plan2code update</code>; × hides it until the next
|
||||
@@ -1740,7 +1775,7 @@
|
||||
bug has its own <strong>Delete</strong> button at the bottom of its
|
||||
chip instead, and needs just one confirm, since the work is done.
|
||||
</p>
|
||||
<p>
|
||||
<p id="help-handoff-copy-text">
|
||||
A <strong>Handoff</strong> is a note a step left when you stopped it
|
||||
with a handoff. It shows as a dashed chip after the specs. Pick one
|
||||
and the cards give way to a preview with its Next task and four
|
||||
@@ -1812,12 +1847,19 @@
|
||||
miss things, and the ring is there to remind you.
|
||||
</p>
|
||||
<h4>What red means</h4>
|
||||
<p>
|
||||
<p class="for-browser">
|
||||
Starting a <strong>new console session</strong> will keep Plan2Code
|
||||
sharp: stop this one, then start Plan2Code again in a new
|
||||
conversation. Resuming this session carries its count along, so it
|
||||
does not help. Your work is all on disk, so nothing is lost.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
A fresh start will keep Plan2Code sharp: finish the step, then press
|
||||
<strong>New Session</strong> at the top of the window. The agent starts
|
||||
again on a clean context, in a new console session whose meter starts
|
||||
over, and the dashboard offers a brief of where you were. Your work is
|
||||
all on disk, so nothing is lost.
|
||||
</p>
|
||||
<p>
|
||||
The meter never blocks anything. Red is advice; you can keep going.
|
||||
</p>
|
||||
@@ -2044,6 +2086,31 @@
|
||||
</li>
|
||||
<li>The button only appears on skills that use helpers, and only when Plan2Code can pass the setting on.</li>
|
||||
</ul>
|
||||
<h4>Helper strength</h4>
|
||||
<p>
|
||||
Under Helpers, the dialog also asks how strong the helpers should be.
|
||||
Like the rest of the dialog it is saved for this project and this
|
||||
skill, and it does nothing under <strong>Work alone</strong>.
|
||||
</p>
|
||||
<ul>
|
||||
<li>
|
||||
<strong>Balanced</strong> (the default): each helper gets the
|
||||
strength its job needs: light for lookups, stronger for reviews and
|
||||
design work.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Thrifty</strong>: one step lighter everywhere to save cost;
|
||||
reviews stay at standard or above.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Best</strong>: the strongest model and high effort for
|
||||
everything except lookups.
|
||||
</li>
|
||||
<li>
|
||||
<strong>Match my session</strong>: helpers run on whatever your
|
||||
session uses; nothing is set for them.
|
||||
</li>
|
||||
</ul>
|
||||
<h4>The Subagents tab</h4>
|
||||
<ul>
|
||||
<li>
|
||||
@@ -2057,6 +2124,12 @@
|
||||
check-ins, not live. The page cannot stop a helper; ask Plan2Code
|
||||
on the Ask tab if one should stop.
|
||||
</li>
|
||||
<li>
|
||||
Under each helper, a line such as "Standard, medium effort" shows
|
||||
what that helper actually ran with. "Session model" means the agent
|
||||
could not set a strength for it, so it ran on the session's own
|
||||
model. A helper that reported neither shows no line.
|
||||
</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
|
||||
@@ -2085,7 +2158,7 @@
|
||||
your answers to the cards, and sending those never holds up a question.
|
||||
</p>
|
||||
<h4>Prompts to carry away</h4>
|
||||
<p>
|
||||
<p id="help-ask-prompt-text">
|
||||
When what you ask is really a new task, or you ask for a prompt,
|
||||
the answer ends with a ready-to-paste prompt in a box with a
|
||||
<strong>Copy</strong> button. Copy it into a new conversation: it
|
||||
@@ -2155,11 +2228,16 @@
|
||||
"That's 10 questions in this conversation" means press
|
||||
<strong>New conversation</strong> to keep going.
|
||||
</li>
|
||||
<li>
|
||||
<li class="for-browser">
|
||||
"No agent is available right now" means the session has finished or
|
||||
Plan2Code has gone quiet. Check the terminal, or resume the session,
|
||||
to ask.
|
||||
</li>
|
||||
<li class="for-app">
|
||||
"No agent is available right now" means the session has finished or
|
||||
Plan2Code has gone quiet. Check the terminal panel, or press
|
||||
<strong>New Session</strong> if the agent has ended, to ask.
|
||||
</li>
|
||||
</ul>
|
||||
<p>Either way, the conversation above stays readable.</p>
|
||||
<h4>When an answer lands</h4>
|
||||
@@ -2177,7 +2255,7 @@
|
||||
run next, whether it finished on its own or you stopped it.
|
||||
</p>
|
||||
<h4>Stopping early</h4>
|
||||
<p>
|
||||
<p id="help-finishing-stop-text">
|
||||
<strong>Stop session</strong>, at the top, ends the session and saves
|
||||
your place. Any answers you have ready go with it, and Plan2Code
|
||||
gives you a command to pick up where you left off, in a new
|
||||
@@ -2239,7 +2317,7 @@
|
||||
this step is over.
|
||||
</p>
|
||||
<h4>Running the next command</h4>
|
||||
<p>
|
||||
<p id="help-finishing-command-text">
|
||||
Press <strong>Copy</strong>, then paste the command into the terminal
|
||||
where you started Plan2Code, in a new conversation. When the next
|
||||
step is another Plan2Code step, the command already ends with
|
||||
@@ -2247,7 +2325,7 @@
|
||||
you carry on here rather than in the terminal.
|
||||
</p>
|
||||
<h4>Back to the dashboard</h4>
|
||||
<p>
|
||||
<p id="help-finishing-dashboard-text">
|
||||
A finished screen (never a paused one) has a <strong>Back to the
|
||||
dashboard</strong> button. It turns this page back into the cards, in
|
||||
the same conversation, so the next step starts right here.
|
||||
@@ -2266,7 +2344,7 @@
|
||||
"Commit this now?" and you say yes, it carries on to Git.
|
||||
</p>
|
||||
<h4>Continue here</h4>
|
||||
<p>
|
||||
<p id="help-finishing-continue-text">
|
||||
When the next step is another Plan2Code step, the Next step block also
|
||||
has a <strong>Continue here</strong> button. It starts that step in
|
||||
this same conversation, the way a dashboard card would, with this page
|
||||
@@ -2405,20 +2483,33 @@
|
||||
your project.
|
||||
</p>
|
||||
<h4>On this machine only</h4>
|
||||
<p>
|
||||
<p class="for-browser">
|
||||
The page is served on <strong>127.0.0.1</strong>, which only this
|
||||
computer can reach. It is not visible on your network, so sharing the
|
||||
link with someone on another machine will not work, by design. To work
|
||||
through a session together, share your screen.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
The page is served on <strong>127.0.0.1</strong>, which only this
|
||||
computer can reach. It is not visible on your network, and the app
|
||||
shows it in its own window, so there is no link to share. To work
|
||||
through a session together, share your screen.
|
||||
</p>
|
||||
<h4>The link is a key</h4>
|
||||
<p>
|
||||
<p class="for-browser">
|
||||
The link carries a long private code. The first time it is opened, the
|
||||
page swaps that code for a cookie in this browser and takes it out of
|
||||
the address bar, so it does not linger in your history or show in a
|
||||
screenshot. Treat the link like a password all the same: anyone on
|
||||
this machine who has it can open the session.
|
||||
</p>
|
||||
<p class="for-app">
|
||||
The page's address carries a long private code. The app opens it for
|
||||
you, and the page swaps that code for a cookie in the app's own web
|
||||
view, so it never shows in the window, and the agent leaves it out of
|
||||
the terminal panel. Anyone on this machine who has the address can
|
||||
still open the session, so treat it like a password if you ever see it.
|
||||
</p>
|
||||
<h4>What is kept, and where</h4>
|
||||
<p>
|
||||
Everything lives in your home folder, under
|
||||
@@ -2579,6 +2670,14 @@
|
||||
<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 looks-row" id="subagents-strength-row">
|
||||
<legend>Helper strength</legend>
|
||||
<label><input type="radio" name="subagents-strength" value="balanced" checked /> <span>Balanced</span></label>
|
||||
<label><input type="radio" name="subagents-strength" value="thrifty" /> <span>Thrifty</span></label>
|
||||
<label><input type="radio" name="subagents-strength" value="best" /> <span>Best</span></label>
|
||||
<label><input type="radio" name="subagents-strength" value="session" /> <span>Match my session</span></label>
|
||||
<p class="help" id="subagents-strength-help"></p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>Instruction</legend>
|
||||
<textarea id="subagents-instruction" rows="4" maxlength="2000" aria-label="Instruction"></textarea>
|
||||
@@ -2755,7 +2854,7 @@
|
||||
<svg viewBox="0 0 20 20" aria-hidden="true" focusable="false"><circle cx="10" cy="10" r="7" opacity="0.35" /><circle cx="10" cy="10" r="7" pathLength="100" stroke-dasharray="50 100" stroke-dashoffset="25" transform="rotate(-90 10 10)" /></svg>
|
||||
</span>
|
||||
<h3>Refresh at half way</h3>
|
||||
<p>Once the session meter passes half, finish the step and start a new conversation.</p>
|
||||
<p id="welcome-refresh-text">Once the session meter passes half, finish the step and start a new conversation.</p>
|
||||
</div>
|
||||
<div class="welcome-col">
|
||||
<span class="welcome-dot is-bare">
|
||||
|
||||
@@ -8,6 +8,7 @@ import { DEFAULT_ACCENT, soundPrefs, DEFAULT_CARD_WIDTH, ACCENTS, cardWidth, sou
|
||||
import { normalizeRole, ROLE_NOT_SET } from "./starters.js";
|
||||
import { bootData, hooks } from "./state.js";
|
||||
import { el } from "./render.js";
|
||||
import { tellApp } from "./app-bridge.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -129,6 +130,9 @@ const effectiveTheme = () => (looks.theme === "system" ? (systemDark() ? "dark"
|
||||
|
||||
export function applyLooks() {
|
||||
const root = document.documentElement;
|
||||
// The desktop app's bar lights its buttons in the same highlight. That bar
|
||||
// is always dark, so it gets the dark shades whatever this page's theme is.
|
||||
tellApp("looks", { accent: ACCENTS[looks.accent].dark });
|
||||
// The server's stand-in for the saved accent, which only has to last until
|
||||
// this runs. From here on the colors are set below, and a stale rule left
|
||||
// switched on would win over "Back to default".
|
||||
|
||||
@@ -291,6 +291,12 @@ export function tooltipFor(points) {
|
||||
export const RED_BANNER =
|
||||
"This console session has done a lot. Starting a new console session will keep the agent sharp.";
|
||||
|
||||
// The same advice, worded for the desktop app: there the app's own New
|
||||
// Session button already replaces the agent on a fresh context in one click,
|
||||
// so this never tells anyone to copy a command into a new conversation.
|
||||
export const RED_BANNER_IN_APP =
|
||||
"This console session has done a lot. Press New Session at the top of the window to start the agent fresh.";
|
||||
|
||||
// Everything the pill draws, from the ledger alone.
|
||||
export function meterView(entries) {
|
||||
const points = pointsFrom(entries);
|
||||
|
||||
@@ -10,7 +10,7 @@ import { thumbs, uploadUrl, docChip, attachTray, CHAT_IMAGES, attachFiles, incom
|
||||
import { attachMentions } from "../mention-box.js";
|
||||
import { pickerAccept, attachmentKind, noteAwaiting, threadWho, threadText } from "../answers.js";
|
||||
import { postJson } from "../net.js";
|
||||
import { CHECKIN_LINE, helperRows, showSwitch, switchLabel, defaultInstruction, PATHFINDER_RESEARCH_LINE } from "../subagents.js";
|
||||
import { CHECKIN_LINE, helperRows, showSwitch, switchLabel, defaultInstruction, PATHFINDER_RESEARCH_LINE, STRENGTHS, DEFAULT_STRENGTH, STRENGTH_HELP } from "../subagents.js";
|
||||
|
||||
const $ = (id) => document.getElementById(id);
|
||||
|
||||
@@ -724,6 +724,7 @@ export function renderSubagents(main) {
|
||||
head.appendChild(pill);
|
||||
item.appendChild(head);
|
||||
item.appendChild(el("p", "sa-ask", row.ask));
|
||||
if (row.strengthLine) item.appendChild(el("p", "sa-strength", row.strengthLine));
|
||||
if (row.result) item.appendChild(el("p", "sa-result", row.result));
|
||||
list.appendChild(item);
|
||||
}
|
||||
@@ -755,6 +756,9 @@ export function openSubagents() {
|
||||
}
|
||||
$("subagents-instruction").value = page.subagentsFrame.instruction ?? defaultInstruction(page.S.workflow);
|
||||
$("subagents-max").value = String(page.subagentsFrame.max);
|
||||
const strength = STRENGTHS.includes(page.subagentsFrame.strength) ? page.subagentsFrame.strength : DEFAULT_STRENGTH;
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.checked = radio.value === strength;
|
||||
syncStrengthHelp();
|
||||
$("subagents-checkin").textContent = CHECKIN_LINE;
|
||||
const research = $("subagents-research");
|
||||
research.textContent = PATHFINDER_RESEARCH_LINE;
|
||||
@@ -767,17 +771,25 @@ export function openSubagents() {
|
||||
if (checked) checked.focus();
|
||||
}
|
||||
|
||||
// Instruction and "at most" only mean anything with helpers on, so they are
|
||||
// inert under Work alone (kept as typed, for when helpers go back on).
|
||||
// Instruction, "at most" and strength only mean anything with helpers on, so
|
||||
// they are inert under Work alone (kept as picked, for when helpers go back on).
|
||||
export function syncSubagentsFields() {
|
||||
const picked = document.querySelector('input[name="subagents-on"]:checked');
|
||||
const off = !picked || picked.value !== "on";
|
||||
for (const id of ["subagents-instruction", "subagents-max", "subagents-default"]) $(id).disabled = off;
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.disabled = off;
|
||||
}
|
||||
|
||||
// The line under the strength radios explains the picked one.
|
||||
function syncStrengthHelp() {
|
||||
const picked = document.querySelector('input[name="subagents-strength"]:checked');
|
||||
$("subagents-strength-help").textContent = STRENGTH_HELP[picked ? picked.value : DEFAULT_STRENGTH];
|
||||
}
|
||||
|
||||
const SUBAGENTS_ERRORS = {
|
||||
max: "Pick a number from 1 to 20.",
|
||||
"too-long": "The instruction is over 2,000 characters.",
|
||||
strength: "That strength isn't one of the four choices.",
|
||||
"not-offered": "This skill doesn't use helpers.",
|
||||
bad: "That didn't save. Try again.",
|
||||
};
|
||||
@@ -792,7 +804,13 @@ export async function saveSubagents() {
|
||||
// The shipped default is stored as null, so a later release's wording
|
||||
// reaches everyone who never changed it.
|
||||
const instruction = text === defaultInstruction(page.S.workflow) ? null : text;
|
||||
const body = { on: Boolean(picked && picked.value === "on"), instruction, max: Number($("subagents-max").value) };
|
||||
const strength = document.querySelector('input[name="subagents-strength"]:checked');
|
||||
const body = {
|
||||
on: Boolean(picked && picked.value === "on"),
|
||||
instruction,
|
||||
max: Number($("subagents-max").value),
|
||||
strength: strength ? strength.value : DEFAULT_STRENGTH,
|
||||
};
|
||||
save.disabled = true;
|
||||
status.textContent = "";
|
||||
const res = await postJson("/subagents", body);
|
||||
@@ -811,6 +829,7 @@ export const askOfflineFlipped = () => (askState().send.state === "offline") !==
|
||||
// The Subagents dialog's buttons, and dropping files onto the notes panel.
|
||||
export function wireAsk() {
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-on"]')) radio.addEventListener("change", syncSubagentsFields);
|
||||
for (const radio of document.querySelectorAll('input[name="subagents-strength"]')) radio.addEventListener("change", syncStrengthHelp);
|
||||
lightDismiss($("subagents-modal"));
|
||||
$("btn-subagents").addEventListener("click", openSubagents);
|
||||
$("subagents-default").addEventListener("click", () => {
|
||||
|
||||
@@ -1495,22 +1495,29 @@ function buildList(card, item, staged) {
|
||||
}
|
||||
card.appendChild(row);
|
||||
card.appendChild(el("p", "help", "Drag to reorder, click a name to rename it."));
|
||||
commentField(card, item, "Anything else about this breakdown?", false, "no changes");
|
||||
const quick = [{ label: "No changes", text: "no changes" }];
|
||||
// Only a plan's breakdown is phases; a list card elsewhere is something else.
|
||||
if (PHASE_WORKFLOWS.includes(page.S.workflow)) quick.push({ label: "Combine phases", text: COMBINE_PHASES });
|
||||
commentField(card, item, "Anything else about this breakdown?", false, quick);
|
||||
}
|
||||
|
||||
function commentField(card, item, labelText, required, quickText) {
|
||||
const PHASE_WORKFLOWS = ["plan", "revise-plan"];
|
||||
const COMBINE_PHASES =
|
||||
"Combine phases where possible to simplify and reduce the total number of phases, while still keeping a clear separation of concerns.";
|
||||
|
||||
function commentField(card, item, labelText, required, quickAnswers = []) {
|
||||
const wrap = el("div", "field");
|
||||
const id = "note-" + item.id;
|
||||
const label = el("label", null, labelText);
|
||||
label.htmlFor = id;
|
||||
wrap.appendChild(label);
|
||||
let quick = null;
|
||||
if (quickText) {
|
||||
quick = el("button", "btn tiny", quickText.charAt(0).toUpperCase() + quickText.slice(1));
|
||||
quick.type = "button";
|
||||
quick.title = "Fill in \"" + quickText + "\"";
|
||||
wrap.appendChild(quick);
|
||||
}
|
||||
const quicks = quickAnswers.map(({ label, text }) => {
|
||||
const b = el("button", "btn tiny quick-answer", label);
|
||||
b.type = "button";
|
||||
b.title = "Fill in \"" + text + "\"";
|
||||
wrap.appendChild(b);
|
||||
return [b, text];
|
||||
});
|
||||
const ta = el("textarea");
|
||||
ta.id = id;
|
||||
ta.placeholder = required ? "Tell Plan2Code what to change." : "Optional.";
|
||||
@@ -1531,9 +1538,9 @@ function commentField(card, item, labelText, required, quickText) {
|
||||
stagedChanged();
|
||||
});
|
||||
wrap.appendChild(ta);
|
||||
if (quick)
|
||||
quick.addEventListener("click", () => {
|
||||
ta.value = quickText;
|
||||
for (const [b, text] of quicks)
|
||||
b.addEventListener("click", () => {
|
||||
ta.value = text;
|
||||
ta.dispatchEvent(new Event("input", { bubbles: true }));
|
||||
ta.focus();
|
||||
});
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
STALE_MS,
|
||||
agentRepliedAfterSend,
|
||||
approvalHint,
|
||||
APPROVAL_HINT_IN_APP,
|
||||
cardAvailability,
|
||||
cardPresentation,
|
||||
finishPaused,
|
||||
@@ -66,6 +67,7 @@ import { renderBriefButton, renderDoc, renderOverview } from "./docs.js";
|
||||
import { board, renderGitBoard, resetBoard } from "./git-host.js";
|
||||
import { renderWorkspace, tellFolderIssues } from "./workspace.js";
|
||||
import { openHelpOn } from "./help-dialog.js";
|
||||
import { linkLeavesPage, tellApp } from "../app-bridge.js";
|
||||
import { askOfflineFlipped, askState, declineOpen, renderAside, renderAsk, renderSubagents, renderSubagentsButton } from "./ask.js";
|
||||
import { renderHandoff, renderHomeButton, renderStopButton, renderStopControls, renderStopping, stopInProgress, stopWarning } from "./ending.js";
|
||||
import { renderNotepadButton } from "./notepad.js";
|
||||
@@ -238,6 +240,10 @@ export function adopt(body) {
|
||||
page.chatFrame = body.chat || null;
|
||||
if (body.workspace) page.wsFrame = body.workspace;
|
||||
if (body.meter) page.meterFrame = body.meter;
|
||||
// Fixed for the session's whole life, but cheap enough to just copy.
|
||||
page.inApp = Boolean(body.inApp);
|
||||
// Help's `.for-app` / `.for-browser` wording switches on this (help.css).
|
||||
document.documentElement.classList.toggle("in-app", page.inApp);
|
||||
// Always replaced: an absent key means no update.
|
||||
page.updateFrame = body.update || null;
|
||||
// Always replaced too: an older server sends none, and then there is no switch.
|
||||
@@ -925,11 +931,21 @@ function renderMeter() {
|
||||
return li;
|
||||
})
|
||||
);
|
||||
// Once the session is past fresh, say how to start a new one.
|
||||
// Once the session is past fresh, say how to start a new one. Under the app
|
||||
// that is one button doing what the app bar's New Session does, instead of
|
||||
// a command to copy into a new conversation.
|
||||
const fresh = $("meter-fresh");
|
||||
fresh.hidden = page.meterFrame.level === "green";
|
||||
if (fresh.hidden || fresh.dataset.built) return;
|
||||
fresh.dataset.built = "1";
|
||||
if (page.inApp) {
|
||||
// The same press as the app bar's New Session, confirm and all.
|
||||
const press = el("button", "btn small primary meter-fresh-btn", "Start a New Session");
|
||||
press.type = "button";
|
||||
press.addEventListener("click", () => tellApp("new-session"));
|
||||
fresh.append(press);
|
||||
return;
|
||||
}
|
||||
const text = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const code = el("code", "handoff-code", text);
|
||||
const row = el("div", "handoff-command meter-fresh-row");
|
||||
@@ -1007,6 +1023,27 @@ let moodNow = null;
|
||||
|
||||
let moodVar = 0;
|
||||
|
||||
// Sent answers that nothing is collecting (stranded() in selectors.js).
|
||||
const STRANDED_LINE =
|
||||
"Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval.";
|
||||
|
||||
// The status line's **continue**, under the app: a press asks the app to type
|
||||
// it into the agent's terminal. Held off for a few seconds after, so a double
|
||||
// press does not send it twice.
|
||||
const CONTINUE_HOLD_MS = 4000;
|
||||
|
||||
function continueButton() {
|
||||
const btn = el("button", "agent-key agent-key-btn", "continue");
|
||||
btn.type = "button";
|
||||
btn.title = "Type continue in the agent's terminal";
|
||||
btn.addEventListener("click", () => {
|
||||
btn.disabled = true;
|
||||
tellApp("agent-continue");
|
||||
setTimeout(() => (btn.disabled = false), CONTINUE_HOLD_MS);
|
||||
});
|
||||
return btn;
|
||||
}
|
||||
|
||||
export function renderStatus() {
|
||||
if (!page.S) return;
|
||||
const bot = $("planny");
|
||||
@@ -1031,6 +1068,9 @@ export function renderStatus() {
|
||||
text.dataset.line = shown;
|
||||
const parts = line.split(/\*\*(.+?)\*\*/).map((part, i) => {
|
||||
if (i % 2 === 0) return document.createTextNode(part);
|
||||
// Under the app the terminal is in the same window, so the word to
|
||||
// type is a button that types it there instead.
|
||||
if (page.inApp && part === "continue") return continueButton();
|
||||
const key = document.createElement("strong");
|
||||
key.className = "agent-key";
|
||||
key.textContent = part;
|
||||
@@ -1064,15 +1104,17 @@ export function renderStatus() {
|
||||
if (page.local.afterBuild === "changelog" && !page.gone) return say("work", "Opening Changelog…", "", true);
|
||||
if (page.local.afterBuild === "launch" && !page.gone) return say("work", "Starting the next step…", "", true);
|
||||
const offer = reviewPending();
|
||||
// There is no tab to close under the app, only the one window.
|
||||
const closeWord = page.inApp ? "window" : "tab";
|
||||
if (dashboardLive(finish()) && !page.gone && !offer) {
|
||||
return say("point", "Done. Head back to the dashboard, or close this tab.");
|
||||
return say("point", `Done. Head back to the dashboard, or close this ${closeWord}.`);
|
||||
}
|
||||
if (offer === "asked") return say("work", "Review requested. Plan2Code is starting it.", "", true);
|
||||
if (offer === "open") return say("point", "Done. Review it here first, or close this tab.");
|
||||
if (offer === "open") return say("point", `Done. Review it here first, or close this ${closeWord}.`);
|
||||
// A stop past a warning kept nothing, so it promises no saved place.
|
||||
if (finishPaused(finish()))
|
||||
return say("done", stopWarning() ? "Paused. The command above starts it again." : "Paused. Your place is saved: the command above picks it up.");
|
||||
return say("done", "All done. You can close this tab.");
|
||||
return say("done", `All done. You can close this ${closeWord}.`);
|
||||
}
|
||||
if (page.gone) return say("gone", "Not connected. Your answers are saved.", "", false, true);
|
||||
// On the way home: the request is sent, and the page stays this skill's
|
||||
@@ -1107,6 +1149,10 @@ export function renderStatus() {
|
||||
return say("work", `Starting ${workflowTitle(page.S.workflow)}…`, "", true);
|
||||
}
|
||||
|
||||
// Answers nobody collected outrank a working line: the agent's last word
|
||||
// was "working", but it is not in `wait` to take them (agentAdrift).
|
||||
if (stranded()) return say("adrift", STRANDED_LINE, "", false, true);
|
||||
|
||||
// Show the AGENT's liveness, not the server's: if the agent's turn crashed
|
||||
// the server is still happily up, and a plain spinner would lie forever.
|
||||
if (agentWorking()) {
|
||||
@@ -1121,7 +1167,8 @@ export function renderStatus() {
|
||||
}
|
||||
// Same clock as agentStale(), so the soft line at 30 s hands over to the
|
||||
// stale message at two minutes on one timeline.
|
||||
const hint = page.agentLastSeen ? approvalHint(page.S.agent, Date.now() - Date.parse(page.agentLastSeen)) : "";
|
||||
const quiet = page.agentLastSeen ? approvalHint(page.S.agent, Date.now() - Date.parse(page.agentLastSeen)) : "";
|
||||
const hint = quiet && page.inApp ? APPROVAL_HINT_IN_APP : quiet;
|
||||
return say("work", hint || activity() || "Plan2Code is thinking…", fmtMs(workingMs()), true, Boolean(hint));
|
||||
}
|
||||
// Between pressing Send and the agent picking it up, the agent's own status
|
||||
@@ -1133,9 +1180,7 @@ export function renderStatus() {
|
||||
if (agentAdrift()) {
|
||||
return say(
|
||||
"adrift",
|
||||
stranded()
|
||||
? "Plan2Code is not running. Your answers are saved and waiting for it. If the terminal is idle, type **continue** there and it will pick them up; it may also be waiting for your permission approval."
|
||||
: "Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval.",
|
||||
"Plan2Code is not running right now. Anything you answer here is saved. If the terminal is idle, type **continue** there to wake it; it may also be waiting for your permission approval.",
|
||||
"",
|
||||
false,
|
||||
true
|
||||
@@ -1750,7 +1795,13 @@ export async function send() {
|
||||
e.pending = true;
|
||||
throw e;
|
||||
}
|
||||
if (!res.ok) throw new Error(String(res.status));
|
||||
if (!res.ok) {
|
||||
const body = await res.json().catch(() => null);
|
||||
const e = new Error(String(res.status));
|
||||
e.reason = (body && (body.message || body.error)) || `error ${res.status}`;
|
||||
e.status = res.status;
|
||||
throw e;
|
||||
}
|
||||
markSent(payload);
|
||||
banner("Sent. Plan2Code is picking it up now.", "good");
|
||||
setTimeout(() => banner(null), 4000);
|
||||
@@ -1762,8 +1813,10 @@ export async function send() {
|
||||
);
|
||||
page.pendingBannerUp = true;
|
||||
page.pendingResult = true;
|
||||
} else if (err && err.reason) {
|
||||
banner(refusedLine(err), "warn");
|
||||
} else {
|
||||
banner("That did not go through. Nothing was lost, try Send again.", "warn");
|
||||
await sendLost();
|
||||
}
|
||||
} finally {
|
||||
btn.textContent = "Send to Plan2Code";
|
||||
@@ -1771,6 +1824,36 @@ export async function send() {
|
||||
}
|
||||
}
|
||||
|
||||
// A send that never reached an answer: ask the server at once, rather than
|
||||
// leaving one line for every cause until the page's own timers catch up. No
|
||||
// server is the lost-contact state now, with its reconnect help; a server
|
||||
// still there was a blip, and Send is the whole fix.
|
||||
async function sendLost() {
|
||||
const up = await fetch("/state", { cache: "no-store" })
|
||||
.then((res) => res.ok)
|
||||
.catch(() => false);
|
||||
if (up) {
|
||||
banner("That did not go through, but the console is still up. Nothing was lost, press Send again.", "warn");
|
||||
return;
|
||||
}
|
||||
lastContact = 0;
|
||||
markGone();
|
||||
// A stream left half open (after the machine slept) still reads as
|
||||
// connected, so markGone() can leave the page up: the send still needs
|
||||
// saying it did not go.
|
||||
if (!page.gone) {
|
||||
banner("That did not go through. Nothing was lost, try Send again.", "warn");
|
||||
}
|
||||
}
|
||||
|
||||
// The server said no. A 5xx can pass on a retry; a 4xx is the same refusal
|
||||
// every time, so it gets no "try again", and the one a person can fix says how.
|
||||
function refusedLine(err) {
|
||||
if (err.status === 413) return "That is too big to send in one go. Nothing was lost: remove an attachment, then press Send.";
|
||||
if (err.status >= 400 && err.status < 500) return `The console turned that send down: ${err.reason}. Nothing was lost.`;
|
||||
return `The console turned that send down: ${err.reason}. Nothing was lost, try Send again.`;
|
||||
}
|
||||
|
||||
const STATE_WORDS = { done: "all done", blocked: "blocked", help: "need help", defer: "later" };
|
||||
|
||||
// Turn a staged answer into the words the person would have typed in the
|
||||
@@ -1829,6 +1912,21 @@ let whereResizeTimer = null;
|
||||
|
||||
// The listeners that belong to no screen: leaving the page, the session meter's
|
||||
// pop-over, the footer's label on a resize, Send, Clear, and the page-wide keys.
|
||||
// A link the console could not hand to a browser is shown, with a Copy
|
||||
// button, for the person to paste into one.
|
||||
async function openOutside(href) {
|
||||
const ok = await fetch("/open-link", {
|
||||
method: "POST",
|
||||
headers: { "content-type": "application/json" },
|
||||
body: JSON.stringify({ url: href }),
|
||||
})
|
||||
.then((res) => res.ok)
|
||||
.catch(() => false);
|
||||
if (ok) return;
|
||||
const link = el("code", "banner-link", href);
|
||||
banner("That link could not open from here. Copy it and paste it into your browser: ", "warn", [link, document.createTextNode(" "), copyButton(href, "btn small", link)]);
|
||||
}
|
||||
|
||||
export function wireChrome() {
|
||||
addEventListener("pagehide", () => {
|
||||
try {
|
||||
@@ -1836,6 +1934,21 @@ export function wireChrome() {
|
||||
} catch {}
|
||||
});
|
||||
|
||||
// Under the app, a link off the page goes to the default browser through
|
||||
// the console: the app's window opens no new ones, so the click alone would
|
||||
// do nothing. Capture phase, ahead of any handler on the link itself.
|
||||
document.addEventListener(
|
||||
"click",
|
||||
(e) => {
|
||||
if (!page.inApp || e.defaultPrevented || !(e.target instanceof Element)) return;
|
||||
const a = e.target.closest("a[href]");
|
||||
if (!a || !linkLeavesPage(a.href, location.origin)) return;
|
||||
e.preventDefault();
|
||||
openOutside(a.href);
|
||||
},
|
||||
true
|
||||
);
|
||||
|
||||
$("meter-pill").addEventListener("click", () => toggleMeterPop());
|
||||
$("meter-help").addEventListener("click", () => {
|
||||
toggleMeterPop(false);
|
||||
|
||||
@@ -14,7 +14,7 @@ import { hooks, page, redraw, saveNow } from "../state.js";
|
||||
import { el, approvalTip, mdInto, releasesLink, copyButton, lightDismiss } from "../render.js";
|
||||
import { needsRoleNudge, ROLE_NOT_SET } from "../starters.js";
|
||||
import { looks, renderSwatches, saveLooks } from "../looks.js";
|
||||
import { RED_BANNER } from "../meter.js";
|
||||
import { RED_BANNER, RED_BANNER_IN_APP } from "../meter.js";
|
||||
import {
|
||||
dashNoteKind,
|
||||
defaultSpec,
|
||||
@@ -148,12 +148,14 @@ export function renderDashboard(main) {
|
||||
if (needsRoleNudge(looks)) wrap.appendChild(roleNudge());
|
||||
// Advice only: words, never a button, and nothing is blocked.
|
||||
if (page.meterFrame && page.meterFrame.level === "red") {
|
||||
const warn = el("div", "dash-nudge meter-banner", RED_BANNER);
|
||||
const warn = el("div", "dash-nudge meter-banner", page.inApp ? RED_BANNER_IN_APP : RED_BANNER);
|
||||
warn.setAttribute("role", "status");
|
||||
wrap.appendChild(warn);
|
||||
}
|
||||
// Built here only, so no other workflow's page ever shows it.
|
||||
if (page.updateFrame && !updateDismissed()) {
|
||||
// Built here only, so no other workflow's page ever shows it. Under the app
|
||||
// this never shows at all: the app's own top bar already says so and, unlike
|
||||
// this banner's copy-pasted command, updates the skills itself in one click.
|
||||
if (page.updateFrame && !page.inApp && !updateDismissed()) {
|
||||
const notice = el("div", "dash-nudge update-banner");
|
||||
notice.setAttribute("role", "status");
|
||||
const open = el("button", "update-banner-open", "UPDATE AVAILABLE · v" + page.updateFrame.latest);
|
||||
@@ -556,13 +558,14 @@ function renderHandoffPreview(h) {
|
||||
const read = el("button", "btn", "Read it all");
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => readHandoff(h));
|
||||
const copy = el("button", "btn", "Copy for a new conversation");
|
||||
const copyLabel = page.inApp ? "Copy for another session" : "Copy for a new conversation";
|
||||
const copy = el("button", "btn", copyLabel);
|
||||
copy.type = "button";
|
||||
copy.addEventListener("click", () => {
|
||||
const dir = (scan() && scan().handoffsDir) || "";
|
||||
const sep = dir.includes("\\") ? "\\" : "/";
|
||||
const file = dir ? dir.replace(/[\\/]+$/, "") + sep + h.id + ".md" : h.id + ".md";
|
||||
copyHandoffText(handoffCopyText(file), copy);
|
||||
copyHandoffText(handoffCopyText(file), copy, copyLabel);
|
||||
});
|
||||
const del = el("button", "btn danger", "Delete");
|
||||
del.type = "button";
|
||||
@@ -575,14 +578,14 @@ function renderHandoffPreview(h) {
|
||||
|
||||
// The prompt that sends a new conversation to the handoff. A refused
|
||||
// clipboard gets a plain word on the button instead of a silent nothing.
|
||||
async function copyHandoffText(text, button) {
|
||||
async function copyHandoffText(text, button, label) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Copy was refused";
|
||||
}
|
||||
setTimeout(() => (button.textContent = "Copy for a new conversation"), 1500);
|
||||
setTimeout(() => (button.textContent = label), 1500);
|
||||
}
|
||||
|
||||
// Pick it up here: a hop like a card launch. The page sends only the id; the
|
||||
|
||||
@@ -11,11 +11,13 @@ import {
|
||||
handoffShape,
|
||||
ALL_DONE_LEAD,
|
||||
ALL_DONE_REST,
|
||||
ALL_DONE_REST_IN_APP,
|
||||
handoffText,
|
||||
DASHBOARD_COMMAND,
|
||||
resumeCommand,
|
||||
afterFinishButton,
|
||||
DASHBOARD_NOTE,
|
||||
DASHBOARD_NOTE_IN_APP,
|
||||
turnGate,
|
||||
homeButtonState,
|
||||
HOME_REPLY,
|
||||
@@ -88,25 +90,43 @@ function renderCloseGuide(shape, fin = {}) {
|
||||
const title = el("h3", "handoff-guide-title", "Before you close this");
|
||||
title.id = "handoff-guide-title";
|
||||
panel.appendChild(title);
|
||||
// Under the app this reads differently: there is one window, not a tab, and
|
||||
// the app's own New Session button already starts the agent fresh in one
|
||||
// click, so nothing here asks anyone to close a session or open another.
|
||||
const rows = [
|
||||
["safe", "Safe to close", "This tab is only a window: whatever this session wrote is on disk, and nothing here needs you."],
|
||||
[
|
||||
"safe",
|
||||
"Safe to close",
|
||||
page.inApp
|
||||
? "This window is only a view: whatever this session wrote is on disk, and nothing here needs you."
|
||||
: "This tab is only a window: whatever this session wrote is on disk, and nothing here needs you.",
|
||||
],
|
||||
[
|
||||
"fresh",
|
||||
"Start fresh",
|
||||
shape === "paused"
|
||||
? stopWarning()
|
||||
? "Restart your agent window, or close the old session and start a new one. The command above starts it again."
|
||||
: "Restart your agent window, or close the old session and start a new one. Your saved place is picked up by the resume command above."
|
||||
: "Restart your agent window, or close the old session and start a new one. A new session starts from clean context. This one is full of this step's instructions, so continuing in it is slower and can confuse the next step.",
|
||||
page.inApp
|
||||
? "Press New Session at the top of the window to start the agent fresh."
|
||||
: shape === "paused"
|
||||
? stopWarning()
|
||||
? "Restart your agent window, or close the old session and start a new one. The command above starts it again."
|
||||
: "Restart your agent window, or close the old session and start a new one. Your saved place is picked up by the resume command above."
|
||||
: "Restart your agent window, or close the old session and start a new one. A new session starts from clean context. This one is full of this step's instructions, so continuing in it is slower and can confuse the next step.",
|
||||
],
|
||||
[
|
||||
"carry",
|
||||
"Carry on",
|
||||
// The app's terminal panel runs the agent itself, so a slash command
|
||||
// still goes there, not into some other "new session" or "new
|
||||
// conversation" that does not exist under the app.
|
||||
shape === "all-done"
|
||||
? `In the new session, start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
? page.inApp
|
||||
? `In the terminal panel, start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: `In the new session, start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: shell
|
||||
? `Run the command above in your terminal, then start the next step from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: `Paste the command above in the new session, or start from the dashboard with \`${DASHBOARD_COMMAND}\`.`,
|
||||
: page.inApp
|
||||
? `Paste the command above into the terminal panel, or start from the dashboard with \`${DASHBOARD_COMMAND}\`.`
|
||||
: `Paste the command above in the new session, or start from the dashboard with \`${DASHBOARD_COMMAND}\`.`,
|
||||
],
|
||||
];
|
||||
const list = el("ul", "handoff-guide-rows");
|
||||
@@ -160,7 +180,10 @@ export function renderHandoff(fin) {
|
||||
const shape = handoffShape(fin);
|
||||
if (shape === "all-done") {
|
||||
const done = el("div", "handoff-done");
|
||||
done.appendChild(md(`${ALL_DONE_LEAD} ${ALL_DONE_REST}`, "md handoff-done-text"));
|
||||
done.appendChild(md(`${ALL_DONE_LEAD} ${page.inApp ? ALL_DONE_REST_IN_APP : ALL_DONE_REST}`, "md handoff-done-text"));
|
||||
// The command still works under the app: its terminal panel runs the
|
||||
// agent itself, so pasting this there reaches the dashboard exactly as
|
||||
// it would in a plain terminal.
|
||||
const text = handoffText({ command: DASHBOARD_COMMAND });
|
||||
const row = el("div", "handoff-command");
|
||||
const code = el("code", "handoff-code", text);
|
||||
@@ -182,7 +205,9 @@ export function renderHandoff(fin) {
|
||||
"handoff-where",
|
||||
fin.where ||
|
||||
(command.startsWith("/")
|
||||
? "Run this in the terminal where you started Plan2Code, in a new conversation:"
|
||||
? page.inApp
|
||||
? "Paste this into the terminal panel below:"
|
||||
: "Run this in the terminal where you started Plan2Code, in a new conversation:"
|
||||
: "Run this in your terminal:")
|
||||
)
|
||||
);
|
||||
@@ -213,7 +238,12 @@ export function renderHandoff(fin) {
|
||||
if (shape === "next") {
|
||||
const offerDash = dashboardLive(fin);
|
||||
if (offerDash) card.appendChild(renderDashboardOffer(false));
|
||||
if (!(offerDash && page.gone)) {
|
||||
// Under the app this paragraph never shows: renderCloseGuide's own
|
||||
// "carry" row already says the same thing ("Paste the command above
|
||||
// into the terminal panel, or start from the dashboard with
|
||||
// `/plan2code`"), right below this card, so repeating it here would
|
||||
// be the third mention of the one action on this screen.
|
||||
if (!page.inApp && !(offerDash && page.gone)) {
|
||||
card.appendChild(
|
||||
textWithCode(
|
||||
"p",
|
||||
@@ -303,9 +333,13 @@ function renderReviewOffer(offer) {
|
||||
el(
|
||||
"p",
|
||||
"review-offer-text",
|
||||
asked
|
||||
? "The session closed before the review could start. To run it now, use this in the terminal, in a new conversation:"
|
||||
: "This session has closed, so the review cannot start from here any more. To run it, use this in the terminal, in a new conversation:"
|
||||
page.inApp
|
||||
? asked
|
||||
? "The session closed before the review could start. To run it now, paste this into the terminal panel:"
|
||||
: "This session has closed, so the review cannot start from here any more. To run it, paste this into the terminal panel:"
|
||||
: asked
|
||||
? "The session closed before the review could start. To run it now, use this in the terminal, in a new conversation:"
|
||||
: "This session has closed, so the review cannot start from here any more. To run it, use this in the terminal, in a new conversation:"
|
||||
)
|
||||
);
|
||||
const text = "/plan2code-review";
|
||||
@@ -422,6 +456,19 @@ function renderChangelogOffer() {
|
||||
function renderDashboardOffer(primary) {
|
||||
const box = el("section", "dashboard-offer");
|
||||
if (page.gone) {
|
||||
if (page.inApp) {
|
||||
// The app's own bar already notices a dead console and offers to
|
||||
// reconnect it (its next-step slot, "Reconnect the console"); nothing here
|
||||
// is a command for anyone to run themselves.
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
null,
|
||||
"This session has closed. Plan2Code will try to reconnect the console on its own; if it cannot, the app's bar offers Reconnect the console."
|
||||
)
|
||||
);
|
||||
return box;
|
||||
}
|
||||
box.appendChild(
|
||||
el(
|
||||
"p",
|
||||
@@ -447,7 +494,7 @@ function renderDashboardOffer(primary) {
|
||||
go.disabled = disabled;
|
||||
go.addEventListener("click", () => sendAfterBuild("dashboard"));
|
||||
box.appendChild(go);
|
||||
box.appendChild(textWithCode("p", "dashboard-note", DASHBOARD_NOTE));
|
||||
box.appendChild(textWithCode("p", "dashboard-note", page.inApp ? DASHBOARD_NOTE_IN_APP : DASHBOARD_NOTE));
|
||||
return box;
|
||||
}
|
||||
|
||||
@@ -497,6 +544,10 @@ async function sendAfterBuild(kind, launch = null) {
|
||||
}
|
||||
|
||||
let stoppingHidden = false;
|
||||
// The wrapping-up dialog stays up once the stop has landed, saying it is done,
|
||||
// until it is closed: someone who pressed Stop and stepped away comes back to
|
||||
// an answer rather than to a dialog that quietly went away.
|
||||
let stopDoneShown = false;
|
||||
|
||||
// A stop is under way if this browser sent one, or if the server is holding
|
||||
// one nobody has collected: the second covers a reload on a resumed session,
|
||||
@@ -690,18 +741,21 @@ async function stopSession(handoff = false) {
|
||||
// whether the finish has landed.
|
||||
export function renderStopping() {
|
||||
const dlg = $("stopping-modal");
|
||||
if (stopDoneShown) return;
|
||||
const stopping = page.S && stopInProgress();
|
||||
if (!stopping) {
|
||||
if (dlg.open) dlg.close();
|
||||
return;
|
||||
}
|
||||
// The finish is the end of it: the hand-off card on the page says the rest.
|
||||
// Shown, the dialog says so and waits to be closed; hidden, it stays hidden.
|
||||
if (finish()) {
|
||||
page.local.stopping = null;
|
||||
saveNow();
|
||||
if (dlg.open) dlg.close();
|
||||
if (dlg.open) showStopDone(stopping.answers);
|
||||
return;
|
||||
}
|
||||
setStoppingDone(false);
|
||||
|
||||
const sent = stopping.answers;
|
||||
const collected = !page.pendingResult;
|
||||
@@ -717,19 +771,7 @@ export function renderStopping() {
|
||||
},
|
||||
{ text: "Saving your place and writing the command to pick it up", state: collected ? (stuck ? "stuck" : "now") : "later" },
|
||||
];
|
||||
const list = $("stop-steps");
|
||||
list.replaceChildren(
|
||||
...steps.map((s) => {
|
||||
const li = el("li", "is-" + s.state);
|
||||
li.appendChild(
|
||||
s.state === "now"
|
||||
? el("span", "spinner tiny")
|
||||
: el("span", "stop-mark", s.state === "done" ? "✓" : s.state === "stuck" ? "!" : "·")
|
||||
);
|
||||
li.appendChild(el("span", null, s.text));
|
||||
return li;
|
||||
})
|
||||
);
|
||||
drawStopSteps(steps);
|
||||
|
||||
const extra = $("stop-extra");
|
||||
extra.replaceChildren();
|
||||
@@ -738,9 +780,13 @@ export function renderStopping() {
|
||||
el(
|
||||
"p",
|
||||
"stop-note",
|
||||
page.gone
|
||||
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
page.inApp
|
||||
? (page.gone
|
||||
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. Paste this into the terminal panel below to carry on:"
|
||||
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. Paste this into the terminal panel below to carry on:")
|
||||
: page.gone
|
||||
? "The session closed without saying how to pick it up. Your answers and the stop are saved, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
: "Plan2Code is not running right now, so nothing new has been saved yet. Your answers and the stop are held, and the next session collects them. To carry on, run this in the terminal, in a new conversation (or alternatively run `/plan2code` to relaunch the dashboard):"
|
||||
)
|
||||
);
|
||||
const text = handoffText({ command: resumeCommand(page.S) });
|
||||
@@ -756,7 +802,7 @@ export function renderStopping() {
|
||||
"stop-note",
|
||||
agentWorking() && !collected
|
||||
? "Plan2Code is in the middle of something. It stops as soon as that is done."
|
||||
: "This usually takes a moment. You can close the tab if you need to: the command also appears in the terminal."
|
||||
: "This usually takes a moment."
|
||||
)
|
||||
);
|
||||
}
|
||||
@@ -764,6 +810,48 @@ export function renderStopping() {
|
||||
if (!stoppingHidden && !dlg.open) dlg.showModal();
|
||||
}
|
||||
|
||||
function drawStopSteps(steps) {
|
||||
$("stop-steps").replaceChildren(
|
||||
...steps.map((s) => {
|
||||
const li = el("li", "is-" + s.state);
|
||||
li.appendChild(
|
||||
s.state === "now"
|
||||
? el("span", "spinner tiny")
|
||||
: el("span", "stop-mark", s.state === "done" ? "✓" : s.state === "stuck" ? "!" : "·")
|
||||
);
|
||||
li.appendChild(el("span", null, s.text));
|
||||
return li;
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
// The title and the button, between wrapping up and done.
|
||||
function setStoppingDone(done) {
|
||||
$("stopping-title").textContent = done ? "Done" : "Wrapping up";
|
||||
$("stopping-hide").textContent = done ? "Close" : "Back to the page";
|
||||
}
|
||||
|
||||
// The stop has landed: every step ticked, and a line on where the rest is.
|
||||
function showStopDone(sent) {
|
||||
stopDoneShown = true;
|
||||
setStoppingDone(true);
|
||||
drawStopSteps([
|
||||
{ text: sent ? `Sent your ${sent === 1 ? "answer" : sent + " answers"} and the stop` : "Sent the stop", state: "done" },
|
||||
{ text: "Plan2Code picked it up", state: "done" },
|
||||
{ text: "Saved your place and wrote the command to pick it up", state: "done" },
|
||||
]);
|
||||
$("stop-extra").replaceChildren(
|
||||
el("p", "stop-note stop-done-note", "The session is stopped. The page behind this shows what was saved and the command to pick it up.")
|
||||
);
|
||||
}
|
||||
|
||||
// Closed by its button or Esc: done is read, so the next stop starts fresh.
|
||||
function closeStopping() {
|
||||
stoppingHidden = true;
|
||||
stopDoneShown = false;
|
||||
setStoppingDone(false);
|
||||
}
|
||||
|
||||
// The top bar's way home and Stop, wired once at start-up.
|
||||
export function wireEnding() {
|
||||
$("btn-home").addEventListener("click", openHomeConfirm);
|
||||
@@ -774,12 +862,12 @@ export function wireEnding() {
|
||||
$("stop-handoff").addEventListener("click", () => stopSession(true));
|
||||
$("stop-go").addEventListener("click", () => stopSession(false));
|
||||
$("stopping-hide").addEventListener("click", () => {
|
||||
stoppingHidden = true;
|
||||
closeStopping();
|
||||
$("stopping-modal").close();
|
||||
});
|
||||
// Esc on a native dialog closes it without our say; count that as hiding, or
|
||||
// the next render would open it straight back up.
|
||||
$("stopping-modal").addEventListener("cancel", () => (stoppingHidden = true));
|
||||
$("stopping-modal").addEventListener("cancel", closeStopping);
|
||||
}
|
||||
|
||||
// The three stop-related controls, drawn again when the agent comes or goes.
|
||||
|
||||
@@ -19,7 +19,15 @@ export function maybeWelcome() {
|
||||
openWelcome();
|
||||
}
|
||||
|
||||
// The same "finish the step and start fresh" tip the meter popover and the
|
||||
// dashboard's own red banner give, worded for the app's New Session button there.
|
||||
function renderWelcomeRefreshHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("welcome-refresh-text").textContent = "Once the session meter passes half, finish the step and press New Session at the top of the window.";
|
||||
}
|
||||
|
||||
export function openWelcome() {
|
||||
renderWelcomeRefreshHelp();
|
||||
if ($("help-modal").open) $("help-modal").close();
|
||||
const slot = $("welcome-bot");
|
||||
if (!slot.firstElementChild) {
|
||||
@@ -44,18 +52,149 @@ function renderAbout() {
|
||||
line.textContent = "Right now: the session is finished, and the command above is all that is left to do.";
|
||||
} else if (page.gone) {
|
||||
line.classList.add("is-bad");
|
||||
line.textContent =
|
||||
"Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The link from the terminal will bring it back.";
|
||||
line.textContent = page.inApp
|
||||
? "Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The app's own bar notices and offers to reconnect it."
|
||||
: "Right now: this page cannot reach that program. Either it has stopped, or the machine went to sleep. The link from the terminal will bring it back.";
|
||||
} else if (agentAdrift()) {
|
||||
line.classList.add("is-bad");
|
||||
line.textContent =
|
||||
"Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
|
||||
line.textContent = page.inApp
|
||||
? "Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal panel; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, press continue in the line beside Planny to wake it."
|
||||
: "Right now: this page is fine, but Plan2Code has not checked in for a few minutes. Have a look at the terminal; it may have finished its turn, hit an error, or be waiting on you there. If it is idle, type continue there to wake it.";
|
||||
} else {
|
||||
line.classList.add("is-good");
|
||||
line.textContent = "Right now: both halves are talking to each other.";
|
||||
}
|
||||
}
|
||||
|
||||
// Under the app, the dashboard's own UPDATE AVAILABLE banner never shows (the
|
||||
// app's bar already nags about a skills/app mismatch and updates in one
|
||||
// click, see docs/desktop-app.md), so this line would describe a banner the
|
||||
// reader can never find and send them to a terminal the app's own button
|
||||
// already makes unnecessary. Patched once, the first time Help opens, since
|
||||
// page.inApp never changes for the session's life.
|
||||
function renderUpdateHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-update-text").replaceChildren(
|
||||
"When the app and the installed skills fall out of step, its own top bar says so and offers ",
|
||||
el("strong", null, "Update skills"),
|
||||
", which brings them level in one click, no terminal needed."
|
||||
);
|
||||
}
|
||||
|
||||
// Same reasoning as ending.js's own close guide: the command still works
|
||||
// under the app (its terminal panel runs the agent itself), just not in "a
|
||||
// new conversation" that does not exist there.
|
||||
function renderFinishingHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-finishing-command-text").replaceChildren(
|
||||
"Press ",
|
||||
el("strong", null, "Copy"),
|
||||
", then paste the command into the terminal panel below. When the next step is another Plan2Code step, the command already ends with ",
|
||||
el("code", null, "--web"),
|
||||
", which asks Plan2Code to open this page again, so you carry on here rather than in the terminal panel."
|
||||
);
|
||||
}
|
||||
|
||||
// Two more Finishing explainers that describe behavior already reworded for
|
||||
// the app elsewhere (renderDashboardOffer's gone branch, the meter-fresh
|
||||
// popover): kept in sync here so Help never teaches the classic-only version
|
||||
// of something the screen itself no longer does under the app.
|
||||
function renderFinishingDashboardHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-finishing-dashboard-text").replaceChildren(
|
||||
"A finished screen (never a paused one) has a ",
|
||||
el("strong", null, "Back to the dashboard"),
|
||||
" button. It turns this page back into the cards, in the same conversation, so the next step starts right here. Plan2Code listens for it for as long as the session is open. Once the session has closed, the app's own bar notices and offers to reconnect it, no command needed."
|
||||
);
|
||||
}
|
||||
|
||||
function renderFinishingContinueHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-finishing-continue-text").replaceChildren(
|
||||
"When the next step is another Plan2Code step, the Next step block also has a ",
|
||||
el("strong", null, "Continue here"),
|
||||
" button. It starts that step in this same conversation, the way a dashboard card would, with this page turning into the new step. It goes away once the session meter is red, because a long conversation is the reason to start a fresh one: press New Session at the top of the window instead."
|
||||
);
|
||||
}
|
||||
|
||||
// The Troubleshooting tab's own "getting a new link" recovery flow: classic
|
||||
// only, since it ends with a command that prints a fresh browser link. Under
|
||||
// the app there is no link to print or open: the bar's next-step slot and its
|
||||
// Reconnect the console (app.js) already notice and bring the page back.
|
||||
function renderStuckReconnectHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-stuck-not-connected-ref").textContent = "the app's own bar notices and offers to reconnect it";
|
||||
$("help-stuck-table-reconnect-text").textContent = "The app's own bar notices and offers Reconnect the console.";
|
||||
$("help-stuck-reconnect-title").textContent = "Reconnecting";
|
||||
$("help-stuck-reconnect-text").textContent =
|
||||
"To get it back, press Reconnect the console in the app's own bar (it tries on its own first). Everything you typed, sent or not, is still there.";
|
||||
// Not just .hidden: .handoff-command's own display:flex outranks the
|
||||
// default [hidden] rule, so the element comes out of the DOM instead.
|
||||
$("help-stuck-reconnect-command").remove();
|
||||
}
|
||||
|
||||
// A handoff's "Copy for a new conversation" button is for carrying work to
|
||||
// a wholly separate agent (another machine, another terminal); under the app
|
||||
// that still works, but "a new conversation" is this one's own wording for
|
||||
// what New Session does, so name that instead to avoid sounding like a
|
||||
// second, missing feature.
|
||||
function renderHandoffCopyHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-handoff-copy-text").replaceChildren(
|
||||
"A ",
|
||||
el("strong", null, "Handoff"),
|
||||
" is a note a step left when you stopped it with a handoff. It shows as a dashed chip after the specs. Pick one and the cards give way to a preview with its Next task and four buttons: ",
|
||||
el("strong", null, "Pick it up here"),
|
||||
" carries on in the same step and spec, ",
|
||||
el("strong", null, "Read it all"),
|
||||
" shows the whole note, ",
|
||||
el("strong", null, "Copy for another session"),
|
||||
" puts a ready prompt on the clipboard, for pasting into the terminal panel after a New Session or anywhere else you carry the work, and ",
|
||||
el("strong", null, "Delete"),
|
||||
" removes it. A picked-up handoff drops off the list, but stays in ",
|
||||
el("code", null, "~/.plan2code/handoffs/"),
|
||||
" until the 30-day sweep."
|
||||
);
|
||||
}
|
||||
|
||||
// The Ask tab's "carry away" prompt is meant to start a genuinely fresh,
|
||||
// separate task: under the app that means pasting it into the terminal panel
|
||||
// after a New Session, not into "a new conversation" that does not exist there.
|
||||
function renderAskPromptHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-ask-prompt-text").replaceChildren(
|
||||
"When what you ask is really a new task, or you ask for a prompt, the answer ends with a ready-to-paste prompt in a box with a ",
|
||||
el("strong", null, "Copy"),
|
||||
" button. Press New Session for a clean context, then paste it into the terminal panel: it names the skill to use and the files to read, so nothing said here needs repeating."
|
||||
);
|
||||
}
|
||||
|
||||
// Matches ending.js's own renderStopping, which already says "paste into the
|
||||
// terminal panel" under the app instead of "a new conversation".
|
||||
// The Planny-poses catalog's own "Done" entry said the same "close the tab":
|
||||
// there is no tab under the app, only the one window.
|
||||
function renderPlannyDoneHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-planny-done-text").textContent = "A green star and both arms up. The session is finished. You can close the window.";
|
||||
}
|
||||
|
||||
function renderFinishingStopHelp() {
|
||||
if (!page.inApp) return;
|
||||
$("help-finishing-stop-text").replaceChildren(
|
||||
el("strong", null, "Stop session"),
|
||||
", at the top, ends the session and saves your place. Any answers you have ready go with it, and Plan2Code gives you a command to pick up where you left off, to paste into the terminal panel."
|
||||
);
|
||||
}
|
||||
|
||||
// A phrase that reads differently under the app carries its app wording in
|
||||
// `data-app`, and the browser wording stays in the markup as it was. Whole
|
||||
// paragraphs that differ are `.for-app` / `.for-browser` siblings instead,
|
||||
// switched by help.css. Plain text only: anything with markup in it is a pair.
|
||||
function renderAppWording(root) {
|
||||
if (!page.inApp) return;
|
||||
for (const node of root.querySelectorAll("[data-app]")) node.textContent = node.getAttribute("data-app");
|
||||
}
|
||||
|
||||
let helpBuilt = false;
|
||||
|
||||
async function renderHelpVersion() {
|
||||
@@ -162,7 +301,19 @@ export function selectHelpTab(id) {
|
||||
}
|
||||
|
||||
export function openHelp() {
|
||||
if (!helpBuilt) buildHelp();
|
||||
if (!helpBuilt) {
|
||||
buildHelp();
|
||||
renderAppWording($("help-panels"));
|
||||
renderUpdateHelp();
|
||||
renderFinishingHelp();
|
||||
renderFinishingDashboardHelp();
|
||||
renderFinishingContinueHelp();
|
||||
renderStuckReconnectHelp();
|
||||
renderAskPromptHelp();
|
||||
renderFinishingStopHelp();
|
||||
renderPlannyDoneHelp();
|
||||
renderHandoffCopyHelp();
|
||||
}
|
||||
const id = helpTabFor({
|
||||
view: page.view,
|
||||
dashboard: isDashboard(),
|
||||
|
||||
@@ -202,7 +202,20 @@ export const doingNow = () => workingLine(page.S && page.S.agent, page.S && page
|
||||
// itself "working", and the normal state while someone answers is "waiting".
|
||||
export function agentAdrift() {
|
||||
if (!page.agentLastSeen || page.gone || finish()) return false;
|
||||
return Date.now() - Date.parse(page.agentLastSeen) > patience(ADRIFT_MS);
|
||||
const silent = Date.now() - Date.parse(page.agentLastSeen);
|
||||
return silent > (page.pendingResult ? uncollectedLimit() : patience(ADRIFT_MS));
|
||||
}
|
||||
|
||||
// With answers sent and nothing collecting them, the agent's quiet allowance
|
||||
// stops counting: those answers are what it is meant to come back for. An
|
||||
// agent that said it is waiting pings from `wait` every five seconds, so a
|
||||
// minute of silence means it is not there. One that said it is working (it
|
||||
// asked and carried on) collects at its next `wait`, so it gets the plain
|
||||
// three minutes, never the half hour a build task may have asked for.
|
||||
const UNCOLLECTED_MS = 60 * 1000;
|
||||
|
||||
function uncollectedLimit() {
|
||||
return agentWorking() ? ADRIFT_MS : UNCOLLECTED_MS;
|
||||
}
|
||||
|
||||
// Answers that went nowhere: pressed Send, and nothing has collected them.
|
||||
|
||||
@@ -46,7 +46,7 @@
|
||||
|
||||
// Shared by Implement and Implement + Review.
|
||||
const BUILD_HELPERS =
|
||||
"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.";
|
||||
"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. Pick each helper's strength and effort from helper-strength.md's table: light for a 1-2 file task the task file spells out, standard for multi-file or debugging work.";
|
||||
|
||||
// Pathfinder's and Plan's reason on a finished spec (a fixed bug).
|
||||
export const FIXED_REASON = "This bug is fixed. Delete it with the Delete button on its chip, or move it to specs--completed/.";
|
||||
@@ -110,7 +110,7 @@ export const SKILLS = Object.freeze([
|
||||
pose: "pathfinder",
|
||||
builds: false, phased: false, metered: false, templates: true,
|
||||
weight: null, started: null, ran: null, resume: "folder",
|
||||
subagents: "Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you.",
|
||||
subagents: "Use helpers for codebase recon, sketches and lookups beside the conversation. Keep every question for the person with you. Recon and lookups at light strength, research questions at standard.",
|
||||
states: ["none", "unrecognized", "exploring"], marksNext: true,
|
||||
greyed: {
|
||||
default: "This spec is already past the questions",
|
||||
@@ -264,7 +264,7 @@ export const SKILLS = Object.freeze([
|
||||
pose: "quick-task",
|
||||
builds: true, phased: false, metered: true, templates: true,
|
||||
weight: 1, started: "Quick task started", ran: "Quick task built", resume: null,
|
||||
subagents: "Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself.",
|
||||
subagents: "Use helpers for side lookups, such as reading unfamiliar code or checking documentation, while you make the change yourself. Side lookups at light strength, low effort.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
@@ -284,7 +284,7 @@ export const SKILLS = Object.freeze([
|
||||
pose: "review",
|
||||
builds: false, phased: false, metered: true, templates: false,
|
||||
weight: 2, started: "Review started", ran: "Code review run", resume: null,
|
||||
subagents: "Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report.",
|
||||
subagents: "Run the review's analysis in one fresh helper briefed only with the spec and the change set (references/reviewer-brief.md); verify every finding yourself before you report. At standard strength or above (strongest for branch or full scope), high effort.",
|
||||
states: "any",
|
||||
greyed: null,
|
||||
card: {
|
||||
|
||||
@@ -101,6 +101,10 @@ export const page = {
|
||||
// The frame's update ({ installed, latest }), present only when a newer
|
||||
// release is out; null otherwise.
|
||||
updateFrame: null,
|
||||
// Whether the desktop app is driving this session (the frame's `inApp`):
|
||||
// false until the first frame lands, same as every other flag here, and
|
||||
// from an older server that sends none.
|
||||
inApp: false,
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
subagentsFrame: null,
|
||||
|
||||
@@ -175,3 +175,10 @@
|
||||
.about-live.is-good { background: var(--ok-soft); border-color: var(--ok); color: var(--ok); }
|
||||
.about-live.is-bad { background: var(--stage-soft); border-color: var(--stage); color: var(--stage); }
|
||||
|
||||
|
||||
/* Help says some things two ways, once for a browser tab and once for the
|
||||
desktop app's window: `.for-browser` and `.for-app` siblings, with the root
|
||||
marked `in-app` under the app (core.js). Important, because a block's own
|
||||
display (a flex row, say) would otherwise outrank this. */
|
||||
:root:not(.in-app) .for-app,
|
||||
:root.in-app .for-browser { display: none !important; }
|
||||
@@ -161,6 +161,7 @@
|
||||
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-strength { margin: 4px 0 0; color: var(--ink-3); font-size: 12.5px; }
|
||||
.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); }
|
||||
@@ -441,6 +442,7 @@ input[type="text"].invalid { border-color: var(--warn); }
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
.btn.tiny:hover:not(:disabled) { background: var(--accent-soft); filter: brightness(1.04); }
|
||||
.quick-answer + .quick-answer { margin-left: 6px; }
|
||||
|
||||
.btn-row { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 18px; align-items: center; }
|
||||
|
||||
|
||||
@@ -127,6 +127,15 @@
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
}
|
||||
/* Under the app, the word is a button that types it into the agent's terminal. */
|
||||
.agent-key-btn {
|
||||
font: inherit; font-weight: 700; color: var(--accent);
|
||||
background: var(--accent-soft); border: 1px solid var(--accent-line); border-radius: 6px;
|
||||
padding: 0 6px; cursor: pointer;
|
||||
}
|
||||
.agent-key-btn:hover:not(:disabled) { border-color: var(--accent); }
|
||||
.agent-key-btn:disabled { opacity: 0.55; cursor: default; }
|
||||
.agent-key-btn:focus-visible { outline: 2px solid var(--focus); outline-offset: 2px; }
|
||||
|
||||
/* "What to check", beside the quiet and Not running lines. A link in a button's clothes. */
|
||||
.status-help {
|
||||
|
||||
@@ -146,6 +146,8 @@
|
||||
.meter-fresh { margin: 0 0 8px; padding-top: 6px; border-top: 1px solid var(--rule); }
|
||||
.meter-fresh[hidden] { display: none; }
|
||||
.meter-fresh-text { margin: 0 0 6px; font-size: 12px; color: var(--ink-2); }
|
||||
/* Under the app the whole note is one button: a press is the bar's New Session. */
|
||||
.meter-fresh-btn { display: block; width: 100%; margin: 2px 0 6px; }
|
||||
.meter-fresh-row .handoff-code { flex-basis: 180px; font-size: 12px; padding: 6px 10px; }
|
||||
.meter-item-points { flex: none; font-weight: 600; color: var(--ink); font-variant-numeric: tabular-nums; }
|
||||
|
||||
|
||||
@@ -31,6 +31,20 @@ 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"]);
|
||||
// The person's Helper strength profile, applied on top of helper-strength.md's table.
|
||||
export const STRENGTHS = Object.freeze(["balanced", "thrifty", "best", "session"]);
|
||||
export const DEFAULT_STRENGTH = "balanced";
|
||||
// What the dialog's strength radios say, and the line under them for the picked one.
|
||||
export const STRENGTH_LABELS = Object.freeze({ balanced: "Balanced", thrifty: "Thrifty", best: "Best", session: "Match my session" });
|
||||
export const STRENGTH_HELP = Object.freeze({
|
||||
balanced: "Each helper gets the strength its job needs: light for lookups, stronger for reviews and design work.",
|
||||
thrifty: "One step lighter everywhere to save cost; reviews stay at standard or above.",
|
||||
best: "The strongest model and high effort for everything except lookups.",
|
||||
session: "Helpers run on whatever your session uses; nothing is set for them.",
|
||||
});
|
||||
// What a reported helper may say it actually ran with.
|
||||
export const HELPER_STRENGTHS = Object.freeze(["light", "standard", "strongest", "inherit"]);
|
||||
export const HELPER_EFFORTS = Object.freeze(["low", "medium", "high"]);
|
||||
|
||||
/* ------------------------------------------------------------- settings */
|
||||
|
||||
@@ -46,12 +60,13 @@ export function effectiveInstruction(setting) {
|
||||
|
||||
export function defaultSetting(workflow) {
|
||||
// On until the person turns it off, for the workflows that offer the switch.
|
||||
return { workflow, on: offered(workflow), instruction: null, max: DEFAULT_MAX };
|
||||
return { workflow, on: offered(workflow), instruction: null, max: DEFAULT_MAX, strength: DEFAULT_STRENGTH };
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ on, instruction, max }` from untrusted input, or `{ error }` naming the
|
||||
* field that failed: "bad" (wrong type), "too-long" (instruction) or "max".
|
||||
* `{ on, instruction, max, strength }` from untrusted input, or `{ error }`
|
||||
* naming the field that failed: "bad" (wrong type), "too-long" (instruction),
|
||||
* "max" or "strength". A missing strength is the default, balanced.
|
||||
* Returns an error object rather than throwing, so the route and the store
|
||||
* reader share one validator. An empty instruction means the default: null.
|
||||
*/
|
||||
@@ -67,7 +82,9 @@ export function cleanSetting(input) {
|
||||
}
|
||||
const max = input.max;
|
||||
if (!Number.isInteger(max) || max < MAX_MIN || max > MAX_MAX) return { error: "max" };
|
||||
return { on: input.on, instruction, max };
|
||||
const strength = input.strength === undefined || input.strength === null ? DEFAULT_STRENGTH : input.strength;
|
||||
if (!STRENGTHS.includes(strength)) return { error: "strength" };
|
||||
return { on: input.on, instruction, max, strength };
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------ the lines */
|
||||
@@ -77,13 +94,22 @@ 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-subagents.md); 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.',
|
||||
"Match each helper's strength and effort to its job, as helper-strength.md says; when your tools cannot set them, start the helper without them.",
|
||||
]);
|
||||
|
||||
export const PATHFINDER_RESEARCH_LINE = "Research questions always use helpers, whatever this switch says.";
|
||||
|
||||
// The profile line each strength adds to an "on" block.
|
||||
export const STRENGTH_LINES = Object.freeze({
|
||||
balanced: "Helper strength: balanced (the table in helper-strength.md as written).",
|
||||
thrifty: "Helper strength: thrifty (one step lighter in strength and effort than the table; reviews never below standard).",
|
||||
best: "Helper strength: best (strongest and high effort for every helper except lookups, which stay light).",
|
||||
session: "Helper strength: match the session (set no model or effort on any helper, whatever the skill files say).",
|
||||
});
|
||||
|
||||
// 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 }) {
|
||||
export function onLines({ revision, replaces, max, instruction, strength }) {
|
||||
const label = replaces ? `revision ${revision}, replaces revision ${replaces}` : `revision ${revision}`;
|
||||
const own = String(instruction || "")
|
||||
.split("\n")
|
||||
@@ -91,7 +117,7 @@ export function onLines({ revision, replaces, max, instruction }) {
|
||||
.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),
|
||||
...[...FRAME_LINES, ...own, STRENGTH_LINES[strength] || STRENGTH_LINES[DEFAULT_STRENGTH], `At most ${max} helpers at once.`].map((line) => " " + line),
|
||||
];
|
||||
}
|
||||
|
||||
@@ -110,17 +136,18 @@ export function blockFor(setting, told) {
|
||||
if (!setting || !offered(setting.workflow) || !(setting.revision > last.revision)) return null;
|
||||
const { revision, max } = setting;
|
||||
const instruction = effectiveInstruction(setting);
|
||||
const strength = STRENGTHS.includes(setting.strength) ? setting.strength : DEFAULT_STRENGTH;
|
||||
if (setting.on) {
|
||||
const replaces = last.state === "on" ? last.revision : undefined;
|
||||
return {
|
||||
field: { state: "on", revision, max, instruction },
|
||||
lines: onLines({ revision, replaces, max, instruction }),
|
||||
field: { state: "on", revision, max, instruction, strength },
|
||||
lines: onLines({ revision, replaces, max, instruction, strength }),
|
||||
cursor: { revision, state: "on" },
|
||||
};
|
||||
}
|
||||
if (last.state !== "on") return null;
|
||||
return {
|
||||
field: { state: "off", revision, max, instruction },
|
||||
field: { state: "off", revision, max, instruction, strength },
|
||||
lines: [offLine(revision)],
|
||||
cursor: { revision, state: "off" },
|
||||
};
|
||||
@@ -147,6 +174,8 @@ export function checkHelper(entry) {
|
||||
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`);
|
||||
}
|
||||
if (entry.strength !== undefined && !HELPER_STRENGTHS.includes(entry.strength)) problems.push(`${who}: strength must be light, standard, strongest or inherit`);
|
||||
if (entry.effort !== undefined && !HELPER_EFFORTS.includes(entry.effort)) problems.push(`${who}: effort must be low, medium or high`);
|
||||
return problems;
|
||||
}
|
||||
|
||||
@@ -191,22 +220,43 @@ export function switchLabel(frame) {
|
||||
// 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.
|
||||
// reported. A result shows once the helper ended, and a reported strength or
|
||||
// effort as one line ("Standard, medium effort").
|
||||
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 } : {}),
|
||||
}));
|
||||
const rows = real.map(({ id, title, ask, state, result, strength, effort }) => {
|
||||
const ran = {
|
||||
...(HELPER_STRENGTHS.includes(strength) ? { strength } : {}),
|
||||
...(HELPER_EFFORTS.includes(effort) ? { effort } : {}),
|
||||
};
|
||||
const line = strengthLine(ran.strength, ran.effort);
|
||||
return {
|
||||
id,
|
||||
title,
|
||||
ask,
|
||||
state,
|
||||
stateLabel: STATE_LABELS[state] || STATE_LABELS.running,
|
||||
...((state === "done" || state === "failed") && typeof result === "string" && result ? { result } : {}),
|
||||
...ran,
|
||||
...(line ? { strengthLine: line } : {}),
|
||||
};
|
||||
});
|
||||
return { alone: false, rows };
|
||||
}
|
||||
|
||||
const HELPER_STRENGTH_WORDS = Object.freeze({ light: "Light", standard: "Standard", strongest: "Strongest", inherit: "Session model" });
|
||||
|
||||
// "Standard, medium effort", "Light", "Medium effort", or "" when neither was reported.
|
||||
function strengthLine(strength, effort) {
|
||||
const parts = [];
|
||||
if (strength) parts.push(HELPER_STRENGTH_WORDS[strength]);
|
||||
if (effort) parts.push(`${effort} effort`);
|
||||
const line = parts.join(", ");
|
||||
return line && line[0].toUpperCase() + line.slice(1);
|
||||
}
|
||||
|
||||
// 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) {
|
||||
|
||||
@@ -42,6 +42,7 @@ import { cleanSetting, offered } from "./public/subagents.js";
|
||||
import { ACCENTS, DEFAULT_ACCENT, DEFAULT_CARD_WIDTH, cardWidth } from "./public/palette.js";
|
||||
import { SERVABLE, TYPES, asset } from "./static.mjs";
|
||||
import { handoffsDir, isHandoffId } from "./handoffs.mjs";
|
||||
import { linkToOpen, openLink } from "./open-link.mjs";
|
||||
import {
|
||||
NotepadError,
|
||||
addImage,
|
||||
@@ -99,6 +100,7 @@ const ROUTES = [
|
||||
{ match: (p, req) => p.startsWith("/shots/") || req.url.startsWith("/shots/"), run: shot },
|
||||
{ match: (p, req) => p.startsWith("/uploads/") || req.url.startsWith("/uploads/"), run: uploads },
|
||||
{ path: "/submit", method: "POST", origin: true, run: submit },
|
||||
{ path: "/open-link", method: "POST", origin: true, run: openLinkRoute },
|
||||
{ path: "/chat", method: "POST", origin: true, run: chat },
|
||||
{ path: "/chat/decision", method: "POST", origin: true, run: chatDecision },
|
||||
{ path: "/workspace", method: "GET", run: workspaceGet },
|
||||
@@ -455,15 +457,15 @@ function subagentsPost(req, res, ctx) {
|
||||
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 { on, instruction, max, strength } = clean;
|
||||
const current = readSubagentSetting(ctx.dir);
|
||||
const next = { workflow: state.workflow, on, instruction, max };
|
||||
const next = { workflow: state.workflow, on, instruction, max, strength };
|
||||
// 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(ctx.worktree(), state.workflow, { on, instruction, max });
|
||||
saveSubagentStoreEntry(ctx.worktree(), state.workflow, { on, instruction, max, strength });
|
||||
if (!unchanged) writeSubagentSetting(ctx.dir, { ...next, revision: (current ? current.revision : 0) + 1 });
|
||||
} catch (e) {
|
||||
return json(res, 500, { error: String(e.message) });
|
||||
@@ -1025,6 +1027,18 @@ function recordSubmitted(state, actions) {
|
||||
}
|
||||
}
|
||||
|
||||
// A link the page inside the desktop app cannot open itself (open-link.mjs).
|
||||
// http and https only; the page shows the link to paste when this says no.
|
||||
function openLinkRoute(req, res) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
const href = linkToOpen(body && body.url);
|
||||
if (!href) return json(res, 400, { error: "only http and https links open" });
|
||||
if (!openLink(href)) return json(res, 500, { error: "no browser could be started" });
|
||||
return json(res, 200, { ok: true, url: href });
|
||||
});
|
||||
}
|
||||
|
||||
function submit(req, res, ctx) {
|
||||
return readBody(req, (err, body) => {
|
||||
if (err) return json(res, err.tooBig ? 413 : 400, { error: err.tooBig ? "too large" : "body must be JSON" });
|
||||
|
||||
@@ -45,6 +45,7 @@ import {
|
||||
} from "./inbox.mjs";
|
||||
import { serverWorkspace } from "./workspace.mjs";
|
||||
import { serverSubagents } from "./settings.mjs";
|
||||
import { inAppSignal } from "./in-app.mjs";
|
||||
import { chatOffline } from "./public/chat.js";
|
||||
import { meterView } from "./public/meter.js";
|
||||
import { startsClean } from "./public/hops.js";
|
||||
@@ -246,6 +247,13 @@ function ensureConversation(state) {
|
||||
// writer, this server.
|
||||
const subagents = serverSubagents({ dir: DIR, worktree: sessionWorktree });
|
||||
|
||||
// Whether the agent driving this session is the desktop app: fixed for the
|
||||
// process's whole life (the env var that says so is set once, at spawn), so
|
||||
// read once rather than on every frame. The page uses it to drop advice that
|
||||
// only makes sense in a plain terminal (a command to copy into a new
|
||||
// conversation) in favour of the app's own Restart and Update skills buttons.
|
||||
const IN_APP = Boolean(inAppSignal());
|
||||
|
||||
// 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).
|
||||
@@ -261,6 +269,7 @@ function stateFrame(state) {
|
||||
workspace: workspace.workspaceView(),
|
||||
meter: meterView(ledgerEntries()),
|
||||
subagents: subagents.view(state),
|
||||
inApp: IN_APP,
|
||||
...(updateInfo ? { update: updateInfo } : {}),
|
||||
have: haveKey(),
|
||||
};
|
||||
|
||||
@@ -514,7 +514,10 @@ export async function readOverview(root, specDir) {
|
||||
}
|
||||
|
||||
// The line every CLI command hands the agent to end its terminal messages with.
|
||||
export function terminalLine(url) {
|
||||
// Under the desktop app the page is already in the window beside the terminal,
|
||||
// so the address would only be noise there: the line points at the window.
|
||||
export function terminalLine(url, env = process.env) {
|
||||
if (env.PLAN2CODE_IN_APP === "1") return "→ Look at the dashboard beside this terminal.";
|
||||
return `→ Look at the web console: ${url}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import path from "node:path";
|
||||
|
||||
import { cleanSetting, defaultSetting, offered } from "./public/subagents.js";
|
||||
import { cleanSetting, defaultSetting, DEFAULT_STRENGTH, offered } from "./public/subagents.js";
|
||||
import { ensureDir, fileStamp, HOME_DIR, readJson, readJsonLines, withStateLock, writeJsonAtomic } from "./files.mjs";
|
||||
import { foldKey } from "./workspace.mjs";
|
||||
|
||||
@@ -10,10 +10,11 @@ import { foldKey } from "./workspace.mjs";
|
||||
|
||||
// The person's Subagents switch, remembered per project folder and workflow:
|
||||
//
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max } } }
|
||||
// { "<folded project path>": { "<workflow>": { on, instruction, max, strength } } }
|
||||
//
|
||||
// Keyed with foldKey(), as workspaces.json is. `instruction: null` is the
|
||||
// workflow's shipped default.
|
||||
// workflow's shipped default; an entry saved before `strength` existed reads
|
||||
// as balanced.
|
||||
export const SUBAGENTS_FILE = path.join(HOME_DIR, "subagents.json");
|
||||
const SUBAGENTS_LOCK = "subagents.json.lock";
|
||||
|
||||
@@ -22,13 +23,13 @@ function readSubagentStore() {
|
||||
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.
|
||||
// The saved `{ on, instruction, max, strength }` 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 { on, instruction, max, strength } = 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 };
|
||||
return saved && !saved.error ? saved : { on, instruction, max, strength };
|
||||
}
|
||||
|
||||
// Single-writer rule: only the server may call this (its routes).
|
||||
@@ -40,7 +41,7 @@ export function saveSubagentStoreEntry(worktree, workflow, value) {
|
||||
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 } };
|
||||
store[key] = { ...project, [workflow]: { on: value.on, instruction: value.instruction, max: value.max, strength: value.strength } };
|
||||
writeJsonAtomic(SUBAGENTS_FILE, store);
|
||||
},
|
||||
SUBAGENTS_LOCK
|
||||
@@ -127,7 +128,14 @@ export function latestOpenCaps(dir) {
|
||||
|
||||
/* ------------------------------------------------- the server's Subagents */
|
||||
|
||||
export const sameSetting = (a, b) => a.workflow === b.workflow && a.on === b.on && a.instruction === b.instruction && a.max === b.max;
|
||||
// A side without `strength` (a session file written before it existed) is
|
||||
// balanced, so an upgrade alone never bumps the revision.
|
||||
export const sameSetting = (a, b) =>
|
||||
a.workflow === b.workflow &&
|
||||
a.on === b.on &&
|
||||
a.instruction === b.instruction &&
|
||||
a.max === b.max &&
|
||||
(a.strength || DEFAULT_STRENGTH) === (b.strength || DEFAULT_STRENGTH);
|
||||
|
||||
/**
|
||||
* The Subagents switch as the server keeps it. subagents-setting.json has one
|
||||
@@ -166,8 +174,8 @@ export function serverSubagents(ctx) {
|
||||
function sync(state) {
|
||||
if (!state || typeof state.workflow !== "string") return;
|
||||
const { workflow } = state;
|
||||
const { on, instruction, max } = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max };
|
||||
const { on, instruction, max, strength } = offered(workflow) ? subagentStoreEntry(ctx.worktree(), workflow) : defaultSetting(workflow);
|
||||
const target = { workflow, on, instruction, max, strength };
|
||||
const current = readSubagentSetting(dir);
|
||||
if (current && sameSetting(current, target)) return;
|
||||
writeSubagentSetting(dir, { ...target, revision: (current ? current.revision : 0) + 1 });
|
||||
@@ -178,8 +186,8 @@ export function serverSubagents(ctx) {
|
||||
// is the shipped default, which the page reads from subagents.js itself.
|
||||
function view(state) {
|
||||
const workflow = state && state.workflow;
|
||||
const { on, instruction, max, revision } = settingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: capsNow().includes("subagents"), on, instruction, max, revision };
|
||||
const { on, instruction, max, strength, revision } = settingNow() || { ...defaultSetting(workflow), revision: 0 };
|
||||
return { offered: offered(workflow), supported: capsNow().includes("subagents"), on, instruction, max, strength: strength || DEFAULT_STRENGTH, revision };
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -46,6 +46,7 @@ export const SERVABLE = new Set([
|
||||
"subagents.js",
|
||||
"mentions.js",
|
||||
"favicon.js",
|
||||
"app-bridge.js",
|
||||
"git-board.js",
|
||||
"git-board-view.js",
|
||||
"pr-url.js",
|
||||
|
||||
+1
-1
@@ -17,6 +17,6 @@
|
||||
"url": "https://github.com/jparkerweb/plan2code"
|
||||
},
|
||||
"homepage": "https://github.com/jparkerweb/plan2code",
|
||||
"releaseDate": "2026-10-20",
|
||||
"releaseDate": "2026-10-25",
|
||||
"mode": "utility"
|
||||
}
|
||||
Reference in new issue
Block a user