mirror of
https://github.com/jparkerweb/plan2code.git
synced 2026-11-19 13:11:18 -08:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d5d8278cfe | ||
|
|
77ddcc048d | ||
|
|
7d5e78179e | ||
|
|
46f1f17261 | ||
|
|
0d569954c4 | ||
|
|
2709252daa | ||
|
|
5043b424cf | ||
|
|
dd2ab86584 | ||
|
|
78153576a9 | ||
|
|
c3ee918b62 | ||
|
|
d4d64987fe | ||
|
|
10379e3870 |
No files matched your search
@@ -58,6 +58,7 @@ plan2code/
|
||||
│ ├── parse-check.mjs # Imports every shipped browser module as real ESM
|
||||
│ ├── screenshots/ # JSON payloads posted per shot (`ask` reuses `question.json`; `finish` follows `signoff.json`)
|
||||
│ ├── test-web-console-*.mjs, web-console-test-helpers.mjs # Web console suites, split by area (the page tests are `-page-*`, the source shape `-shape`), and their shared setup
|
||||
│ ├── node-test.mjs, page-test-helpers.mjs # `npm test`'s `node --test`, files at once capped at one per spare core; the page tests' browser sessions and their redraw-safe `styleOf()`, `stylesOf()`, `scrollCard()`
|
||||
│ ├── test-launcher.mjs, test-getting-started.mjs # Launcher suite; newcomer docs kept in step
|
||||
│ ├── test-skill-scripts.mjs, test-script-<skill>.mjs, test-git-repo.mjs, skill-script-helpers.mjs, fixture-helpers.mjs # Skill script suites and fixtures
|
||||
│ └── validate-char-count.js # Pre-commit character count validator
|
||||
@@ -302,7 +303,7 @@ Key design points:
|
||||
- **The CLI hands the agent its terminal line.** `open`, `post` and `wait` (exits `0` and `10`) print `terminalLine: "→ Look at the web console: <url>"` (`terminalLine()` in `sessions.mjs`), and `console.md` asks the agent to end every terminal message with the latest one verbatim, so the tool builds the line rather than the model. In `wait` it is added to the printed result only; the collected `result.json` on disk never carries it. `open` also prints `swept: { sessions, scratch, handoffs }` when it found anything to clean.
|
||||
- **State fields written by `open`, not the agent.** Every `open` (fresh or resume) records `state.worktree` and `state.branch` from `repoRoots()` — the branch is read off `<gitdir>/HEAD` on the walk that already finds the gitdir (`""` on a detached HEAD or outside git; env-relocated repos ask git, as before) — and the page shows them in the footer as the workspace label (`footerLabel()`: `folder · branch`, or `folder + N folders · branch` once folders are added, stepping down through narrower tiers); a click opens the Workspace dialog. `state.wake = true` is set only by a fresh `open --workflow dashboard` and deleted by every resume (server restart, launch, Back to the dashboard); the page also keeps a per-sid `sessionStorage` guard so a reload never replays it.
|
||||
- **`looks.width` is a person-level preference** alongside theme, accent and sounds in `looks.json`. `CARD_WIDTHS` in `public/palette.js` (`narrow` 720, `comfortable` 880 — default — `wide` 1080) is read by the page (`cardWidth()` validates a saved value) and by `routes.mjs`, which paints `data-width` on first load; `styles/tokens.css` maps `data-width` onto the single `--card-width` variable that every column rule uses.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or `404 { "error": "no overview" }`. A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readOverview()` resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all 404.
|
||||
- **`GET /overview` is the one route that reads a project file.** It serves `<spec>/overview.md` as `text/markdown` with `cache-control: no-store` (so the Overview tab is always fresh), or with `?file=map` / `?file=draft` the spec's `pathfinder/map.md` / live `PLAN-DRAFT-*.md` (the dashboard's Map and Plan draft tabs, shown only while the spec has no overview; `readSpecFile()` picks the file and names it in `x-spec-file`), or an empty `204` when there is no such file (normal for most specs, and no failed request in the browser console). A dashboard session honors `?spec=` only when it equals a `dir` in `state.scan.specs`; every other workflow uses `state.specDir` and ignores the query. The root is `state.worktree` (fallback `state.project`), and `readSpecFile()` (which `readOverview()` wraps) resolves and `realpath`s the file and refuses anything outside the root's realpath, so `../`, absolute paths and outward symlinks all get the same 204, as do an unscanned `?spec=` and an unknown `?file=`.
|
||||
- **Month-old sessions are deleted whole.** `open` lists `staleSessions()` (directories matching the session-id pattern whose `state.json` mtime is older than 30 days, never the sid being opened — no exceptions for paused sessions or unread sends) and `staleScratch()` (top-level regular `.json` / `.mjs` files in the console folder older than 30 days, never `looks.json` or `console-dir` — `PROTECTED_CONSOLE_FILES` — never a directory or symlink) before it prints, and removes them after; `removeSessions()` / `removeScratch()` re-check every name against the session-id pattern / the scratch-name rule before deleting — not the age, the skipped sid or the file type, which the `stale*` listing already decided, so never hand them names that did not come from it. `console.md` tells agents to write temporary payload files into the session's own folder so they go with it.
|
||||
- **User Preferences → Cleanup deletes on demand, from a list the server makes.** `POST /cleanup` (origin-checked) with `{ scan: true }` returns `cleanupFindings()`: `{ items: [{ id, where, name, kind, bytes, folder? }], bytes }` (`folder` on `notepad:` items only), ids `session:<sid>` (the `staleSessions()` rule, and every file in the folder that old too, never the serving sid), `console:<name>` (anything at the top of the console home but `PROTECTED_CONSOLE_FILES`, `sessions` and `runtime`, directories too) and `root:<name>` (anything at the top of `~/.plan2code` but `KEPT_PLAN2CODE_ENTRIES`: `console`, `bin`, `launcher.json`, `install.json`, `models.json`, `handoffs`, `notepads`, `app`, `app.json`, `agents.json`), `notepad:<key>` (a month-old notepad, whole; see Notebook below) and `completed:<name>` (each folder or link directly under the session worktree's `specs--completed/` whose newest mtime is older than the session age, 30 days; loose files there stay; the server passes `project: sessionWorktree() || PROJECT`, and without a `project` the archive is never scanned). Both stray kinds must be untouched for `STRAY_GRACE_MS` (an hour, by the newest `lstat` mtime anywhere inside, since rewriting a file never moves its folder's mtime; unreadable reads as fresh): the same folders hold `workspaces.json.lock` and `writeJsonAtomic()`'s `<file>.<pid>.tmp`, which live for milliseconds. `root:` is only scanned when the console home is `<PLAN2CODE_MODELS_DIR or ~/.plan2code>/console`, so a test or dev home never reaches the real folder. Paths never go to the page. `{ delete: [id] }` runs `removeCleanup()`, which re-scans and removes only ids still on the fresh list (symlinks unlinked, never followed), returning `{ removed, bytes, failed }`. The page always shows the list before **Delete these**.
|
||||
- **The console's path is stated, not searched for.** Each Interface line names `references/web-console/` beside the SKILL.md and the `~/.plan2code/console/console-dir` fallback; the prompts with room (all but pathfinder, plan, document and finalize, which sit near the char limit) also name the canonical global install path `~/.agents/skills/<skill>/references/web-console/` (the skills CLI's real store; every agent dir links into it), and every `console.mjs open` writes `HERE` to `~/.plan2code/console/console-dir` (only `open`, so a `help` or dev run from `src/` never repoints it) so a later session can read the path from a fixed place. Without these the agent hunts the skill install dirs on every session.
|
||||
|
||||
@@ -47,12 +47,20 @@ cd plan2code-metrics && npm install # First time setup
|
||||
cd plan2code-metrics && npm run build # Build the CLI
|
||||
cd plan2code-metrics && npm test # vitest (aggregator, community, improver)
|
||||
|
||||
# Desktop app (plan2code-app/, Rust + Tauri). CI's `app` workflow runs all three on
|
||||
# Windows, macOS and Linux and fails on any rustfmt difference or clippy warning, so run
|
||||
# them before pushing, not only cargo test (see plan2code-app/README.md "Tests").
|
||||
# First time: rustup component add rustfmt clippy (for the toolchain in rust-toolchain.toml)
|
||||
cd plan2code-app && node scripts/vendor.mjs && cargo fmt --check
|
||||
cd plan2code-app && cargo clippy --workspace --all-targets -- -D warnings
|
||||
cd plan2code-app && cargo test --workspace
|
||||
|
||||
# Plan2Code Bot (end-to-end workflow runner, Claude Agent SDK)
|
||||
cd plan2code-bot && npm install && npm run build
|
||||
cd plan2code-bot && npm test # vitest
|
||||
```
|
||||
|
||||
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in loop, metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel.
|
||||
The root `npm test` does not run the metrics or bot vitest suites; run them in their package. `npm run dev` in loop, metrics and bot is `tsup --watch`. The web console and launcher suites isolate themselves with `PLAN2CODE_CONSOLE_HOME`, `PLAN2CODE_MODELS_DIR` and `PLAN2CODE_NO_BROWSER=1` (`scripts/web-console-test-helpers.mjs`), so they never open a browser or touch your real console home. The web console suites are split by area so `node --test` runs them in parallel. `npm test` runs them through `scripts/node-test.mjs`, which caps the files run at once at one per spare core (8 at most): each page test file drives a browser, and more at once than the cores can carry fails page tests at random (a flat 8 did on 3 and 4 core CI runners). Page tests (`test-web-console-page-*.mjs`) read styles and set scrolls only through `styleOf()`, `stylesOf()` and `scrollCard()` from `page-test-helpers.mjs`, which retry until the element is still on the page; `test-web-console-shape.mjs` fails a raw `locator.evaluate` that does either.
|
||||
|
||||
## Test/Dev Env Vars
|
||||
|
||||
|
||||
@@ -313,7 +313,7 @@ Built for a mixed product and engineering room reading one screen together.
|
||||
- **A switch per sound.** Every cue is an event in `SOUND_EVENTS` (`palette.js`), each naming its file and rank: `startSkill` (`start-skill.mp3`, played once the dashboard's **Start** is accepted) 5, `bootup` 4, `sessionStart` / `sessionEnd` (`start-stop.mp3`) 3, `question` / `skillReady` / `chatReply` (`next.mp3`) 2, `newTab` (`insert.mp3`) 1, `snore` (`sleeping.mp3`, looped by the wake-up outside the queue) 0. The queue, the held slot and the one-at-a-time rule in `app.js` work on events, one `Audio` per file shared by the events that use it. User Preferences shows a *Play sounds* master (`looks.sound`) over one box per event, saved flat as `sound<Event>` (`soundStartSkill`, …) because `looks.json` only holds flat values; `soundPrefs()` turns any missing or non-boolean switch on, so a file from before the switches keeps every sound. A cue plays only while the master and its own switch are both on; the master off grays the boxes but keeps their ticks, and ticking a box plays it.
|
||||
- **Send breathes.** `#btn-send:not(:disabled)` runs `send-pulse`, a soft accent ring that spreads and fades every 2.4s; a disabled Send is still, and reduced motion switches it off.
|
||||
- **Per-tab scroll memory.** An in-memory `Map` keyed by view id holds the scroller's position (the main column on a document or the Overview, the card on the questions view, with the item it belonged to), restored when the tab comes back. Page-local, never persisted, cleared when the session turns into or out of the dashboard.
|
||||
- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record.
|
||||
- **The Overview tab.** Appears only while `GET /overview` returns a file for the session's spec (on the dashboard: the picker's spec; gone for *start from scratch*), fetched with `no-store` on load, on a spec change and on every tab click, so it always shows the file as it is on disk. On the dashboard, a spec with no overview gets a **Map** tab (`?file=map`, `pathfinder/map.md`) and a **Plan draft** tab (`?file=draft`, the live `PLAN-DRAFT-*.md`) in its place, each while its file exists, fetched and drawn the same way; away from the dashboard only the overview is read, since a session's own map or draft is the work already in front of it. Rendered through the same DOM-only markdown path as every doc, captioned read-only. It never becomes a doc: the page is not the record.
|
||||
- **The footer slot.** The workspace label sits centered in the footer's middle track, 12px and muted: `footerLabel()` in `public/workspace.js` builds `folder · branch` (from the workspace's original folder and `state.branch`), or `folder + N folders · branch` once folders are added, and `renderWhere()` steps down through its narrower tiers (`FOOTER_TIERS`) until the text fits. A warning dot marks a missing or unreadable folder. A click opens the Workspace dialog (`#workspace-modal`), where each folder has its own **Copy path**. The notification pill is fixed over the same spot and covers it while it shows, on purpose: nothing there needs pressing while the pill is up. The dashboard keeps the footer for this label alone: `renderFooter()` puts `is-dash` on it, which hides the summary and Send (and on a narrow screen keeps the label, the one thing left in the bar); the footer only disappears there when there is no label to show.
|
||||
- **The wake-up.** A fresh dashboard (`state.wake`, plus a per-sid `sessionStorage` guard) plays Planny powering on center stage, as proven in `pathfinder/sketch-01`. The wake layer hides the dashboard behind a solid `var(--bg)` backdrop (`.wake::before`, so it follows the theme) whose opacity fades out over the same 0.6s as the glide, revealing the menu as he lands; the notification pill (`.banner`, z-index 46) stays above the layer (45). Before the first click or key he sleeps there on loop under a "Click to wake Planny" hint (`.wake.dormant`): Z's rising, slow breathing, slack arms swaying out of step, his feet pulsing like a standby light. While he sleeps the page tries to loop `sleeping.mp3` (browsers usually refuse until the first click, so this is normally silent). That click fades the hint and nudges him (`.wake.stirring`): he rocks gently about his feet (`wake-nudge`) while exactly one snore plays from the top, via the `stir()` callback `playWake()` awaits — timed by the snore's `ended`, capped at 6s, or a 2.6s timer when sounds are off or refused. Then the boot starts to `bootup.mp3` (in place of the opening chime; outranked only by the Start-skill cue, which cannot coincide with it because the wake layer swallows every click and key until the run ends), which fades out over 0.5s the moment the run ends or is aborted. The boot pops the Z's outward: 0.4s power-on and his feet blink · 1.35s feet plant · 1.5s / 1.9s arms lift off his sides · 2.5s the star opens lit, with a scan · 2.85s he glances left, right, then ahead · 3.2s smile · 3.6s hop and a cheer, star back to ink · 4.3s a 0.6s glide into the rail, measured once by `boot.js` and handed to CSS as `--wake-glide` · the menu groups rise in 60ms apart as he lands, and the note types in. Done by 5s (a fallback timer covers a hidden tab whose transition never fires). The beats are CSS keyframes on delays under `.wake.booting`, all inside `@media (prefers-reduced-motion: no-preference)`; there is no skip: from the waking click on, clicks and plain keys (no Ctrl/Meta/Alt) are swallowed so the nudge, boot and sound always play out; only a launch mid-run aborts it (snore stopped, boot-up faded), and under reduced motion `playWake()` resolves at once and the awake dashboard is simply there.
|
||||
|
||||
|
||||
@@ -129,7 +129,10 @@ Scroll down for the utilities. Outside a git repository the **Git** card says so
|
||||
spec that has an `overview.md`, an **Overview** tab shows it — read-only,
|
||||
and read fresh from disk each time you open the tab, so an edit shows up
|
||||
straight away. No file, no tab. On the dashboard it follows the spec picked
|
||||
at the top, and disappears for *start from scratch*.
|
||||
at the top, and disappears for *start from scratch*. A picked spec that is
|
||||
not documented yet shows its **Map** (`pathfinder/map.md`) and its
|
||||
**Plan draft** (the live `PLAN-DRAFT-*.md`) as tabs instead, each when it
|
||||
exists.
|
||||
- **Where you are, at the bottom.** The footer names the folder the session
|
||||
was launched from and its git branch (`plan2code · feature/…`), muted in
|
||||
the middle. Click it to open the Workspace dialog (see *Your workspace*).
|
||||
@@ -869,7 +872,7 @@ origin.
|
||||
| `POST /submit` | The Send. A note may carry `images` and `files`, each `[{ path, name }]`: at most 5 together, images in `images` and documents in `files`, every path inside this session's `uploads/`, otherwise 400. |
|
||||
| `POST /chat` | A Quick question `{ text, about?, images?, files?, conversation }`, or `{ reset: true, conversation }` for New conversation. Appended to the session's `chat.ndjson`. 400 `too-long` (over 4,000 characters), `image`, `file` or `bad`; 409 `offline`, `stale` or `limit` (10 per conversation). Never refused because a card send is still uncollected. |
|
||||
| `POST /chat/decision` | Approve or Decline on an edit the agent proposed: `{ re, decision, text?, conversation }`. Once per proposal; does not count toward the 10. |
|
||||
| `GET /overview?spec=specs/<name>` | The Overview tab's read of `<spec>/overview.md`, as `text/markdown` with `cache-control: no-store`. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get 404. |
|
||||
| `GET /overview?spec=specs/<name>[&file=map\|draft]` | The Overview tab's read of `<spec>/overview.md` (or, with `file=`, the Map tab's `pathfinder/map.md` or the Plan draft tab's live `PLAN-DRAFT-*.md`), as `text/markdown` with `cache-control: no-store` and the file's spec-relative name, URL-encoded, in `x-spec-file`. A missing file is a 204. On the dashboard `spec` must be one of the scanned specs; elsewhere the session's own spec is used. The file's real path must stay inside the project, so `../`, absolute paths and symlinks pointing out all get the same 204 as a missing file, as does an unscanned `spec` or an unknown `file`. |
|
||||
| `GET /handoff?id=<id>` | *Read it all*: the handoff's `.md` from `~/.plan2code/handoffs/`, as `text/markdown` with `cache-control: no-store`. A dashboard only, and only an id its own scan listed: a used, unknown or malformed id is 404. |
|
||||
| `GET /workspace` | The Workspace dialog's list: folders, `missing`, `remote` and the agent's folder `issues`. `?check=1` re-checks every folder on disk first. |
|
||||
| `POST /workspace/add` | `{ path, name?, description? }`. The path is resolved against the folder the session started in (`~` expanded) and must be a folder: 400 `not-a-folder`, `duplicate` (with its `name`; compared case-insensitively on Windows and macOS), `bad-name`, or `name-taken` with a `suggest`. Answers the new entry, `nested: true` when it sits inside another folder in the list. |
|
||||
|
||||
@@ -103,8 +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). In helper-strength, the page-cards test "a card cut by the window fades at its bottom edge..." did the same.
|
||||
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not.
|
||||
- When a page test (`scripts/test-web-console-page-*.mjs`) fails only on CI or only in a full run, look for a race with a redraw before suspecting the change, and fix the test, not the timeout: read styles and set scrolls through `styleOf()`, `stylesOf()` and `scrollCard()` in `page-test-helpers.mjs` (a card a redraw replaced reads "" for every style and scrolls nothing; `test-web-console-shape.mjs` now fails a raw `locator.evaluate` that does either), and wait for the page to hold what the next step needs before acting (the workspace frame before typing `@`, the notepad's drawn marks, a newly selected tab). Keep `npm test`'s file concurrency under `scripts/node-test.mjs`'s cap of one file per spare core: a flat `--test-concurrency=8` ran 8 browsers on 3 and 4 core runners and failed a different page test on every CI run. On a busy local machine, rerun the failing files alone first; the chat stress test and the session suite's "no submitted frame within 5s" cascade still fail that way under load.
|
||||
- Run `npm test` and `cargo test` from a terminal outside the desktop app, or with `PLAN2CODE_IN_APP`, `PLAN2CODE_APP_TOKEN`, `PLAN2CODE_APP_VERSION`, `PLAN2CODE_APP_ANNOUNCE`, `PLAN2CODE_EMBED_ORIGIN` and `PLAN2CODE_CONSOLE_SID` unset (`env -u ... npm test`): inherited from the app they fail about 34 tests that check behavior outside the app (the update banner, the terminal line, cookies, open's browser launch), and a test console announces itself to the live window. A `cargo test` run mid-build once took the window over that way, then left an agent-less dashboard in it, and the build's question was never seen. The app now ignores sessions outside its console store (`take_announced` in `main.rs`), and the Rust console tests scrub the variables, but the JS suites do not. Before pushing a change under `plan2code-app/`, also run `cargo fmt --check` and `cargo clippy --workspace --all-targets -- -D warnings` there, not only `cargo test`: CI's `app` workflow fails on either, and the Rust code once reached a PR never formatted (20 files) with three clippy errors, one only macOS and Linux could see (see plan2code-app/README.md "Tests").
|
||||
- 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.
|
||||
|
||||
@@ -12,6 +12,7 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
- **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.
|
||||
- **helpers**: Plan and Revise Plan now offer helpers (subagents), with the web console's **Subagents** button in the top bar, on by default like the other opted-in skills. Each skill has its own rule for what is independent enough to hand off. Plan uses helpers for reading the sources the person names, mapping separate areas of the codebase in Phase 2, gathering evidence on each open tech choice in Phase 4, and one fresh cross-check of the PLAN-DRAFT against the conversation in Phase 7; questions, decisions, sign-offs and the writing of the PLAN-DRAFT stay with the session. Revise Plan uses read-only lookups on the code behind affected and at-risk completed tasks at Steps 1 and 2 and, only after approval and when a revision touches 3 or more phase files, one helper per phase file to apply the approved edits under `specs/`. The rules live in each skill's Helpers section, so they apply in terminal sessions too. `helper-strength.md` now ships in both, with a row for each new kind of helper job (Plan's recon reuses the lookups row) and the PLAN-DRAFT cross-check held at `standard` or above, like a review.
|
||||
- **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 each as a colored badge with a small three-bar level mark (teal for low, amber for medium, violet for high; the session's own model in plain gray), while screen readers still hear one line, such as "Standard, medium effort".
|
||||
- **web console**: picking a spec on the dashboard that is not documented yet now shows its main files as read-only tabs in the top bar, like the **Overview** tab of a documented spec: **Map** for a Pathfinder map (`pathfinder/map.md`) and **Plan draft** for Plan's live `PLAN-DRAFT-*.md`, each when it exists. Once the spec has an `overview.md`, Overview replaces them.
|
||||
- `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.
|
||||
- **custom agents**: add your own agent CLIs in the web console under **User Preferences → Agents** (name, command, arguments with `{prompt}` and `{model}` tokens, start prompt, bypass arguments, models) with a **Test** button that shows where the command is found. They are saved in `~/.plan2code/agents.json`, listed after Claude Code, Devin and Codex by both the `plan2code` command (`--cli <id>` picks one) and the desktop app, and New Session reuses the same agent. A broken file or entry is skipped with a warning and never stops anything. `/plan2code` only works in an agent that loads the installed Plan2Code skills; a blank start prompt starts the agent with nothing typed.
|
||||
- **desktop app**: when no agent CLI is installed, the first-run checklist and the launch card explain what to install, with each agent's install command, an **Install page** link, and a **Check again** button that finds a newly installed agent (or a custom one) without restarting the app.
|
||||
@@ -21,7 +22,9 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
- **docs**: all prose, help text, skill prompts and comments now use US English spelling (color, gray, behavior, canceled, -ize), and `npm test` checks it (`scripts/test-us-english.mjs`).
|
||||
- **web console**: **User Preferences → Highlight color** now offers 38 colors in two rows of nineteen, covering the range of a Paint-style picker: new **Maroon**, **Peach**, **Brown**, **Cream**, **Lemon**, **Forest**, **Mint**, **Aqua**, **Lavender**, **Pink** and **Mono** (near-black in light mode, near-white in dark). Five near twins were merged (Copper into Rust, Marigold into Gold, Mustard into Lemon, Jade into Emerald, Lilac into Violet); a saved choice of one of those keeps its twin instead of falling back to Ocean.
|
||||
- **web console**: the **Subagents** dialog is wider and shorter, like the Notebook: Helpers and At most share a row, and the four Helper strength choices sit side by side, each wearing the Subagents tab's colored level badge (Thrifty light, Balanced standard, Best strongest, Match my session plain), now ordered from lightest to strongest.
|
||||
- **launcher**: when no agent CLI is installed, `plan2code` now prints each supported agent's install command and official page, and points at User Preferences → Agents for another CLI, before it exits.
|
||||
- **desktop app**: a clean start is now one press. Pathfinder's **Start fresh** menu option reads **Start New Session** under the app, and sending it asks the app for its New Session (the resume command is copied first; declining the app's confirm leaves the usual finish). A finished step that names a skill to run next shows a **Start a New Session** button beside its command, also copying the command first. The plain web console keeps its wording and does neither. The app's console frame also now allows clipboard writes, so the copied command and every **Copy** button can reach the clipboard there.
|
||||
- **desktop app**: the launch card's agent choice is built from the agents that are installed, so a machine with only Devin or Codex starts on it with Start enabled, instead of assuming Claude Code.
|
||||
- **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.
|
||||
@@ -43,6 +46,9 @@ All notable changes to Plan2Code will be documented in this file.
|
||||
|
||||
### 🐛 Fixed
|
||||
|
||||
- **web console**: on the dashboard, canceling one spec's Delete and quickly opening another's no longer leaves **Delete it** doing nothing; the first dialog's late close cleared the second dialog's spec.
|
||||
- **web console**: a handoff's **Copy** button keeps showing **Copied** (or **Copy was refused**) when the dashboard redraws while the clipboard answers, instead of the word landing on a button that was already replaced.
|
||||
- **web console**: a finished screen's press (**Commit it now**, **Update CHANGELOG first**, **Back to the dashboard**, **Continue here**, a review) that nothing picks up, because the agent's turn ended while the screen waited, no longer says "Opening Changelog…" forever. After a minute of silence the line beside Planny says Plan2Code is not running and the choice is saved, with **continue** to type in the terminal (a button that types it there, under the app).
|
||||
- **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.
|
||||
|
||||
+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 --test-concurrency=8 scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-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-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-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 scripts/node-test.mjs scripts/test-us-english.mjs scripts/test-script-git.mjs scripts/test-git-repo.mjs scripts/test-skill-scripts.mjs scripts/test-script-changelog.mjs scripts/test-web-console-git.mjs scripts/test-web-console-git-board.mjs scripts/test-web-console-chat.mjs scripts/test-web-console-subagents.mjs scripts/test-web-console-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-agents-file.mjs scripts/test-web-console-source.mjs scripts/test-web-console-hardening.mjs scripts/test-web-console-embed.mjs scripts/test-web-console-in-app.mjs scripts/test-web-console-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",
|
||||
|
||||
@@ -44,7 +44,12 @@ npm run build # build the installable bundle
|
||||
|
||||
```
|
||||
cd plan2code-app
|
||||
node scripts/vendor.mjs # once: the xterm files cargo builds against
|
||||
cargo fmt --check
|
||||
cargo clippy --workspace --all-targets -- -D warnings
|
||||
cargo test --workspace
|
||||
```
|
||||
|
||||
The `app` workflow runs all three on Windows, macOS and Linux, and fails on any rustfmt difference or clippy warning, so run them before pushing, not only `cargo test`. Clippy on one system does not see code for another: an import used only inside a `#[cfg(windows)]` test is clean on Windows and an unused-import error on macOS and Linux, so put such imports inside the `cfg`'d item.
|
||||
|
||||
Real Claude, Devin and Codex are never started by a test. The real window and terminal panel are checked by hand before each release.
|
||||
@@ -19,7 +19,8 @@ file directly after checking it against the release's checksum list.
|
||||
- [ ] `node scripts/check-versions.mjs --tag v<version>` passes (version.json, package.json,
|
||||
CHANGELOG.md and the app's tauri.conf.json, package.json and Cargo.toml all agree)
|
||||
- [ ] `npm test` passes at the repo root, with the app absent
|
||||
- [ ] `cargo test --workspace` passes in `plan2code-app/`, and the `app` workflow is green on all
|
||||
- [ ] `cargo fmt --check`, `cargo clippy --workspace --all-targets -- -D warnings` and
|
||||
`cargo test --workspace` pass in `plan2code-app/`, and the `app` workflow is green on all
|
||||
three systems
|
||||
- [ ] The pre-release has one `plan2code-app-<version>-<os>-<arch>` file per system and a
|
||||
`plan2code-app-<version>-SHA256SUMS.txt`
|
||||
|
||||
@@ -102,7 +102,10 @@ fn main() {
|
||||
}
|
||||
Command::Size => say(&size_text().unwrap_or_else(|| "SIZE unknown".into())),
|
||||
Command::Pid => say(&format!("PID {}", std::process::id())),
|
||||
Command::Env(name) => say(&format!("ENV {name}={}", std::env::var(&name).unwrap_or_default())),
|
||||
Command::Env(name) => say(&format!(
|
||||
"ENV {name}={}",
|
||||
std::env::var(&name).unwrap_or_default()
|
||||
)),
|
||||
Command::Echo(text) => say(&format!("echo: {text}")),
|
||||
}
|
||||
}
|
||||
@@ -118,7 +121,10 @@ mod tests {
|
||||
assert_eq!(parse("EXIT 7\r\n"), Command::Exit(7));
|
||||
assert_eq!(parse("SIZE"), Command::Size);
|
||||
assert_eq!(parse("PID"), Command::Pid);
|
||||
assert_eq!(parse("ENV PLAN2CODE_IN_APP"), Command::Env("PLAN2CODE_IN_APP".into()));
|
||||
assert_eq!(
|
||||
parse("ENV PLAN2CODE_IN_APP"),
|
||||
Command::Env("PLAN2CODE_IN_APP".into())
|
||||
);
|
||||
assert_eq!(parse("hello there"), Command::Echo("hello there".into()));
|
||||
}
|
||||
|
||||
|
||||
@@ -19,7 +19,9 @@ pub enum AgentState {
|
||||
Idle,
|
||||
Running,
|
||||
/// The agent ended without a Restart press, or could not be started.
|
||||
Ended { reason: String },
|
||||
Ended {
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// Runs just before a Restart starts the fresh agent, and returns the line the
|
||||
@@ -114,7 +116,9 @@ pub struct AgentManager {
|
||||
|
||||
fn lock(inner: &Mutex<Inner>) -> MutexGuard<'_, Inner> {
|
||||
// A panic in another thread must not take the whole app's agent control down.
|
||||
inner.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
inner
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
}
|
||||
|
||||
impl AgentManager {
|
||||
@@ -173,7 +177,15 @@ impl AgentManager {
|
||||
return Err("an agent is already running for this project".to_string());
|
||||
}
|
||||
inner.brief_note = None;
|
||||
let previous = inner.last_start.replace((StartChoice { kind, model, effort, mode }, brief));
|
||||
let previous = inner.last_start.replace((
|
||||
StartChoice {
|
||||
kind,
|
||||
model,
|
||||
effort,
|
||||
mode,
|
||||
},
|
||||
brief,
|
||||
));
|
||||
match self.shared.spawn(&mut inner) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
@@ -210,7 +222,10 @@ impl AgentManager {
|
||||
}
|
||||
|
||||
pub fn input(&self, bytes: &[u8]) -> Result<(), String> {
|
||||
let host = lock(&self.shared.inner).running.as_ref().map(|r| Arc::clone(&r.host));
|
||||
let host = lock(&self.shared.inner)
|
||||
.running
|
||||
.as_ref()
|
||||
.map(|r| Arc::clone(&r.host));
|
||||
match host {
|
||||
Some(host) => host.write(bytes),
|
||||
None => Ok(()),
|
||||
@@ -271,7 +286,10 @@ impl Shared {
|
||||
fn snapshot(&self, inner: &Inner) -> AgentSnapshot {
|
||||
AgentSnapshot {
|
||||
state: inner.state.clone(),
|
||||
kind: inner.last_start.as_ref().map(|(choice, _)| choice.kind.id().to_string()),
|
||||
kind: inner
|
||||
.last_start
|
||||
.as_ref()
|
||||
.map(|(choice, _)| choice.kind.id().to_string()),
|
||||
mode: inner.last_start.as_ref().map(|(choice, _)| choice.mode),
|
||||
generation: self.generation.load(Ordering::SeqCst),
|
||||
brief_note: inner.brief_note.clone(),
|
||||
@@ -284,10 +302,19 @@ impl Shared {
|
||||
|
||||
/// Start the agent in `inner.last_start` and watch for it to end.
|
||||
fn spawn(self: &Arc<Self>, inner: &mut Inner) -> Result<(), String> {
|
||||
let (choice, brief) = inner.last_start.clone().ok_or("no agent has been started")?;
|
||||
let (choice, brief) = inner
|
||||
.last_start
|
||||
.clone()
|
||||
.ok_or("no agent has been started")?;
|
||||
let prompt = brief.unwrap_or_else(|| choice.kind.default_prompt().to_string());
|
||||
let mut spec =
|
||||
agent_launch_spec(&choice.kind, &self.folder, choice.model.as_deref(), choice.effort.as_deref(), choice.mode, &prompt);
|
||||
let mut spec = agent_launch_spec(
|
||||
&choice.kind,
|
||||
&self.folder,
|
||||
choice.model.as_deref(),
|
||||
choice.effort.as_deref(),
|
||||
choice.mode,
|
||||
&prompt,
|
||||
);
|
||||
if let Ok(extra) = self.extra_env.lock() {
|
||||
spec.env.extend(extra.iter().cloned());
|
||||
}
|
||||
@@ -329,7 +356,9 @@ impl Shared {
|
||||
on_output,
|
||||
)?);
|
||||
|
||||
inner.running = Some(Running { host: Arc::clone(&host) });
|
||||
inner.running = Some(Running {
|
||||
host: Arc::clone(&host),
|
||||
});
|
||||
inner.state = AgentState::Running;
|
||||
// A fresh agent starts on a clean screen; its replay must too.
|
||||
inner.replay.clear();
|
||||
@@ -360,7 +389,9 @@ impl Shared {
|
||||
match self.spawn(inner) {
|
||||
Ok(()) => Ok(()),
|
||||
Err(e) => {
|
||||
inner.state = AgentState::Ended { reason: format!("could not start the agent: {e}") };
|
||||
inner.state = AgentState::Ended {
|
||||
reason: format!("could not start the agent: {e}"),
|
||||
};
|
||||
self.emit(inner);
|
||||
Err(e)
|
||||
}
|
||||
|
||||
@@ -124,14 +124,25 @@ impl PermissionMode {
|
||||
/// or with `.exe`, `.cmd` or `.bat` on Windows (as `windows_command` resolves
|
||||
/// a program to run).
|
||||
pub fn find_on_path(program: &str, path_var: &str) -> Option<PathBuf> {
|
||||
let exts: &[&str] = if cfg!(windows) { &["exe", "cmd", "bat"] } else { &[""] };
|
||||
path_var.split(if cfg!(windows) { ';' } else { ':' }).filter(|dir| !dir.is_empty()).find_map(|dir| {
|
||||
exts.iter().find_map(|ext| {
|
||||
let name = if ext.is_empty() { program.to_string() } else { format!("{program}.{ext}") };
|
||||
let candidate = Path::new(dir).join(name);
|
||||
candidate.is_file().then_some(candidate)
|
||||
let exts: &[&str] = if cfg!(windows) {
|
||||
&["exe", "cmd", "bat"]
|
||||
} else {
|
||||
&[""]
|
||||
};
|
||||
path_var
|
||||
.split(if cfg!(windows) { ';' } else { ':' })
|
||||
.filter(|dir| !dir.is_empty())
|
||||
.find_map(|dir| {
|
||||
exts.iter().find_map(|ext| {
|
||||
let name = if ext.is_empty() {
|
||||
program.to_string()
|
||||
} else {
|
||||
format!("{program}.{ext}")
|
||||
};
|
||||
let candidate = Path::new(dir).join(name);
|
||||
candidate.is_file().then_some(candidate)
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
/// Where `kind`'s CLI runs from: the test override when it is set, else its
|
||||
@@ -166,11 +177,17 @@ pub fn launch_spec(
|
||||
mode: PermissionMode,
|
||||
prompt: &str,
|
||||
) -> LaunchSpec {
|
||||
let bin = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty());
|
||||
let bin = std::env::var(AGENT_BIN_ENV)
|
||||
.ok()
|
||||
.filter(|bin| !bin.is_empty());
|
||||
let mut spec = launch_spec_with(kind, folder, model, effort, mode, prompt, bin.as_deref());
|
||||
// The override names a program to run as it is; a real agent is looked up on PATH.
|
||||
if cfg!(windows) && bin.is_none() {
|
||||
let (program, args) = windows_command(&spec.program, spec.args, &std::env::var("PATH").unwrap_or_default());
|
||||
let (program, args) = windows_command(
|
||||
&spec.program,
|
||||
spec.args,
|
||||
&std::env::var("PATH").unwrap_or_default(),
|
||||
);
|
||||
spec.program = program;
|
||||
spec.args = args;
|
||||
}
|
||||
@@ -188,7 +205,12 @@ fn launch_spec_with(
|
||||
) -> LaunchSpec {
|
||||
let cwd = folder.to_path_buf();
|
||||
if let Some(bin) = bin_override {
|
||||
return LaunchSpec { program: bin.to_string(), args: vec![], env: vec![], cwd };
|
||||
return LaunchSpec {
|
||||
program: bin.to_string(),
|
||||
args: vec![],
|
||||
env: vec![],
|
||||
cwd,
|
||||
};
|
||||
}
|
||||
|
||||
let strings = |list: &[&str]| list.iter().map(|s| s.to_string()).collect::<Vec<_>>();
|
||||
@@ -245,7 +267,12 @@ fn launch_spec_with(
|
||||
// directories (Task 9.9): the agent CLI itself, and anything it shells
|
||||
// out to, needs a PATH that finds them anyway.
|
||||
let env = vec![("PATH".to_string(), crate::node_check::resolved_path())];
|
||||
LaunchSpec { program: program.to_string(), args, env, cwd }
|
||||
LaunchSpec {
|
||||
program: program.to_string(),
|
||||
args,
|
||||
env,
|
||||
cwd,
|
||||
}
|
||||
}
|
||||
|
||||
/// An agent installed with npm is, on Windows, a `.cmd` shim beside an
|
||||
@@ -330,7 +357,12 @@ pub fn load_custom_agents(file: &Path) -> (Vec<CustomAgent>, Vec<String>) {
|
||||
match std::fs::read_to_string(file) {
|
||||
Ok(text) => parse_agents_file(&text),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => (Vec::new(), Vec::new()),
|
||||
Err(e) => (Vec::new(), vec![format!("agents.json could not be read ({e}), so no custom agents are used")]),
|
||||
Err(e) => (
|
||||
Vec::new(),
|
||||
vec![format!(
|
||||
"agents.json could not be read ({e}), so no custom agents are used"
|
||||
)],
|
||||
),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -344,19 +376,30 @@ pub fn parse_agents_file(text: &str) -> (Vec<CustomAgent>, Vec<String>) {
|
||||
return none("agents.json is not an object, so no custom agents are used".to_string());
|
||||
};
|
||||
if file.get("schema").and_then(Value::as_f64) != Some(1.0) {
|
||||
let shown = file.get("schema").map_or("undefined".to_string(), |v| v.to_string());
|
||||
return none(format!("agents.json has schema {shown}, not 1, so no custom agents are used"));
|
||||
let shown = file
|
||||
.get("schema")
|
||||
.map_or("undefined".to_string(), |v| v.to_string());
|
||||
return none(format!(
|
||||
"agents.json has schema {shown}, not 1, so no custom agents are used"
|
||||
));
|
||||
}
|
||||
let list = match file.get("agents") {
|
||||
None | Some(Value::Null) => return (Vec::new(), Vec::new()),
|
||||
Some(Value::Array(list)) => list,
|
||||
Some(_) => return none("agents.json: agents is not a list, so no custom agents are used".to_string()),
|
||||
Some(_) => {
|
||||
return none(
|
||||
"agents.json: agents is not a list, so no custom agents are used".to_string(),
|
||||
)
|
||||
}
|
||||
};
|
||||
|
||||
let mut warnings = Vec::new();
|
||||
let mut list: &[Value] = list;
|
||||
if list.len() > MAX_CUSTOM_AGENTS {
|
||||
warnings.push(format!("agents.json lists {} agents; only the first {MAX_CUSTOM_AGENTS} are used", list.len()));
|
||||
warnings.push(format!(
|
||||
"agents.json lists {} agents; only the first {MAX_CUSTOM_AGENTS} are used",
|
||||
list.len()
|
||||
));
|
||||
list = &list[..MAX_CUSTOM_AGENTS];
|
||||
}
|
||||
let mut agents: Vec<CustomAgent> = Vec::new();
|
||||
@@ -377,8 +420,12 @@ pub fn parse_agents_file(text: &str) -> (Vec<CustomAgent>, Vec<String>) {
|
||||
|
||||
fn valid_agent_id(id: &str) -> bool {
|
||||
let mut chars = id.chars();
|
||||
let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
|
||||
first_ok && id.len() <= 32 && chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
let first_ok = chars
|
||||
.next()
|
||||
.is_some_and(|c| c.is_ascii_lowercase() || c.is_ascii_digit());
|
||||
first_ok
|
||||
&& id.len() <= 32
|
||||
&& chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
|
||||
}
|
||||
|
||||
fn text_list(entry: &Value, field: &str, default: Vec<String>) -> Result<Vec<String>, String> {
|
||||
@@ -394,8 +441,14 @@ fn text_list(entry: &Value, field: &str, default: Vec<String>) -> Result<Vec<Str
|
||||
}
|
||||
|
||||
// One entry against the rules, in the same order as `checkEntry` in agents.mjs.
|
||||
fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) -> Result<CustomAgent, String> {
|
||||
let Some(object) = entry.as_object() else { return Err("not an object".to_string()) };
|
||||
fn check_entry(
|
||||
entry: &Value,
|
||||
ids: &HashSet<String>,
|
||||
names: &HashSet<String>,
|
||||
) -> Result<CustomAgent, String> {
|
||||
let Some(object) = entry.as_object() else {
|
||||
return Err("not an object".to_string());
|
||||
};
|
||||
let id = match object.get("id").and_then(Value::as_str) {
|
||||
Some(id) if !id.is_empty() => id,
|
||||
_ => return Err("id is missing".to_string()),
|
||||
@@ -412,7 +465,10 @@ fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) ->
|
||||
return Err(format!("id \"{id}\" is already used"));
|
||||
}
|
||||
|
||||
let name = object.get("name").and_then(Value::as_str).map_or("", str::trim);
|
||||
let name = object
|
||||
.get("name")
|
||||
.and_then(Value::as_str)
|
||||
.map_or("", str::trim);
|
||||
if name.is_empty() {
|
||||
return Err("name is missing".to_string());
|
||||
}
|
||||
@@ -423,7 +479,10 @@ fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) ->
|
||||
return Err(format!("name \"{name}\" is already used"));
|
||||
}
|
||||
|
||||
let command = object.get("command").and_then(Value::as_str).map_or("", str::trim);
|
||||
let command = object
|
||||
.get("command")
|
||||
.and_then(Value::as_str)
|
||||
.map_or("", str::trim);
|
||||
if command.is_empty() {
|
||||
return Err("command is missing".to_string());
|
||||
}
|
||||
@@ -451,8 +510,15 @@ fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) ->
|
||||
if model_id.is_empty() || !seen.insert(model_id.to_string()) {
|
||||
continue;
|
||||
}
|
||||
let label = item.get("label").and_then(Value::as_str).map(str::trim).filter(|l| !l.is_empty());
|
||||
models.push(CustomModel { id: model_id.to_string(), label: label.map(str::to_string) });
|
||||
let label = item
|
||||
.get("label")
|
||||
.and_then(Value::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|l| !l.is_empty());
|
||||
models.push(CustomModel {
|
||||
id: model_id.to_string(),
|
||||
label: label.map(str::to_string),
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(_) => return Err("models must be a list".to_string()),
|
||||
@@ -475,7 +541,12 @@ fn check_entry(entry: &Value, ids: &HashSet<String>, names: &HashSet<String>) ->
|
||||
/// argument holds it), then `model_args` when a model is chosen, then
|
||||
/// `bypass_args` when checks are off. `prompt` defaults to the entry's own; a
|
||||
/// blank one drops an argument that is exactly `{prompt}`. Plain text only.
|
||||
pub fn build_custom_args(agent: &CustomAgent, prompt: Option<&str>, model: Option<&str>, bypass: bool) -> Vec<String> {
|
||||
pub fn build_custom_args(
|
||||
agent: &CustomAgent,
|
||||
prompt: Option<&str>,
|
||||
model: Option<&str>,
|
||||
bypass: bool,
|
||||
) -> Vec<String> {
|
||||
let text = prompt.unwrap_or(&agent.prompt);
|
||||
let blank = text.trim().is_empty();
|
||||
let mut out = Vec::new();
|
||||
@@ -495,7 +566,12 @@ pub fn build_custom_args(agent: &CustomAgent, prompt: Option<&str>, model: Optio
|
||||
out.push(text.to_string());
|
||||
}
|
||||
if let Some(model) = model.filter(|m| !m.is_empty()) {
|
||||
out.extend(agent.model_args.iter().map(|arg| arg.replace("{model}", model)));
|
||||
out.extend(
|
||||
agent
|
||||
.model_args
|
||||
.iter()
|
||||
.map(|arg| arg.replace("{model}", model)),
|
||||
);
|
||||
}
|
||||
if bypass {
|
||||
out.extend(agent.bypass_args.iter().cloned());
|
||||
@@ -563,18 +639,26 @@ pub fn find_agent_in(id: &str, file: Option<&Path>) -> Option<Agent> {
|
||||
return Some(Agent::Builtin(kind));
|
||||
}
|
||||
let (agents, _) = load_custom_agents(file?);
|
||||
agents.into_iter().find(|agent| agent.id == id).map(Agent::Custom)
|
||||
agents
|
||||
.into_iter()
|
||||
.find(|agent| agent.id == id)
|
||||
.map(Agent::Custom)
|
||||
}
|
||||
|
||||
/// Every custom agent in `~/.plan2code/agents.json`, read afresh, with the
|
||||
/// warnings about anything in the file that was skipped.
|
||||
pub fn custom_agents() -> (Vec<CustomAgent>, Vec<String>) {
|
||||
agents_file().map(|file| load_custom_agents(&file)).unwrap_or_default()
|
||||
agents_file()
|
||||
.map(|file| load_custom_agents(&file))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
fn clean_command(command: &str) -> &str {
|
||||
let command = command.trim();
|
||||
command.strip_prefix('"').and_then(|c| c.strip_suffix('"')).unwrap_or(command)
|
||||
command
|
||||
.strip_prefix('"')
|
||||
.and_then(|c| c.strip_suffix('"'))
|
||||
.unwrap_or(command)
|
||||
}
|
||||
|
||||
fn has_separator(command: &str, windows: bool) -> bool {
|
||||
@@ -634,8 +718,16 @@ pub fn agent_launch_spec(
|
||||
match agent {
|
||||
Agent::Builtin(kind) => launch_spec(*kind, folder, model, effort, mode, prompt),
|
||||
Agent::Custom(custom) => {
|
||||
if let Some(bin) = std::env::var(AGENT_BIN_ENV).ok().filter(|bin| !bin.is_empty()) {
|
||||
return LaunchSpec { program: bin, args: vec![], env: vec![], cwd: folder.to_path_buf() };
|
||||
if let Some(bin) = std::env::var(AGENT_BIN_ENV)
|
||||
.ok()
|
||||
.filter(|bin| !bin.is_empty())
|
||||
{
|
||||
return LaunchSpec {
|
||||
program: bin,
|
||||
args: vec![],
|
||||
env: vec![],
|
||||
cwd: folder.to_path_buf(),
|
||||
};
|
||||
}
|
||||
let resolved = agent.installed_at();
|
||||
custom_launch_spec(
|
||||
@@ -667,13 +759,21 @@ fn custom_launch_spec(
|
||||
) -> LaunchSpec {
|
||||
let mut args = build_custom_args(custom, Some(prompt), model, mode == PermissionMode::Bypass);
|
||||
let mut path = base_path.to_string();
|
||||
let mut program =
|
||||
resolved.map_or_else(|| clean_command(&custom.command).to_string(), |p| p.to_string_lossy().into_owned());
|
||||
let mut program = resolved.map_or_else(
|
||||
|| clean_command(&custom.command).to_string(),
|
||||
|p| p.to_string_lossy().into_owned(),
|
||||
);
|
||||
let mut extra_env = Vec::new();
|
||||
if windows {
|
||||
let ext = resolved.and_then(|p| p.extension()).map(|e| e.to_string_lossy().to_lowercase()).unwrap_or_default();
|
||||
let ext = resolved
|
||||
.and_then(|p| p.extension())
|
||||
.map(|e| e.to_string_lossy().to_lowercase())
|
||||
.unwrap_or_default();
|
||||
if let (true, Some(file)) = (ext == "cmd" || ext == "bat", resolved) {
|
||||
let file_name = file.file_name().map(|n| n.to_string_lossy().into_owned()).unwrap_or_default();
|
||||
let file_name = file
|
||||
.file_name()
|
||||
.map(|n| n.to_string_lossy().into_owned())
|
||||
.unwrap_or_default();
|
||||
// A full path may have a space in its folder, and `cmd /c` mangles a
|
||||
// command line that starts with a quote: run the bare file name with
|
||||
// its folder at the front of the child's PATH instead.
|
||||
@@ -687,18 +787,33 @@ fn custom_launch_spec(
|
||||
// quoted as the launcher's `quoteForCmd` does and handed over in a
|
||||
// variable: `cmd` expands it once and then parses it, so its quotes
|
||||
// hold and a `%` inside it is not expanded again.
|
||||
let line: Vec<String> = std::iter::once(file_name).chain(args).map(|arg| quote_for_cmd(&arg)).collect();
|
||||
let line: Vec<String> = std::iter::once(file_name)
|
||||
.chain(args)
|
||||
.map(|arg| quote_for_cmd(&arg))
|
||||
.collect();
|
||||
extra_env.push((CMD_LINE_ENV.to_string(), line.join(" ")));
|
||||
// `cmd` looks in the current folder (the project) before PATH: a
|
||||
// same-named file there must not run in the agent's place.
|
||||
extra_env.push(("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
|
||||
args = vec!["/d".to_string(), "/c".to_string(), format!("%{CMD_LINE_ENV}%")];
|
||||
extra_env.push((
|
||||
"NoDefaultCurrentDirectoryInExePath".to_string(),
|
||||
"1".to_string(),
|
||||
));
|
||||
args = vec![
|
||||
"/d".to_string(),
|
||||
"/c".to_string(),
|
||||
format!("%{CMD_LINE_ENV}%"),
|
||||
];
|
||||
program = "cmd".to_string();
|
||||
}
|
||||
}
|
||||
let mut env = vec![("PATH".to_string(), path)];
|
||||
env.append(&mut extra_env);
|
||||
LaunchSpec { program, args, env, cwd: folder.to_path_buf() }
|
||||
LaunchSpec {
|
||||
program,
|
||||
args,
|
||||
env,
|
||||
cwd: folder.to_path_buf(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The variable a custom `.cmd` or `.bat` agent's command line reaches `cmd` in.
|
||||
@@ -716,7 +831,9 @@ fn quote_for_cmd(arg: &str) -> String {
|
||||
|
||||
/// The page a built-in agent installs from; any other id is an error.
|
||||
pub fn install_page_url(id: &str) -> Result<&'static str, String> {
|
||||
AgentKind::from_id(id).map(AgentKind::install_url).ok_or_else(|| format!("no install page for agent: {id}"))
|
||||
AgentKind::from_id(id)
|
||||
.map(AgentKind::install_url)
|
||||
.ok_or_else(|| format!("no install page for agent: {id}"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -727,15 +844,31 @@ mod tests {
|
||||
PathBuf::from("project")
|
||||
}
|
||||
|
||||
fn args(kind: AgentKind, model: Option<&str>, mode: PermissionMode, prompt: &str) -> Vec<String> {
|
||||
fn args(
|
||||
kind: AgentKind,
|
||||
model: Option<&str>,
|
||||
mode: PermissionMode,
|
||||
prompt: &str,
|
||||
) -> Vec<String> {
|
||||
launch_spec_with(kind, &folder(), model, None, mode, prompt, None).args
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_puts_the_prompt_first() {
|
||||
let spec = launch_spec_with(AgentKind::Claude, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None);
|
||||
let spec = launch_spec_with(
|
||||
AgentKind::Claude,
|
||||
&folder(),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(spec.program, "claude");
|
||||
assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions"]);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["/plan2code", "--permission-mode", "bypassPermissions"]
|
||||
);
|
||||
assert_eq!(spec.cwd, folder());
|
||||
// A PATH that can still find nvm, Homebrew or Volta's directories (Task 9.9).
|
||||
assert_eq!(spec.env.iter().filter(|(k, _)| k == "PATH").count(), 1);
|
||||
@@ -744,21 +877,56 @@ mod tests {
|
||||
#[test]
|
||||
fn claude_with_a_model() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Claude, Some("sonnet"), PermissionMode::Bypass, "/plan2code"),
|
||||
["/plan2code", "--permission-mode", "bypassPermissions", "--model", "sonnet"]
|
||||
args(
|
||||
AgentKind::Claude,
|
||||
Some("sonnet"),
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code"
|
||||
),
|
||||
[
|
||||
"/plan2code",
|
||||
"--permission-mode",
|
||||
"bypassPermissions",
|
||||
"--model",
|
||||
"sonnet"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_checked_mode_skips_the_bypass_flag() {
|
||||
assert_eq!(args(AgentKind::Claude, None, PermissionMode::Checked, "/plan2code"), ["/plan2code"]);
|
||||
assert_eq!(
|
||||
args(
|
||||
AgentKind::Claude,
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"/plan2code"
|
||||
),
|
||||
["/plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn claude_with_an_effort() {
|
||||
let spec =
|
||||
launch_spec_with(AgentKind::Claude, &folder(), None, Some("high"), PermissionMode::Bypass, "/plan2code", None);
|
||||
assert_eq!(spec.args, ["/plan2code", "--permission-mode", "bypassPermissions", "--effort", "high"]);
|
||||
let spec = launch_spec_with(
|
||||
AgentKind::Claude,
|
||||
&folder(),
|
||||
None,
|
||||
Some("high"),
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
[
|
||||
"/plan2code",
|
||||
"--permission-mode",
|
||||
"bypassPermissions",
|
||||
"--effort",
|
||||
"high"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -774,7 +942,15 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["/plan2code", "--permission-mode", "bypassPermissions", "--model", "opus", "--effort", "xhigh"]
|
||||
[
|
||||
"/plan2code",
|
||||
"--permission-mode",
|
||||
"bypassPermissions",
|
||||
"--model",
|
||||
"opus",
|
||||
"--effort",
|
||||
"xhigh"
|
||||
]
|
||||
);
|
||||
let checked = launch_spec_with(
|
||||
AgentKind::Codex,
|
||||
@@ -785,72 +961,171 @@ mod tests {
|
||||
"$plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(checked.args, ["--model", "gpt-5", "-c", "model_reasoning_effort=medium", "$plan2code"]);
|
||||
assert_eq!(
|
||||
checked.args,
|
||||
[
|
||||
"--model",
|
||||
"gpt-5",
|
||||
"-c",
|
||||
"model_reasoning_effort=medium",
|
||||
"$plan2code"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_puts_the_prompt_after_a_double_dash() {
|
||||
let spec = launch_spec_with(AgentKind::Devin, &folder(), None, None, PermissionMode::Bypass, "/plan2code", None);
|
||||
let spec = launch_spec_with(
|
||||
AgentKind::Devin,
|
||||
&folder(),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(spec.program, "devin");
|
||||
assert_eq!(spec.args, ["--permission-mode", "bypass", "--", "/plan2code"]);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["--permission-mode", "bypass", "--", "/plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_with_a_model_keeps_the_prompt_last() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Devin, Some("opus"), PermissionMode::Bypass, "/plan2code"),
|
||||
["--permission-mode", "bypass", "--model", "opus", "--", "/plan2code"]
|
||||
args(
|
||||
AgentKind::Devin,
|
||||
Some("opus"),
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code"
|
||||
),
|
||||
[
|
||||
"--permission-mode",
|
||||
"bypass",
|
||||
"--model",
|
||||
"opus",
|
||||
"--",
|
||||
"/plan2code"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn devin_checked_mode_skips_the_bypass_flag() {
|
||||
assert_eq!(args(AgentKind::Devin, None, PermissionMode::Checked, "/plan2code"), ["--", "/plan2code"]);
|
||||
assert_eq!(
|
||||
args(
|
||||
AgentKind::Devin,
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"/plan2code"
|
||||
),
|
||||
["--", "/plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_uses_its_own_flag_and_dollar_prompt() {
|
||||
let prompt = AgentKind::Codex.default_prompt();
|
||||
let spec = launch_spec_with(AgentKind::Codex, &folder(), None, None, PermissionMode::Bypass, prompt, None);
|
||||
let spec = launch_spec_with(
|
||||
AgentKind::Codex,
|
||||
&folder(),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
prompt,
|
||||
None,
|
||||
);
|
||||
assert_eq!(spec.program, "codex");
|
||||
assert_eq!(spec.args, ["--dangerously-bypass-approvals-and-sandbox", "$plan2code"]);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["--dangerously-bypass-approvals-and-sandbox", "$plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_with_a_model() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Codex, Some("gpt-5"), PermissionMode::Bypass, "$plan2code"),
|
||||
["--dangerously-bypass-approvals-and-sandbox", "--model", "gpt-5", "$plan2code"]
|
||||
args(
|
||||
AgentKind::Codex,
|
||||
Some("gpt-5"),
|
||||
PermissionMode::Bypass,
|
||||
"$plan2code"
|
||||
),
|
||||
[
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"--model",
|
||||
"gpt-5",
|
||||
"$plan2code"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_with_an_effort_uses_a_config_override() {
|
||||
let spec =
|
||||
launch_spec_with(AgentKind::Codex, &folder(), None, Some("low"), PermissionMode::Bypass, "$plan2code", None);
|
||||
let spec = launch_spec_with(
|
||||
AgentKind::Codex,
|
||||
&folder(),
|
||||
None,
|
||||
Some("low"),
|
||||
PermissionMode::Bypass,
|
||||
"$plan2code",
|
||||
None,
|
||||
);
|
||||
assert_eq!(
|
||||
spec.args,
|
||||
["--dangerously-bypass-approvals-and-sandbox", "-c", "model_reasoning_effort=low", "$plan2code"]
|
||||
[
|
||||
"--dangerously-bypass-approvals-and-sandbox",
|
||||
"-c",
|
||||
"model_reasoning_effort=low",
|
||||
"$plan2code"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_checked_mode_skips_the_bypass_flag() {
|
||||
assert_eq!(args(AgentKind::Codex, None, PermissionMode::Checked, "$plan2code"), ["$plan2code"]);
|
||||
assert_eq!(
|
||||
args(
|
||||
AgentKind::Codex,
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"$plan2code"
|
||||
),
|
||||
["$plan2code"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_prompt_means_nothing_typed() {
|
||||
assert_eq!(args(AgentKind::Claude, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypassPermissions"]);
|
||||
assert_eq!(args(AgentKind::Devin, None, PermissionMode::Bypass, ""), ["--permission-mode", "bypass"]);
|
||||
assert_eq!(args(AgentKind::Codex, None, PermissionMode::Bypass, ""), ["--dangerously-bypass-approvals-and-sandbox"]);
|
||||
assert_eq!(
|
||||
args(AgentKind::Claude, None, PermissionMode::Bypass, ""),
|
||||
["--permission-mode", "bypassPermissions"]
|
||||
);
|
||||
assert_eq!(
|
||||
args(AgentKind::Devin, None, PermissionMode::Bypass, ""),
|
||||
["--permission-mode", "bypass"]
|
||||
);
|
||||
assert_eq!(
|
||||
args(AgentKind::Codex, None, PermissionMode::Bypass, ""),
|
||||
["--dangerously-bypass-approvals-and-sandbox"]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_custom_prompt_is_passed_through() {
|
||||
assert_eq!(
|
||||
args(AgentKind::Claude, None, PermissionMode::Bypass, "/plan2code pick up the brief"),
|
||||
["/plan2code pick up the brief", "--permission-mode", "bypassPermissions"]
|
||||
args(
|
||||
AgentKind::Claude,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code pick up the brief"
|
||||
),
|
||||
[
|
||||
"/plan2code pick up the brief",
|
||||
"--permission-mode",
|
||||
"bypassPermissions"
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -912,13 +1187,23 @@ mod tests {
|
||||
|
||||
let (program, wrapped) = windows_command("tool", args.clone(), &path);
|
||||
assert_eq!(program, "cmd");
|
||||
assert_eq!(wrapped, ["/c".to_string(), "tool.cmd".to_string(), "--flag".to_string()]);
|
||||
assert_eq!(
|
||||
wrapped,
|
||||
[
|
||||
"/c".to_string(),
|
||||
"tool.cmd".to_string(),
|
||||
"--flag".to_string()
|
||||
]
|
||||
);
|
||||
|
||||
let (program, same) = windows_command("real", args.clone(), &path);
|
||||
assert_eq!(program, dir.join("real.exe").to_string_lossy());
|
||||
assert_eq!(same, args);
|
||||
|
||||
assert_eq!(windows_command("missing", args.clone(), &path), ("missing".to_string(), args));
|
||||
assert_eq!(
|
||||
windows_command("missing", args.clone(), &path),
|
||||
("missing".to_string(), args)
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
@@ -957,7 +1242,10 @@ mod tests {
|
||||
}
|
||||
for part in parts {
|
||||
let part = part.as_str().unwrap();
|
||||
assert!(warnings.iter().any(|w| w.contains(part)), "{name}: no warning names {part}: {warnings:?}");
|
||||
assert!(
|
||||
warnings.iter().any(|w| w.contains(part)),
|
||||
"{name}: no warning names {part}: {warnings:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -983,7 +1271,8 @@ mod tests {
|
||||
}
|
||||
|
||||
fn temp_dir(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-agents-{}-{name}", std::process::id()));
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-agents-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
@@ -994,7 +1283,10 @@ mod tests {
|
||||
#[test]
|
||||
fn a_missing_file_is_empty_and_a_bad_one_warns() {
|
||||
let dir = temp_dir("load");
|
||||
assert_eq!(load_custom_agents(&dir.join("agents.json")), (Vec::new(), Vec::new()));
|
||||
assert_eq!(
|
||||
load_custom_agents(&dir.join("agents.json")),
|
||||
(Vec::new(), Vec::new())
|
||||
);
|
||||
std::fs::write(dir.join("agents.json"), "{ nope").unwrap();
|
||||
let (agents, warnings) = load_custom_agents(&dir.join("agents.json"));
|
||||
assert!(agents.is_empty() && warnings.len() == 1);
|
||||
@@ -1006,9 +1298,20 @@ mod tests {
|
||||
let dir = temp_dir("find");
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(&file, GOOSE).unwrap();
|
||||
assert_eq!(find_agent_in("claude", Some(&file)), Some(Agent::Builtin(AgentKind::Claude)));
|
||||
assert_eq!(
|
||||
find_agent_in("claude", Some(&file)),
|
||||
Some(Agent::Builtin(AgentKind::Claude))
|
||||
);
|
||||
let goose = find_agent_in("goose", Some(&file)).unwrap();
|
||||
assert_eq!((goose.id(), goose.label(), goose.has_effort(), goose.default_prompt()), ("goose", "Goose", false, "/plan2code"));
|
||||
assert_eq!(
|
||||
(
|
||||
goose.id(),
|
||||
goose.label(),
|
||||
goose.has_effort(),
|
||||
goose.default_prompt()
|
||||
),
|
||||
("goose", "Goose", false, "/plan2code")
|
||||
);
|
||||
assert_eq!(find_agent_in("goose", None), None);
|
||||
assert_eq!(find_agent_in("nope", Some(&file)), None);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
@@ -1021,13 +1324,40 @@ mod tests {
|
||||
#[test]
|
||||
fn a_custom_launch_spec_has_its_program_and_arguments() {
|
||||
let bin = Path::new("tools").join("goose");
|
||||
let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), None, PermissionMode::Checked, "/plan2code", "P", false);
|
||||
let spec = custom_launch_spec(
|
||||
&goose(),
|
||||
Some(&bin),
|
||||
&folder(),
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"/plan2code",
|
||||
"P",
|
||||
false,
|
||||
);
|
||||
assert_eq!(spec.program, bin.to_string_lossy());
|
||||
assert_eq!(spec.args, ["/plan2code"]);
|
||||
assert_eq!(spec.env, [("PATH".to_string(), "P".to_string())]);
|
||||
let spec = custom_launch_spec(&goose(), Some(&bin), &folder(), Some("m"), PermissionMode::Bypass, "/plan2code", "P", false);
|
||||
let spec = custom_launch_spec(
|
||||
&goose(),
|
||||
Some(&bin),
|
||||
&folder(),
|
||||
Some("m"),
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
"P",
|
||||
false,
|
||||
);
|
||||
assert_eq!(spec.args, ["/plan2code", "--model", "m", "--yes"]);
|
||||
let spec = custom_launch_spec(&goose(), None, &folder(), None, PermissionMode::Checked, "", "P", false);
|
||||
let spec = custom_launch_spec(
|
||||
&goose(),
|
||||
None,
|
||||
&folder(),
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"",
|
||||
"P",
|
||||
false,
|
||||
);
|
||||
assert_eq!((spec.program.as_str(), spec.args.len()), ("goose", 0));
|
||||
}
|
||||
|
||||
@@ -1036,15 +1366,51 @@ mod tests {
|
||||
let mut full = goose();
|
||||
full.command = "C:\\with space\\goose.cmd".to_string();
|
||||
let found = Path::new("C:\\with space").join("goose.cmd");
|
||||
let spec = custom_launch_spec(&full, Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
let spec = custom_launch_spec(
|
||||
&full,
|
||||
Some(&found),
|
||||
&folder(),
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"/p",
|
||||
"BASE",
|
||||
true,
|
||||
);
|
||||
assert_eq!(spec.program, "cmd");
|
||||
assert_eq!(spec.args, ["/d", "/c", "%PLAN2CODE_AGENT_LINE%"]);
|
||||
assert_eq!(spec.env[0].1, format!("{};BASE", found.parent().unwrap().to_string_lossy()));
|
||||
assert_eq!(spec.env[1], ("PLAN2CODE_AGENT_LINE".to_string(), "goose.cmd /p".to_string()));
|
||||
assert_eq!(spec.env[2], ("NoDefaultCurrentDirectoryInExePath".to_string(), "1".to_string()));
|
||||
assert_eq!(
|
||||
spec.env[0].1,
|
||||
format!("{};BASE", found.parent().unwrap().to_string_lossy())
|
||||
);
|
||||
assert_eq!(
|
||||
spec.env[1],
|
||||
(
|
||||
"PLAN2CODE_AGENT_LINE".to_string(),
|
||||
"goose.cmd /p".to_string()
|
||||
)
|
||||
);
|
||||
assert_eq!(
|
||||
spec.env[2],
|
||||
(
|
||||
"NoDefaultCurrentDirectoryInExePath".to_string(),
|
||||
"1".to_string()
|
||||
)
|
||||
);
|
||||
// A bare name keeps the plain PATH.
|
||||
let bare = custom_launch_spec(&goose(), Some(&found), &folder(), None, PermissionMode::Checked, "/p", "BASE", true);
|
||||
assert_eq!((bare.program.as_str(), bare.env[0].1.as_str()), ("cmd", "BASE"));
|
||||
let bare = custom_launch_spec(
|
||||
&goose(),
|
||||
Some(&found),
|
||||
&folder(),
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"/p",
|
||||
"BASE",
|
||||
true,
|
||||
);
|
||||
assert_eq!(
|
||||
(bare.program.as_str(), bare.env[0].1.as_str()),
|
||||
("cmd", "BASE")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -1057,7 +1423,16 @@ mod tests {
|
||||
let mut agent = goose();
|
||||
agent.args = vec!["--filter=a|b".to_string(), "{prompt}".to_string()];
|
||||
let found = Path::new("C:\\tools").join("goose.cmd");
|
||||
let spec = custom_launch_spec(&agent, Some(&found), &folder(), None, PermissionMode::Checked, "/p & x", "BASE", true);
|
||||
let spec = custom_launch_spec(
|
||||
&agent,
|
||||
Some(&found),
|
||||
&folder(),
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"/p & x",
|
||||
"BASE",
|
||||
true,
|
||||
);
|
||||
assert_eq!(spec.env[1].1, "goose.cmd \"--filter=a|b\" \"/p & x\"");
|
||||
}
|
||||
|
||||
@@ -1069,17 +1444,35 @@ mod tests {
|
||||
let project = root.join("project");
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::fs::write(dir.join("goose.cmd"), "@echo off\r\necho REAL [%1] [%2]\r\n").unwrap();
|
||||
std::fs::write(
|
||||
dir.join("goose.cmd"),
|
||||
"@echo off\r\necho REAL [%1] [%2]\r\n",
|
||||
)
|
||||
.unwrap();
|
||||
// A same-named file in the project folder must not run instead.
|
||||
std::fs::write(project.join("goose.cmd"), "@echo off\r\necho DECOY\r\n").unwrap();
|
||||
let mut agent = goose();
|
||||
agent.command = dir.join("goose.cmd").to_string_lossy().into_owned();
|
||||
agent.args = vec!["a|b".to_string(), "%PATH%".to_string()];
|
||||
let found = Agent::Custom(agent.clone()).installed_at().expect("resolves");
|
||||
let spec = custom_launch_spec(&agent, Some(&found), &project, None, PermissionMode::Checked, "", &std::env::var("PATH").unwrap_or_default(), true);
|
||||
let found = Agent::Custom(agent.clone())
|
||||
.installed_at()
|
||||
.expect("resolves");
|
||||
let spec = custom_launch_spec(
|
||||
&agent,
|
||||
Some(&found),
|
||||
&project,
|
||||
None,
|
||||
PermissionMode::Checked,
|
||||
"",
|
||||
&std::env::var("PATH").unwrap_or_default(),
|
||||
true,
|
||||
);
|
||||
let mut command = std::process::Command::new(&spec.program);
|
||||
// Some shells already set the switch the spec sets; start without it.
|
||||
command.args(&spec.args).current_dir(&spec.cwd).env_remove("NoDefaultCurrentDirectoryInExePath");
|
||||
command
|
||||
.args(&spec.args)
|
||||
.current_dir(&spec.cwd)
|
||||
.env_remove("NoDefaultCurrentDirectoryInExePath");
|
||||
for (key, value) in &spec.env {
|
||||
command.env(key, value);
|
||||
}
|
||||
@@ -1091,7 +1484,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn install_pages_are_for_built_ins_only() {
|
||||
assert_eq!(install_page_url("codex").unwrap(), "https://github.com/openai/codex");
|
||||
assert_eq!(
|
||||
install_page_url("codex").unwrap(),
|
||||
"https://github.com/openai/codex"
|
||||
);
|
||||
assert!(install_page_url("goose").is_err());
|
||||
for kind in AgentKind::ALL {
|
||||
assert!(kind.install_url().starts_with("https://"));
|
||||
|
||||
@@ -90,7 +90,9 @@ pub fn acceptable_url(url: &str) -> bool {
|
||||
let Some((port, path)) = rest.split_once('/') else {
|
||||
return false;
|
||||
};
|
||||
port.parse::<u16>().is_ok_and(|p| p > 0) && path.starts_with("s/") && !url.contains(char::is_whitespace)
|
||||
port.parse::<u16>().is_ok_and(|p| p > 0)
|
||||
&& path.starts_with("s/")
|
||||
&& !url.contains(char::is_whitespace)
|
||||
}
|
||||
|
||||
/// Check one request (its head as text, its body as bytes) against `token`.
|
||||
@@ -103,7 +105,9 @@ pub fn check_request(head: &str, body: &[u8], token: &str) -> Result<Request, Re
|
||||
}
|
||||
let mut given = None;
|
||||
for line in lines {
|
||||
let Some((name, value)) = line.split_once(':') else { continue };
|
||||
let Some((name, value)) = line.split_once(':') else {
|
||||
continue;
|
||||
};
|
||||
match name.trim().to_ascii_lowercase().as_str() {
|
||||
"x-plan2code-token" => given = Some(value.trim().to_string()),
|
||||
// A browser page sending this would be some site guessing at the port.
|
||||
@@ -186,7 +190,8 @@ impl AnnounceServer {
|
||||
/// Listen on a random loopback port. `on_page` runs on the server's own
|
||||
/// thread for every accepted notice.
|
||||
pub fn start(on_page: OnPage) -> Result<AnnounceServer, String> {
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0))).map_err(|e| e.to_string())?;
|
||||
let listener = TcpListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, 0)))
|
||||
.map_err(|e| e.to_string())?;
|
||||
let port = listener.local_addr().map_err(|e| e.to_string())?.port();
|
||||
let token = random_token();
|
||||
let expected = token.clone();
|
||||
@@ -211,14 +216,21 @@ impl AnnounceServer {
|
||||
}
|
||||
Ok(Request::Session) => {
|
||||
let now = shared.lock().ok().and_then(|slot| slot.clone());
|
||||
(200, serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string()))
|
||||
(
|
||||
200,
|
||||
serde_json::to_string(&now).unwrap_or_else(|_| "null".to_string()),
|
||||
)
|
||||
}
|
||||
Err(Refused(status, _)) => (status, String::new()),
|
||||
};
|
||||
respond(&mut stream, status, &body);
|
||||
}
|
||||
});
|
||||
Ok(AnnounceServer { port, token, current })
|
||||
Ok(AnnounceServer {
|
||||
port,
|
||||
token,
|
||||
current,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn url(&self) -> String {
|
||||
@@ -250,7 +262,10 @@ impl AnnounceServer {
|
||||
vec![
|
||||
("PLAN2CODE_IN_APP".to_string(), "1".to_string()),
|
||||
("PLAN2CODE_APP_VERSION".to_string(), app_version.to_string()),
|
||||
("PLAN2CODE_EMBED_ORIGIN".to_string(), embed_origin.to_string()),
|
||||
(
|
||||
"PLAN2CODE_EMBED_ORIGIN".to_string(),
|
||||
embed_origin.to_string(),
|
||||
),
|
||||
("PLAN2CODE_APP_ANNOUNCE".to_string(), self.url()),
|
||||
("PLAN2CODE_APP_TOKEN".to_string(), self.token.clone()),
|
||||
]
|
||||
@@ -275,39 +290,76 @@ mod tests {
|
||||
#[test]
|
||||
fn accepts_a_good_notice() {
|
||||
let (head, body) = request("t", GOOD);
|
||||
let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else { panic!("not accepted") };
|
||||
assert_eq!((notice.sid.as_str(), notice.workflow.as_str()), ("s1", "plan"));
|
||||
let Ok(Request::Page(notice)) = check_request(&head, &body, "t") else {
|
||||
panic!("not accepted")
|
||||
};
|
||||
assert_eq!(
|
||||
(notice.sid.as_str(), notice.workflow.as_str()),
|
||||
("s1", "plan")
|
||||
);
|
||||
let get = "GET /session HTTP/1.1\r\nx-plan2code-token: t";
|
||||
assert_eq!(check_request(get, b"", "t"), Ok(Request::Session));
|
||||
assert_eq!(check_request(get, b"", "other"), Err(Refused(403, "bad token")));
|
||||
assert_eq!(
|
||||
check_request(get, b"", "other"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_wrong_or_missing_token() {
|
||||
let (head, body) = request("nope", GOOD);
|
||||
assert_eq!(check_request(&head, &body, "t"), Err(Refused(403, "bad token")));
|
||||
assert_eq!(
|
||||
check_request(&head, &body, "t"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
let head = "POST /page HTTP/1.1\r\nHost: x";
|
||||
assert_eq!(check_request(head, GOOD.as_bytes(), "t"), Err(Refused(403, "bad token")));
|
||||
assert_eq!(
|
||||
check_request(head, GOOD.as_bytes(), "t"),
|
||||
Err(Refused(403, "bad token"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_browser_origin_and_other_routes() {
|
||||
let (head, body) = request("t", GOOD);
|
||||
let with_origin = format!("{head}\r\nOrigin: http://evil.example");
|
||||
assert_eq!(check_request(&with_origin, &body, "t"), Err(Refused(403, "not from a page")));
|
||||
assert_eq!(
|
||||
check_request(&with_origin, &body, "t"),
|
||||
Err(Refused(403, "not from a page"))
|
||||
);
|
||||
let other = head.replace("/page", "/other");
|
||||
assert_eq!(check_request(&other, &body, "t"), Err(Refused(404, "not found")));
|
||||
assert_eq!(
|
||||
check_request(&other, &body, "t"),
|
||||
Err(Refused(404, "not found"))
|
||||
);
|
||||
let get = head.replace("POST", "GET");
|
||||
assert_eq!(check_request(&get, &body, "t"), Err(Refused(404, "not found")), "GET is for /session only");
|
||||
assert_eq!(
|
||||
check_request(&get, &body, "t"),
|
||||
Err(Refused(404, "not found")),
|
||||
"GET is for /session only"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_a_bad_body_and_a_url_that_is_not_the_console() {
|
||||
let (head, _) = request("t", "x");
|
||||
assert_eq!(check_request(&head, b"not json", "t"), Err(Refused(400, "bad body")));
|
||||
for url in ["http://example.com/s/abc/", "https://127.0.0.1:5/s/a/", "http://127.0.0.1:5/other", "javascript:alert(1)", "http://127.0.0.1:0/s/a/"] {
|
||||
assert_eq!(
|
||||
check_request(&head, b"not json", "t"),
|
||||
Err(Refused(400, "bad body"))
|
||||
);
|
||||
for url in [
|
||||
"http://example.com/s/abc/",
|
||||
"https://127.0.0.1:5/s/a/",
|
||||
"http://127.0.0.1:5/other",
|
||||
"javascript:alert(1)",
|
||||
"http://127.0.0.1:0/s/a/",
|
||||
] {
|
||||
let body = format!(r#"{{"url":"{url}","sid":"s","workflow":"w"}}"#);
|
||||
assert_eq!(check_request(&head, body.as_bytes(), "t"), Err(Refused(400, "bad page")), "{url}");
|
||||
assert_eq!(
|
||||
check_request(&head, body.as_bytes(), "t"),
|
||||
Err(Refused(400, "bad page")),
|
||||
"{url}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -336,13 +388,27 @@ mod tests {
|
||||
let (tx_a, rx_a) = channel();
|
||||
let (tx_b, rx_b) = channel();
|
||||
let (tx_a, tx_b) = (Mutex::new(tx_a), Mutex::new(tx_b));
|
||||
let a = AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
let b = AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
let a =
|
||||
AnnounceServer::start(Arc::new(move |n| tx_a.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
let b =
|
||||
AnnounceServer::start(Arc::new(move |n| tx_b.lock().unwrap().send(n).is_ok())).unwrap();
|
||||
assert_ne!(a.url(), b.url());
|
||||
let port = |s: &AnnounceServer| s.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse::<u16>().unwrap();
|
||||
let port = |s: &AnnounceServer| {
|
||||
s.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse::<u16>()
|
||||
.unwrap()
|
||||
};
|
||||
|
||||
assert_eq!(post(port(&a), a.token(), GOOD), 204);
|
||||
assert_eq!(post(port(&b), a.token(), GOOD), 403, "window A's token does nothing in window B");
|
||||
assert_eq!(
|
||||
post(port(&b), a.token(), GOOD),
|
||||
403,
|
||||
"window A's token does nothing in window B"
|
||||
);
|
||||
assert_eq!(rx_a.recv_timeout(Duration::from_secs(3)).unwrap().sid, "s1");
|
||||
assert!(rx_b.recv_timeout(Duration::from_millis(300)).is_err());
|
||||
}
|
||||
@@ -353,17 +419,31 @@ mod tests {
|
||||
let env = server.agent_env("http://127.0.0.1:1430", "3.0.0");
|
||||
let get = |key: &str| env.iter().find(|(k, _)| k == key).map(|(_, v)| v.clone());
|
||||
assert_eq!(get("PLAN2CODE_IN_APP").as_deref(), Some("1"));
|
||||
assert_eq!(get("PLAN2CODE_EMBED_ORIGIN").as_deref(), Some("http://127.0.0.1:1430"));
|
||||
assert_eq!(
|
||||
get("PLAN2CODE_EMBED_ORIGIN").as_deref(),
|
||||
Some("http://127.0.0.1:1430")
|
||||
);
|
||||
assert_eq!(get("PLAN2CODE_APP_VERSION").as_deref(), Some("3.0.0"));
|
||||
assert_eq!(get("PLAN2CODE_APP_ANNOUNCE"), Some(server.url()));
|
||||
assert_eq!(get("PLAN2CODE_APP_TOKEN").as_deref(), Some(server.token()));
|
||||
assert_eq!(get("PLAN2CODE_CONSOLE_SID"), None, "the window's session is asked for, not fixed at start");
|
||||
assert_eq!(
|
||||
get("PLAN2CODE_CONSOLE_SID"),
|
||||
None,
|
||||
"the window's session is asked for, not fixed at start"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_current_session_is_what_was_announced_last() {
|
||||
let server = AnnounceServer::start(Arc::new(|_| true)).unwrap();
|
||||
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
|
||||
let port: u16 = server
|
||||
.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse()
|
||||
.unwrap();
|
||||
let ask = |token: &str| {
|
||||
let mut stream = TcpStream::connect(("127.0.0.1", port)).unwrap();
|
||||
write!(stream, "GET /session HTTP/1.1\r\nHost: 127.0.0.1\r\nx-plan2code-token: {token}\r\nConnection: close\r\n\r\n").unwrap();
|
||||
@@ -371,13 +451,19 @@ mod tests {
|
||||
stream.read_to_string(&mut answer).unwrap();
|
||||
answer
|
||||
};
|
||||
assert!(ask(server.token()).ends_with("null"), "nothing announced yet");
|
||||
assert!(
|
||||
ask(server.token()).ends_with("null"),
|
||||
"nothing announced yet"
|
||||
);
|
||||
assert_eq!(post(port, server.token(), GOOD), 204);
|
||||
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!(
|
||||
ask(server.token()).ends_with("null"),
|
||||
"forgotten: the next open starts its own session"
|
||||
);
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
|
||||
@@ -386,8 +472,19 @@ mod tests {
|
||||
// A test's throwaway console: remembered, it would steer the next
|
||||
// agent `open` away from the window's real session.
|
||||
let server = AnnounceServer::start(Arc::new(|_| false)).unwrap();
|
||||
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().unwrap();
|
||||
assert_eq!(post(port, server.token(), GOOD), 409, "open hears that the app did not take it");
|
||||
let port: u16 = server
|
||||
.url()
|
||||
.rsplit_once(':')
|
||||
.unwrap()
|
||||
.1
|
||||
.trim_end_matches("/page")
|
||||
.parse()
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
post(port, server.token(), GOOD),
|
||||
409,
|
||||
"open hears that the app did not take it"
|
||||
);
|
||||
assert_eq!(server.current(), None);
|
||||
}
|
||||
}
|
||||
@@ -121,7 +121,12 @@ fn parse_hex(hex: &str) -> [u8; 3] {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SIGNALS: [Signal; 4] = [Signal::Busy, Signal::Ready, Signal::Attention, Signal::Plain];
|
||||
const SIGNALS: [Signal; 4] = [
|
||||
Signal::Busy,
|
||||
Signal::Ready,
|
||||
Signal::Attention,
|
||||
Signal::Plain,
|
||||
];
|
||||
|
||||
fn pixel(buf: &[u8], size: u32, x: u32, y: u32) -> [u8; 4] {
|
||||
let i = ((y * size + x) * 4) as usize;
|
||||
@@ -149,8 +154,16 @@ mod tests {
|
||||
(Signal::Plain, "freebsd", Badge::None),
|
||||
];
|
||||
for (signal, os, want) in table {
|
||||
assert_eq!(badge_for(signal, os, true), want, "{signal:?} on {os}, enabled");
|
||||
assert_eq!(badge_for(signal, os, false), Badge::None, "{signal:?} on {os}, disabled");
|
||||
assert_eq!(
|
||||
badge_for(signal, os, true),
|
||||
want,
|
||||
"{signal:?} on {os}, enabled"
|
||||
);
|
||||
assert_eq!(
|
||||
badge_for(signal, os, false),
|
||||
Badge::None,
|
||||
"{signal:?} on {os}, disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -177,22 +190,41 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn no_flash_for_a_repeat_of_the_same_signal() {
|
||||
assert!(!should_flash(Some(Signal::Ready), Signal::Ready, false, true));
|
||||
assert!(!should_flash(Some(Signal::Attention), Signal::Attention, false, true));
|
||||
assert!(!should_flash(
|
||||
Some(Signal::Ready),
|
||||
Signal::Ready,
|
||||
false,
|
||||
true
|
||||
));
|
||||
assert!(!should_flash(
|
||||
Some(Signal::Attention),
|
||||
Signal::Attention,
|
||||
false,
|
||||
true
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_for_busy_or_plain() {
|
||||
for prev in [None, Some(Signal::Ready), Some(Signal::Attention)] {
|
||||
assert!(!should_flash(prev, Signal::Busy, false, true), "busy from {prev:?}");
|
||||
assert!(!should_flash(prev, Signal::Plain, false, true), "plain from {prev:?}");
|
||||
assert!(
|
||||
!should_flash(prev, Signal::Busy, false, true),
|
||||
"busy from {prev:?}"
|
||||
);
|
||||
assert!(
|
||||
!should_flash(prev, Signal::Plain, false, true),
|
||||
"plain from {prev:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn no_flash_when_flashing_is_turned_off() {
|
||||
for signal in SIGNALS.iter().copied() {
|
||||
assert!(!should_flash(Some(Signal::Busy), signal, false, false), "{signal:?} while disabled");
|
||||
assert!(
|
||||
!should_flash(Some(Signal::Busy), signal, false, false),
|
||||
"{signal:?} while disabled"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -210,7 +242,11 @@ mod tests {
|
||||
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
|
||||
let center = pixel(&buf, size, 8, 8);
|
||||
assert_eq!(center[3], 255, "the middle is opaque");
|
||||
assert_eq!(¢er[..3], &parse_hex(GREEN_HEX)[..], "the middle is the green fill");
|
||||
assert_eq!(
|
||||
¢er[..3],
|
||||
&parse_hex(GREEN_HEX)[..],
|
||||
"the middle is the green fill"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -221,14 +257,27 @@ mod tests {
|
||||
assert_eq!(pixel(&buf, size, 0, 0)[3], 0, "a corner is transparent");
|
||||
let center = pixel(&buf, size, 8, 8);
|
||||
assert_eq!(center[3], 255, "the middle is opaque");
|
||||
assert_eq!(¢er[..3], &parse_hex(RED_HEX)[..], "the middle is the red fill");
|
||||
assert_eq!(
|
||||
¢er[..3],
|
||||
&parse_hex(RED_HEX)[..],
|
||||
"the middle is the red fill"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_fill_colors_match_the_web_console_favicon() {
|
||||
let path = concat!(env!("CARGO_MANIFEST_DIR"), "/../../src/web-console/public/favicon.js");
|
||||
let path = concat!(
|
||||
env!("CARGO_MANIFEST_DIR"),
|
||||
"/../../src/web-console/public/favicon.js"
|
||||
);
|
||||
let text = std::fs::read_to_string(path).unwrap();
|
||||
assert!(text.contains(&format!("ready: \"{GREEN_HEX}\"")), "ready color in favicon.js");
|
||||
assert!(text.contains(&format!("attention: \"{RED_HEX}\"")), "attention color in favicon.js");
|
||||
assert!(
|
||||
text.contains(&format!("ready: \"{GREEN_HEX}\"")),
|
||||
"ready color in favicon.js"
|
||||
);
|
||||
assert!(
|
||||
text.contains(&format!("attention: \"{RED_HEX}\"")),
|
||||
"attention color in favicon.js"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -66,7 +66,12 @@ const GIT_TIMEOUT: Duration = Duration::from_secs(2);
|
||||
|
||||
fn git(folder: &Path, args: &[&str]) -> Option<String> {
|
||||
let mut command = Command::new("git");
|
||||
command.arg("-C").arg(folder).args(args).stdout(Stdio::piped()).stderr(Stdio::null());
|
||||
command
|
||||
.arg("-C")
|
||||
.arg(folder)
|
||||
.args(args)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
@@ -92,14 +97,21 @@ fn git(folder: &Path, args: &[&str]) -> Option<String> {
|
||||
thread::sleep(Duration::from_millis(20));
|
||||
};
|
||||
let bytes = reader.join().ok()?;
|
||||
status.success().then(|| String::from_utf8_lossy(&bytes).trim_end().to_string())
|
||||
status
|
||||
.success()
|
||||
.then(|| String::from_utf8_lossy(&bytes).trim_end().to_string())
|
||||
}
|
||||
|
||||
/// The brief as Markdown. `state` is a session's `state.json`; `spec_dir` is
|
||||
/// the spec folder on disk, when the session has one; `git` is the repository
|
||||
/// summary, when the folder is one; `events` is the session's `events.ndjson`,
|
||||
/// oldest first.
|
||||
pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSummary>, events: &[Value]) -> String {
|
||||
pub fn build_brief(
|
||||
state: &Value,
|
||||
spec_dir: Option<&Path>,
|
||||
git: Option<&GitSummary>,
|
||||
events: &[Value],
|
||||
) -> String {
|
||||
let workflow = str_field(state, "workflow").unwrap_or("");
|
||||
let skill = skill_for_workflow(workflow);
|
||||
let spec = str_field(state, "specDir");
|
||||
@@ -119,9 +131,19 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma
|
||||
out.push_str("## Progress\n\n");
|
||||
let headline = state.get("headline");
|
||||
let stage = headline.and_then(|h| str_field(h, "stage")).unwrap_or("");
|
||||
let cleared = headline.and_then(|h| h.get("cleared")).and_then(Value::as_u64).unwrap_or(0);
|
||||
let total = headline.and_then(|h| h.get("total")).and_then(Value::as_u64).unwrap_or(0);
|
||||
let activity = state.get("agent").and_then(|a| str_field(a, "activity")).map(str::trim).filter(|a| !a.is_empty());
|
||||
let cleared = headline
|
||||
.and_then(|h| h.get("cleared"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let total = headline
|
||||
.and_then(|h| h.get("total"))
|
||||
.and_then(Value::as_u64)
|
||||
.unwrap_or(0);
|
||||
let activity = state
|
||||
.get("agent")
|
||||
.and_then(|a| str_field(a, "activity"))
|
||||
.map(str::trim)
|
||||
.filter(|a| !a.is_empty());
|
||||
if !stage.is_empty() {
|
||||
out.push_str(&format!("{stage}: {cleared} of {total} done.\n"));
|
||||
if let Some(activity) = activity {
|
||||
@@ -134,10 +156,17 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma
|
||||
out.push_str("No progress posted yet.\n\n");
|
||||
}
|
||||
|
||||
let items = state.get("items").and_then(Value::as_array).map(Vec::as_slice).unwrap_or(&[]);
|
||||
let items = state
|
||||
.get("items")
|
||||
.and_then(Value::as_array)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[]);
|
||||
|
||||
out.push_str("### Open questions\n\n");
|
||||
let open: Vec<&Value> = items.iter().filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened"))).collect();
|
||||
let open: Vec<&Value> = items
|
||||
.iter()
|
||||
.filter(|i| matches!(str_field(i, "status"), Some("open" | "reopened")))
|
||||
.collect();
|
||||
if open.is_empty() {
|
||||
out.push_str("None.\n\n");
|
||||
} else {
|
||||
@@ -148,14 +177,21 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma
|
||||
}
|
||||
|
||||
out.push_str("## Recent answers and decisions\n\n");
|
||||
let answered: Vec<&Value> = items.iter().filter(|i| str_field(i, "status") == Some("answered")).collect();
|
||||
let answered: Vec<&Value> = items
|
||||
.iter()
|
||||
.filter(|i| str_field(i, "status") == Some("answered"))
|
||||
.collect();
|
||||
let recent = &answered[answered.len().saturating_sub(RECENT_ANSWERS)..];
|
||||
if recent.is_empty() {
|
||||
out.push_str("None yet.\n\n");
|
||||
} else {
|
||||
for item in recent {
|
||||
let answer = answer_text(item);
|
||||
let answer = if answer.is_empty() { "answered".to_string() } else { answer };
|
||||
let answer = if answer.is_empty() {
|
||||
"answered".to_string()
|
||||
} else {
|
||||
answer
|
||||
};
|
||||
out.push_str(&format!("- {}: {answer}\n", title_of(item)));
|
||||
}
|
||||
out.push('\n');
|
||||
@@ -164,7 +200,11 @@ pub fn build_brief(state: &Value, spec_dir: Option<&Path>, git: Option<&GitSumma
|
||||
if let Some(git) = git {
|
||||
out.push_str("## Git\n\n");
|
||||
out.push_str("Changes:\n\n```\n");
|
||||
out.push_str(if git.status.is_empty() { "clean" } else { &git.status });
|
||||
out.push_str(if git.status.is_empty() {
|
||||
"clean"
|
||||
} else {
|
||||
&git.status
|
||||
});
|
||||
out.push_str("\n```\n\n");
|
||||
if !git.log.is_empty() {
|
||||
out.push_str("Last commits:\n\n```\n");
|
||||
@@ -202,7 +242,11 @@ fn render_event(event: &Value) -> String {
|
||||
None => "consume".to_string(),
|
||||
},
|
||||
"open" => {
|
||||
if event.get("resumed").and_then(Value::as_bool).unwrap_or(false) {
|
||||
if event
|
||||
.get("resumed")
|
||||
.and_then(Value::as_bool)
|
||||
.unwrap_or(false)
|
||||
{
|
||||
"open (resumed)".to_string()
|
||||
} else {
|
||||
"open".to_string()
|
||||
@@ -230,7 +274,10 @@ fn open_task(spec_dir: &Path) -> Option<String> {
|
||||
let overview = fs::read_to_string(spec_dir.join("overview.md")).ok()?;
|
||||
let phase = active_phase(&overview)?;
|
||||
let text = fs::read_to_string(spec_dir.join(format!("phase-{phase}.md"))).ok()?;
|
||||
let line = text.lines().map(str::trim_start).find(|l| l.starts_with("- [ ]"))?;
|
||||
let line = text
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.find(|l| l.starts_with("- [ ]"))?;
|
||||
Some(line.trim_start_matches("- [ ]").trim().replace("**", ""))
|
||||
}
|
||||
|
||||
@@ -242,8 +289,16 @@ fn active_phase(overview: &str) -> Option<u32> {
|
||||
let digits: String = rest.chars().take_while(|c| c.is_ascii_digit()).collect();
|
||||
digits.parse::<u32>().ok()
|
||||
};
|
||||
let rows = || overview.lines().map(str::trim_start).filter(|l| l.starts_with("- ["));
|
||||
rows().find(|l| l.starts_with("- [/]")).and_then(phase_of).or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of))
|
||||
let rows = || {
|
||||
overview
|
||||
.lines()
|
||||
.map(str::trim_start)
|
||||
.filter(|l| l.starts_with("- ["))
|
||||
};
|
||||
rows()
|
||||
.find(|l| l.starts_with("- [/]"))
|
||||
.and_then(phase_of)
|
||||
.or_else(|| rows().find(|l| l.starts_with("- [ ]")).and_then(phase_of))
|
||||
}
|
||||
|
||||
fn cut(text: &str) -> String {
|
||||
@@ -259,14 +314,18 @@ fn str_field<'a>(value: &'a Value, key: &str) -> Option<&'a str> {
|
||||
}
|
||||
|
||||
fn title_of(item: &Value) -> String {
|
||||
let title = str_field(item, "title").or_else(|| str_field(item, "id")).unwrap_or("(untitled)");
|
||||
let title = str_field(item, "title")
|
||||
.or_else(|| str_field(item, "id"))
|
||||
.unwrap_or("(untitled)");
|
||||
title.trim().to_string()
|
||||
}
|
||||
|
||||
/// An answer as the person gave it: the option's label for a pick, plus any
|
||||
/// words they typed. Empty when the answer carries nothing to show.
|
||||
fn answer_text(item: &Value) -> String {
|
||||
let Some(answer) = item.get("answer") else { return String::new() };
|
||||
let Some(answer) = item.get("answer") else {
|
||||
return String::new();
|
||||
};
|
||||
let options = item.get("options").and_then(Value::as_array);
|
||||
let label = |k: &str| {
|
||||
options
|
||||
@@ -291,7 +350,10 @@ fn answer_text(item: &Value) -> String {
|
||||
if let Some(verdict) = str_field(answer, "verdict") {
|
||||
parts.push(verdict.to_string());
|
||||
}
|
||||
if let Some(text) = str_field(answer, "text").map(str::trim).filter(|t| !t.is_empty()) {
|
||||
if let Some(text) = str_field(answer, "text")
|
||||
.map(str::trim)
|
||||
.filter(|t| !t.is_empty())
|
||||
{
|
||||
parts.push(text.to_string());
|
||||
}
|
||||
parts.join("; ")
|
||||
@@ -303,7 +365,8 @@ mod tests {
|
||||
use serde_json::json;
|
||||
|
||||
fn fixture(name: &str) -> std::path::PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id()));
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-brief-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
@@ -340,7 +403,10 @@ mod tests {
|
||||
#[test]
|
||||
fn a_mid_implement_session_carries_every_section() {
|
||||
let spec = mid_implement_spec();
|
||||
let git = GitSummary { status: " M src/lib.rs".to_string(), log: "abc1234 Add the reader".to_string() };
|
||||
let git = GitSummary {
|
||||
status: " M src/lib.rs".to_string(),
|
||||
log: "abc1234 Add the reader".to_string(),
|
||||
};
|
||||
let brief = build_brief(&mid_implement_state(), Some(&spec), Some(&git), &[]);
|
||||
assert!(brief.contains("Skill: plan2code-3-implement (workflow `implement`)"));
|
||||
assert!(brief.contains("Spec: specs/feature"));
|
||||
@@ -379,7 +445,9 @@ mod tests {
|
||||
#[test]
|
||||
fn a_session_with_no_spec_and_no_skill_opens_the_dashboard() {
|
||||
let state = json!({ "schema": 1, "workflow": "dashboard" });
|
||||
assert!(build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n"));
|
||||
assert!(
|
||||
build_brief(&state, None, None, &[]).ends_with("## Next task\n\nOpen the dashboard\n")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -387,8 +455,16 @@ mod tests {
|
||||
let home = fixture("chat");
|
||||
let dir = home.join("sessions").join("s1");
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
fs::write(dir.join("state.json"), r#"{"schema": 1, "workflow": "implement"}"#).unwrap();
|
||||
fs::write(dir.join("chat.ndjson"), "{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n").unwrap();
|
||||
fs::write(
|
||||
dir.join("state.json"),
|
||||
r#"{"schema": 1, "workflow": "implement"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
dir.join("chat.ndjson"),
|
||||
"{\"kind\":\"ask\",\"text\":\"CHAT-ONLY-WORDS\"}\n",
|
||||
)
|
||||
.unwrap();
|
||||
let session = crate::session_reader::load(&home, "s1").unwrap();
|
||||
let brief = build_brief(&session.state, None, None, &[]);
|
||||
assert!(!brief.contains("CHAT-ONLY-WORDS"));
|
||||
@@ -408,7 +484,9 @@ mod tests {
|
||||
"agent": { "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" },
|
||||
});
|
||||
let brief = build_brief(&state, None, None, &[]);
|
||||
assert!(brief.contains("Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n"));
|
||||
assert!(brief.contains(
|
||||
"Phase 2: Restart: 1 of 3 done.\nDoing: Spiking Claude's context signal (Task 10.1)\n"
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -442,7 +520,9 @@ mod tests {
|
||||
#[test]
|
||||
fn only_the_last_five_events_are_named() {
|
||||
let state = json!({ "schema": 1, "workflow": "implement" });
|
||||
let events: Vec<Value> = (0..8).map(|n| json!({ "type": "upload", "id": format!("f{n}") })).collect();
|
||||
let events: Vec<Value> = (0..8)
|
||||
.map(|n| json!({ "type": "upload", "id": format!("f{n}") }))
|
||||
.collect();
|
||||
let brief = build_brief(&state, None, None, &events);
|
||||
assert_eq!(brief.matches("- upload\n").count(), RECENT_EVENTS);
|
||||
}
|
||||
@@ -455,7 +535,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_skill_name_maps_to_its_workflow() {
|
||||
assert_eq!(skill_for_workflow("quick-task"), Some("plan2code-quick-task"));
|
||||
assert_eq!(
|
||||
skill_for_workflow("quick-task"),
|
||||
Some("plan2code-quick-task")
|
||||
);
|
||||
assert_eq!(skill_for_workflow("unknown"), None);
|
||||
}
|
||||
}
|
||||
@@ -156,7 +156,9 @@ fn parse_open_output(stdout: &[u8]) -> Result<ConsoleSession, String> {
|
||||
/// Split `http://<host>:<port><path>` into its parts; the console only ever
|
||||
/// listens on loopback http.
|
||||
fn split_url(url: &str) -> Result<(String, u16, String), String> {
|
||||
let rest = url.strip_prefix("http://").ok_or_else(|| format!("not an http url: {url}"))?;
|
||||
let rest = url
|
||||
.strip_prefix("http://")
|
||||
.ok_or_else(|| format!("not an http url: {url}"))?;
|
||||
let (authority, path) = match rest.split_once('/') {
|
||||
Some((a, p)) => (a, format!("/{p}")),
|
||||
None => (rest, "/".to_string()),
|
||||
@@ -164,7 +166,9 @@ fn split_url(url: &str) -> Result<(String, u16, String), String> {
|
||||
let (host, port) = authority
|
||||
.rsplit_once(':')
|
||||
.ok_or_else(|| format!("no port in url: {url}"))?;
|
||||
let port: u16 = port.parse().map_err(|_| format!("bad port in url: {url}"))?;
|
||||
let port: u16 = port
|
||||
.parse()
|
||||
.map_err(|_| format!("bad port in url: {url}"))?;
|
||||
Ok((host.to_string(), port, path))
|
||||
}
|
||||
|
||||
@@ -175,7 +179,13 @@ impl ConsoleSupervisor {
|
||||
pub fn start(project_dir: PathBuf, embed_origin: String) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let session = Self::open_session(&console_dir, &project_dir, &embed_origin, None)?;
|
||||
Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, session, stopped: false })
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// `open` for the dashboard, or, with `resume`, the same session again on
|
||||
@@ -190,8 +200,20 @@ impl ConsoleSupervisor {
|
||||
) -> Result<ConsoleSupervisor, String> {
|
||||
let console_dir = find_console_dir()?;
|
||||
let (_, port, _) = split_url(url)?;
|
||||
let session = ConsoleSession { sid: sid.to_string(), url: url.to_string(), pid: 0, port, embed: true };
|
||||
Ok(ConsoleSupervisor { console_dir, project_dir, embed_origin, session, stopped: false })
|
||||
let session = ConsoleSession {
|
||||
sid: sid.to_string(),
|
||||
url: url.to_string(),
|
||||
pid: 0,
|
||||
port,
|
||||
embed: true,
|
||||
};
|
||||
Ok(ConsoleSupervisor {
|
||||
console_dir,
|
||||
project_dir,
|
||||
embed_origin,
|
||||
session,
|
||||
stopped: false,
|
||||
})
|
||||
}
|
||||
|
||||
fn open_session(
|
||||
@@ -264,7 +286,10 @@ impl ConsoleSupervisor {
|
||||
let Ok((host, port, path)) = split_url(&self.session.url) else {
|
||||
return false;
|
||||
};
|
||||
let Some(addr) = (host.as_str(), port).to_socket_addrs().ok().and_then(|mut a| a.next())
|
||||
let Some(addr) = (host.as_str(), port)
|
||||
.to_socket_addrs()
|
||||
.ok()
|
||||
.and_then(|mut a| a.next())
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
@@ -293,7 +318,8 @@ impl ConsoleSupervisor {
|
||||
}
|
||||
let sid = self.session.sid.clone();
|
||||
let on_disk = session_on_disk(&sid);
|
||||
let (console_dir, project_dir, embed_origin) = (&self.console_dir, &self.project_dir, &self.embed_origin);
|
||||
let (console_dir, project_dir, embed_origin) =
|
||||
(&self.console_dir, &self.project_dir, &self.embed_origin);
|
||||
self.session = resume_or_fresh(&sid, on_disk, |resume| {
|
||||
Self::open_session(console_dir, project_dir, embed_origin, resume)
|
||||
})?;
|
||||
@@ -329,7 +355,8 @@ pub fn session_on_disk(sid: &str) -> bool {
|
||||
if Path::new(sid).file_name() != Some(std::ffi::OsStr::new(sid)) {
|
||||
return false;
|
||||
}
|
||||
session_reader::console_home().map_or(true, |home| session_reader::session_dir(&home, sid).is_dir())
|
||||
session_reader::console_home()
|
||||
.is_none_or(|home| session_reader::session_dir(&home, sid).is_dir())
|
||||
}
|
||||
|
||||
/// The same session, so the page and a skill's place in it survive, tried
|
||||
@@ -362,7 +389,10 @@ mod tests {
|
||||
#[test]
|
||||
fn splits_the_session_url() {
|
||||
let (host, port, path) = split_url("http://127.0.0.1:51617/s/abc/").unwrap();
|
||||
assert_eq!((host.as_str(), port, path.as_str()), ("127.0.0.1", 51617, "/s/abc/"));
|
||||
assert_eq!(
|
||||
(host.as_str(), port, path.as_str()),
|
||||
("127.0.0.1", 51617, "/s/abc/")
|
||||
);
|
||||
let (_, _, path) = split_url("http://localhost:9").unwrap();
|
||||
assert_eq!(path, "/");
|
||||
assert!(split_url("https://127.0.0.1:1/x").is_err());
|
||||
@@ -371,10 +401,22 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn origin_comes_from_the_pages_own_url() {
|
||||
assert_eq!(origin_of("http://127.0.0.1:1430/index.html").as_deref(), Some("http://127.0.0.1:1430"));
|
||||
assert_eq!(origin_of("http://tauri.localhost/").as_deref(), Some("http://tauri.localhost"));
|
||||
assert_eq!(origin_of("https://tauri.localhost").as_deref(), Some("https://tauri.localhost"));
|
||||
assert_eq!(origin_of("tauri://localhost/index.html?x=1").as_deref(), Some("tauri://localhost"));
|
||||
assert_eq!(
|
||||
origin_of("http://127.0.0.1:1430/index.html").as_deref(),
|
||||
Some("http://127.0.0.1:1430")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("http://tauri.localhost/").as_deref(),
|
||||
Some("http://tauri.localhost")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("https://tauri.localhost").as_deref(),
|
||||
Some("https://tauri.localhost")
|
||||
);
|
||||
assert_eq!(
|
||||
origin_of("tauri://localhost/index.html?x=1").as_deref(),
|
||||
Some("tauri://localhost")
|
||||
);
|
||||
assert_eq!(origin_of("file:///x"), None);
|
||||
assert_eq!(origin_of("not a url"), None);
|
||||
assert_eq!(origin_of("http:///x"), None);
|
||||
@@ -385,18 +427,38 @@ mod tests {
|
||||
// Only needs a console to be installed; skipped where there is none.
|
||||
let Ok(dir) = find_console_dir() else { return };
|
||||
let _ = dir;
|
||||
let mut sup = ConsoleSupervisor::adopt(PathBuf::from("."), "http://tauri.localhost".into(), "http://127.0.0.1:5555/s/t/", "sid-9").unwrap();
|
||||
assert_eq!((sup.session().port, sup.session().sid.as_str()), (5555, "sid-9"));
|
||||
let mut sup = ConsoleSupervisor::adopt(
|
||||
PathBuf::from("."),
|
||||
"http://tauri.localhost".into(),
|
||||
"http://127.0.0.1:5555/s/t/",
|
||||
"sid-9",
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
(sup.session().port, sup.session().sid.as_str()),
|
||||
(5555, "sid-9")
|
||||
);
|
||||
assert!(sup.session().embed);
|
||||
assert!(ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err());
|
||||
assert!(
|
||||
ConsoleSupervisor::adopt(PathBuf::from("."), String::new(), "https://x/", "s").is_err()
|
||||
);
|
||||
sup.follow("http://127.0.0.1:6000/s/u/", "sid-10");
|
||||
assert_eq!((sup.session().port, sup.session().sid.as_str()), (6000, "sid-10"));
|
||||
assert_eq!(
|
||||
(sup.session().port, sup.session().sid.as_str()),
|
||||
(6000, "sid-10")
|
||||
);
|
||||
// Never started a server here: nothing for Drop to stop.
|
||||
sup.stopped = true;
|
||||
}
|
||||
|
||||
fn opened(sid: &str) -> ConsoleSession {
|
||||
ConsoleSession { sid: sid.to_string(), url: "http://127.0.0.1:5/s/t/".into(), pid: 1, port: 5, embed: true }
|
||||
ConsoleSession {
|
||||
sid: sid.to_string(),
|
||||
url: "http://127.0.0.1:5/s/t/".into(),
|
||||
pid: 1,
|
||||
port: 5,
|
||||
embed: true,
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -417,7 +479,10 @@ mod tests {
|
||||
Err("busy".to_string())
|
||||
});
|
||||
assert!(result.is_err(), "the failure is reported, not papered over");
|
||||
assert!(calls.iter().all(|c| c.as_deref() == Some("s1")), "only ever resumed: {calls:?}");
|
||||
assert!(
|
||||
calls.iter().all(|c| c.as_deref() == Some("s1")),
|
||||
"only ever resumed: {calls:?}"
|
||||
);
|
||||
assert_eq!(calls.len(), 2, "the resume is tried twice");
|
||||
}
|
||||
|
||||
@@ -427,7 +492,11 @@ mod tests {
|
||||
let session = resume_or_fresh("s1", true, |resume| {
|
||||
tries += 1;
|
||||
assert_eq!(resume, Some("s1"));
|
||||
if tries == 1 { Err("busy".to_string()) } else { Ok(opened("s1")) }
|
||||
if tries == 1 {
|
||||
Err("busy".to_string())
|
||||
} else {
|
||||
Ok(opened("s1"))
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(session.sid, "s1");
|
||||
@@ -447,13 +516,20 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn parses_open_output() {
|
||||
let json = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1}
|
||||
let json =
|
||||
br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42,"embed":1}
|
||||
"#;
|
||||
let session = parse_open_output(json).unwrap();
|
||||
assert_eq!((session.sid.as_str(), session.port, session.pid), ("s1", 5, 42));
|
||||
assert_eq!(
|
||||
(session.sid.as_str(), session.port, session.pid),
|
||||
("s1", 5, 42)
|
||||
);
|
||||
assert!(session.embed);
|
||||
let old = br#"{"ok":true,"sid":"s1","url":"http://127.0.0.1:5/s/t/","port":5,"pid":42}"#;
|
||||
assert!(!parse_open_output(old).unwrap().embed, "a console that does not say it embeds is too old");
|
||||
assert!(
|
||||
!parse_open_output(old).unwrap().embed,
|
||||
"a console that does not say it embeds is too old"
|
||||
);
|
||||
assert!(parse_open_output(b"not json\n").is_err());
|
||||
assert!(parse_open_output(br#"{"ok":true,"sid":"s1"}"#).is_err());
|
||||
}
|
||||
|
||||
@@ -34,7 +34,12 @@ pub struct Record<'a> {
|
||||
/// id made from `when`'s local minute. Returns the id. The record is claimed
|
||||
/// exclusively, so two writes in the same minute never share an id; a failed
|
||||
/// write leaves nothing behind.
|
||||
pub fn write(dir: &Path, when: DateTime<Local>, record: &Record, body: &str) -> Result<String, String> {
|
||||
pub fn write(
|
||||
dir: &Path,
|
||||
when: DateTime<Local>,
|
||||
record: &Record,
|
||||
body: &str,
|
||||
) -> Result<String, String> {
|
||||
validate(record)?;
|
||||
fs::create_dir_all(dir).map_err(|e| e.to_string())?;
|
||||
let base = format!(
|
||||
@@ -45,15 +50,25 @@ pub fn write(dir: &Path, when: DateTime<Local>, record: &Record, body: &str) ->
|
||||
when.hour(),
|
||||
when.minute()
|
||||
);
|
||||
let written = when.with_timezone(&Utc).to_rfc3339_opts(SecondsFormat::Millis, true);
|
||||
let written = when
|
||||
.with_timezone(&Utc)
|
||||
.to_rfc3339_opts(SecondsFormat::Millis, true);
|
||||
for n in 1.. {
|
||||
let id = if n == 1 { base.clone() } else { format!("{base}-{n}") };
|
||||
let id = if n == 1 {
|
||||
base.clone()
|
||||
} else {
|
||||
format!("{base}-{n}")
|
||||
};
|
||||
let md = dir.join(format!("{id}.md"));
|
||||
let json_file = dir.join(format!("{id}.json"));
|
||||
if md.exists() {
|
||||
continue;
|
||||
}
|
||||
let mut claim = match OpenOptions::new().write(true).create_new(true).open(&json_file) {
|
||||
let mut claim = match OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(&json_file)
|
||||
{
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => continue,
|
||||
Err(e) => return Err(e.to_string()),
|
||||
@@ -86,8 +101,13 @@ pub fn write(dir: &Path, when: DateTime<Local>, record: &Record, body: &str) ->
|
||||
}
|
||||
|
||||
fn write_document(md: &Path, heading: &str, body: &str) -> Result<(), String> {
|
||||
let mut file = OpenOptions::new().write(true).create_new(true).open(md).map_err(|e| e.to_string())?;
|
||||
file.write_all(format!("{heading}\n\n{body}").as_bytes()).map_err(|e| e.to_string())
|
||||
let mut file = OpenOptions::new()
|
||||
.write(true)
|
||||
.create_new(true)
|
||||
.open(md)
|
||||
.map_err(|e| e.to_string())?;
|
||||
file.write_all(format!("{heading}\n\n{body}").as_bytes())
|
||||
.map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
fn title_line(title: &str) -> String {
|
||||
@@ -98,8 +118,12 @@ fn title_line(title: &str) -> String {
|
||||
/// both files. A picked-up one, or one already gone, is left alone.
|
||||
pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> {
|
||||
let json_file = dir.join(format!("{id}.json"));
|
||||
let Ok(text) = fs::read_to_string(&json_file) else { return Ok(()) };
|
||||
let used = serde_json::from_str::<serde_json::Value>(&text).ok().is_some_and(|meta| !meta["usedAt"].is_null());
|
||||
let Ok(text) = fs::read_to_string(&json_file) else {
|
||||
return Ok(());
|
||||
};
|
||||
let used = serde_json::from_str::<serde_json::Value>(&text)
|
||||
.ok()
|
||||
.is_some_and(|meta| !meta["usedAt"].is_null());
|
||||
if used {
|
||||
return Ok(());
|
||||
}
|
||||
@@ -116,17 +140,30 @@ pub fn retire_if_unused(dir: &Path, id: &str) -> Result<(), String> {
|
||||
/// The same rules the console applies to the record, so a bad field is refused
|
||||
/// here rather than written and then ignored.
|
||||
fn validate(record: &Record) -> Result<(), String> {
|
||||
let lower_dashes = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-');
|
||||
let lower_dashes =
|
||||
|s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_lowercase() || c == '-');
|
||||
if !lower_dashes(record.workflow) {
|
||||
return Err(format!("workflow must be lowercase letters and dashes, got {:?}", record.workflow));
|
||||
return Err(format!(
|
||||
"workflow must be lowercase letters and dashes, got {:?}",
|
||||
record.workflow
|
||||
));
|
||||
}
|
||||
let skill_ok = !record.skill.is_empty() && record.skill.chars().all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
|
||||
let skill_ok = !record.skill.is_empty()
|
||||
&& record
|
||||
.skill
|
||||
.chars()
|
||||
.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-');
|
||||
if !skill_ok {
|
||||
return Err(format!("skill must be a skill name, got {:?}", record.skill));
|
||||
return Err(format!(
|
||||
"skill must be a skill name, got {:?}",
|
||||
record.skill
|
||||
));
|
||||
}
|
||||
if let Some(spec) = record.spec {
|
||||
let name = spec.strip_prefix("specs/");
|
||||
if name.is_none_or(|n| n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\')) {
|
||||
if name.is_none_or(|n| {
|
||||
n.is_empty() || n == "." || n == ".." || n.contains('/') || n.contains('\\')
|
||||
}) {
|
||||
return Err(format!("spec must be specs/<name>, got {spec:?}"));
|
||||
}
|
||||
}
|
||||
@@ -144,7 +181,8 @@ mod tests {
|
||||
use chrono::TimeZone;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id()));
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-handoff-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
dir
|
||||
}
|
||||
@@ -161,7 +199,9 @@ mod tests {
|
||||
}
|
||||
|
||||
fn at(hour: u32, minute: u32) -> DateTime<Local> {
|
||||
Local.with_ymd_and_hms(2026, 10, 21, hour, minute, 0).unwrap()
|
||||
Local
|
||||
.with_ymd_and_hms(2026, 10, 21, hour, minute, 0)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -169,7 +209,9 @@ mod tests {
|
||||
let dir = fixture("shape");
|
||||
let id = write(&dir, at(13, 52), &record(), "## Next task\n\nTask 5.2").unwrap();
|
||||
assert_eq!(id, "2026-10-21-1352-handoff");
|
||||
let meta: serde_json::Value = serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap()).unwrap();
|
||||
let meta: serde_json::Value =
|
||||
serde_json::from_str(&fs::read_to_string(dir.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(meta["v"], 1);
|
||||
assert_eq!(meta["id"], id.as_str());
|
||||
assert_eq!(meta["workflow"], "implement");
|
||||
@@ -206,7 +248,11 @@ mod tests {
|
||||
let dir = fixture("retire");
|
||||
let unused = write(&dir, at(10, 0), &record(), "one").unwrap();
|
||||
let used = write(&dir, at(10, 1), &record(), "two").unwrap();
|
||||
fs::write(dir.join(format!("{used}.json")), r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#).unwrap();
|
||||
fs::write(
|
||||
dir.join(format!("{used}.json")),
|
||||
r#"{"v":1,"usedAt":"2026-10-21T10:02:00.000Z"}"#,
|
||||
)
|
||||
.unwrap();
|
||||
retire_if_unused(&dir, &unused).unwrap();
|
||||
retire_if_unused(&dir, &used).unwrap();
|
||||
assert!(!dir.join(format!("{unused}.json")).exists());
|
||||
|
||||
@@ -3,11 +3,13 @@
|
||||
|
||||
use std::sync::{Arc, Mutex, OnceLock};
|
||||
|
||||
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentState, BeforeFresh, Sink};
|
||||
use plan2code_app_lib::agents::{self, Agent, AgentKind, PermissionMode};
|
||||
use plan2code_app_lib::announce::{AnnounceServer, PageNotice};
|
||||
use plan2code_app_lib::attention::{self, Badge, Signal};
|
||||
use plan2code_app_lib::console_supervisor::{app_origin, origin_of, session_on_disk, ConsoleSupervisor};
|
||||
use plan2code_app_lib::console_supervisor::{
|
||||
app_origin, origin_of, session_on_disk, ConsoleSupervisor,
|
||||
};
|
||||
use plan2code_app_lib::node_check;
|
||||
use plan2code_app_lib::project::{self, ProjectDir};
|
||||
use plan2code_app_lib::restart_brief;
|
||||
@@ -54,7 +56,10 @@ struct AttentionState {
|
||||
|
||||
impl Default for AttentionState {
|
||||
fn default() -> Self {
|
||||
AttentionState { last: None, enabled: true }
|
||||
AttentionState {
|
||||
last: None,
|
||||
enabled: true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -135,23 +140,35 @@ fn open_install_page(id: String) -> Result<(), String> {
|
||||
c.arg(url);
|
||||
c
|
||||
} else {
|
||||
let browser = std::env::var("BROWSER").ok().filter(|b| !b.is_empty()).unwrap_or_else(|| "xdg-open".to_string());
|
||||
let browser = std::env::var("BROWSER")
|
||||
.ok()
|
||||
.filter(|b| !b.is_empty())
|
||||
.unwrap_or_else(|| "xdg-open".to_string());
|
||||
let mut c = std::process::Command::new(browser);
|
||||
c.arg(url);
|
||||
c
|
||||
};
|
||||
command.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::null()).stderr(std::process::Stdio::null());
|
||||
command
|
||||
.stdin(std::process::Stdio::null())
|
||||
.stdout(std::process::Stdio::null())
|
||||
.stderr(std::process::Stdio::null());
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x0800_0000); // CREATE_NO_WINDOW
|
||||
}
|
||||
command.spawn().map(|_| ()).map_err(|e| format!("could not open {url}: {e}"))
|
||||
command
|
||||
.spawn()
|
||||
.map(|_| ())
|
||||
.map_err(|e| format!("could not open {url}: {e}"))
|
||||
}
|
||||
|
||||
// `cmd /c ver` prints e.g. `Microsoft Windows [Version 10.0.26300.1234]`.
|
||||
fn windows_build() -> Option<u32> {
|
||||
let out = std::process::Command::new("cmd").args(["/c", "ver"]).output().ok()?;
|
||||
let out = std::process::Command::new("cmd")
|
||||
.args(["/c", "ver"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let text = String::from_utf8_lossy(&out.stdout);
|
||||
let version = text.split("Version ").nth(1)?;
|
||||
version.split('.').nth(2)?.trim().parse().ok()
|
||||
@@ -168,7 +185,9 @@ fn page_sink(page: PageChannel, app: Arc<OnceLock<tauri::AppHandle>>) -> Sink {
|
||||
}
|
||||
}
|
||||
let Ok(guard) = page.lock() else { return };
|
||||
let Some(channel) = guard.as_ref() else { return };
|
||||
let Some(channel) = guard.as_ref() else {
|
||||
return;
|
||||
};
|
||||
let body = match event {
|
||||
AgentEvent::Output(bytes) => InvokeResponseBody::Raw(bytes),
|
||||
AgentEvent::State(snapshot) => match serde_json::to_string(&snapshot) {
|
||||
@@ -185,7 +204,10 @@ fn page_sink(page: PageChannel, app: Arc<OnceLock<tauri::AppHandle>>) -> Sink {
|
||||
fn agent_for_project(state: &AppState) -> Result<Arc<AgentManager>, String> {
|
||||
let dir = {
|
||||
let project = state.project.lock().map_err(|e| e.to_string())?;
|
||||
project.as_ref().map(|p| p.dir.clone()).ok_or("no project folder chosen")?
|
||||
project
|
||||
.as_ref()
|
||||
.map(|p| p.dir.clone())
|
||||
.ok_or("no project folder chosen")?
|
||||
};
|
||||
let mut guard = state.agent.lock().map_err(|e| e.to_string())?;
|
||||
if let Some(agent) = guard.as_ref() {
|
||||
@@ -213,7 +235,10 @@ 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 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() {
|
||||
@@ -238,7 +263,12 @@ fn current_agent(state: &AppState) -> Option<Arc<AgentManager>> {
|
||||
/// once announced a test's throwaway console, the window followed it, and
|
||||
/// when the test shut it down the reconnect opened an empty dashboard, so the
|
||||
/// build's own page was never seen again.
|
||||
fn take_announced(state: &AppState, notice: &PageNotice, origin: String, on_disk: impl Fn(&str) -> bool) -> bool {
|
||||
fn take_announced(
|
||||
state: &AppState,
|
||||
notice: &PageNotice,
|
||||
origin: String,
|
||||
on_disk: impl Fn(&str) -> bool,
|
||||
) -> bool {
|
||||
if !on_disk(¬ice.sid) {
|
||||
return false;
|
||||
}
|
||||
@@ -246,9 +276,14 @@ fn take_announced(state: &AppState, notice: &PageNotice, origin: String, on_disk
|
||||
match guard.as_mut() {
|
||||
Some(sup) => sup.follow(¬ice.url, ¬ice.sid),
|
||||
None => {
|
||||
let dir = state.project.lock().ok().and_then(|p| p.as_ref().map(|p| p.dir.clone()));
|
||||
let dir = state
|
||||
.project
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|p| p.as_ref().map(|p| p.dir.clone()));
|
||||
if let Some(dir) = dir {
|
||||
if let Ok(sup) = ConsoleSupervisor::adopt(dir, origin, ¬ice.url, ¬ice.sid) {
|
||||
if let Ok(sup) = ConsoleSupervisor::adopt(dir, origin, ¬ice.url, ¬ice.sid)
|
||||
{
|
||||
*guard = Some(sup);
|
||||
}
|
||||
}
|
||||
@@ -271,11 +306,15 @@ fn window_origin(app: &tauri::AppHandle) -> String {
|
||||
// agent gets nothing and opens pages the plain way.
|
||||
fn sync_agent_env(app: &tauri::AppHandle) {
|
||||
let state = app.state::<AppState>();
|
||||
let Some(agent) = current_agent(&state) else { return };
|
||||
let Some(agent) = current_agent(&state) else {
|
||||
return;
|
||||
};
|
||||
let env = match state.announce.lock().ok() {
|
||||
Some(guard) => guard
|
||||
.as_ref()
|
||||
.map(|server| server.agent_env(&window_origin(app), &app.package_info().version.to_string()))
|
||||
.map(|server| {
|
||||
server.agent_env(&window_origin(app), &app.package_info().version.to_string())
|
||||
})
|
||||
.unwrap_or_default(),
|
||||
None => Vec::new(),
|
||||
};
|
||||
@@ -290,6 +329,7 @@ fn sync_agent_env(app: &tauri::AppHandle) {
|
||||
// reattach registration) sends the frontend an "end" message that
|
||||
// unregisters that id for good, breaking all future sends through it.
|
||||
#[tauri::command]
|
||||
#[allow(clippy::too_many_arguments)] // one argument per key the frontend passes to invoke
|
||||
fn agent_start(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
@@ -301,7 +341,8 @@ fn agent_start(
|
||||
rows: u16,
|
||||
) -> Result<(), String> {
|
||||
let kind = agents::find_agent(&kind).ok_or_else(|| format!("unknown agent: {kind}"))?;
|
||||
let mode = PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
|
||||
let mode =
|
||||
PermissionMode::from_id(&mode).ok_or_else(|| format!("unknown permission mode: {mode}"))?;
|
||||
let agent = agent_for_project(&state)?;
|
||||
agent.resize(cols, rows)?;
|
||||
sync_agent_env(&app);
|
||||
@@ -331,7 +372,9 @@ fn agent_resize(state: State<'_, AppState>, cols: u16, rows: u16) -> Result<(),
|
||||
|
||||
#[tauri::command]
|
||||
fn agent_restart(state: State<'_, AppState>) -> Result<(), String> {
|
||||
current_agent(&state).ok_or("no agent has been started")?.restart()
|
||||
current_agent(&state)
|
||||
.ok_or("no agent has been started")?
|
||||
.restart()
|
||||
}
|
||||
|
||||
fn idle_snapshot_json() -> serde_json::Value {
|
||||
@@ -344,7 +387,10 @@ fn idle_snapshot_json() -> serde_json::Value {
|
||||
/// current generation's recent output on it at once, so the terminal does
|
||||
/// not come up blank.
|
||||
#[tauri::command]
|
||||
fn agent_reattach(state: State<'_, AppState>, on_output: Channel<InvokeResponseBody>) -> Result<serde_json::Value, String> {
|
||||
fn agent_reattach(
|
||||
state: State<'_, AppState>,
|
||||
on_output: Channel<InvokeResponseBody>,
|
||||
) -> Result<serde_json::Value, String> {
|
||||
let agent = current_agent(&state);
|
||||
*state.page.lock().map_err(|e| e.to_string())? = Some(on_output.clone());
|
||||
if let Some(agent) = &agent {
|
||||
@@ -401,13 +447,22 @@ fn quit_app(app: &tauri::AppHandle) {
|
||||
// unknown word does nothing.
|
||||
#[tauri::command]
|
||||
fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: String) {
|
||||
let Some(next) = Signal::from_id(&signal) else { return };
|
||||
let Some(window) = app.get_webview_window("main") else { return };
|
||||
let Some(next) = Signal::from_id(&signal) else {
|
||||
return;
|
||||
};
|
||||
let Some(window) = app.get_webview_window("main") else {
|
||||
return;
|
||||
};
|
||||
let (prev, enabled) = {
|
||||
let Ok(mut guard) = state.attention.lock() else { return };
|
||||
let Ok(mut guard) = state.attention.lock() else {
|
||||
return;
|
||||
};
|
||||
(guard.last.replace(next), guard.enabled)
|
||||
};
|
||||
apply_badge(&window, attention::badge_for(next, std::env::consts::OS, enabled));
|
||||
apply_badge(
|
||||
&window,
|
||||
attention::badge_for(next, std::env::consts::OS, enabled),
|
||||
);
|
||||
if attention::should_flash(prev, next, window.is_focused().unwrap_or(true), enabled) {
|
||||
let _ = window.request_user_attention(Some(tauri::UserAttentionType::Informational));
|
||||
}
|
||||
@@ -415,7 +470,10 @@ fn set_attention(app: tauri::AppHandle, state: State<'_, AppState>, signal: Stri
|
||||
|
||||
// The one place a badge reaches the window, in each system's own form. A call
|
||||
// that fails changes nothing else: the taskbar is a hint, never a blocker.
|
||||
#[cfg_attr(not(any(target_os = "windows", target_os = "macos", target_os = "linux")), allow(unused_variables))]
|
||||
#[cfg_attr(
|
||||
not(any(target_os = "windows", target_os = "macos", target_os = "linux")),
|
||||
allow(unused_variables)
|
||||
)]
|
||||
fn apply_badge(window: &tauri::WebviewWindow, badge: Badge) {
|
||||
#[cfg(target_os = "windows")]
|
||||
{
|
||||
@@ -453,7 +511,9 @@ fn clear_attention(app: &tauri::AppHandle) {
|
||||
if let Ok(mut guard) = app.state::<AppState>().attention.lock() {
|
||||
guard.last = Some(Signal::Plain);
|
||||
}
|
||||
let Some(window) = app.get_webview_window("main") else { return };
|
||||
let Some(window) = app.get_webview_window("main") else {
|
||||
return;
|
||||
};
|
||||
apply_badge(&window, Badge::None);
|
||||
let _ = window.request_user_attention(None);
|
||||
}
|
||||
@@ -470,17 +530,26 @@ fn clear_attention_cmd(app: tauri::AppHandle) {
|
||||
// Either way the last state is kept. Saved in the app's own app.json, never
|
||||
// in the console's files.
|
||||
#[tauri::command]
|
||||
fn set_taskbar_signal(app: tauri::AppHandle, state: State<'_, AppState>, on: bool) -> Result<(), String> {
|
||||
fn set_taskbar_signal(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
on: bool,
|
||||
) -> Result<(), String> {
|
||||
let saved = settings::settings_file()
|
||||
.ok_or_else(|| "no home folder found".to_string())
|
||||
.and_then(|file| settings::save_taskbar_signal(&file, on));
|
||||
let last = {
|
||||
let Ok(mut guard) = state.attention.lock() else { return saved };
|
||||
let Ok(mut guard) = state.attention.lock() else {
|
||||
return saved;
|
||||
};
|
||||
guard.enabled = on;
|
||||
guard.last.unwrap_or(Signal::Plain)
|
||||
};
|
||||
if let Some(window) = app.get_webview_window("main") {
|
||||
apply_badge(&window, attention::badge_for(last, std::env::consts::OS, on));
|
||||
apply_badge(
|
||||
&window,
|
||||
attention::badge_for(last, std::env::consts::OS, on),
|
||||
);
|
||||
if !on {
|
||||
let _ = window.request_user_attention(None);
|
||||
}
|
||||
@@ -502,7 +571,12 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
.agent
|
||||
.clone()
|
||||
.filter(known)
|
||||
.or_else(|| settings_file.as_ref().and_then(|file| settings::load_last_agent(file)).filter(known))
|
||||
.or_else(|| {
|
||||
settings_file
|
||||
.as_ref()
|
||||
.and_then(|file| settings::load_last_agent(file))
|
||||
.filter(known)
|
||||
})
|
||||
.or_else(|| project::remembered_agent().filter(known));
|
||||
let term_panel = settings_file.as_ref().map_or(
|
||||
settings::TermPanelSettings {
|
||||
@@ -512,7 +586,9 @@ fn app_state(state: State<'_, AppState>) -> serde_json::Value {
|
||||
},
|
||||
|file| settings::load_term_panel(file),
|
||||
);
|
||||
let first_run_done = settings_file.as_ref().is_some_and(|file| settings::load_first_run_done(file));
|
||||
let first_run_done = settings_file
|
||||
.as_ref()
|
||||
.is_some_and(|file| settings::load_first_run_done(file));
|
||||
serde_json::json!({
|
||||
"projectDir": project.as_ref().map(|p| p.dir.to_string_lossy().into_owned()),
|
||||
"projectDirSource": project.as_ref().map(|p| p.source),
|
||||
@@ -555,7 +631,10 @@ fn save_first_run_done() -> Result<(), String> {
|
||||
/// installed skills' version. The bar shows its Update line when they differ (FR-14).
|
||||
#[tauri::command]
|
||||
fn version_status(app: tauri::AppHandle) -> versions::VersionStatus {
|
||||
versions::status(&app.package_info().version.to_string(), versions::installed_skills_version())
|
||||
versions::status(
|
||||
&app.package_info().version.to_string(),
|
||||
versions::installed_skills_version(),
|
||||
)
|
||||
}
|
||||
|
||||
/// What `update_skills` resolves with: the installer's last line, and the version status
|
||||
@@ -570,7 +649,10 @@ struct UpdateOutcome {
|
||||
/// button asks for it: never silently. `progress` carries each line of the installer's own
|
||||
/// output live, for the bar to show while it runs.
|
||||
#[tauri::command]
|
||||
async fn update_skills(app: tauri::AppHandle, progress: Channel<String>) -> Result<UpdateOutcome, String> {
|
||||
async fn update_skills(
|
||||
app: tauri::AppHandle,
|
||||
progress: Channel<String>,
|
||||
) -> Result<UpdateOutcome, String> {
|
||||
let version = app.package_info().version.to_string();
|
||||
let message = tauri::async_runtime::spawn_blocking(move || {
|
||||
versions::run_update(&version, |line| {
|
||||
@@ -579,14 +661,20 @@ async fn update_skills(app: tauri::AppHandle, progress: Channel<String>) -> Resu
|
||||
})
|
||||
.await
|
||||
.map_err(|e| e.to_string())??;
|
||||
let status = versions::status(&app.package_info().version.to_string(), versions::installed_skills_version());
|
||||
let status = versions::status(
|
||||
&app.package_info().version.to_string(),
|
||||
versions::installed_skills_version(),
|
||||
);
|
||||
Ok(UpdateOutcome { message, status })
|
||||
}
|
||||
|
||||
/// The OS folder picker, shown when no folder is known; a choice becomes the
|
||||
/// launcher's remembered folder.
|
||||
#[tauri::command]
|
||||
fn pick_project_folder(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||
fn pick_project_folder(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
@@ -631,7 +719,10 @@ fn teardown_project(state: &AppState) -> Result<(), String> {
|
||||
/// nothing (canceled) leaves the current project untouched. One project per
|
||||
/// window stays; this replaces it, it does not add a second.
|
||||
#[tauri::command]
|
||||
fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<Option<String>, String> {
|
||||
fn change_project(
|
||||
app: tauri::AppHandle,
|
||||
state: State<'_, AppState>,
|
||||
) -> Result<Option<String>, String> {
|
||||
let picked = app
|
||||
.dialog()
|
||||
.file()
|
||||
@@ -650,7 +741,7 @@ fn change_project(app: tauri::AppHandle, state: State<'_, AppState>) -> Result<O
|
||||
}
|
||||
|
||||
/// The console the agent opened, alive and as it is now, or restarted on the
|
||||
/// same session when it died. The app never starts a dashboard of its own:
|
||||
/// same session when it died. The app never starts a dashboard of its own:
|
||||
/// the agent does, by running the skill, and announces it. Nothing to show yet
|
||||
/// is an error the page words for the person.
|
||||
#[tauri::command]
|
||||
@@ -660,7 +751,9 @@ fn console_start(state: State<'_, AppState>) -> Result<serde_json::Value, String
|
||||
|
||||
fn console_start_impl(state: &AppState) -> Result<serde_json::Value, String> {
|
||||
let mut guard = state.console.lock().map_err(|e| e.to_string())?;
|
||||
let sup = guard.as_mut().ok_or("The agent has not opened the dashboard yet.")?;
|
||||
let sup = guard
|
||||
.as_mut()
|
||||
.ok_or("The agent has not opened the dashboard yet.")?;
|
||||
if !sup.health() {
|
||||
sup.restart_if_dead()?;
|
||||
}
|
||||
@@ -676,7 +769,9 @@ fn console_status(state: State<'_, AppState>) -> serde_json::Value {
|
||||
};
|
||||
match guard.as_ref() {
|
||||
Some(sup) if sup.stopped() => serde_json::json!({ "state": "none", "url": null }),
|
||||
Some(sup) if sup.health() => serde_json::json!({ "state": "running", "url": sup.session().url }),
|
||||
Some(sup) if sup.health() => {
|
||||
serde_json::json!({ "state": "running", "url": sup.session().url })
|
||||
}
|
||||
Some(sup) => serde_json::json!({ "state": "dead", "url": sup.session().url }),
|
||||
None => serde_json::json!({ "state": "none", "url": null }),
|
||||
}
|
||||
@@ -699,7 +794,9 @@ fn main() {
|
||||
node_check::NodeStatus::Ok(version) => Some(version.clone()),
|
||||
_ => None,
|
||||
};
|
||||
let node_binary = node_version.as_ref().and_then(|_| node_check::node_binary_path());
|
||||
let node_binary = node_version
|
||||
.as_ref()
|
||||
.and_then(|_| node_check::node_binary_path());
|
||||
|
||||
let args = std::env::args().collect::<Vec<_>>();
|
||||
tauri::Builder::default()
|
||||
@@ -711,7 +808,8 @@ fn main() {
|
||||
node_binary,
|
||||
attention: Mutex::new(AttentionState {
|
||||
last: None,
|
||||
enabled: settings::settings_file().map_or(true, |file| settings::load_taskbar_signal(&file)),
|
||||
enabled: settings::settings_file()
|
||||
.is_none_or(|file| settings::load_taskbar_signal(&file)),
|
||||
}),
|
||||
..AppState::default()
|
||||
})
|
||||
@@ -759,11 +857,15 @@ fn main() {
|
||||
let handle = app.handle().clone();
|
||||
let server = AnnounceServer::start(Arc::new(move |notice| {
|
||||
let state = handle.state::<AppState>();
|
||||
let taken = take_announced(&state, ¬ice, window_origin(&handle), session_on_disk);
|
||||
let taken =
|
||||
take_announced(&state, ¬ice, window_origin(&handle), session_on_disk);
|
||||
if taken {
|
||||
let _ = handle.emit("console-page", ¬ice);
|
||||
} else {
|
||||
eprintln!("plan2code: ignored a page outside the console store: {}", notice.sid);
|
||||
eprintln!(
|
||||
"plan2code: ignored a page outside the console store: {}",
|
||||
notice.sid
|
||||
);
|
||||
}
|
||||
taken
|
||||
}));
|
||||
@@ -791,7 +893,10 @@ fn main() {
|
||||
.run(|app, event| {
|
||||
// Cmd+Q and the app menu's Quit on macOS end the app without closing the
|
||||
// window first. An exit asked for in code (`code` is set) is `quit_app`'s own.
|
||||
if let tauri::RunEvent::ExitRequested { api, code: None, .. } = event {
|
||||
if let tauri::RunEvent::ExitRequested {
|
||||
api, code: None, ..
|
||||
} = event
|
||||
{
|
||||
if agent_is_active(app) {
|
||||
api.prevent_exit();
|
||||
confirm_quit(app);
|
||||
@@ -807,25 +912,48 @@ mod tests {
|
||||
|
||||
fn state_for(dir: &str) -> AppState {
|
||||
AppState {
|
||||
project: Mutex::new(Some(ProjectDir { dir: PathBuf::from(dir), source: project::ProjectSource::Picked })),
|
||||
project: Mutex::new(Some(ProjectDir {
|
||||
dir: PathBuf::from(dir),
|
||||
source: project::ProjectSource::Picked,
|
||||
})),
|
||||
..AppState::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn notice(sid: &str) -> PageNotice {
|
||||
PageNotice { url: "http://127.0.0.1:5555/s/t/".into(), sid: sid.into(), workflow: "dashboard".into() }
|
||||
PageNotice {
|
||||
url: "http://127.0.0.1:5555/s/t/".into(),
|
||||
sid: sid.into(),
|
||||
workflow: "dashboard".into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A supervisor following the build's console, adopted with the repo's own
|
||||
/// console source so it never depends on an installed one.
|
||||
fn following_the_build() -> ConsoleSupervisor {
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"));
|
||||
ConsoleSupervisor::adopt(PathBuf::from("."), app_origin().to_string(), "http://127.0.0.1:4444/s/b/", "build")
|
||||
.expect("adopt with the repo's console")
|
||||
std::env::set_var(
|
||||
"PLAN2CODE_CONSOLE_DIR",
|
||||
PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console"),
|
||||
);
|
||||
ConsoleSupervisor::adopt(
|
||||
PathBuf::from("."),
|
||||
app_origin().to_string(),
|
||||
"http://127.0.0.1:4444/s/b/",
|
||||
"build",
|
||||
)
|
||||
.expect("adopt with the repo's console")
|
||||
}
|
||||
|
||||
fn sid_followed(state: &AppState) -> String {
|
||||
state.console.lock().unwrap().as_ref().unwrap().session().sid.clone()
|
||||
state
|
||||
.console
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.session()
|
||||
.sid
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Adopted, never started here: skip Drop's `stop`.
|
||||
@@ -839,12 +967,22 @@ mod tests {
|
||||
// the agent's in-app variables: following it swapped a build's page for
|
||||
// the test's, then for an empty dashboard once the test shut it down.
|
||||
let state = state_for("project-a");
|
||||
assert!(!take_announced(&state, ¬ice("test-console"), app_origin().to_string(), |_| false));
|
||||
assert!(!take_announced(
|
||||
&state,
|
||||
¬ice("test-console"),
|
||||
app_origin().to_string(),
|
||||
|_| false
|
||||
));
|
||||
assert!(state.console.lock().unwrap().is_none(), "nothing adopted");
|
||||
|
||||
// Already following the build's own console: it stays on that one.
|
||||
*state.console.lock().unwrap() = Some(following_the_build());
|
||||
assert!(!take_announced(&state, ¬ice("test-console"), app_origin().to_string(), |_| false));
|
||||
assert!(!take_announced(
|
||||
&state,
|
||||
¬ice("test-console"),
|
||||
app_origin().to_string(),
|
||||
|_| false
|
||||
));
|
||||
assert_eq!(sid_followed(&state), "build");
|
||||
let_go(&state);
|
||||
}
|
||||
@@ -853,7 +991,12 @@ mod tests {
|
||||
fn a_page_from_the_console_store_is_followed() {
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(following_the_build());
|
||||
assert!(take_announced(&state, ¬ice("next"), app_origin().to_string(), |_| true));
|
||||
assert!(take_announced(
|
||||
&state,
|
||||
¬ice("next"),
|
||||
app_origin().to_string(),
|
||||
|_| true
|
||||
));
|
||||
assert_eq!(sid_followed(&state), "next");
|
||||
let_go(&state);
|
||||
}
|
||||
@@ -871,21 +1014,41 @@ mod tests {
|
||||
|
||||
// The project moved on; the slot still holds project-a's manager
|
||||
// until a fresh call replaces it.
|
||||
*state.project.lock().unwrap() = Some(ProjectDir { dir: PathBuf::from("project-b"), source: project::ProjectSource::Picked });
|
||||
*state.project.lock().unwrap() = Some(ProjectDir {
|
||||
dir: PathBuf::from("project-b"),
|
||||
source: project::ProjectSource::Picked,
|
||||
});
|
||||
let second = agent_for_project(&state).expect("a manager for project-b");
|
||||
assert_eq!(second.folder(), &PathBuf::from("project-b"));
|
||||
assert!(!Arc::ptr_eq(&first, &second), "project-a's manager must never stand in for project-b's");
|
||||
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(|_| true)).unwrap();
|
||||
let port: u16 = server.url().rsplit_once(':').unwrap().1.trim_end_matches("/page").parse().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();
|
||||
let token = state
|
||||
.announce
|
||||
.lock()
|
||||
.unwrap()
|
||||
.as_ref()
|
||||
.unwrap()
|
||||
.token()
|
||||
.to_string();
|
||||
use std::io::{Read, Write};
|
||||
write!(
|
||||
stream,
|
||||
@@ -895,12 +1058,29 @@ mod tests {
|
||||
.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()));
|
||||
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");
|
||||
assert_eq!(
|
||||
state.announce.lock().unwrap().as_ref().unwrap().current(),
|
||||
None,
|
||||
"the fresh agent's open must not join s1"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -908,11 +1088,18 @@ mod tests {
|
||||
let state = state_for("project-a");
|
||||
let first = agent_for_project(&state).unwrap();
|
||||
let second = agent_for_project(&state).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &second), "the same folder should not make a second manager");
|
||||
assert!(
|
||||
Arc::ptr_eq(&first, &second),
|
||||
"the same folder should not make a second manager"
|
||||
);
|
||||
}
|
||||
|
||||
fn have_node() -> bool {
|
||||
std::process::Command::new("node").arg("--version").output().map(|o| o.status.success()).unwrap_or(false)
|
||||
std::process::Command::new("node")
|
||||
.arg("--version")
|
||||
.output()
|
||||
.map(|o| o.status.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// A real console, the same way `tests/console_supervisor.rs` sets one
|
||||
@@ -925,18 +1112,29 @@ mod tests {
|
||||
}
|
||||
let console_dir = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../../src/web-console");
|
||||
if !console_dir.join("console.mjs").is_file() {
|
||||
eprintln!("skipping: console source missing at {}", console_dir.display());
|
||||
eprintln!(
|
||||
"skipping: console source missing at {}",
|
||||
console_dir.display()
|
||||
);
|
||||
return None;
|
||||
}
|
||||
let pid = std::process::id();
|
||||
let project = std::env::temp_dir().join(format!("p2c-main-test-project-{pid}"));
|
||||
std::fs::create_dir_all(&project).unwrap();
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console_dir);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_HOME", std::env::temp_dir().join(format!("p2c-main-test-home-{pid}")));
|
||||
std::env::set_var(
|
||||
"PLAN2CODE_CONSOLE_HOME",
|
||||
std::env::temp_dir().join(format!("p2c-main-test-home-{pid}")),
|
||||
);
|
||||
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
|
||||
// Run inside the desktop app, the agent's in-app variables would have this
|
||||
// console announce itself to the live window and take it over.
|
||||
for name in ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"] {
|
||||
for name in [
|
||||
"PLAN2CODE_IN_APP",
|
||||
"PLAN2CODE_APP_ANNOUNCE",
|
||||
"PLAN2CODE_APP_TOKEN",
|
||||
"PLAN2CODE_CONSOLE_SID",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
}
|
||||
Some(
|
||||
@@ -953,11 +1151,18 @@ mod tests {
|
||||
let Some(sup) = real_console() else { return };
|
||||
let state = state_for("project-a");
|
||||
*state.console.lock().unwrap() = Some(sup);
|
||||
assert!(console_start_impl(&state).is_ok(), "console_start should work before the project changes");
|
||||
assert!(
|
||||
console_start_impl(&state).is_ok(),
|
||||
"console_start should work before the project changes"
|
||||
);
|
||||
|
||||
teardown_project(&state).unwrap();
|
||||
|
||||
let err = console_start_impl(&state).expect_err("console_start must refuse, not reconnect to the old session");
|
||||
assert!(err.contains("has not opened the dashboard"), "unexpected message: {err:?}");
|
||||
let err = console_start_impl(&state)
|
||||
.expect_err("console_start must refuse, not reconnect to the old session");
|
||||
assert!(
|
||||
err.contains("has not opened the dashboard"),
|
||||
"unexpected message: {err:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -37,7 +37,11 @@ pub fn classify(output: &str) -> NodeStatus {
|
||||
}
|
||||
|
||||
pub fn check_node() -> NodeStatus {
|
||||
match Command::new("node").env("PATH", resolved_path()).arg("--version").output() {
|
||||
match Command::new("node")
|
||||
.env("PATH", resolved_path())
|
||||
.arg("--version")
|
||||
.output()
|
||||
{
|
||||
Ok(out) if out.status.success() => classify(&String::from_utf8_lossy(&out.stdout)),
|
||||
_ => NodeStatus::Missing,
|
||||
}
|
||||
@@ -55,7 +59,9 @@ fn node_override_dir(args: &[String]) -> Option<String> {
|
||||
args[i].strip_prefix("--node=").map(str::to_string)
|
||||
};
|
||||
if let Some(path) = value.filter(|v| !v.is_empty()) {
|
||||
return std::path::Path::new(&path).parent().map(|dir| dir.to_string_lossy().into_owned());
|
||||
return std::path::Path::new(&path)
|
||||
.parent()
|
||||
.map(|dir| dir.to_string_lossy().into_owned());
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
@@ -68,7 +74,10 @@ fn node_override_dir(args: &[String]) -> Option<String> {
|
||||
#[cfg(unix)]
|
||||
fn login_shell_path() -> Option<String> {
|
||||
let shell = std::env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string());
|
||||
let out = Command::new(&shell).args(["-lc", "echo $PATH"]).output().ok()?;
|
||||
let out = Command::new(&shell)
|
||||
.args(["-lc", "echo $PATH"])
|
||||
.output()
|
||||
.ok()?;
|
||||
let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
|
||||
(out.status.success() && !path.is_empty()).then_some(path)
|
||||
}
|
||||
@@ -123,7 +132,10 @@ fn build_path(fresh: bool) -> String {
|
||||
#[cfg(windows)]
|
||||
fn saved_windows_path() -> Vec<String> {
|
||||
use std::os::windows::process::CommandExt;
|
||||
let keys = [r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment", r"HKCU\Environment"];
|
||||
let keys = [
|
||||
r"HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment",
|
||||
r"HKCU\Environment",
|
||||
];
|
||||
keys.iter()
|
||||
.filter_map(|key| {
|
||||
let out = Command::new("reg")
|
||||
@@ -142,7 +154,9 @@ fn saved_windows_path() -> Vec<String> {
|
||||
#[cfg_attr(not(windows), allow(dead_code))]
|
||||
fn parse_reg_query_value(output: &str) -> Option<String> {
|
||||
output.lines().find_map(|line| {
|
||||
let (_, rest) = line.split_once("REG_EXPAND_SZ").or_else(|| line.split_once("REG_SZ"))?;
|
||||
let (_, rest) = line
|
||||
.split_once("REG_EXPAND_SZ")
|
||||
.or_else(|| line.split_once("REG_SZ"))?;
|
||||
let value = rest.trim();
|
||||
(!value.is_empty()).then(|| value.to_string())
|
||||
})
|
||||
@@ -180,12 +194,25 @@ fn expand_percent_vars(text: &str, lookup: impl Fn(&str) -> Option<String>) -> S
|
||||
/// Where `node` actually resolves, with `resolved_path`: for the first-run
|
||||
/// checklist to name (Task 9.9), not for `check_node` itself to decide with.
|
||||
pub fn node_binary_path() -> Option<String> {
|
||||
let (program, arg) = if cfg!(windows) { ("where", "node") } else { ("which", "node") };
|
||||
let out = Command::new(program).env("PATH", resolved_path()).arg(arg).output().ok()?;
|
||||
let (program, arg) = if cfg!(windows) {
|
||||
("where", "node")
|
||||
} else {
|
||||
("which", "node")
|
||||
};
|
||||
let out = Command::new(program)
|
||||
.env("PATH", resolved_path())
|
||||
.arg(arg)
|
||||
.output()
|
||||
.ok()?;
|
||||
if !out.status.success() {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8_lossy(&out.stdout).lines().next().map(str::trim).filter(|s| !s.is_empty()).map(str::to_string)
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.lines()
|
||||
.next()
|
||||
.map(str::trim)
|
||||
.filter(|s| !s.is_empty())
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
/// The plain message shown when the check fails; `None` when Node is fine.
|
||||
@@ -229,20 +256,41 @@ mod tests {
|
||||
#[test]
|
||||
fn message_only_for_a_problem() {
|
||||
assert!(problem_message(&NodeStatus::Ok("v20.0.0".into())).is_none());
|
||||
assert!(problem_message(&NodeStatus::Missing).unwrap().contains("nodejs.org"));
|
||||
assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into())).unwrap().contains("v16.0.0"));
|
||||
assert!(problem_message(&NodeStatus::Missing)
|
||||
.unwrap()
|
||||
.contains("nodejs.org"));
|
||||
assert!(problem_message(&NodeStatus::TooOld("v16.0.0".into()))
|
||||
.unwrap()
|
||||
.contains("v16.0.0"));
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect()
|
||||
std::iter::once("plan2code-app")
|
||||
.chain(list.iter().copied())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_node_override_names_its_directory_in_both_forms() {
|
||||
let want = if cfg!(windows) { "C:\\nvm\\v20" } else { "/home/x/.nvm/v20" };
|
||||
let bin = if cfg!(windows) { "C:\\nvm\\v20\\node.exe" } else { "/home/x/.nvm/v20/node" };
|
||||
assert_eq!(node_override_dir(&args(&["--node", bin])).as_deref(), Some(want));
|
||||
assert_eq!(node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(), Some(want));
|
||||
let want = if cfg!(windows) {
|
||||
"C:\\nvm\\v20"
|
||||
} else {
|
||||
"/home/x/.nvm/v20"
|
||||
};
|
||||
let bin = if cfg!(windows) {
|
||||
"C:\\nvm\\v20\\node.exe"
|
||||
} else {
|
||||
"/home/x/.nvm/v20/node"
|
||||
};
|
||||
assert_eq!(
|
||||
node_override_dir(&args(&["--node", bin])).as_deref(),
|
||||
Some(want)
|
||||
);
|
||||
assert_eq!(
|
||||
node_override_dir(&args(&[&format!("--node={bin}")])).as_deref(),
|
||||
Some(want)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -256,17 +304,31 @@ mod tests {
|
||||
#[test]
|
||||
fn reads_the_saved_path_out_of_reg_query_output() {
|
||||
let out = "\r\nHKEY_CURRENT_USER\\Environment\r\n Path REG_EXPAND_SZ %USERPROFILE%\\.local\\bin;C:\\Tools\r\n\r\n";
|
||||
assert_eq!(parse_reg_query_value(out).as_deref(), Some("%USERPROFILE%\\.local\\bin;C:\\Tools"));
|
||||
assert_eq!(
|
||||
parse_reg_query_value(out).as_deref(),
|
||||
Some("%USERPROFILE%\\.local\\bin;C:\\Tools")
|
||||
);
|
||||
let plain = "HKEY_LOCAL_MACHINE\\x\r\n Path REG_SZ C:\\Windows\r\n";
|
||||
assert_eq!(parse_reg_query_value(plain).as_deref(), Some("C:\\Windows"));
|
||||
assert_eq!(parse_reg_query_value("ERROR: The system was unable to find the specified registry key or value.\r\n"), None);
|
||||
assert_eq!(
|
||||
parse_reg_query_value(
|
||||
"ERROR: The system was unable to find the specified registry key or value.\r\n"
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn expands_known_percent_names_and_keeps_the_rest() {
|
||||
let lookup = |name: &str| (name == "USERPROFILE").then(|| "C:\\Users\\sam".to_string());
|
||||
assert_eq!(expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup), "C:\\Users\\sam\\.local\\bin;C:\\x");
|
||||
assert_eq!(expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup), "%NOPE%\\bin;C:\\Users\\sam");
|
||||
assert_eq!(
|
||||
expand_percent_vars("%USERPROFILE%\\.local\\bin;C:\\x", lookup),
|
||||
"C:\\Users\\sam\\.local\\bin;C:\\x"
|
||||
);
|
||||
assert_eq!(
|
||||
expand_percent_vars("%NOPE%\\bin;%USERPROFILE%", lookup),
|
||||
"%NOPE%\\bin;C:\\Users\\sam"
|
||||
);
|
||||
assert_eq!(expand_percent_vars("50%", lookup), "50%");
|
||||
assert_eq!(expand_percent_vars("a%%b", lookup), "a%%b");
|
||||
}
|
||||
|
||||
@@ -29,7 +29,11 @@ fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
}
|
||||
|
||||
fn launcher_file() -> Option<PathBuf> {
|
||||
Some(std::env::home_dir()?.join(".plan2code").join("launcher.json"))
|
||||
Some(
|
||||
std::env::home_dir()?
|
||||
.join(".plan2code")
|
||||
.join("launcher.json"),
|
||||
)
|
||||
}
|
||||
|
||||
fn read_launcher() -> serde_json::Map<String, serde_json::Value> {
|
||||
@@ -97,7 +101,10 @@ fn flag_value(args: &[String], flag: &str) -> Option<String> {
|
||||
while i < args.len() {
|
||||
let arg = &args[i];
|
||||
if arg == flag {
|
||||
return args.get(i + 1).filter(|v| !v.is_empty() && !v.starts_with('-')).cloned();
|
||||
return args
|
||||
.get(i + 1)
|
||||
.filter(|v| !v.is_empty() && !v.starts_with('-'))
|
||||
.cloned();
|
||||
}
|
||||
if let Some(value) = arg.strip_prefix(&prefix) {
|
||||
return (!value.is_empty()).then(|| value.to_string());
|
||||
@@ -124,9 +131,15 @@ pub fn launch_choice_in(args: &[String], agents_file: Option<&Path>) -> LaunchCh
|
||||
/// nothing (the page asks with the folder picker).
|
||||
pub fn resolve(args: &[String]) -> Option<ProjectDir> {
|
||||
if let Some(dir) = argument_folder(args) {
|
||||
return Some(ProjectDir { dir, source: ProjectSource::Argument });
|
||||
return Some(ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Argument,
|
||||
});
|
||||
}
|
||||
remembered_folder().map(|dir| ProjectDir { dir, source: ProjectSource::Remembered })
|
||||
remembered_folder().map(|dir| ProjectDir {
|
||||
dir,
|
||||
source: ProjectSource::Remembered,
|
||||
})
|
||||
}
|
||||
|
||||
/// A folder the person picked becomes the remembered one, so the next start
|
||||
@@ -143,7 +156,10 @@ pub fn remember_folder(dir: &Path) -> Result<ProjectDir, String> {
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(state)).map_err(err)?;
|
||||
std::fs::write(file, json).map_err(err)?;
|
||||
Ok(ProjectDir { dir: dir.to_path_buf(), source: ProjectSource::Picked })
|
||||
Ok(ProjectDir {
|
||||
dir: dir.to_path_buf(),
|
||||
source: ProjectSource::Picked,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -156,36 +172,76 @@ mod tests {
|
||||
}
|
||||
|
||||
fn args(list: &[&str]) -> Vec<String> {
|
||||
std::iter::once("plan2code-app").chain(list.iter().copied()).map(str::to_string).collect()
|
||||
std::iter::once("plan2code-app")
|
||||
.chain(list.iter().copied())
|
||||
.map(str::to_string)
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_launcher_choice_reads_agent_and_model_in_both_forms() {
|
||||
let want = LaunchChoice { agent: Some(AgentKind::Codex.id().to_string()), model: Some("gpt-5".into()) };
|
||||
assert_eq!(launch_choice(&args(&["--project", ".", "--agent", "codex", "--model", "gpt-5"])), want);
|
||||
assert_eq!(launch_choice(&args(&["--agent=codex", "--model=gpt-5"])), want);
|
||||
assert_eq!(launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])), want);
|
||||
let want = LaunchChoice {
|
||||
agent: Some(AgentKind::Codex.id().to_string()),
|
||||
model: Some("gpt-5".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
launch_choice(&args(&[
|
||||
"--project",
|
||||
".",
|
||||
"--agent",
|
||||
"codex",
|
||||
"--model",
|
||||
"gpt-5"
|
||||
])),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent=codex", "--model=gpt-5"])),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "CODEX", "--model", "gpt-5"])),
|
||||
want
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_agent_alone_is_a_choice_and_a_model_alone_is_not() {
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "claude"])),
|
||||
LaunchChoice { agent: Some(AgentKind::Claude.id().to_string()), model: None }
|
||||
LaunchChoice {
|
||||
agent: Some(AgentKind::Claude.id().to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--model", "opus"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&["--model", "opus"])), LaunchChoice::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_unknown_agent_or_a_missing_value_is_ignored() {
|
||||
assert_eq!(launch_choice(&args(&["--agent", "emacs", "--model", "x"])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "emacs", "--model", "x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&["--agent"])), LaunchChoice::default());
|
||||
assert_eq!(launch_choice(&args(&["--agent", "--model", "x"])), LaunchChoice::default());
|
||||
assert_eq!(launch_choice(&args(&["--agent=", "--model=x"])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "--model", "x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent=", "--model=x"])),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(launch_choice(&args(&[])), LaunchChoice::default());
|
||||
assert_eq!(
|
||||
launch_choice(&args(&["--agent", "devin", "--model"])),
|
||||
LaunchChoice { agent: Some(AgentKind::Devin.id().to_string()), model: None }
|
||||
LaunchChoice {
|
||||
agent: Some(AgentKind::Devin.id().to_string()),
|
||||
model: None
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -194,11 +250,27 @@ mod tests {
|
||||
let dir = std::env::temp_dir().join(format!("p2c-project-custom-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let file = dir.join("agents.json");
|
||||
std::fs::write(&file, r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#).unwrap();
|
||||
let want = LaunchChoice { agent: Some("goose".into()), model: Some("m1".into()) };
|
||||
assert_eq!(launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)), want);
|
||||
assert_eq!(launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)), LaunchChoice::default());
|
||||
assert_eq!(launch_choice_in(&args(&["--agent", "goose"]), None), LaunchChoice::default());
|
||||
std::fs::write(
|
||||
&file,
|
||||
r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose"}]}"#,
|
||||
)
|
||||
.unwrap();
|
||||
let want = LaunchChoice {
|
||||
agent: Some("goose".into()),
|
||||
model: Some("m1".into()),
|
||||
};
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "goose", "--model", "m1"]), Some(&file)),
|
||||
want
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "other", "--model", "m1"]), Some(&file)),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
assert_eq!(
|
||||
launch_choice_in(&args(&["--agent", "goose"]), None),
|
||||
LaunchChoice::default()
|
||||
);
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
}
|
||||
|
||||
|
||||
@@ -55,7 +55,12 @@ pub struct PtyHost {
|
||||
}
|
||||
|
||||
fn size(cols: u16, rows: u16) -> PtySize {
|
||||
PtySize { rows, cols, pixel_width: 0, pixel_height: 0 }
|
||||
PtySize {
|
||||
rows,
|
||||
cols,
|
||||
pixel_width: 0,
|
||||
pixel_height: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn err<E: std::fmt::Display>(e: E) -> String {
|
||||
@@ -159,7 +164,11 @@ impl PtyHost {
|
||||
|
||||
/// Tell the command the terminal changed size.
|
||||
pub fn resize(&self, cols: u16, rows: u16) -> Result<(), String> {
|
||||
self.master.lock().map_err(err)?.resize(size(cols, rows)).map_err(err)
|
||||
self.master
|
||||
.lock()
|
||||
.map_err(err)?
|
||||
.resize(size(cols, rows))
|
||||
.map_err(err)
|
||||
}
|
||||
|
||||
/// End the command. Safe to call while `wait` is blocked in another thread.
|
||||
@@ -236,8 +245,13 @@ mod windows_job {
|
||||
use winapi::shared::minwindef::DWORD;
|
||||
use winapi::shared::ntdef::HANDLE;
|
||||
use winapi::um::handleapi::CloseHandle;
|
||||
use winapi::um::jobapi2::{AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject};
|
||||
use winapi::um::winnt::{JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION, JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE};
|
||||
use winapi::um::jobapi2::{
|
||||
AssignProcessToJobObject, CreateJobObjectW, SetInformationJobObject, TerminateJobObject,
|
||||
};
|
||||
use winapi::um::winnt::{
|
||||
JobObjectExtendedLimitInformation, JOBOBJECT_EXTENDED_LIMIT_INFORMATION,
|
||||
JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
};
|
||||
|
||||
/// Create a job, set it to kill everything in it when its last handle
|
||||
/// closes, and assign `child` to it. `None` on any failure (an older
|
||||
|
||||
@@ -28,11 +28,18 @@ static LAST_BRIEF: Mutex<Option<String>> = Mutex::new(None);
|
||||
/// 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> {
|
||||
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 Some(skill) = brief::skill_for_workflow(workflow) else { return Ok(None) };
|
||||
let Some(skill) = brief::skill_for_workflow(workflow) else {
|
||||
return Ok(None);
|
||||
};
|
||||
if finished(state) || empty(state) {
|
||||
return Ok(None);
|
||||
}
|
||||
@@ -47,7 +54,14 @@ pub fn leave_brief(console_home: &Path, handoffs: &Path, sid: &str, when: DateTi
|
||||
Some(spec) => format!("Restart of {skill} on {spec}"),
|
||||
None => format!("Restart of {skill}"),
|
||||
};
|
||||
let record = handoff::Record { title: &title, worktree, project, spec, workflow, skill };
|
||||
let record = handoff::Record {
|
||||
title: &title,
|
||||
worktree,
|
||||
project,
|
||||
spec,
|
||||
workflow,
|
||||
skill,
|
||||
};
|
||||
handoff::write(handoffs, when, &record, &body).map(Some)
|
||||
}
|
||||
|
||||
@@ -58,7 +72,10 @@ pub fn note_for_restart(sid: &str) -> Option<String> {
|
||||
let handoffs = handoff::handoffs_dir()?;
|
||||
match leave_brief(&console_home, &handoffs, sid, handoff::now()) {
|
||||
Ok(Some(id)) => {
|
||||
let previous = LAST_BRIEF.lock().ok().and_then(|mut last| last.replace(id.clone()));
|
||||
let previous = LAST_BRIEF
|
||||
.lock()
|
||||
.ok()
|
||||
.and_then(|mut last| last.replace(id.clone()));
|
||||
if let Some(previous) = previous.filter(|p| *p != id) {
|
||||
let _ = handoff::retire_if_unused(&handoffs, &previous);
|
||||
}
|
||||
@@ -70,27 +87,46 @@ pub fn note_for_restart(sid: &str) -> Option<String> {
|
||||
}
|
||||
|
||||
fn text<'a>(state: &'a Value, key: &str) -> Option<&'a str> {
|
||||
state.get(key).and_then(Value::as_str).filter(|s| !s.is_empty())
|
||||
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"))
|
||||
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());
|
||||
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(['/', '\\']))
|
||||
spec.strip_prefix("specs/").is_some_and(|name| {
|
||||
!name.is_empty() && name != "." && name != ".." && !name.contains(['/', '\\'])
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -101,7 +137,8 @@ mod tests {
|
||||
use std::path::PathBuf;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id()));
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-restart-{}-{name}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
@@ -137,12 +174,24 @@ mod tests {
|
||||
let (home, project, handoffs) = session("pickup", "implement", Some("specs/feature"));
|
||||
let spec = project.join("specs").join("feature");
|
||||
fs::create_dir_all(&spec).unwrap();
|
||||
fs::write(spec.join("overview.md"), "- [/] [Phase 5: Restart](./phase-5.md)\n").unwrap();
|
||||
fs::write(spec.join("phase-5.md"), "- [ ] **Task 5.1:** Create the reader\n").unwrap();
|
||||
fs::write(
|
||||
spec.join("overview.md"),
|
||||
"- [/] [Phase 5: Restart](./phase-5.md)\n",
|
||||
)
|
||||
.unwrap();
|
||||
fs::write(
|
||||
spec.join("phase-5.md"),
|
||||
"- [ ] **Task 5.1:** Create the reader\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff");
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.expect("a handoff");
|
||||
assert_eq!(id, "2026-10-21-1405-handoff");
|
||||
let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap();
|
||||
let record: Value =
|
||||
serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(record["workflow"], "implement");
|
||||
assert_eq!(record["spec"], "specs/feature");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
@@ -178,14 +227,17 @@ mod tests {
|
||||
|
||||
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());
|
||||
assert!(leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_brief_carries_the_agent_activity_and_recent_events() {
|
||||
let (home, _project, handoffs) = session("activity", "implement", None);
|
||||
let dir = home.join("sessions").join("s1");
|
||||
let mut state: Value = serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap();
|
||||
let mut state: Value =
|
||||
serde_json::from_str(&fs::read_to_string(dir.join("state.json")).unwrap()).unwrap();
|
||||
state["agent"] = serde_json::json!({ "status": "working", "activity": "Spiking Claude's context signal (Task 10.1)" });
|
||||
fs::write(dir.join("state.json"), state.to_string()).unwrap();
|
||||
fs::write(
|
||||
@@ -194,7 +246,9 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().expect("a handoff");
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.expect("a handoff");
|
||||
let doc = fs::read_to_string(handoffs.join(format!("{id}.md"))).unwrap();
|
||||
assert!(doc.contains("Doing: Spiking Claude's context signal (Task 10.1)"));
|
||||
assert!(doc.contains("## Recent activity\n\n- post (0 items)\n- consume: submit\n"));
|
||||
@@ -209,8 +263,12 @@ mod tests {
|
||||
#[test]
|
||||
fn a_spec_that_is_not_one_folder_is_left_out_of_the_record() {
|
||||
let (home, _, handoffs) = session("badspec", "pathfinder", Some("specs/a/b"));
|
||||
let id = leave_brief(&home, &handoffs, "s1", when()).unwrap().unwrap();
|
||||
let record: Value = serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap()).unwrap();
|
||||
let id = leave_brief(&home, &handoffs, "s1", when())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
let record: Value =
|
||||
serde_json::from_str(&fs::read_to_string(handoffs.join(format!("{id}.json"))).unwrap())
|
||||
.unwrap();
|
||||
assert!(record["spec"].is_null());
|
||||
}
|
||||
}
|
||||
@@ -43,7 +43,10 @@ impl std::fmt::Display for ReadError {
|
||||
ReadError::Unreadable(why) => write!(f, "could not read the session: {why}"),
|
||||
ReadError::Malformed(why) => write!(f, "the session file is not valid: {why}"),
|
||||
ReadError::Schema(found) => {
|
||||
write!(f, "session schema {found} is not supported (this app reads schema {SCHEMA})")
|
||||
write!(
|
||||
f,
|
||||
"session schema {found} is not supported (this app reads schema {SCHEMA})"
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -73,7 +76,9 @@ pub fn session_dir(console_home: &Path, sid: &str) -> PathBuf {
|
||||
/// Open and parse the session `sid` under `console_home`.
|
||||
pub fn load(console_home: &Path, sid: &str) -> Result<Session, ReadError> {
|
||||
let dir = session_dir(console_home, sid);
|
||||
let text = read_with_retry(&dir.join("state.json"), |file| std::fs::read_to_string(file))?;
|
||||
let text = read_with_retry(&dir.join("state.json"), |file| {
|
||||
std::fs::read_to_string(file)
|
||||
})?;
|
||||
let state = parse_state(&text)?;
|
||||
Ok(Session { dir, state })
|
||||
}
|
||||
@@ -90,7 +95,9 @@ where
|
||||
loop {
|
||||
match read(file) {
|
||||
Ok(text) => return Ok(text),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => return Err(ReadError::Missing(file.to_path_buf())),
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {
|
||||
return Err(ReadError::Missing(file.to_path_buf()))
|
||||
}
|
||||
Err(e) if is_locked(&e) => {
|
||||
if retries == LOCKED_RETRIES {
|
||||
return Err(ReadError::Busy);
|
||||
@@ -104,12 +111,15 @@ where
|
||||
}
|
||||
|
||||
fn is_locked(e: &io::Error) -> bool {
|
||||
e.kind() == io::ErrorKind::PermissionDenied || e.raw_os_error().is_some_and(|code| WINDOWS_SHARING.contains(&code))
|
||||
e.kind() == io::ErrorKind::PermissionDenied
|
||||
|| e.raw_os_error()
|
||||
.is_some_and(|code| WINDOWS_SHARING.contains(&code))
|
||||
}
|
||||
|
||||
/// Parse `state.json` text: a JSON object whose `schema` is `SCHEMA`.
|
||||
pub fn parse_state(text: &str) -> Result<Value, ReadError> {
|
||||
let state: Value = serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?;
|
||||
let state: Value =
|
||||
serde_json::from_str(text).map_err(|e| ReadError::Malformed(e.to_string()))?;
|
||||
if !state.is_object() {
|
||||
return Err(ReadError::Malformed("not a JSON object".to_string()));
|
||||
}
|
||||
@@ -134,7 +144,10 @@ pub fn read_ndjson(file: &Path) -> Vec<Value> {
|
||||
}
|
||||
|
||||
pub fn parse_ndjson(text: &str) -> Vec<Value> {
|
||||
text.lines().filter(|line| !line.trim().is_empty()).filter_map(|line| serde_json::from_str(line).ok()).collect()
|
||||
text.lines()
|
||||
.filter(|line| !line.trim().is_empty())
|
||||
.filter_map(|line| serde_json::from_str(line).ok())
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -143,13 +156,15 @@ mod tests {
|
||||
use std::cell::Cell;
|
||||
|
||||
fn fixture(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id()));
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-reader-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
dir
|
||||
}
|
||||
|
||||
const STATE: &str = r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#;
|
||||
const STATE: &str =
|
||||
r#"{"schema": 1, "sid": "s1", "workflow": "implement", "specDir": "specs/x"}"#;
|
||||
|
||||
#[test]
|
||||
fn a_complete_session_loads() {
|
||||
@@ -165,7 +180,10 @@ mod tests {
|
||||
#[test]
|
||||
fn a_partial_last_line_is_dropped() {
|
||||
let lines = parse_ndjson("{\"a\":1}\n{\"b\":2}\n{\"c\":");
|
||||
assert_eq!(lines, vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})]);
|
||||
assert_eq!(
|
||||
lines,
|
||||
vec![serde_json::json!({"a": 1}), serde_json::json!({"b": 2})]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -46,7 +46,10 @@ pub fn load_last_agent(file: &Path) -> Option<String> {
|
||||
/// Save the pick, keeping any other key the file holds.
|
||||
pub fn save_last_agent(file: &Path, id: &str) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(LAST_AGENT_KEY.to_string(), serde_json::Value::String(id.to_string()));
|
||||
settings.insert(
|
||||
LAST_AGENT_KEY.to_string(),
|
||||
serde_json::Value::String(id.to_string()),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
@@ -65,13 +68,25 @@ pub fn load_term_panel(file: &Path) -> TermPanelSettings {
|
||||
.and_then(|v| v.as_f64())
|
||||
.filter(|f| (TERM_FRACTION_MIN..=TERM_FRACTION_MAX).contains(f))
|
||||
.unwrap_or(DEFAULT_TERM_FRACTION);
|
||||
let collapsed = settings.get(TERM_COLLAPSED_KEY).and_then(|v| v.as_bool()).unwrap_or(false);
|
||||
TermPanelSettings { dock, fraction, collapsed }
|
||||
let collapsed = settings
|
||||
.get(TERM_COLLAPSED_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false);
|
||||
TermPanelSettings {
|
||||
dock,
|
||||
fraction,
|
||||
collapsed,
|
||||
}
|
||||
}
|
||||
|
||||
/// Save the terminal pane's shape, keeping any other key the file holds. An
|
||||
/// invalid dock or an out-of-range fraction is rejected rather than saved.
|
||||
pub fn save_term_panel(file: &Path, dock: &str, fraction: f64, collapsed: bool) -> Result<(), String> {
|
||||
pub fn save_term_panel(
|
||||
file: &Path,
|
||||
dock: &str,
|
||||
fraction: f64,
|
||||
collapsed: bool,
|
||||
) -> Result<(), String> {
|
||||
if dock != "bottom" && dock != "right" {
|
||||
return Err(format!("unknown dock: {dock}"));
|
||||
}
|
||||
@@ -79,25 +94,39 @@ pub fn save_term_panel(file: &Path, dock: &str, fraction: f64, collapsed: bool)
|
||||
return Err(format!("fraction out of range: {fraction}"));
|
||||
}
|
||||
let mut settings = read(file);
|
||||
settings.insert(TERM_DOCK_KEY.to_string(), serde_json::Value::String(dock.to_string()));
|
||||
settings.insert(
|
||||
TERM_DOCK_KEY.to_string(),
|
||||
serde_json::Value::String(dock.to_string()),
|
||||
);
|
||||
settings.insert(
|
||||
TERM_FRACTION_KEY.to_string(),
|
||||
serde_json::Number::from_f64(fraction).map(serde_json::Value::Number).unwrap_or(serde_json::Value::Null),
|
||||
serde_json::Number::from_f64(fraction)
|
||||
.map(serde_json::Value::Number)
|
||||
.unwrap_or(serde_json::Value::Null),
|
||||
);
|
||||
settings.insert(
|
||||
TERM_COLLAPSED_KEY.to_string(),
|
||||
serde_json::Value::Bool(collapsed),
|
||||
);
|
||||
settings.insert(TERM_COLLAPSED_KEY.to_string(), serde_json::Value::Bool(collapsed));
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
/// Whether the first-run checklist has already passed once. Once it has,
|
||||
/// later launches go straight to the launch card (Task 9.4).
|
||||
pub fn load_first_run_done(file: &Path) -> bool {
|
||||
read(file).get(FIRST_RUN_DONE_KEY).and_then(|v| v.as_bool()).unwrap_or(false)
|
||||
read(file)
|
||||
.get(FIRST_RUN_DONE_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
/// Remember that the checklist passed, keeping any other key the file holds.
|
||||
pub fn save_first_run_done(file: &Path) -> Result<(), String> {
|
||||
let mut settings = read(file);
|
||||
settings.insert(FIRST_RUN_DONE_KEY.to_string(), serde_json::Value::Bool(true));
|
||||
settings.insert(
|
||||
FIRST_RUN_DONE_KEY.to_string(),
|
||||
serde_json::Value::Bool(true),
|
||||
);
|
||||
write(file, settings)
|
||||
}
|
||||
|
||||
@@ -105,7 +134,10 @@ pub fn save_first_run_done(file: &Path) -> Result<(), String> {
|
||||
/// Desktop app switch in the console's User Preferences). On unless the file
|
||||
/// says `false`; anything but a boolean reads as on.
|
||||
pub fn load_taskbar_signal(file: &Path) -> bool {
|
||||
read(file).get(TASKBAR_SIGNAL_KEY).and_then(|v| v.as_bool()).unwrap_or(true)
|
||||
read(file)
|
||||
.get(TASKBAR_SIGNAL_KEY)
|
||||
.and_then(|v| v.as_bool())
|
||||
.unwrap_or(true)
|
||||
}
|
||||
|
||||
/// Save the switch, keeping any other key the file holds.
|
||||
@@ -119,7 +151,8 @@ fn write(file: &Path, settings: serde_json::Map<String, serde_json::Value>) -> R
|
||||
if let Some(parent) = file.parent() {
|
||||
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
|
||||
}
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings)).map_err(|e| e.to_string())?;
|
||||
let json = serde_json::to_string_pretty(&serde_json::Value::Object(settings))
|
||||
.map_err(|e| e.to_string())?;
|
||||
std::fs::write(file, json).map_err(|e| e.to_string())
|
||||
}
|
||||
|
||||
@@ -128,7 +161,8 @@ mod tests {
|
||||
use super::*;
|
||||
|
||||
fn temp_file(name: &str) -> PathBuf {
|
||||
let dir = std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id()));
|
||||
let dir =
|
||||
std::env::temp_dir().join(format!("plan2code-settings-{}-{name}", std::process::id()));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
dir.join("app.json")
|
||||
}
|
||||
@@ -146,8 +180,14 @@ mod tests {
|
||||
save_last_agent(&file, "devin").unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("devin".to_string()));
|
||||
save_last_agent(&file, "goose").unwrap();
|
||||
assert_eq!(load_last_agent(&file), Some("goose".to_string()), "a custom id round-trips");
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
assert_eq!(
|
||||
load_last_agent(&file),
|
||||
Some("goose".to_string()),
|
||||
"a custom id round-trips"
|
||||
);
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
@@ -163,7 +203,11 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_term_panel_defaults_to_bottom_at_a_quarter() {
|
||||
let want = TermPanelSettings { dock: "bottom".into(), fraction: 0.25, collapsed: false };
|
||||
let want = TermPanelSettings {
|
||||
dock: "bottom".into(),
|
||||
fraction: 0.25,
|
||||
collapsed: false,
|
||||
};
|
||||
assert_eq!(load_term_panel(&temp_file("term-missing")), want);
|
||||
}
|
||||
|
||||
@@ -175,9 +219,15 @@ mod tests {
|
||||
save_term_panel(&file, "right", 0.4, true).unwrap();
|
||||
assert_eq!(
|
||||
load_term_panel(&file),
|
||||
TermPanelSettings { dock: "right".into(), fraction: 0.4, collapsed: true }
|
||||
TermPanelSettings {
|
||||
dock: "right".into(),
|
||||
fraction: 0.4,
|
||||
collapsed: true
|
||||
}
|
||||
);
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
@@ -198,7 +248,9 @@ mod tests {
|
||||
std::fs::write(&file, r#"{"other": 1}"#).unwrap();
|
||||
save_first_run_done(&file).unwrap();
|
||||
assert!(load_first_run_done(&file));
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
@@ -213,7 +265,9 @@ mod tests {
|
||||
assert!(!load_taskbar_signal(&file));
|
||||
save_taskbar_signal(&file, true).unwrap();
|
||||
assert!(load_taskbar_signal(&file));
|
||||
assert!(std::fs::read_to_string(&file).unwrap().contains("\"other\""));
|
||||
assert!(std::fs::read_to_string(&file)
|
||||
.unwrap()
|
||||
.contains("\"other\""));
|
||||
let _ = std::fs::remove_dir_all(file.parent().unwrap());
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +65,12 @@ pub fn status(app: &str, skills: Option<String>) -> VersionStatus {
|
||||
(Some(a), Some(s)) => (a != s, s > a),
|
||||
_ => (false, false),
|
||||
};
|
||||
VersionStatus { app: app.to_string(), skills, mismatch, skills_ahead }
|
||||
VersionStatus {
|
||||
app: app.to_string(),
|
||||
skills,
|
||||
mismatch,
|
||||
skills_ahead,
|
||||
}
|
||||
}
|
||||
|
||||
/// Run the existing installer's update (`plan2code update`, through the launcher's own copy),
|
||||
@@ -80,10 +85,19 @@ pub fn run_update(app_version: &str, on_line: impl FnMut(&str)) -> Result<String
|
||||
|
||||
/// `run_update`, with the timeout as a parameter so a test can use a short one instead of
|
||||
/// `UPDATE_TIMEOUT`'s real five minutes.
|
||||
fn run_update_within(app_version: &str, timeout: Duration, mut on_line: impl FnMut(&str)) -> Result<String, String> {
|
||||
let launcher = launcher_dir().ok_or("no home folder found")?.join("plan2code.js");
|
||||
fn run_update_within(
|
||||
app_version: &str,
|
||||
timeout: Duration,
|
||||
mut on_line: impl FnMut(&str),
|
||||
) -> Result<String, String> {
|
||||
let launcher = launcher_dir()
|
||||
.ok_or("no home folder found")?
|
||||
.join("plan2code.js");
|
||||
if !launcher.is_file() {
|
||||
return Err(format!("the plan2code command is not installed ({} is missing)", launcher.display()));
|
||||
return Err(format!(
|
||||
"the plan2code command is not installed ({} is missing)",
|
||||
launcher.display()
|
||||
));
|
||||
}
|
||||
let mut command = Command::new("node");
|
||||
// A Dock or Start-menu launch often lacks nvm, Homebrew or Volta's
|
||||
@@ -103,7 +117,9 @@ fn run_update_within(app_version: &str, timeout: Duration, mut on_line: impl FnM
|
||||
use std::os::windows::process::CommandExt;
|
||||
command.creation_flags(0x08000000); // CREATE_NO_WINDOW, as the console calls are
|
||||
}
|
||||
let mut child = command.spawn().map_err(|e| format!("could not run node: {e}"))?;
|
||||
let mut child = command
|
||||
.spawn()
|
||||
.map_err(|e| format!("could not run node: {e}"))?;
|
||||
let stdout = child.stdout.take().ok_or("no stdout from the update")?;
|
||||
let stderr = child.stderr.take().ok_or("no stderr from the update")?;
|
||||
let (tx, rx) = mpsc::channel::<String>();
|
||||
@@ -169,7 +185,12 @@ mod tests {
|
||||
let s = status("3.0.0", Some("3.0.0".into()));
|
||||
assert_eq!(
|
||||
s,
|
||||
VersionStatus { app: "3.0.0".into(), skills: Some("3.0.0".into()), mismatch: false, skills_ahead: false }
|
||||
VersionStatus {
|
||||
app: "3.0.0".into(),
|
||||
skills: Some("3.0.0".into()),
|
||||
mismatch: false,
|
||||
skills_ahead: false
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
@@ -202,7 +223,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn a_missing_or_broken_version_file_reads_as_none() {
|
||||
let missing = std::env::temp_dir().join("p2c-versions-does-not-exist").join("version.json");
|
||||
let missing = std::env::temp_dir()
|
||||
.join("p2c-versions-does-not-exist")
|
||||
.join("version.json");
|
||||
assert_eq!(version_in(&missing), None);
|
||||
assert_eq!(version_in(&temp_file("broken", "{ not json")), None);
|
||||
assert_eq!(version_in(&temp_file("nover", r#"{ "name": "x" }"#)), None);
|
||||
@@ -215,7 +238,10 @@ mod tests {
|
||||
/// source, no quoting needed), runs `body`, then restores the environment.
|
||||
fn with_fake_launcher<T>(name: &str, script: &str, body: impl FnOnce() -> T) -> T {
|
||||
let _guard = ENV_LOCK.lock().unwrap();
|
||||
let dir = std::env::temp_dir().join(format!("p2c-versions-launcher-{}-{name}", std::process::id()));
|
||||
let dir = std::env::temp_dir().join(format!(
|
||||
"p2c-versions-launcher-{}-{name}",
|
||||
std::process::id()
|
||||
));
|
||||
let _ = std::fs::remove_dir_all(&dir);
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
std::fs::write(dir.join("plan2code.js"), script).unwrap();
|
||||
@@ -229,11 +255,17 @@ mod tests {
|
||||
#[test]
|
||||
fn run_update_streams_lines_live_and_returns_the_last_one_on_success() {
|
||||
let lines = std::sync::Mutex::new(Vec::<String>::new());
|
||||
let result = with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || {
|
||||
run_update_within("9.9.9", Duration::from_secs(10), |line| lines.lock().unwrap().push(line.to_string()))
|
||||
});
|
||||
let result =
|
||||
with_fake_launcher("ok", "console.log('line1'); console.log('line2');", || {
|
||||
run_update_within("9.9.9", Duration::from_secs(10), |line| {
|
||||
lines.lock().unwrap().push(line.to_string())
|
||||
})
|
||||
});
|
||||
assert_eq!(result, Ok("line2".to_string()));
|
||||
assert_eq!(*lines.lock().unwrap(), vec!["line1".to_string(), "line2".to_string()]);
|
||||
assert_eq!(
|
||||
*lines.lock().unwrap(),
|
||||
vec!["line1".to_string(), "line2".to_string()]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -8,7 +8,9 @@ use std::sync::{Arc, Mutex, Once};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use plan2code_app_lib::agent_manager::{AgentEvent, AgentManager, AgentSnapshot, AgentState};
|
||||
use plan2code_app_lib::agents::{agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV};
|
||||
use plan2code_app_lib::agents::{
|
||||
agent_launch_spec, parse_agents_file, Agent, AgentKind, PermissionMode, AGENT_BIN_ENV,
|
||||
};
|
||||
|
||||
mod common;
|
||||
use common::process_alive;
|
||||
@@ -36,7 +38,13 @@ impl Harness {
|
||||
let sink = Arc::new(move |event| {
|
||||
let _ = tx.lock().unwrap().send(event);
|
||||
});
|
||||
Harness { manager: AgentManager::new(PathBuf::from("."), sink), rx, seen: String::new(), states: Vec::new(), cursor: 0 }
|
||||
Harness {
|
||||
manager: AgentManager::new(PathBuf::from("."), sink),
|
||||
rx,
|
||||
seen: String::new(),
|
||||
states: Vec::new(),
|
||||
cursor: 0,
|
||||
}
|
||||
}
|
||||
|
||||
fn take(&mut self, event: AgentEvent) {
|
||||
@@ -80,7 +88,11 @@ impl Harness {
|
||||
}
|
||||
|
||||
/// The next state change (after the last one this returned) that matches.
|
||||
fn wait_state(&mut self, what: &str, matches: impl Fn(&AgentSnapshot) -> bool) -> AgentSnapshot {
|
||||
fn wait_state(
|
||||
&mut self,
|
||||
what: &str,
|
||||
matches: impl Fn(&AgentSnapshot) -> bool,
|
||||
) -> AgentSnapshot {
|
||||
let deadline = Instant::now() + TIMEOUT;
|
||||
loop {
|
||||
while self.cursor < self.states.len() {
|
||||
@@ -99,7 +111,15 @@ impl Harness {
|
||||
}
|
||||
|
||||
fn start_and_wait_ready(&mut self) {
|
||||
self.manager.start(Agent::Builtin(AgentKind::Claude), None, None, PermissionMode::Bypass, None).expect("start the fake agent");
|
||||
self.manager
|
||||
.start(
|
||||
Agent::Builtin(AgentKind::Claude),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
self.wait_for_output(READY, 1);
|
||||
}
|
||||
|
||||
@@ -118,11 +138,20 @@ fn a_second_start_while_running_is_refused() {
|
||||
h.start_and_wait_ready();
|
||||
let generation = h.manager.snapshot().generation;
|
||||
|
||||
let refused = h.manager.start(Agent::Builtin(AgentKind::Devin), None, None, PermissionMode::Bypass, None);
|
||||
let refused = h.manager.start(
|
||||
Agent::Builtin(AgentKind::Devin),
|
||||
None,
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
None,
|
||||
);
|
||||
assert!(refused.is_err(), "a second start must be refused");
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(after.state, AgentState::Running);
|
||||
assert_eq!(after.generation, generation, "the running agent was replaced");
|
||||
assert_eq!(
|
||||
after.generation, generation,
|
||||
"the running agent was replaced"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
@@ -130,19 +159,36 @@ fn a_second_start_while_running_is_refused() {
|
||||
fn restart_keeps_the_previous_agent_kind_mode_model_and_effort() {
|
||||
let mut h = Harness::new();
|
||||
h.manager
|
||||
.start(Agent::Builtin(AgentKind::Codex), Some("gpt-5".to_string()), Some("high".to_string()), PermissionMode::Checked, None)
|
||||
.start(
|
||||
Agent::Builtin(AgentKind::Codex),
|
||||
Some("gpt-5".to_string()),
|
||||
Some("high".to_string()),
|
||||
PermissionMode::Checked,
|
||||
None,
|
||||
)
|
||||
.expect("start the fake agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
let before = h.manager.snapshot();
|
||||
assert_eq!(before.kind, Some("codex".to_string()));
|
||||
assert_eq!(before.mode, Some(PermissionMode::Checked));
|
||||
assert_eq!(h.manager.model_and_effort(), (Some("gpt-5".to_string()), Some("high".to_string())));
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
(Some("gpt-5".to_string()), Some("high".to_string()))
|
||||
);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let after = h.manager.snapshot();
|
||||
assert_eq!(after.kind, Some("codex".to_string()), "restart must keep the same agent");
|
||||
assert_eq!(after.mode, Some(PermissionMode::Checked), "restart must keep the same permission mode");
|
||||
assert_eq!(
|
||||
after.kind,
|
||||
Some("codex".to_string()),
|
||||
"restart must keep the same agent"
|
||||
);
|
||||
assert_eq!(
|
||||
after.mode,
|
||||
Some(PermissionMode::Checked),
|
||||
"restart must keep the same permission mode"
|
||||
);
|
||||
assert_eq!(
|
||||
h.manager.model_and_effort(),
|
||||
(Some("gpt-5".to_string()), Some("high".to_string())),
|
||||
@@ -179,8 +225,15 @@ fn restart_mid_step_kills_the_step_at_once_instead_of_waiting_for_it() {
|
||||
// Running again straight away: no wait for the step to finish.
|
||||
h.wait_state("Running again", is_running);
|
||||
h.wait_for_output(READY, 2);
|
||||
assert!(started.elapsed() < Duration::from_secs(5), "restart must not wait on the step; took {:?}", started.elapsed());
|
||||
assert!(!h.seen.contains("STEP DONE"), "the step should have been cut short, not finished");
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(5),
|
||||
"restart must not wait on the step; took {:?}",
|
||||
started.elapsed()
|
||||
);
|
||||
assert!(
|
||||
!h.seen.contains("STEP DONE"),
|
||||
"the step should have been cut short, not finished"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
@@ -198,8 +251,15 @@ fn an_agent_that_exits_by_itself_ends_with_its_code_and_nothing_restarts() {
|
||||
|
||||
// Nothing starts without a press.
|
||||
h.pump_for(Duration::from_millis(1500));
|
||||
assert!(matches!(h.manager.snapshot().state, AgentState::Ended { .. }));
|
||||
assert_eq!(h.seen.matches(READY).count(), 1, "an agent started by itself");
|
||||
assert!(matches!(
|
||||
h.manager.snapshot().state,
|
||||
AgentState::Ended { .. }
|
||||
));
|
||||
assert_eq!(
|
||||
h.seen.matches(READY).count(),
|
||||
1,
|
||||
"an agent started by itself"
|
||||
);
|
||||
assert!(!h.manager.is_active());
|
||||
|
||||
// A press of Restart starts a fresh one on the same brief.
|
||||
@@ -216,8 +276,21 @@ fn quitting_with_a_running_agent_stops_it() {
|
||||
assert!(h.manager.is_active());
|
||||
h.type_line("PID");
|
||||
h.wait_for_output("PID ", 1);
|
||||
let pid = h.seen.rsplit("PID ").next().unwrap().trim_start().split(|c: char| !c.is_ascii_digit()).next().unwrap().parse::<u32>().expect("the agent's pid");
|
||||
assert!(process_alive(pid), "the agent should be running before the stop");
|
||||
let pid = h
|
||||
.seen
|
||||
.rsplit("PID ")
|
||||
.next()
|
||||
.unwrap()
|
||||
.trim_start()
|
||||
.split(|c: char| !c.is_ascii_digit())
|
||||
.next()
|
||||
.unwrap()
|
||||
.parse::<u32>()
|
||||
.expect("the agent's pid");
|
||||
assert!(
|
||||
process_alive(pid),
|
||||
"the agent should be running before the stop"
|
||||
);
|
||||
|
||||
h.manager.stop();
|
||||
|
||||
@@ -228,8 +301,14 @@ fn quitting_with_a_running_agent_stops_it() {
|
||||
// The stopped agent does not come back or print again.
|
||||
let before = h.seen.len();
|
||||
h.pump_for(Duration::from_millis(1000));
|
||||
assert!(!h.seen[before..].contains(READY), "an agent started after the stop");
|
||||
assert!(h.manager.restart().is_err(), "there is nothing left to restart");
|
||||
assert!(
|
||||
!h.seen[before..].contains(READY),
|
||||
"an agent started after the stop"
|
||||
);
|
||||
assert!(
|
||||
h.manager.restart().is_err(),
|
||||
"there is nothing left to restart"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -237,12 +316,19 @@ fn the_replay_buffer_holds_recent_output_and_clears_on_a_fresh_agent() {
|
||||
let mut h = Harness::new();
|
||||
h.start_and_wait_ready();
|
||||
let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned();
|
||||
assert!(replay.contains(READY), "replay should hold what was just printed; got {replay:?}");
|
||||
assert!(
|
||||
replay.contains(READY),
|
||||
"replay should hold what was just printed; got {replay:?}"
|
||||
);
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
let replay = String::from_utf8_lossy(&h.manager.replay()).into_owned();
|
||||
assert_eq!(replay.matches(READY).count(), 1, "a fresh agent's replay must not carry the old one's output");
|
||||
assert_eq!(
|
||||
replay.matches(READY).count(),
|
||||
1,
|
||||
"a fresh agent's replay must not carry the old one's output"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
@@ -261,8 +347,15 @@ fn a_restart_runs_the_brief_hook_and_the_bar_gets_its_note() {
|
||||
|
||||
h.manager.restart().unwrap();
|
||||
|
||||
assert_eq!(*runs.lock().unwrap(), 1, "the restart did not run the brief once");
|
||||
assert_eq!(h.manager.snapshot().brief_note.as_deref(), Some("Brief ready on the dashboard"));
|
||||
assert_eq!(
|
||||
*runs.lock().unwrap(),
|
||||
1,
|
||||
"the restart did not run the brief once"
|
||||
);
|
||||
assert_eq!(
|
||||
h.manager.snapshot().brief_note.as_deref(),
|
||||
Some("Brief ready on the dashboard")
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
|
||||
@@ -271,7 +364,10 @@ fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() {
|
||||
let mut h = Harness::new();
|
||||
h.manager.set_env(vec![
|
||||
("PLAN2CODE_IN_APP".to_string(), "1".to_string()),
|
||||
("PLAN2CODE_CONSOLE_SID".to_string(), "sid-window-a".to_string()),
|
||||
(
|
||||
"PLAN2CODE_CONSOLE_SID".to_string(),
|
||||
"sid-window-a".to_string(),
|
||||
),
|
||||
]);
|
||||
h.start_and_wait_ready();
|
||||
h.type_line("ENV PLAN2CODE_IN_APP");
|
||||
@@ -280,7 +376,10 @@ fn the_agent_gets_the_in_app_signal_and_a_restart_keeps_it() {
|
||||
h.wait_for_output("ENV PLAN2CODE_CONSOLE_SID=sid-window-a", 1);
|
||||
|
||||
// The signal changes with the console; a Restart starts on the newest.
|
||||
h.manager.set_env(vec![("PLAN2CODE_CONSOLE_SID".to_string(), "sid-window-b".to_string())]);
|
||||
h.manager.set_env(vec![(
|
||||
"PLAN2CODE_CONSOLE_SID".to_string(),
|
||||
"sid-window-b".to_string(),
|
||||
)]);
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
h.type_line("ENV PLAN2CODE_CONSOLE_SID");
|
||||
@@ -304,17 +403,32 @@ fn an_agent_with_no_signal_set_gets_none() {
|
||||
fn a_custom_agent_runs_the_override_too_and_restart_keeps_its_id() {
|
||||
let mut h = Harness::new();
|
||||
// Its command is nowhere on PATH: the override replaces it, as for a built-in.
|
||||
let (mut agents, warnings) = parse_agents_file(r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#);
|
||||
let (mut agents, warnings) = parse_agents_file(
|
||||
r#"{"schema":1,"agents":[{"id":"goose","name":"Goose","command":"goose-not-installed","bypassArgs":["--yes"]}]}"#,
|
||||
);
|
||||
assert!(warnings.is_empty(), "{warnings:?}");
|
||||
let goose = Agent::Custom(agents.remove(0));
|
||||
let spec = agent_launch_spec(&goose, &std::env::temp_dir(), Some("m"), None, PermissionMode::Bypass, "/plan2code");
|
||||
let spec = agent_launch_spec(
|
||||
&goose,
|
||||
&std::env::temp_dir(),
|
||||
Some("m"),
|
||||
None,
|
||||
PermissionMode::Bypass,
|
||||
"/plan2code",
|
||||
);
|
||||
assert_eq!(PathBuf::from(&spec.program), common::fake_agent());
|
||||
assert!(spec.args.is_empty());
|
||||
h.manager.start(goose, None, None, PermissionMode::Checked, None).expect("start the custom agent");
|
||||
h.manager
|
||||
.start(goose, None, None, PermissionMode::Checked, None)
|
||||
.expect("start the custom agent");
|
||||
h.wait_for_output(READY, 1);
|
||||
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()));
|
||||
h.manager.restart().unwrap();
|
||||
h.wait_for_output(READY, 2);
|
||||
assert_eq!(h.manager.snapshot().kind, Some("goose".to_string()), "restart must keep the custom agent");
|
||||
assert_eq!(
|
||||
h.manager.snapshot().kind,
|
||||
Some("goose".to_string()),
|
||||
"restart must keep the custom agent"
|
||||
);
|
||||
h.manager.stop();
|
||||
}
|
||||
@@ -9,10 +9,19 @@ use std::sync::Once;
|
||||
#[allow(dead_code)]
|
||||
pub fn process_alive(pid: u32) -> bool {
|
||||
if cfg!(windows) {
|
||||
let out = Command::new("tasklist").args(["/FI", &format!("PID eq {pid}"), "/NH"]).output().unwrap();
|
||||
String::from_utf8_lossy(&out.stdout).split_whitespace().any(|word| word == pid.to_string())
|
||||
let out = Command::new("tasklist")
|
||||
.args(["/FI", &format!("PID eq {pid}"), "/NH"])
|
||||
.output()
|
||||
.unwrap();
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.split_whitespace()
|
||||
.any(|word| word == pid.to_string())
|
||||
} else {
|
||||
Command::new("kill").args(["-0", &pid.to_string()]).status().map(|s| s.success()).unwrap_or(false)
|
||||
Command::new("kill")
|
||||
.args(["-0", &pid.to_string()])
|
||||
.status()
|
||||
.map(|s| s.success())
|
||||
.unwrap_or(false)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,6 +42,10 @@ pub fn fake_agent() -> PathBuf {
|
||||
.and_then(|deps| deps.parent())
|
||||
.unwrap()
|
||||
.join(format!("fake-agent{}", std::env::consts::EXE_SUFFIX));
|
||||
assert!(path.exists(), "{} is missing after building the fake agent", path.display());
|
||||
assert!(
|
||||
path.exists(),
|
||||
"{} is missing after building the fake agent",
|
||||
path.display()
|
||||
);
|
||||
path
|
||||
}
|
||||
@@ -33,13 +33,22 @@ fn setup() -> Option<PathBuf> {
|
||||
return None;
|
||||
}
|
||||
let console = repo_console_dir();
|
||||
assert!(console.join("console.mjs").is_file(), "console source missing at {}", console.display());
|
||||
assert!(
|
||||
console.join("console.mjs").is_file(),
|
||||
"console source missing at {}",
|
||||
console.display()
|
||||
);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_DIR", &console);
|
||||
std::env::set_var("PLAN2CODE_CONSOLE_HOME", temp_dir("home"));
|
||||
std::env::set_var("PLAN2CODE_NO_BROWSER", "1");
|
||||
// Run inside the desktop app, the agent's in-app variables would have this
|
||||
// console announce itself to the live window and take it over.
|
||||
for name in ["PLAN2CODE_IN_APP", "PLAN2CODE_APP_ANNOUNCE", "PLAN2CODE_APP_TOKEN", "PLAN2CODE_CONSOLE_SID"] {
|
||||
for name in [
|
||||
"PLAN2CODE_IN_APP",
|
||||
"PLAN2CODE_APP_ANNOUNCE",
|
||||
"PLAN2CODE_APP_TOKEN",
|
||||
"PLAN2CODE_CONSOLE_SID",
|
||||
] {
|
||||
std::env::remove_var(name);
|
||||
}
|
||||
Some(temp_dir("project"))
|
||||
@@ -76,7 +85,10 @@ fn starts_answers_and_stops() {
|
||||
assert!(until_health(&sup, true), "the console URL never answered");
|
||||
|
||||
sup.stop().expect("stop");
|
||||
assert!(until_health(&sup, false), "the console still answered after stop()");
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"the console still answered after stop()"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -87,11 +99,24 @@ fn a_killed_console_is_dead_and_restarts() {
|
||||
let first_sid = sup.session().sid.clone();
|
||||
|
||||
kill_pid(sup.session().pid);
|
||||
assert!(until_health(&sup, false), "a killed console still looked alive");
|
||||
assert!(
|
||||
until_health(&sup, false),
|
||||
"a killed console still looked alive"
|
||||
);
|
||||
|
||||
assert!(sup.restart_if_dead().expect("restart"), "restart_if_dead did nothing");
|
||||
assert_eq!(sup.session().sid, first_sid, "a dead console comes back on the same session, so its page and place survive");
|
||||
assert!(until_health(&sup, true), "the restarted console never answered");
|
||||
assert!(
|
||||
sup.restart_if_dead().expect("restart"),
|
||||
"restart_if_dead did nothing"
|
||||
);
|
||||
assert_eq!(
|
||||
sup.session().sid,
|
||||
first_sid,
|
||||
"a dead console comes back on the same session, so its page and place survive"
|
||||
);
|
||||
assert!(
|
||||
until_health(&sup, true),
|
||||
"the restarted console never answered"
|
||||
);
|
||||
sup.stop().expect("stop");
|
||||
}
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ use std::time::{Duration, Instant};
|
||||
use plan2code_app_lib::pty_host::{PtyHost, StartOptions};
|
||||
|
||||
mod common;
|
||||
use common::{fake_agent, process_alive};
|
||||
use common::fake_agent;
|
||||
|
||||
fn start_fake() -> (PtyHost, Receiver<Vec<u8>>) {
|
||||
let (tx, rx) = channel();
|
||||
@@ -97,7 +97,10 @@ fn kill_ends_a_running_step() {
|
||||
let started = Instant::now();
|
||||
host.kill().unwrap();
|
||||
host.wait().unwrap();
|
||||
assert!(started.elapsed() < Duration::from_secs(10), "kill took too long");
|
||||
assert!(
|
||||
started.elapsed() < Duration::from_secs(10),
|
||||
"kill took too long"
|
||||
);
|
||||
}
|
||||
|
||||
/// An npm `.cmd` shim: `cmd.exe` is the directly spawned process, the real
|
||||
@@ -106,6 +109,7 @@ fn kill_ends_a_running_step() {
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn kill_ends_a_cmd_wrapped_grandchild_too() {
|
||||
use common::process_alive;
|
||||
use plan2code_app_lib::agents::windows_command;
|
||||
use std::fs;
|
||||
|
||||
@@ -113,15 +117,30 @@ fn kill_ends_a_cmd_wrapped_grandchild_too() {
|
||||
let _ = fs::remove_dir_all(&dir);
|
||||
fs::create_dir_all(&dir).unwrap();
|
||||
let shim = dir.join("shim.cmd");
|
||||
fs::write(&shim, format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display())).unwrap();
|
||||
fs::write(
|
||||
&shim,
|
||||
format!("@echo off\r\n\"{}\" %*\r\n", fake_agent().display()),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let (program, args) = windows_command("shim", vec![], &dir.to_string_lossy());
|
||||
let path = format!("{};{}", dir.to_string_lossy(), std::env::var("PATH").unwrap_or_default());
|
||||
let path = format!(
|
||||
"{};{}",
|
||||
dir.to_string_lossy(),
|
||||
std::env::var("PATH").unwrap_or_default()
|
||||
);
|
||||
let (tx, rx) = channel();
|
||||
let host = PtyHost::start(
|
||||
// `cmd /c shim.cmd` is a bare name: like a real npm shim, cmd.exe
|
||||
// only finds it on PATH, never by the current directory alone.
|
||||
StartOptions { program, args, env: vec![("PATH".to_string(), path)], cwd: None, cols: 80, rows: 24 },
|
||||
StartOptions {
|
||||
program,
|
||||
args,
|
||||
env: vec![("PATH".to_string(), path)],
|
||||
cwd: None,
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
},
|
||||
move |bytes| {
|
||||
let _ = tx.send(bytes);
|
||||
},
|
||||
@@ -142,7 +161,10 @@ fn kill_ends_a_cmd_wrapped_grandchild_too() {
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("the grandchild's pid");
|
||||
assert!(process_alive(pid), "the grandchild should be running before kill");
|
||||
assert!(
|
||||
process_alive(pid),
|
||||
"the grandchild should be running before kill"
|
||||
);
|
||||
|
||||
host.kill().unwrap();
|
||||
let deadline = Instant::now() + Duration::from_secs(10);
|
||||
|
||||
@@ -255,7 +255,7 @@
|
||||
</header>
|
||||
<div id="workspace">
|
||||
<main id="dashboard">
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard"></iframe>
|
||||
<iframe id="console-frame" title="Plan2Code console dashboard" allow="clipboard-write"></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
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
// `node --test` with the files run side by side capped at 8 and at one per
|
||||
// spare core. A flat 8 kept a big machine from swamping the page tests, but on
|
||||
// a 3 or 4 core CI runner it ran 8 browsers at once, nearly triple Node's own
|
||||
// default, and page tests timed out at random. Arguments pass straight through.
|
||||
|
||||
import { spawnSync } from "node:child_process";
|
||||
import os from "node:os";
|
||||
|
||||
const concurrency = Math.max(1, Math.min(8, os.availableParallelism() - 1));
|
||||
const r = spawnSync(process.execPath, ["--test", `--test-concurrency=${concurrency}`, ...process.argv.slice(2)], { stdio: "inherit" });
|
||||
process.exit(r.status ?? 1);
|
||||
@@ -134,3 +134,38 @@ export const textOf = async (locator) => (await locator.innerText()).trim();
|
||||
|
||||
// The scroll offset of the first element matching `selector`.
|
||||
export const scrollTopOf = (page, selector) => page.$eval(selector, (el) => el.scrollTop);
|
||||
|
||||
// Scrolls what `locator` names to `top` ("end" for its bottom), or as far as
|
||||
// it goes when that is less, and returns where it landed. A redraw can replace
|
||||
// the element between Playwright finding it and the scroll, and one not laid
|
||||
// out yet cannot scroll, so it scrolls again until the element on the page
|
||||
// holds a place past its top.
|
||||
export async function scrollCard(locator, top) {
|
||||
const deadline = Date.now() + 5000;
|
||||
for (;;) {
|
||||
const at = await locator.evaluate((el, want) => {
|
||||
if (!el.isConnected) return null;
|
||||
const max = el.scrollHeight - el.clientHeight;
|
||||
const target = want === "end" ? max : Math.min(want, max);
|
||||
el.scrollTop = target;
|
||||
return max > 0 && Math.abs(el.scrollTop - target) < 1 ? el.scrollTop : null;
|
||||
}, top);
|
||||
if (at !== null) return at;
|
||||
if (Date.now() > deadline) throw new Error(`the element never held a scroll to ${top}`);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
|
||||
// The computed `props` of the element `locator` names. A redraw can replace the
|
||||
// element between Playwright finding it and the read, and an element off the
|
||||
// page reads "" for every style, so a read of one is taken again.
|
||||
export async function stylesOf(locator, props) {
|
||||
const deadline = Date.now() + 5000;
|
||||
for (;;) {
|
||||
const got = await locator.evaluate((x, ps) => (x.isConnected ? Object.fromEntries(ps.map((p) => [p, getComputedStyle(x)[p]])) : null), props);
|
||||
if (got) return got;
|
||||
if (Date.now() > deadline) throw new Error(`${props.join(", ")}: the element never stayed on the page long enough to read`);
|
||||
await new Promise((r) => setTimeout(r, 50));
|
||||
}
|
||||
}
|
||||
export const styleOf = async (locator, prop) => (await stylesOf(locator, [prop]))[prop];
|
||||
@@ -99,6 +99,11 @@ export function gitInit(dir, branch = "main") {
|
||||
g("config", "user.email", "t@example.com");
|
||||
g("config", "user.name", "Test");
|
||||
g("config", "commit.gpgsign", "false");
|
||||
// No background maintenance after a commit: on macOS it held
|
||||
// .git/objects/maintenance.lock while copyFixture copied the template, and
|
||||
// the copy failed with ENOENT once the lock was gone.
|
||||
g("config", "maintenance.auto", "false");
|
||||
g("config", "gc.auto", "0");
|
||||
return g;
|
||||
}
|
||||
|
||||
|
||||
@@ -174,6 +174,7 @@ test("pathfinder trail: exact footer for forms A, B and C", () => {
|
||||
assert.ok(c.json.text.endsWith("OR START FRESH · new conversation, paste:\n`/plan2code-0-pathfinder specs/audit-export/pathfinder --web`"));
|
||||
assert.deepEqual(c.json.menu.options.map((o) => o.label), ["Row-count ceiling", "Start fresh"]);
|
||||
assert.equal(c.json.menu.recommended, "Start fresh", "the checkpoint after ~3 decisions");
|
||||
assert.equal(c.json.menu.options.find((o) => o.label === "Start fresh").fresh, true, "the page reads it as a clean start");
|
||||
assert.equal(P("trail", "audit-export", "--form", "C").json.menu.recommended, "Row-count ceiling");
|
||||
});
|
||||
|
||||
|
||||
@@ -39,6 +39,7 @@ const CONTRACTS = [
|
||||
/\bconst greyed\b/g,
|
||||
/\bgreyed(?=, card)/g,
|
||||
/^\/\/\s+greyed\b/gm,
|
||||
/`greyed`/g,
|
||||
/\bcancelled(?=\s*:)/g,
|
||||
/\.cancelled\b/g,
|
||||
/"cancelled"/g,
|
||||
|
||||
@@ -11,7 +11,7 @@ import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { gitInit } from "./skill-script-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf } from "./page-test-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, sendAndCollect, itemCard, scrollTopOf, scrollCard, stylesOf, styleOf } from "./page-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
|
||||
@@ -209,8 +209,7 @@ test("a redraw keeps your place: the scroll and the focused field survive an age
|
||||
|
||||
// Reading a question part-way down: the card scrolls itself.
|
||||
const card = itemCard(s.page, "q1");
|
||||
await card.evaluate((el) => (el.scrollTop = 400));
|
||||
assert.equal(await card.evaluate((el) => el.scrollTop), 400, "the question card scrolls");
|
||||
assert.equal(await scrollCard(card, 400), 400, "the question card scrolls");
|
||||
await unrelatedPost(s, "Audit export, take two");
|
||||
assert.equal(await itemCard(s.page, "q1").evaluate((el) => el.scrollTop), 400);
|
||||
|
||||
@@ -229,7 +228,7 @@ test("a redraw keeps your place: the scroll and the focused field survive an age
|
||||
// On a doc: the column scrolls.
|
||||
await s.page.locator("#views").getByRole("button", { name: /What we've agreed/ }).click();
|
||||
await s.page.getByText("Paragraph 80.").waitFor();
|
||||
await s.page.locator("#main").evaluate((el) => (el.scrollTop = 900));
|
||||
await scrollCard(s.page.locator("#main"), 900);
|
||||
const docBefore = await scrollTopOf(s.page, "#main");
|
||||
assert.ok(docBefore > 0, "the doc column scrolls");
|
||||
await unrelatedPost(s, "Audit export, take four");
|
||||
@@ -296,7 +295,7 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
|
||||
const welcomeDone = s.page.getByRole("button", { name: "Start building" });
|
||||
if (await welcomeDone.isVisible()) await welcomeDone.click();
|
||||
await welcomeDone.waitFor({ state: "hidden" });
|
||||
await s.page.locator("#main > .dash").evaluate((el) => (el.scrollTop = 150));
|
||||
await scrollCard(s.page.locator("#main > .dash"), 150);
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard scrolls");
|
||||
await unrelatedPost(s, "Dashboard, take two");
|
||||
assert.equal(await scrollTopOf(s.page, "#main > .dash"), 150, "the dashboard lost its place");
|
||||
@@ -311,7 +310,7 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
|
||||
await s.page.setViewportSize({ width: 1280, height: 300 });
|
||||
const pane = "#main > .waiting-pane";
|
||||
await s.page.locator(pane).waitFor();
|
||||
await s.page.locator(pane).evaluate((el) => (el.scrollTop = 60));
|
||||
await scrollCard(s.page.locator(pane), 60);
|
||||
const waitingAt = await scrollTopOf(s.page, pane);
|
||||
assert.ok(waitingAt > 0, "the waiting screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take two");
|
||||
@@ -320,7 +319,7 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
|
||||
s.post({ finish: { headline: "Phase 1 is done", body: longText(30), command: "/plan2code-3-implement specs/audit-export/overview.md" } });
|
||||
await s.page.locator("#main").getByRole("heading", { name: "Phase 1 is done" }).waitFor();
|
||||
const end = "#main > .card";
|
||||
await s.page.locator(end).evaluate((el) => (el.scrollTop = 300));
|
||||
await scrollCard(s.page.locator(end), 300);
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen scrolls");
|
||||
await unrelatedPost(s, "Phase 1, take three");
|
||||
assert.equal(await scrollTopOf(s.page, end), 300, "the finished screen lost its place");
|
||||
@@ -332,7 +331,7 @@ test("a redraw keeps the place of the dashboard, the waiting screen and the fini
|
||||
workflow: "plan",
|
||||
payload: { items: [{ id: "q1", kind: "text", title: "What to call it", body: longText(40) }] },
|
||||
});
|
||||
await itemCard(s.page, "q1").evaluate((el) => (el.scrollTop = 400));
|
||||
await scrollCard(itemCard(s.page, "q1"), 400);
|
||||
s.post({ items: [{ id: "q2", kind: "text", title: "Who uses it", body: longText(40) }] });
|
||||
await itemCard(s.page, "q2").waitFor();
|
||||
assert.equal(await itemCard(s.page, "q2").evaluate((el) => el.scrollTop), 0, "the new question opened part-way down");
|
||||
@@ -349,7 +348,7 @@ const accentOf = (page) =>
|
||||
probe.remove();
|
||||
return color;
|
||||
});
|
||||
const outlineOf = (button) => button.evaluate((b) => getComputedStyle(b).borderTopColor);
|
||||
const outlineOf = (button) => styleOf(button, "borderTopColor");
|
||||
const warnOf = (page) =>
|
||||
page.evaluate(() => {
|
||||
const probe = document.createElement("i");
|
||||
@@ -373,7 +372,7 @@ test("on a sign-off card, approve and yes are outlined in the accent until picke
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "I want changes" })), accent, "the other verdict is not");
|
||||
await approve.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await approve.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, approve fills with the accent");
|
||||
assert.equal(await styleOf(approve, "backgroundColor"), accent, "picked, approve fills with the accent");
|
||||
|
||||
card = await ask(s, review("so2", [{ id: "yes", label: "Build it" }, { id: "no", label: "Not yet" }]));
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Build it" })), accent, "an unpicked yes is outlined too");
|
||||
@@ -388,7 +387,7 @@ test("Skip this one and a comment box's quick answer are the same small accent b
|
||||
const card = await ask(s, { id: "l1", kind: "list", title: "The steps", body: "Rename.", required: false, rows });
|
||||
const skip = card.getByRole("button", { name: "Skip this one" });
|
||||
const quick = card.getByRole("button", { name: "No changes" });
|
||||
const look = (b) => b.evaluate((x) => { const c = getComputedStyle(x); return [c.fontSize, c.paddingTop, c.paddingLeft, c.color]; });
|
||||
const look = async (b) => Object.values(await stylesOf(b, ["fontSize", "paddingTop", "paddingLeft", "color"]));
|
||||
assert.deepEqual(await look(skip), await look(quick), "the two chips look alike");
|
||||
const [size, , , color] = await look(skip);
|
||||
assert.equal(size, "12px", "small, not a full-size button");
|
||||
@@ -425,7 +424,7 @@ test("a confirm's safe yes and a recap's yes are outlined in the accent, and a d
|
||||
assert.notEqual(await outlineOf(card.getByRole("button", { name: "No" })), accent, "the no does not");
|
||||
await yes.click();
|
||||
await s.page.waitForFunction(() => document.querySelector("#btn-send:not(:disabled)"));
|
||||
assert.equal(await yes.evaluate((b) => getComputedStyle(b).backgroundColor), accent, "picked, it fills");
|
||||
assert.equal(await styleOf(yes, "backgroundColor"), accent, "picked, it fills");
|
||||
|
||||
card = await ask(s, { id: "y2", kind: "confirm", title: "Delete it", body: "Really?", danger: true });
|
||||
assert.equal(await outlineOf(card.getByRole("button", { name: "Yes" })), warn, "a dangerous yes stays red");
|
||||
@@ -440,11 +439,11 @@ test("a card cut by the window fades at its bottom edge while there is more belo
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "plan" });
|
||||
await s.page.setViewportSize({ width: 1280, height: 420 });
|
||||
const card = await ask(s, { id: "q1", kind: "text", title: "What to call it", body: longText(40) });
|
||||
const fades = () => card.evaluate((el) => { const c = getComputedStyle(el); return (c.maskImage || c.webkitMaskImage || "none") !== "none"; });
|
||||
const fades = async () => { const c = await stylesOf(card, ["maskImage", "webkitMaskImage"]); return (c.maskImage || c.webkitMaskImage || "none") !== "none"; };
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); return c && c.scrollHeight > c.clientHeight + 4; });
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") !== "none"; });
|
||||
assert.equal(await fades(), true, "a cut card fades at the bottom");
|
||||
await card.evaluate((el) => (el.scrollTop = el.scrollHeight));
|
||||
await scrollCard(card, "end");
|
||||
await s.page.waitForFunction(() => { const c = document.querySelector("#main > .card"); const m = getComputedStyle(c); return (m.maskImage || m.webkitMaskImage || "none") === "none"; });
|
||||
assert.equal(await fades(), false, "at the end, the fade is gone");
|
||||
});
|
||||
|
||||
@@ -11,7 +11,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, tempProject, textOf } from "./page-test-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, textOf, styleOf } from "./page-test-helpers.mjs";
|
||||
import { cli, until, CONSOLE_CLI, HOME } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
@@ -153,7 +153,7 @@ test("a fixed bug is hidden while unavailable workflows are, dimmed when they sh
|
||||
assert.match(await textOf(bug), /Bug fixed/i, "the chip names its state");
|
||||
assert.doesNotMatch(await textOf(bug), /bug fixed\s+bug fixed/i, "the scan's detail does not repeat the label");
|
||||
assert.equal(await bug.getAttribute("aria-current"), "false", "the fixed bug is not picked");
|
||||
const opacity = await bug.evaluate((b) => Number(getComputedStyle(b).opacity));
|
||||
const opacity = Number(await styleOf(bug, "opacity"));
|
||||
assert.ok(opacity < 1, `the fixed bug's chip is dimmed (opacity ${opacity})`);
|
||||
assert.equal(await demo.getAttribute("aria-current"), "true", "the plan stays picked");
|
||||
});
|
||||
@@ -229,6 +229,51 @@ test("picking Start from scratch instead of a spec grays Document, and a launch
|
||||
assert.ok(!launch.spec, `a launch from scratch names no spec: ${JSON.stringify(launch)}`);
|
||||
});
|
||||
|
||||
// What a person would see break: a spec not documented yet offers nothing to
|
||||
// read, or its Map and Plan draft tabs stay up for a spec that has an
|
||||
// overview (or for no spec at all).
|
||||
test("a spec not documented yet shows its Map and Plan draft as tabs, and a documented one shows only Overview", async (t) => {
|
||||
const project = tempProject({
|
||||
...DRAFT_PROJECT,
|
||||
"specs/demo/pathfinder/map.md": "# Map: demo\n\n**Status:** Cleared\n\nWho votes for lunch.\n",
|
||||
"specs/done/overview.md": "# Overview: done\n\nAll written up.\n",
|
||||
"specs/done/phase-1.md": "- [ ] **Task 1.1:** x\n",
|
||||
});
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "dashboard", payload: MENU, project });
|
||||
const main = await toTheMenu(s);
|
||||
const tab = (name) => s.page.locator("#views .view-tab", { hasText: new RegExp(`^${name}$`) });
|
||||
|
||||
await chipFor(main, "demo").click();
|
||||
await pickedChip(main, "demo").waitFor();
|
||||
await tab("Map").waitFor();
|
||||
await tab("Plan draft").waitFor();
|
||||
assert.equal(await tab("Overview").count(), 0, "no overview.md, no Overview tab");
|
||||
|
||||
await tab("Plan draft").click();
|
||||
await main.getByRole("heading", { name: "Plan draft", exact: true }).waitFor();
|
||||
assert.match(await textOf(main), /specs\/demo\/PLAN-DRAFT-20261017\.md · read-only/);
|
||||
assert.match(await textOf(main), /A lunch vote for the team\./);
|
||||
await tab("Map").click();
|
||||
await main.getByRole("heading", { name: "Map", exact: true }).waitFor();
|
||||
assert.match(await textOf(main), /specs\/demo\/pathfinder\/map\.md · read-only/);
|
||||
assert.match(await textOf(main), /Who votes for lunch\./);
|
||||
|
||||
// The documented spec trades both for its Overview, and the open Map tab,
|
||||
// gone with them, sends the person home.
|
||||
await tab("Dashboard").click();
|
||||
await chipFor(main, "done").click();
|
||||
await pickedChip(main, "done").waitFor();
|
||||
await tab("Overview").waitFor();
|
||||
assert.ok(
|
||||
await until(async () => (await tab("Map").count()) === 0 && (await tab("Plan draft").count()) === 0),
|
||||
"the Map and Plan draft tabs go"
|
||||
);
|
||||
|
||||
await chipFor(main, "Start from scratch").click();
|
||||
await pickedChip(main, "Start from scratch").waitFor();
|
||||
assert.ok(await until(async () => (await tab("Overview").count()) === 0), "no spec, no spec tabs");
|
||||
});
|
||||
|
||||
// What a person would see break: the intro cannot be skipped, or it replays
|
||||
// on every reload of the same tab.
|
||||
test("Skip the intro ends the first-open wake-up at once, and a reload of the tab does not play it again", async (t) => {
|
||||
@@ -272,7 +317,7 @@ test("a handoff shows as a dashed Handoff chip even with no spec, and picking it
|
||||
const { main, chip } = await openHandoffMenu(t);
|
||||
assert.match(await textOf(chip), /Handoff/i, "the chip is labeled Handoff");
|
||||
assert.equal(await chip.getAttribute("aria-current"), "false", "a handoff is offered, not picked for you");
|
||||
assert.equal(await chip.evaluate((b) => getComputedStyle(b).borderTopStyle), "dashed", "the chip's border is dashed");
|
||||
assert.equal(await styleOf(chip, "borderTopStyle"), "dashed", "the chip's border is dashed");
|
||||
assert.ok(await lightOf(main, "/plan2code-1-plan").isVisible(), "the cards show before a handoff is picked");
|
||||
|
||||
await chip.click();
|
||||
|
||||
@@ -14,7 +14,7 @@ import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import { pageSuite, openSession, tempProject, textOf, itemCard } from "./page-test-helpers.mjs";
|
||||
import { pageSuite, openSession, tempProject, textOf, itemCard, scrollCard } from "./page-test-helpers.mjs";
|
||||
import { until } from "./web-console-test-helpers.mjs";
|
||||
|
||||
const suite = pageSuite(test);
|
||||
@@ -74,7 +74,7 @@ test("each git tab keeps its own scroll place, across a tab switch and an agent
|
||||
const column = () => page.locator("#main").evaluate((el) => el.scrollTop);
|
||||
await tab("Changes").click();
|
||||
await page.getByRole("tabpanel").getByText("src/app.js", { exact: true }).waitFor();
|
||||
await page.locator("#main").evaluate((el) => (el.scrollTop = 120));
|
||||
await scrollCard(page.locator("#main"), 120);
|
||||
const changesAt = await column();
|
||||
assert.ok(changesAt > 0, "the board's column scrolls");
|
||||
// Another tab opens at its own place, not where Changes was left.
|
||||
|
||||
@@ -20,7 +20,7 @@ import fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import test from "node:test";
|
||||
import assert from "node:assert/strict";
|
||||
import { pageSuite, openSession, drawn } from "./page-test-helpers.mjs";
|
||||
import { pageSuite, openSession, drawn, styleOf } from "./page-test-helpers.mjs";
|
||||
import { JPEG, backdate, cli, until } from "./web-console-test-helpers.mjs";
|
||||
import {
|
||||
LEGACY_TAB_ID,
|
||||
@@ -249,7 +249,7 @@ test("the editor breaks no content-security rule, and hostile Markdown runs noth
|
||||
assert.equal(result.styleTags, 0, "the editor added no <style> element");
|
||||
assert.deepEqual(consoleErrors.filter((e) => /Content.Security.Policy|Refused to/i.test(e)), []);
|
||||
// The heading is styled from the stylesheet the page ships.
|
||||
const h1 = await s.page.locator("#notepad-editor .cm-h1").evaluate((el) => getComputedStyle(el).fontWeight);
|
||||
const h1 = await styleOf(s.page.locator("#notepad-editor .cm-h1"), "fontWeight");
|
||||
assert.ok(Number(h1) >= 600 || h1 === "bold", `the heading is bold (${h1})`);
|
||||
});
|
||||
|
||||
@@ -348,15 +348,23 @@ test("headings grow, bullets draw, and marks come back on the line the cursor is
|
||||
return [...root.querySelectorAll(".cm-line")].map((l) => ({ text: l.textContent, size: parseFloat(getComputedStyle(l).fontSize) }));
|
||||
});
|
||||
// The cursor starts on line 1 (the "# Big" heading): its mark shows, the
|
||||
// second heading's does not.
|
||||
let seen = await lines();
|
||||
// second heading's does not. The editor hides marks and draws bullets a
|
||||
// little after the text lands, so wait for that before looking.
|
||||
let seen;
|
||||
await until(async () => {
|
||||
seen = await lines();
|
||||
return seen[2]?.text === "Smaller" && seen[4] && !seen[4].text.startsWith("-");
|
||||
}, 5000);
|
||||
assert.equal(seen[0].text, "# Big");
|
||||
assert.equal(seen[2].text, "Smaller", "off the cursor line the mark is hidden");
|
||||
assert.ok(seen[0].size > seen[2].size && seen[2].size > seen[7].size, `heading sizes step down: ${seen.map((l) => l.size).join(", ")}`);
|
||||
assert.ok(seen[4].text.startsWith("•") || !seen[4].text.startsWith("-"), `a bullet is drawn, not a hyphen: "${seen[4].text}"`);
|
||||
// Click the second heading: its mark comes back.
|
||||
await s.page.locator("#notepad-editor .cm-h2").click();
|
||||
seen = await lines();
|
||||
await until(async () => {
|
||||
seen = await lines();
|
||||
return seen[2].text === "## Smaller";
|
||||
}, 5000);
|
||||
assert.equal(seen[2].text, "## Smaller");
|
||||
assert.equal(seen[0].text, "Big");
|
||||
});
|
||||
@@ -712,6 +720,8 @@ test("Delete asks twice, Escape backs out of either, and only the second confirm
|
||||
await s.page.click("#notepad-delete-go");
|
||||
await until(() => !fs.existsSync(folder), 4000);
|
||||
await s.page.waitForFunction(() => document.querySelectorAll("#notepad-tabs .notepad-tab").length === 1);
|
||||
// The strip redraws before the neighbor is marked selected.
|
||||
await until(async () => (await selectedName(s)).length === 1, 4000);
|
||||
assert.deepEqual(await selectedName(s), ["Notes"]);
|
||||
assert.equal(await shows(s, "keep me"), "keep me");
|
||||
assert.equal(listTabs(s.project).last, idOf(s, "Notes"), "the neighbor became the last tab");
|
||||
|
||||
@@ -148,6 +148,30 @@ test("Update CHANGELOG first shows beside Commit it now only when the finish ask
|
||||
assert.equal(await main.getByRole("button", { name: "Commit it now" }).isDisabled(), true, "one press locks the other buttons");
|
||||
});
|
||||
|
||||
// Pressed, then left: the agent's turn had ended, so nothing collects the
|
||||
// press. The line stops promising it is opening and offers continue instead.
|
||||
test("a finished screen's press that nothing collects says Plan2Code is not running, with continue as a button under the app", async (t) => {
|
||||
const s = await openSession(await suite.browser(), {
|
||||
t,
|
||||
workflow: "quick-task",
|
||||
clock: true,
|
||||
payload: { agent: { status: "working", activity: "Task 1 of 1" } },
|
||||
env: { PLAN2CODE_IN_APP: "1" },
|
||||
init: FAKE_APP_FRAME,
|
||||
});
|
||||
s.post({ finish: { headline: "Quick task done", command: "git add -A && git commit -m x -m y", commit: true, changelog: true, dashboard: true } });
|
||||
const main = s.page.locator("#main");
|
||||
await main.getByRole("button", { name: "Update CHANGELOG first" }).click();
|
||||
await lineSays(s, /^Opening Changelog…/);
|
||||
await s.page.clock.fastForward(200_000);
|
||||
await lineSays(s, /^Plan2Code is not running\. Your choice is saved/);
|
||||
assert.match(await s.page.locator("#planny").getAttribute("class"), /\bis-adrift\b/);
|
||||
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);
|
||||
});
|
||||
|
||||
test("Continue here is hidden once the session meter is red, and the command and fresh-session advice stay", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
// Ten points: a thirty-task phase scores ten, the red level.
|
||||
@@ -218,6 +242,71 @@ test("under the app, the meter popover's Start a New Session button asks the app
|
||||
assert.deepEqual(await toApp(s, "new-session"), [{ plan2code: "new-session" }], "a named request, nothing else in it");
|
||||
});
|
||||
|
||||
// A menu option the agent marks `fresh` (Pathfinder's "Start fresh") is a clean
|
||||
// start: under the app it reads Start New Session and sending it asks the app
|
||||
// for its New Session; any other option, and the classic console, do not.
|
||||
const FRESH_MENU = {
|
||||
items: [
|
||||
{
|
||||
id: "q1",
|
||||
kind: "menu",
|
||||
title: "Next step",
|
||||
body: "Continue here, or start fresh?",
|
||||
command: "/plan2code-0-pathfinder specs/x/pathfinder",
|
||||
options: [
|
||||
{ k: "1", text: "Row-count ceiling" },
|
||||
{ k: "2", text: "Start fresh", fresh: true },
|
||||
],
|
||||
},
|
||||
],
|
||||
agent: { status: "waiting" },
|
||||
};
|
||||
|
||||
test("under the app, a fresh menu option reads Start New Session, and picking another option starts nothing", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: FRESH_MENU, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
|
||||
assert.equal(await s.page.getByRole("radio", { name: /Start New Session/ }).count(), 1, "the app's wording");
|
||||
assert.equal(await s.page.getByText("Start fresh", { exact: true }).count(), 0, "replaces the classic one");
|
||||
await s.page.getByRole("radio", { name: /Row-count ceiling/ }).check();
|
||||
await s.page.click("#btn-send");
|
||||
await s.page.locator("#btn-send:has-text('Send to Plan2Code')").waitFor();
|
||||
assert.equal((await toApp(s, "new-session")).length, 0, "another option starts nothing");
|
||||
});
|
||||
|
||||
test("under the app, picking the fresh menu option and sending it posts new-session", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: FRESH_MENU, env: { PLAN2CODE_IN_APP: "1" }, init: FAKE_APP_FRAME });
|
||||
await s.page.getByRole("radio", { name: /Start New Session/ }).check();
|
||||
await s.page.click("#btn-send");
|
||||
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("outside the app, a fresh menu option keeps its own wording and starts no session", async (t) => {
|
||||
const s = await openSession(await suite.browser(), { t, workflow: "pathfinder", payload: FRESH_MENU });
|
||||
assert.equal(await s.page.getByRole("radio", { name: /Start New Session/ }).count(), 0);
|
||||
await s.page.getByRole("radio", { name: /Start fresh/ }).check();
|
||||
await s.page.click("#btn-send");
|
||||
await s.page.locator("#btn-send:has-text('Send to Plan2Code')").waitFor();
|
||||
});
|
||||
|
||||
test("under the app, a finish with a skill command offers Start a New Session; outside it does not", async (t) => {
|
||||
const inApp = 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,
|
||||
});
|
||||
inApp.post({ finish: { headline: "A skill next", command: "/plan2code-4-finalize" } });
|
||||
await inApp.page.getByRole("heading", { name: "A skill next" }).waitFor();
|
||||
await inApp.page.getByRole("button", { name: "Start a New Session" }).click();
|
||||
await until(async () => (await toApp(inApp, "new-session")).length === 1, 5000);
|
||||
|
||||
const plain = await openSession(await suite.browser(), { t, workflow: "implement", payload: { agent: { status: "working", activity: "Task 1 of 1" } } });
|
||||
plain.post({ finish: { headline: "A skill next", command: "/plan2code-4-finalize" } });
|
||||
await plain.page.getByRole("heading", { name: "A skill next" }).waitFor();
|
||||
assert.equal(await plain.page.getByRole("button", { name: "Start a New Session" }).count(), 0);
|
||||
});
|
||||
|
||||
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,
|
||||
@@ -615,6 +704,9 @@ test("a workflow page uses its modules: the full footer, the session meter, @ su
|
||||
await s.page.locator("#meter-pill").waitFor();
|
||||
assert.ok((await textOf(s.page.locator("#meter-words"))).length, "the meter pill has no words");
|
||||
// mentions.js: an @ in a text box offers the workspace's folders.
|
||||
// The @ list is the workspace frame, which can land after the page draws;
|
||||
// the footer has one label per width tier once it has.
|
||||
await s.page.waitForFunction(() => (document.getElementById("footer-where").dataset.key || "").includes("\n"));
|
||||
const box = itemCard(s.page, "q1").locator("textarea");
|
||||
await box.click();
|
||||
await box.pressSequentially("See @");
|
||||
|
||||
@@ -73,6 +73,10 @@ test("an @ in a note offers the workspace's folders, and picking one writes its
|
||||
await addFolderFromDialog(s, datasetsFolder());
|
||||
await s.page.locator("#workspace-done").click();
|
||||
await s.page.locator("#workspace-modal[open]").waitFor({ state: "detached" });
|
||||
// The @ list is the page's workspace frame, which can land after the
|
||||
// dialog closes; typed before then, the @ has nothing to offer. The footer
|
||||
// reads the same frame.
|
||||
await s.page.waitForFunction(() => (document.getElementById("footer-where").dataset.key || "").includes("+ 1 folder"));
|
||||
|
||||
const note = s.page.locator("#aside #thread-q1");
|
||||
await note.click();
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
handOff,
|
||||
PROTECTED_CONSOLE_FILES,
|
||||
readOverview,
|
||||
readSpecFile,
|
||||
removeCleanup,
|
||||
removeScratch,
|
||||
removeSessions,
|
||||
@@ -562,6 +563,12 @@ function overviewProject() {
|
||||
fs.writeFileSync(path.join(root, "specs", "a", "overview.md"), "# Overview A\n");
|
||||
fs.writeFileSync(path.join(root, "specs", "a", "phase-1.md"), "- [ ] **Task 1.1:** x\n");
|
||||
fs.writeFileSync(path.join(root, "specs", "b", "notes.md"), "notes\n");
|
||||
// Planned, not documented: a Pathfinder map and a live draft beside the
|
||||
// copy Revise plan keeps of the last one.
|
||||
fs.mkdirSync(path.join(root, "specs", "c", "pathfinder"), { recursive: true });
|
||||
fs.writeFileSync(path.join(root, "specs", "c", "pathfinder", "map.md"), "# Map C\n");
|
||||
fs.writeFileSync(path.join(root, "specs", "c", "PLAN-DRAFT-20261020.md"), "# Draft C\n");
|
||||
fs.writeFileSync(path.join(root, "specs", "c", "PLAN-DRAFT-20261020-prev.md"), "# Old draft C\n");
|
||||
fs.mkdirSync(path.join(base, "outside"));
|
||||
fs.writeFileSync(path.join(base, "outside", "overview.md"), "# SECRET\n");
|
||||
return { base, root };
|
||||
@@ -598,6 +605,22 @@ test("readOverview reads a spec's overview and nothing outside the root", async
|
||||
}
|
||||
});
|
||||
|
||||
test("readSpecFile reads a spec's map and live plan draft, and names the file", async () => {
|
||||
const { base, root } = overviewProject();
|
||||
try {
|
||||
assert.deepEqual(await readSpecFile(root, "specs/c", "map"), { file: "pathfinder/map.md", text: "# Map C\n" });
|
||||
assert.deepEqual(await readSpecFile(root, "specs/c", "draft"), { file: "PLAN-DRAFT-20261020.md", text: "# Draft C\n" });
|
||||
assert.deepEqual(await readSpecFile(root, "specs/a", "overview"), { file: "overview.md", text: "# Overview A\n" });
|
||||
assert.equal(await readSpecFile(root, "specs/c", "overview"), null);
|
||||
assert.equal(await readSpecFile(root, "specs/a", "map"), null);
|
||||
assert.equal(await readSpecFile(root, "specs/a", "draft"), null);
|
||||
assert.equal(await readSpecFile(root, "specs/c", "phase-1.md"), null, "only the known kinds");
|
||||
assert.equal(await readSpecFile(root, "../outside", "draft"), null);
|
||||
} finally {
|
||||
fs.rmSync(base, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
test("GET /overview serves the session's spec, and on the dashboard only a scanned one", async () => {
|
||||
const { base, root } = overviewProject();
|
||||
const sids = [];
|
||||
@@ -628,6 +651,16 @@ test("GET /overview serves the session's spec, and on the dashboard only a scann
|
||||
assert.equal((await get(d, "?spec=specs/b")).status, 204);
|
||||
assert.equal((await get(d, "?spec=specs/../..")).status, 204);
|
||||
assert.equal((await get(d, "?spec=specs/not-scanned")).status, 204);
|
||||
// ?file= picks the map or the live draft, and names it for the page.
|
||||
const map = await get(d, "?spec=specs/c&file=map");
|
||||
assert.equal(map.status, 200);
|
||||
assert.equal(map.headers.get("x-spec-file"), encodeURIComponent("pathfinder/map.md"));
|
||||
assert.equal(await map.text(), "# Map C\n");
|
||||
const draft = await get(d, "?spec=specs/c&file=draft");
|
||||
assert.equal(draft.headers.get("x-spec-file"), "PLAN-DRAFT-20261020.md");
|
||||
assert.equal(await draft.text(), "# Draft C\n");
|
||||
assert.equal((await get(d, "?spec=specs/c")).status, 204, "no overview.md yet");
|
||||
assert.equal((await get(d, "?spec=specs/c&file=nope")).status, 204);
|
||||
} finally {
|
||||
for (const s of sids) cliIn(root, ["stop", "--session", s]);
|
||||
fs.rmSync(base, { recursive: true, force: true });
|
||||
|
||||
@@ -734,6 +734,8 @@ test("help: helpTabFor opens on the tab for where the person is", () => {
|
||||
[{ dashboard: true, meterRed: true, view: "ask" }, "ask"],
|
||||
[{ meterRed: true }, "about"],
|
||||
[{ view: "overview" }, "docs"],
|
||||
[{ view: "map" }, "docs"],
|
||||
[{ view: "draft" }, "docs"],
|
||||
[{ view: "doc:plan" }, "docs"],
|
||||
[{ view: "doc:plan", workflow: "implement" }, "docs"],
|
||||
[{ workflow: "implement" }, "build"],
|
||||
|
||||
@@ -335,3 +335,49 @@ test("shape: the docs-table check names a file with no row, and passes one that
|
||||
fs.rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
// A page test that reads a style or sets a scroll through locator.evaluate
|
||||
// acts on whatever element the locator found, and a redraw can replace that
|
||||
// element before the call runs: one off the page reads "" for every style and
|
||||
// scrolls nothing anyone sees. On 3 and 4 core CI runners that failed a
|
||||
// different page test at random on each run until the reads went through
|
||||
// page-test-helpers.mjs's styleOf(), stylesOf() and scrollCard(), which retry
|
||||
// until the element is still on the page. page.evaluate and waitForFunction
|
||||
// look the element up afresh, so they are not flagged.
|
||||
const RACY_STYLE = /(?<!\bpage)\.evaluate\(\s*\((\w+)\)\s*=>[^\n]*getComputedStyle\(\1\)/;
|
||||
const RACY_SCROLL = /(?<!\bpage)\.evaluate\(\s*\((\w+)\)\s*=>\s*\(?\s*\1\.scrollTop\s*=[^=]/;
|
||||
|
||||
function racyPageReads(name, text) {
|
||||
const problems = [];
|
||||
text.split("\n").forEach((line, i) => {
|
||||
if (RACY_STYLE.test(line)) problems.push(`${name}:${i + 1}: read the style with styleOf() or stylesOf() from page-test-helpers.mjs`);
|
||||
if (RACY_SCROLL.test(line)) problems.push(`${name}:${i + 1}: scroll with scrollCard() from page-test-helpers.mjs`);
|
||||
});
|
||||
return problems;
|
||||
}
|
||||
|
||||
test("shape: page tests read styles and set scrolls through the redraw-safe helpers", () => {
|
||||
const dir = path.join(ROOT, "scripts");
|
||||
const pageTests = fs.readdirSync(dir).filter((f) => /^test-web-console-page-.*\.mjs$/.test(f));
|
||||
assert.ok(pageTests.length > 0, "the page tests were found");
|
||||
const problems = pageTests.flatMap((f) => racyPageReads(f, fs.readFileSync(path.join(dir, f), "utf8")));
|
||||
assert.deepEqual(problems, []);
|
||||
});
|
||||
|
||||
test("shape: the redraw-safe check names a locator's style read and scroll, and passes page-wide ones", () => {
|
||||
const racy = [
|
||||
'await card.evaluate((el) => (el.scrollTop = 400));',
|
||||
'const c = await chip.evaluate((b) => getComputedStyle(b).borderTopStyle);',
|
||||
].join("\n");
|
||||
assert.deepEqual(racyPageReads("x.mjs", racy), [
|
||||
"x.mjs:1: scroll with scrollCard() from page-test-helpers.mjs",
|
||||
"x.mjs:2: read the style with styleOf() or stylesOf() from page-test-helpers.mjs",
|
||||
]);
|
||||
const fine = [
|
||||
'await s.page.evaluate(() => { document.getElementById("main").scrollTop = 4000; });',
|
||||
'const top = await card.evaluate((el) => el.scrollTop === 0);',
|
||||
'await s.page.waitForFunction(() => getComputedStyle(document.body).color);',
|
||||
'const color = await s.page.evaluate((el) => getComputedStyle(el).color);',
|
||||
].join("\n");
|
||||
assert.deepEqual(racyPageReads("x.mjs", fine), []);
|
||||
});
|
||||
@@ -45,7 +45,7 @@ test("state: the rest of the shared state starts as app.js always started it", (
|
||||
updateFrame: null,
|
||||
inApp: false,
|
||||
subagentsFrame: null,
|
||||
overview: { key: null, text: null },
|
||||
overview: { key: null, files: {} },
|
||||
wake: null,
|
||||
dashPick: null,
|
||||
mentionPop: null,
|
||||
|
||||
@@ -947,7 +947,7 @@ async function cmdTrail(loc, args) {
|
||||
menu = {
|
||||
header: "Next step",
|
||||
question: checkpoint ? "Continue here, or start fresh? Everything is saved. I recommend starting fresh, to keep me sharp." : "Continue here, or start fresh? Everything is saved.",
|
||||
options: [...options, { label: "Start fresh" }],
|
||||
options: [...options, { label: "Start fresh", fresh: true }],
|
||||
recommended: checkpoint ? "Start fresh" : options[0].label,
|
||||
why: checkpoint ? (args.heavy ? "a heavy, contested or locked decision just landed" : `${resolvedThisSession} questions resolved this session`) : "lowest NN on the frontier",
|
||||
...(f.frontier.length > 3 ? { more: f.frontier.slice(3).map((x) => displayName(map, byNN.get(x.nn))) } : {}),
|
||||
|
||||
@@ -6,6 +6,7 @@ Workflow notes for `pathfinder`, part of the web console contract (`console.md`)
|
||||
- Post `"stopWarning"` while no map exists (Steps 0 to 4) and `"stopWarning": ""`
|
||||
once it does, and `"specDir": "specs/<idea>"` when the folder is created
|
||||
(`console-stop.md` → Saying what stopping would cost).
|
||||
- The menu after a decision is a `menu` card: its `options` are `trail --form C`'s, and the `Start fresh` one keeps its `"fresh": true` (the page words it "Start New Session" under the desktop app and asks the app for one on Send). Set the card's `command` to the resume command printed under `OR START FRESH`: the page copies it first. A declined confirm leaves you the pick: carry on as for any `Start fresh`.
|
||||
- The fresh-idea card carries `"templates": "idea"` (`console.md` → The kinds).
|
||||
- A doc that is a file exactly as written (the map once it is on disk, a
|
||||
brief) goes up as a `file` block (`{ "id": "body", "file":
|
||||
|
||||
@@ -36,6 +36,23 @@ export function onAppMessage(kind, handler) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ask the app for what its bar's New Session button does, confirm and all.
|
||||
* `command`, when there is one, goes on the clipboard first so it can be
|
||||
* pasted into the new terminal; a refused copy loses nothing, the page still
|
||||
* shows it.
|
||||
*/
|
||||
export async function startNewSession(command = "") {
|
||||
if (command) {
|
||||
try {
|
||||
await navigator.clipboard.writeText(command);
|
||||
} catch {
|
||||
/* the command stays on the page to copy by hand */
|
||||
}
|
||||
}
|
||||
tellApp("new-session");
|
||||
}
|
||||
|
||||
/** Post `message` to the frame's parent, as `{ plan2code: kind, ...extra }`; nothing outside a frame. */
|
||||
export function tellApp(kind, extra = {}) {
|
||||
if (!framed()) return;
|
||||
|
||||
@@ -46,7 +46,7 @@ export function helpTabFor({ view, dashboard, gone, adrift, finished, workflow,
|
||||
if (v === "subagents") return "subagents";
|
||||
if (dashboard && meterRed) return "meter";
|
||||
if (dashboard) return "dashboard";
|
||||
if (v === "overview" || v.startsWith("doc:")) return "docs";
|
||||
if (v === "overview" || v === "map" || v === "draft" || v.startsWith("doc:")) return "docs";
|
||||
if (workflow === "git") return "git";
|
||||
if (HELP_BUILD_WORKFLOWS.has(workflow)) return "build";
|
||||
return "about";
|
||||
|
||||
@@ -1654,13 +1654,19 @@
|
||||
<strong>Out of date</strong> by the title means answers have landed that
|
||||
the document does not reflect yet.
|
||||
</p>
|
||||
<h4>The Overview tab</h4>
|
||||
<h4>The Overview, Map and Plan draft tabs</h4>
|
||||
<p>
|
||||
When the session is working on a spec that has an
|
||||
<code>overview.md</code>, the <strong>Overview</strong> tab shows it. It
|
||||
is read-only, and read fresh from disk each time you open the tab, so an
|
||||
edit shows up straight away. No file, no tab.
|
||||
</p>
|
||||
<p>
|
||||
On the dashboard, a picked spec that is not documented yet shows its
|
||||
main files the same way instead: <strong>Map</strong> for its
|
||||
Pathfinder map and <strong>Plan draft</strong> for its plan draft, each
|
||||
when it exists.
|
||||
</p>
|
||||
<h4>Printing and saving</h4>
|
||||
<ul>
|
||||
<li>
|
||||
@@ -2691,17 +2697,32 @@
|
||||
Let Plan2Code hand independent work to helpers in this skill. Saved for this
|
||||
project and this skill.
|
||||
</p>
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<!-- On a wide dialog the switch and the cap share a row, and the four
|
||||
strengths sit side by side, so the dialog stays short. -->
|
||||
<div class="subagents-top">
|
||||
<fieldset class="modal-ranges looks-row">
|
||||
<legend>Helpers</legend>
|
||||
<label><input type="radio" name="subagents-on" value="on" /> <span>Use helpers</span></label>
|
||||
<label><input type="radio" name="subagents-on" value="off" checked /> <span>Work alone</span></label>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
</div>
|
||||
<!-- Each strength wears the Subagents tab's badge for the rank it leans
|
||||
to: Thrifty light, Balanced standard, Best strongest, and the
|
||||
session's own model with no rank. -->
|
||||
<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>
|
||||
<label><input type="radio" name="subagents-strength" value="thrifty" /> <span class="sa-badge lvl-1"><span class="sa-bars" aria-hidden="true"><i class="on"></i><i></i><i></i></span>Thrifty</span></label>
|
||||
<label><input type="radio" name="subagents-strength" value="balanced" checked /> <span class="sa-badge lvl-2"><span class="sa-bars" aria-hidden="true"><i class="on"></i><i class="on"></i><i></i></span>Balanced</span></label>
|
||||
<label><input type="radio" name="subagents-strength" value="best" /> <span class="sa-badge lvl-3"><span class="sa-bars" aria-hidden="true"><i class="on"></i><i class="on"></i><i class="on"></i></span>Best</span></label>
|
||||
<label><input type="radio" name="subagents-strength" value="session" /> <span class="sa-badge lvl-0">Match my session</span></label>
|
||||
<p class="help" id="subagents-strength-help"></p>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
@@ -2712,14 +2733,6 @@
|
||||
<span class="help">Passed to the agent as written, at its next check-in.</span>
|
||||
</div>
|
||||
</fieldset>
|
||||
<fieldset class="modal-ranges">
|
||||
<legend>At most</legend>
|
||||
<label>
|
||||
<input type="number" id="subagents-max" min="1" max="20" step="1" aria-label="At most this many helpers at once" />
|
||||
<span>helpers at once</span>
|
||||
</label>
|
||||
<p class="help">Advisory: your agent's own limit still applies.</p>
|
||||
</fieldset>
|
||||
<p class="help" id="subagents-checkin"></p>
|
||||
<p class="help" id="subagents-research" hidden></p>
|
||||
<p class="help" id="subagents-status" role="status"></p>
|
||||
|
||||
@@ -1317,11 +1317,13 @@ function buildMenu(card, item, staged) {
|
||||
radio.id = optionId(item, o, i);
|
||||
radio.value = o.k;
|
||||
radio.checked = Boolean(picked);
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${o.text}` : o.text);
|
||||
// Under the app a fresh start is the bar's New Session, so say that.
|
||||
const text = page.inApp && o.fresh === true ? "Start New Session" : o.text;
|
||||
radio.setAttribute("aria-label", o.k ? `${o.k}: ${text}` : text);
|
||||
radio.addEventListener("change", () => stage(item.id, { type: "answer", kind: "menu", k: o.k }));
|
||||
const body = el("div", "option-body");
|
||||
const head = el("div", "option-label");
|
||||
head.appendChild(el("span", null, o.text));
|
||||
head.appendChild(el("span", null, text));
|
||||
if (o.recommended) head.appendChild(el("span", "pill suggested", "Suggested"));
|
||||
body.appendChild(head);
|
||||
if (o.detail) body.appendChild(el("p", "option-detail", o.detail));
|
||||
|
||||
@@ -51,8 +51,8 @@ import { helperRows, showTab } from "../subagents.js";
|
||||
import { FOOTER_TIERS, footerLabel } from "../workspace.js";
|
||||
import {
|
||||
activity, agentAdrift, agentWorking, asked, awaitingReply, byId, dashboardLive, docs, doingNow,
|
||||
finish, gitAwaiting, isDashboard, isGitBoard, isOpen, items, loadOverview, myTurn, openItems,
|
||||
overviewSpec, patience, reviewPending, scan, selSpec, sendCollected, stagedCount, stranded,
|
||||
finish, gitAwaiting, isDashboard, isGitBoard, isOpen, isSpecFileView, items, loadOverview, myTurn, openItems,
|
||||
patience, pressStranded, reviewPending, scan, selSpec, sendCollected, specFileTabs, stagedCount, stranded,
|
||||
topics, workingMs, WORKING_GRACE_MS,
|
||||
workspaceFolders,
|
||||
} from "../selectors.js";
|
||||
@@ -67,7 +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 { linkLeavesPage, startNewSession, 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";
|
||||
@@ -433,9 +433,9 @@ export function adopt(body) {
|
||||
render();
|
||||
if ($("workspace-modal").open) renderWorkspace();
|
||||
tellFolderIssues();
|
||||
// The Overview tab's file changes under a build, so a tab you are watching
|
||||
// A spec file tab's file changes under a build, so a tab you are watching
|
||||
// refetches on every new frame too, not only on the click that opened it.
|
||||
if (firstLoad || page.S.specDir !== prevSpecDir || page.S.workflow !== prevWorkflow || page.view === "overview") loadOverview();
|
||||
if (firstLoad || page.S.specDir !== prevSpecDir || page.S.workflow !== prevWorkflow || isSpecFileView(page.view)) loadOverview();
|
||||
if (announce) showArrival(announce);
|
||||
// New entries land at the bottom of the rail. Gliding down to them beats
|
||||
// leaving the list parked where it was while it grew underneath.
|
||||
@@ -860,7 +860,7 @@ function withFocus(fn) {
|
||||
// (the dashboard menu, the end page).
|
||||
function currentScroller() {
|
||||
if (!drawnView) return null;
|
||||
if (drawnView.startsWith("doc:") || drawnView === "overview") return $("main");
|
||||
if (drawnView.startsWith("doc:") || isSpecFileView(drawnView)) return $("main");
|
||||
if (drawnView === "questions") return $("main").querySelector(":scope > .card.question");
|
||||
if (drawnView === "ask") return $("main").querySelector(".ask-list");
|
||||
return null;
|
||||
@@ -1027,6 +1027,10 @@ let moodVar = 0;
|
||||
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.";
|
||||
|
||||
// A finished screen's press that nothing is collecting (pressStranded()).
|
||||
const PRESS_STRANDED_LINE =
|
||||
"Plan2Code is not running. Your choice is saved and waiting for it. If the terminal is idle, type **continue** there and it will pick it 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.
|
||||
@@ -1109,6 +1113,10 @@ export function renderStatus() {
|
||||
// Before `gone`, deliberately. Once a session has finished, no server is the
|
||||
// expected state, and Planny shutting his eye over it reads as a breakage.
|
||||
if (finish()) {
|
||||
// A press the agent never came back for: its turn ended while the screen
|
||||
// waited. The press is saved, and **continue** in the terminal collects
|
||||
// it (a button that types it there, under the app).
|
||||
if (pressStranded()) return say("adrift", PRESS_STRANDED_LINE, "", false, true);
|
||||
// A finish with the review or the way back to the dashboard still on
|
||||
// offer has something left to press here, and only while the server is
|
||||
// there to take the press.
|
||||
@@ -1241,10 +1249,11 @@ function renderViews() {
|
||||
},
|
||||
];
|
||||
// Built in rather than posted: present exactly while the spec in view has
|
||||
// an overview.md. A tab that vanishes under the person sends them home.
|
||||
const hasOverview = typeof page.overview.text === "string" && page.overview.key === overviewSpec();
|
||||
if (hasOverview) tabs.push({ id: "overview", label: "Overview", count: 0 });
|
||||
else if (page.view === "overview") page.view = "questions";
|
||||
// the file (an overview.md, or before one a map or a plan draft). A tab
|
||||
// that vanishes under the person sends them home.
|
||||
const fileTabs = specFileTabs();
|
||||
for (const f of fileTabs) tabs.push({ id: f.id, label: f.label, count: 0 });
|
||||
if (isSpecFileView(page.view) && !fileTabs.some((f) => f.id === page.view)) page.view = "questions";
|
||||
for (const d of docs()) tabs.push({ id: "doc:" + d.id, label: d.title || "Document", count: 0 });
|
||||
// The helpers the agent reported, from the first one on; cleared by a
|
||||
// dashboard hop, which sends the person home like the Overview tab does.
|
||||
@@ -1293,7 +1302,7 @@ function renderViews() {
|
||||
// The cached text paints at once; the fresh read repaints if the file
|
||||
// changed on disk since.
|
||||
render();
|
||||
if (t.id === "overview") loadOverview();
|
||||
if (isSpecFileView(t.id)) loadOverview();
|
||||
});
|
||||
nav.appendChild(b);
|
||||
}
|
||||
@@ -1428,11 +1437,11 @@ function renderMain() {
|
||||
}
|
||||
|
||||
function paintMain(main) {
|
||||
main.classList.toggle("is-doc", page.view.startsWith("doc:") || page.view === "overview");
|
||||
main.classList.toggle("is-doc", page.view.startsWith("doc:") || isSpecFileView(page.view));
|
||||
main.classList.toggle("is-ask", page.view === "ask");
|
||||
|
||||
if (page.view.startsWith("doc:")) return renderDoc(main, page.view.slice(4));
|
||||
if (page.view === "overview") return renderOverview(main);
|
||||
if (isSpecFileView(page.view)) return renderOverview(main, page.view);
|
||||
if (page.view === "ask") return renderAsk(main);
|
||||
if (page.view === "subagents") return renderSubagents(main);
|
||||
|
||||
@@ -1788,6 +1797,15 @@ export function markSent({ sentIds, sentNotes = {}, summaries, values }) {
|
||||
save();
|
||||
}
|
||||
|
||||
// The menu card whose staged pick is an option marked `fresh`, if any.
|
||||
function freshMenuPick(actions) {
|
||||
for (const a of actions) {
|
||||
const item = a.kind === "menu" ? byId(a.i) : null;
|
||||
if (item && (item.options || []).some((o) => o.k === a.k && o.fresh === true)) return item;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function send() {
|
||||
if (sendState().disabled) return;
|
||||
const payload = stagedPayload();
|
||||
@@ -1818,6 +1836,11 @@ export async function send() {
|
||||
markSent(payload);
|
||||
banner("Sent. Plan2Code is picking it up now.", "good");
|
||||
setTimeout(() => banner(null), 4000);
|
||||
// A menu option the agent marked `fresh` is a clean start, which under the
|
||||
// app is the bar's New Session; the agent still gets the pick, so a
|
||||
// declined confirm carries on with its usual finish.
|
||||
const freshMenu = page.inApp ? freshMenuPick(actions) : null;
|
||||
if (freshMenu) startNewSession(freshMenu.command ? handoffText({ command: freshMenu.command }) : "");
|
||||
} catch (err) {
|
||||
if (err && err.pending) {
|
||||
banner(
|
||||
|
||||
@@ -559,13 +559,15 @@ function renderHandoffPreview(h) {
|
||||
read.type = "button";
|
||||
read.addEventListener("click", () => readHandoff(h));
|
||||
const copyLabel = page.inApp ? "Copy for another session" : "Copy for a new conversation";
|
||||
const copy = el("button", "btn", copyLabel);
|
||||
const shown = handoffCopied && handoffCopied.id === h.id && Date.now() < handoffCopied.until ? handoffCopied.word : copyLabel;
|
||||
const copy = el("button", "btn", shown);
|
||||
copy.type = "button";
|
||||
copy.dataset.handoffCopy = h.id;
|
||||
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, copyLabel);
|
||||
copyHandoffText(handoffCopyText(file), h.id, copyLabel);
|
||||
});
|
||||
const del = el("button", "btn danger", "Delete");
|
||||
del.type = "button";
|
||||
@@ -578,14 +580,29 @@ 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, label) {
|
||||
// A redraw while the clipboard answers rebuilds the button, so the word is
|
||||
// kept in handoffCopied (which the rebuilt button reads) and put on whichever
|
||||
// button is on the page when the answer comes.
|
||||
let handoffCopied = null;
|
||||
const handoffCopyButton = (id) => document.querySelector(`button[data-handoff-copy="${CSS.escape(id)}"]`);
|
||||
async function copyHandoffText(text, id, label) {
|
||||
let word;
|
||||
try {
|
||||
await navigator.clipboard.writeText(text);
|
||||
button.textContent = "Copied";
|
||||
word = "Copied";
|
||||
} catch {
|
||||
button.textContent = "Copy was refused";
|
||||
word = "Copy was refused";
|
||||
}
|
||||
setTimeout(() => (button.textContent = label), 1500);
|
||||
const mark = { id, word, until: Date.now() + 1500 };
|
||||
handoffCopied = mark;
|
||||
const shown = handoffCopyButton(id);
|
||||
if (shown) shown.textContent = word;
|
||||
setTimeout(() => {
|
||||
if (handoffCopied !== mark) return;
|
||||
handoffCopied = null;
|
||||
const live = handoffCopyButton(id);
|
||||
if (live) live.textContent = label;
|
||||
}, 1500);
|
||||
}
|
||||
|
||||
// Pick it up here: a hop like a card launch. The page sends only the id; the
|
||||
@@ -1004,7 +1021,9 @@ export function wireDashboard() {
|
||||
deleteStep();
|
||||
}
|
||||
});
|
||||
// `close` is queued, so it can land after the dialog was opened again for
|
||||
// another spec; that new target must survive it.
|
||||
$("delete-modal").addEventListener("close", () => {
|
||||
deleteTarget = null;
|
||||
if (!$("delete-modal").open) deleteTarget = null;
|
||||
});
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
// Plan2Code Web Console - documents: tabs, blocks, print and download, and the brief button; defines only.
|
||||
|
||||
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish } from "../selectors.js";
|
||||
import { docs, agentWorking, workingMs, patience, WORKING_GRACE_MS, finish, SPEC_FILES } from "../selectors.js";
|
||||
import { el, md } from "../render.js";
|
||||
import { downloadDocHtml, docSavedNote, downloadDoc, blockBody } from "../doc-files.js";
|
||||
import { hooks, page, redraw } from "../state.js";
|
||||
@@ -220,19 +220,22 @@ function printButton() {
|
||||
return print;
|
||||
}
|
||||
|
||||
// The spec's overview.md, read-only and drawn through the same markdown path
|
||||
// as every doc. No Download: the file is already on disk.
|
||||
export function renderOverview(main) {
|
||||
// One of the spec's files (overview.md, the Pathfinder map, the Plan draft),
|
||||
// read-only and drawn through the same markdown path as every doc. No
|
||||
// Download: the file is already on disk.
|
||||
export function renderOverview(main, kind = "overview") {
|
||||
const spec = SPEC_FILES.find((f) => f.id === kind) || SPEC_FILES[0];
|
||||
const found = page.overview.files[spec.id];
|
||||
const head = el("div", "doc-head");
|
||||
head.appendChild(el("h2", null, "Overview"));
|
||||
head.appendChild(el("h2", null, spec.label));
|
||||
const tools = el("div", "doc-tools");
|
||||
tools.appendChild(backButton());
|
||||
tools.appendChild(printButton());
|
||||
head.appendChild(tools);
|
||||
main.appendChild(head);
|
||||
main.appendChild(el("p", "help", `${page.overview.key}/overview.md · read-only, straight from disk`));
|
||||
main.appendChild(el("p", "help", `${page.overview.key}/${found ? found.file : ""} · read-only, straight from disk`));
|
||||
const box = el("div", "block settled");
|
||||
box.appendChild(md(page.overview.text, "md"));
|
||||
box.appendChild(md(found ? found.text : "", "md"));
|
||||
main.appendChild(box);
|
||||
}
|
||||
|
||||
|
||||
@@ -44,6 +44,7 @@ import {
|
||||
isDashboard,
|
||||
} from "../selectors.js";
|
||||
import { docSavedNote, downloadDoc } from "../doc-files.js";
|
||||
import { startNewSession } from "../app-bridge.js";
|
||||
import { pendingNotes } from "../uploads.js";
|
||||
|
||||
// The end of the session, and the only screen in this page whose job is to
|
||||
@@ -220,6 +221,17 @@ export function renderHandoff(fin) {
|
||||
row.appendChild(code);
|
||||
row.appendChild(copyButton(text, "btn small handoff-copy", code));
|
||||
step.appendChild(row);
|
||||
// Under the app a clean start is the bar's New Session: one press, with
|
||||
// the command already on the clipboard to paste into the new terminal.
|
||||
if (page.inApp && command.startsWith("/") && !page.gone) {
|
||||
const fresh = el("div", "handoff-newsession");
|
||||
const press = el("button", "btn small", "Start a New Session");
|
||||
press.type = "button";
|
||||
press.addEventListener("click", () => startNewSession(text));
|
||||
fresh.appendChild(press);
|
||||
fresh.appendChild(el("p", "handoff-note", "The command above is copied first: paste it into the terminal panel once the new session opens."));
|
||||
step.appendChild(fresh);
|
||||
}
|
||||
const next = continueOffer(fin);
|
||||
if (next && continueLive()) step.appendChild(renderContinueOffer(next));
|
||||
if (text !== command) {
|
||||
|
||||
@@ -223,26 +223,74 @@ function uncollectedLimit() {
|
||||
// them up -- but "Sent. Waiting for Plan2Code." forever does not say that.
|
||||
export const stranded = () => page.pendingResult && agentAdrift();
|
||||
|
||||
// The spec whose overview.md the Overview tab shows: the dashboard picker's
|
||||
// A press on a finished screen (Commit it now, Update CHANGELOG first, the way
|
||||
// back to the dashboard, Continue here, a review) that nothing has collected.
|
||||
// agentAdrift() stays quiet after a finish, where no agent is the normal end,
|
||||
// but a press sent to one means somebody is waiting on it: an agent still in
|
||||
// `wait` pings every five seconds, so a minute of silence says it is gone (its
|
||||
// turn ended while the person was away) and the press sits saved until it
|
||||
// is woken.
|
||||
export function pressStranded() {
|
||||
if (!finish() || page.gone || !page.pendingResult || !page.agentLastSeen) return false;
|
||||
if (!page.local.afterBuild || page.local.afterBuild === "done") return false;
|
||||
return Date.now() - Date.parse(page.agentLastSeen) > UNCOLLECTED_MS;
|
||||
}
|
||||
|
||||
// The spec whose files the spec file tabs show: the dashboard picker's
|
||||
// selection on the dashboard, the session's own spec everywhere else.
|
||||
export const overviewSpec = () => (isDashboard() ? selSpec()?.dir || "" : (page.S && page.S.specDir) || "");
|
||||
|
||||
// Fresh from disk every time, never cached: the file changes under a build,
|
||||
// and the tab is only worth having if it shows what is there now. Repaints
|
||||
// only when the tab would appear, vanish or show different text.
|
||||
// The spec files a tab can show, in tab order: each a view id, which is also
|
||||
// the server's ?file= kind. Document's overview stands for the whole spec
|
||||
// once it exists; before that the dashboard offers Pathfinder's map and
|
||||
// Plan's draft.
|
||||
export const SPEC_FILES = [
|
||||
{ id: "overview", label: "Overview" },
|
||||
{ id: "map", label: "Map" },
|
||||
{ id: "draft", label: "Plan draft" },
|
||||
];
|
||||
export const isSpecFileView = (v) => SPEC_FILES.some((f) => f.id === v);
|
||||
|
||||
// The spec file tabs to draw now: Overview alone when the spec has one, else
|
||||
// the map and the draft that exist. Only for the spec in view, so a pick that
|
||||
// moved on never shows the last spec's files.
|
||||
export function specFileTabs() {
|
||||
if (page.overview.key !== overviewSpec()) return [];
|
||||
const has = (id) => Boolean(page.overview.files[id]);
|
||||
if (has("overview")) return SPEC_FILES.filter((f) => f.id === "overview");
|
||||
return SPEC_FILES.filter((f) => f.id !== "overview" && has(f.id));
|
||||
}
|
||||
|
||||
async function fetchSpecFile(spec, kind) {
|
||||
try {
|
||||
const res = await fetch("/overview?spec=" + encodeURIComponent(spec) + "&file=" + kind, { cache: "no-store" });
|
||||
if (res.status !== 200) return null;
|
||||
const file = decodeURIComponent(res.headers.get("x-spec-file") || "") || kind;
|
||||
return { file, text: await res.text() };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Fresh from disk every time, never cached: the files change under a build,
|
||||
// and the tabs are only worth having if they show what is there now. Away
|
||||
// from the dashboard only the overview is read: a session's own map or draft
|
||||
// is the work already in front of it. Repaints only when a tab would appear,
|
||||
// vanish or show different text.
|
||||
export async function loadOverview() {
|
||||
const spec = overviewSpec();
|
||||
let text = null;
|
||||
const kinds = isDashboard() ? SPEC_FILES.map((f) => f.id) : ["overview"];
|
||||
const files = {};
|
||||
if (spec) {
|
||||
try {
|
||||
const res = await fetch("/overview?spec=" + encodeURIComponent(spec), { cache: "no-store" });
|
||||
if (res.status === 200) text = await res.text();
|
||||
} catch {}
|
||||
const found = await Promise.all(kinds.map((k) => fetchSpecFile(spec, k)));
|
||||
kinds.forEach((k, i) => {
|
||||
if (found[i]) files[k] = found[i];
|
||||
});
|
||||
}
|
||||
// The selection moved on while this was in flight; its own fetch will land.
|
||||
if (spec !== overviewSpec()) return;
|
||||
const changed = page.overview.key !== spec || page.overview.text !== text;
|
||||
page.overview = { key: spec, text };
|
||||
const changed = page.overview.key !== spec || JSON.stringify(page.overview.files) !== JSON.stringify(files);
|
||||
page.overview = { key: spec, files };
|
||||
if (changed) redraw();
|
||||
}
|
||||
|
||||
|
||||
@@ -108,9 +108,10 @@ export const page = {
|
||||
// The frame's Subagents switch ({ offered, supported, on, instruction, max,
|
||||
// revision }), or null before a server that sends it.
|
||||
subagentsFrame: null,
|
||||
// The spec's overview.md as last fetched: `key` is the spec dir it was read
|
||||
// for, `text` the file, or null when there is none. See loadOverview().
|
||||
overview: { key: null, text: null },
|
||||
// The spec's files as last fetched: `key` is the spec dir they were read
|
||||
// for, `files` maps each SPEC_FILES kind (overview, map, draft) that exists
|
||||
// to `{ file, text }`. See loadOverview().
|
||||
overview: { key: null, files: {} },
|
||||
// The dashboard's first-open wake-up (boot.js), while it runs. `cards` turns
|
||||
// true at the glide, which lets the menu in; `entered` once its entrance has
|
||||
// played; `typed` is how many characters of the note show, or null once all
|
||||
|
||||
@@ -50,6 +50,7 @@
|
||||
hover it may never get. This one IS the screen's reason to exist. */
|
||||
.handoff-copy { flex: none; }
|
||||
.handoff-note { margin: 8px 0 0; font-size: 12.5px; color: var(--ink-3); }
|
||||
.handoff-newsession { margin-top: 10px; }
|
||||
/* Continue here sits under the command row: keep a gap so the two do not touch. */
|
||||
.continue-offer { margin-top: 14px; }
|
||||
|
||||
|
||||
@@ -194,6 +194,24 @@
|
||||
.sa-pill.is-done { background: var(--ok-soft); color: var(--ok); }
|
||||
.sa-pill.is-failed { background: var(--warn-soft); color: var(--warn); }
|
||||
.sa-pill .spinner.tiny { width: 10px; height: 10px; }
|
||||
/* The Subagents dialog: wide like the Notebook, so it lays its choices out
|
||||
in rows instead of a tall stack. Back to a stack on a narrow window. */
|
||||
.modal.looks.subagents { width: min(1000px, 90vw); max-width: none; }
|
||||
.subagents-top { display: grid; grid-template-columns: minmax(0, 2fr) minmax(0, 1fr); gap: 18px; align-items: start; }
|
||||
.modal.looks .subagents-top .modal-ranges + .modal-ranges { margin-top: 0; }
|
||||
.subagents-top .looks-row { grid-template-columns: repeat(2, minmax(0, 1fr)); }
|
||||
.subagents-top + .modal-ranges { margin-top: 18px; }
|
||||
.subagents #subagents-strength-row { grid-template-columns: repeat(4, minmax(0, 1fr)); }
|
||||
/* Each strength radio carries the tab's badge; the session's own model has no
|
||||
rank, so it keeps the badge's plain ink. A locked row dims with its radios. */
|
||||
.subagents #subagents-strength-row .sa-badge { font-size: 13px; padding: 5px 10px; }
|
||||
.subagents #subagents-strength-row label:has(input:checked) { border-color: var(--accent-line); }
|
||||
.subagents #subagents-strength-row label:has(input:disabled) .sa-badge { opacity: 0.5; }
|
||||
@media (max-width: 720px) {
|
||||
.subagents-top,
|
||||
.subagents-top .looks-row,
|
||||
.subagents #subagents-strength-row { grid-template-columns: 1fr; }
|
||||
}
|
||||
/* The dialog's number box, themed like the page's other inputs. */
|
||||
.subagents input[type="number"] {
|
||||
width: 5em; font: inherit; color: var(--ink); background: var(--panel-2);
|
||||
|
||||
@@ -27,7 +27,7 @@ import {
|
||||
writeJsonAtomic,
|
||||
} from "./files.mjs";
|
||||
import { AGENTS_SCHEMA, normalizeAgents, resolveCommand, validateForSave } from "./agents.mjs";
|
||||
import { checkDocument, cleanupFindings, readOverview, removeCleanup } from "./sessions.mjs";
|
||||
import { checkDocument, cleanupFindings, readSpecFile, removeCleanup } from "./sessions.mjs";
|
||||
import { SHOTS_DIR_NAME, SHOT_NAME, shotType } from "./patches.mjs";
|
||||
import { appendChat, currentConversation, pendingChatCount, typedCount } from "./inbox.mjs";
|
||||
import { specKey } from "./workspace.mjs";
|
||||
@@ -302,12 +302,15 @@ function renderIndex(ctx) {
|
||||
|
||||
/* ------------------------------------------------------ read-only routes */
|
||||
|
||||
// The spec's overview.md, read-only. A dashboard honors ?spec= only for a
|
||||
// spec its own scan found; every other workflow reads its own specDir.
|
||||
// readOverview() keeps the read inside the project root.
|
||||
// One of the spec's files, read-only: overview.md by default, or with
|
||||
// ?file=draft or ?file=map the live PLAN-DRAFT or the Pathfinder map. A
|
||||
// dashboard honors ?spec= only for a spec its own scan found; every other
|
||||
// workflow reads its own specDir. readSpecFile() keeps the read inside the
|
||||
// project root, and names the file it read in X-Spec-File.
|
||||
function overview(req, res, ctx, url) {
|
||||
const state = ctx.readState() || {};
|
||||
const asked = url.searchParams.get("spec");
|
||||
const kind = url.searchParams.get("file") || "overview";
|
||||
const spec =
|
||||
state.workflow === "dashboard"
|
||||
? (state.scan?.specs || []).some((s) => s && s.dir === asked)
|
||||
@@ -320,10 +323,14 @@ function overview(req, res, ctx, url) {
|
||||
res.writeHead(204, baseHeaders({ "cache-control": "no-store" }));
|
||||
res.end();
|
||||
};
|
||||
readOverview(state.worktree || state.project, spec)
|
||||
.then((text) =>
|
||||
typeof text === "string"
|
||||
? send(res, 200, text, "text/markdown; charset=utf-8", { "cache-control": "no-store" })
|
||||
readSpecFile(state.worktree || state.project, spec, kind)
|
||||
.then((found) =>
|
||||
found
|
||||
? send(res, 200, found.text, "text/markdown; charset=utf-8", {
|
||||
"cache-control": "no-store",
|
||||
// Encoded: a header value is bytes, and a file name need not be ASCII.
|
||||
"x-spec-file": encodeURIComponent(found.file),
|
||||
})
|
||||
: noOverview()
|
||||
)
|
||||
.catch(noOverview);
|
||||
|
||||
@@ -500,15 +500,38 @@ export async function removeCleanup(ids, opts = {}) {
|
||||
* and a symlink pointing outside all come back null.
|
||||
*/
|
||||
export async function readOverview(root, specDir) {
|
||||
const found = await readSpecFile(root, specDir, "overview");
|
||||
return found ? found.text : null;
|
||||
}
|
||||
|
||||
// The files a spec folder can show as a tab, by kind: Document's overview,
|
||||
// Plan's live draft (the newest PLAN-DRAFT that is not a `-prev` copy, as in
|
||||
// scan.mjs) and Pathfinder's map.
|
||||
async function specFileName(dir, kind) {
|
||||
if (kind === "overview") return "overview.md";
|
||||
if (kind === "map") return "pathfinder/map.md";
|
||||
if (kind !== "draft") return null;
|
||||
const drafts = (await fs.promises.readdir(dir)).filter((n) => /^PLAN-DRAFT.*\.md$/i.test(n));
|
||||
return drafts.filter((n) => !/-prev\.md$/i.test(n)).sort().reverse()[0] || drafts[0] || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* One of a spec's files (`kind`: overview, draft or map), read-only, as
|
||||
* `{ file, text }` with `file` relative to the spec folder, or null. Kept
|
||||
* inside the root the same way readOverview() is.
|
||||
*/
|
||||
export async function readSpecFile(root, specDir, kind) {
|
||||
if (!root || !specDir || typeof specDir !== "string" || path.isAbsolute(specDir)) return null;
|
||||
try {
|
||||
const file = path.resolve(root, specDir, "overview.md");
|
||||
const name = await specFileName(path.resolve(root, specDir), kind);
|
||||
if (!name) return null;
|
||||
const file = path.resolve(root, specDir, name);
|
||||
const [realFile, realRoot] = await Promise.all([fs.promises.realpath(file), fs.promises.realpath(root)]);
|
||||
// path.relative, not a prefix test: a root of `C:\` or `/` already ends
|
||||
// in the separator, and `root + sep` would then match nothing at all.
|
||||
const rel = path.relative(realRoot, realFile);
|
||||
if (!rel || rel === ".." || rel.startsWith(".." + path.sep) || path.isAbsolute(rel)) return null;
|
||||
return await fs.promises.readFile(realFile, "utf8");
|
||||
return { file: name, text: await fs.promises.readFile(realFile, "utf8") };
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user